Skip to content

Commit

Permalink
[Endpoint] Hook to handle events needing navigation via Router (#63863)…
Browse files Browse the repository at this point in the history
… (#64113)

* new hook providing generic event handler for use with react router
* Refactor of Header Naviagtion to use useNavigateByRouterEventHandler
* Policy list refactor to use useNavigateByRouterEventHandler hook
* Policy list Policy name link to use useNavigateByRouterEventHandler hook
* Host list use of useNavigateByRouteEventHandler
  • Loading branch information
paul-tavares authored Apr 22, 2020
1 parent fb1e365 commit 8c99b0a
Show file tree
Hide file tree
Showing 11 changed files with 244 additions and 84 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@
* you may not use this file except in compliance with the Elastic License.
*/

import React, { MouseEvent, useMemo } from 'react';
import React, { memo, useMemo } from 'react';
import { i18n } from '@kbn/i18n';
import { EuiTabs, EuiTab } from '@elastic/eui';
import { useHistory, useLocation } from 'react-router-dom';
import { useLocation } from 'react-router-dom';
import { useKibana } from '../../../../../../../../src/plugins/kibana_react/public';
import { Immutable } from '../../../../../common/types';
import { useNavigateByRouterEventHandler } from '../hooks/use_navigate_by_router_event_handler';

interface NavTabs {
name: string;
Expand Down Expand Up @@ -48,33 +49,30 @@ const navTabs: Immutable<NavTabs[]> = [
},
];

export const HeaderNavigation: React.FunctionComponent = React.memo(() => {
const history = useHistory();
const location = useLocation();
const NavTab = memo<{ tab: NavTabs }>(({ tab }) => {
const { pathname } = useLocation();
const { services } = useKibana();
const onClickHandler = useNavigateByRouterEventHandler(tab.href);
const BASE_PATH = services.application.getUrlForApp('endpoint');

return (
<EuiTab
data-test-subj={`${tab.id}EndpointTab`}
href={`${BASE_PATH}${tab.href}`}
onClick={onClickHandler}
isSelected={tab.href === pathname || (tab.href !== '/' && pathname.startsWith(tab.href))}
>
{tab.name}
</EuiTab>
);
});

export const HeaderNavigation: React.FunctionComponent = React.memo(() => {
const tabList = useMemo(() => {
return navTabs.map((tab, index) => {
return (
<EuiTab
data-test-subj={`${tab.id}EndpointTab`}
key={index}
href={`${BASE_PATH}${tab.href}`}
onClick={(event: MouseEvent) => {
event.preventDefault();
history.push(tab.href);
}}
isSelected={
tab.href === location.pathname ||
(tab.href !== '/' && location.pathname.startsWith(tab.href))
}
>
{tab.name}
</EuiTab>
);
return <NavTab tab={tab} key={index} />;
});
}, [BASE_PATH, history, location.pathname]);
}, []);

return <EuiTabs>{tabList}</EuiTabs>;
});
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ describe('LinkToApp component', () => {
const clickEventArg = spyOnClickHandler.mock.calls[0][0];
expect(clickEventArg.isDefaultPrevented()).toBe(true);
});
it('should not navigate if onClick callback prevents defalut', () => {
it('should not navigate if onClick callback prevents default', () => {
const spyOnClickHandler: LinkToAppOnClickMock = jest.fn(ev => {
ev.preventDefault();
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import React from 'react';
import { AppContextTestRender, createAppRootMockRenderer } from '../../mocks';
import { useNavigateByRouterEventHandler } from './use_navigate_by_router_event_handler';
import { act, fireEvent, cleanup } from '@testing-library/react';

type ClickHandlerMock<Return = void> = jest.Mock<
Return,
[React.MouseEvent<HTMLAnchorElement, MouseEvent>]
>;

describe('useNavigateByRouterEventHandler hook', () => {
let render: AppContextTestRender['render'];
let history: AppContextTestRender['history'];
let renderResult: ReturnType<AppContextTestRender['render']>;
let linkEle: HTMLAnchorElement;
let clickHandlerSpy: ClickHandlerMock;
const Link = React.memo<{
routeTo: Parameters<typeof useNavigateByRouterEventHandler>[0];
onClick?: Parameters<typeof useNavigateByRouterEventHandler>[1];
}>(({ routeTo, onClick }) => {
const onClickHandler = useNavigateByRouterEventHandler(routeTo, onClick);
return (
<a href="/mock/path" onClick={onClickHandler}>
mock link
</a>
);
});

beforeEach(async () => {
({ render, history } = createAppRootMockRenderer());
clickHandlerSpy = jest.fn();
renderResult = render(<Link routeTo="/mock/path" onClick={clickHandlerSpy} />);
linkEle = (await renderResult.findByText('mock link')) as HTMLAnchorElement;
});
afterEach(cleanup);

it('should navigate to path via Router', () => {
const containerClickSpy = jest.fn();
renderResult.container.addEventListener('click', containerClickSpy);
expect(history.location.pathname).not.toEqual('/mock/path');
act(() => {
fireEvent.click(linkEle);
});
expect(containerClickSpy.mock.calls[0][0].defaultPrevented).toBe(true);
expect(history.location.pathname).toEqual('/mock/path');
renderResult.container.removeEventListener('click', containerClickSpy);
});
it('should support onClick prop', () => {
act(() => {
fireEvent.click(linkEle);
});
expect(clickHandlerSpy).toHaveBeenCalled();
expect(history.location.pathname).toEqual('/mock/path');
});
it('should not navigate if preventDefault is true', () => {
clickHandlerSpy.mockImplementation(event => {
event.preventDefault();
});
act(() => {
fireEvent.click(linkEle);
});
expect(history.location.pathname).not.toEqual('/mock/path');
});
it('should not navigate via router if click was not the primary mouse button', async () => {
act(() => {
fireEvent.click(linkEle, { button: 2 });
});
expect(history.location.pathname).not.toEqual('/mock/path');
});
it('should not navigate via router if anchor has target', () => {
linkEle.setAttribute('target', '_top');
act(() => {
fireEvent.click(linkEle, { button: 2 });
});
expect(history.location.pathname).not.toEqual('/mock/path');
});
it('should not to navigate if meta|alt|ctrl|shift keys are pressed', () => {
['meta', 'alt', 'ctrl', 'shift'].forEach(key => {
act(() => {
fireEvent.click(linkEle, { [`${key}Key`]: true });
});
expect(history.location.pathname).not.toEqual('/mock/path');
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { MouseEventHandler, useCallback } from 'react';
import { useHistory } from 'react-router-dom';
import { LocationDescriptorObject } from 'history';

type EventHandlerCallback = MouseEventHandler<HTMLButtonElement | HTMLAnchorElement>;

/**
* Provides an event handler that can be used with (for example) `onClick` props to prevent the
* event's default behaviour and instead navigate to to a route via the Router
*
* @param routeTo
* @param onClick
*/
export const useNavigateByRouterEventHandler = (
routeTo: string | [string, unknown] | LocationDescriptorObject<unknown>, // Cover the calling signature of `history.push()`

/** Additional onClick callback */
onClick?: EventHandlerCallback
): EventHandlerCallback => {
const history = useHistory();
return useCallback(
ev => {
try {
if (onClick) {
onClick(ev);
}
} catch (error) {
ev.preventDefault();
throw error;
}

if (ev.defaultPrevented) {
return;
}

if (ev.button !== 0) {
return;
}

if (
ev.currentTarget instanceof HTMLAnchorElement &&
ev.currentTarget.target !== '' &&
ev.currentTarget.target !== '_self'
) {
return;
}

if (ev.metaKey || ev.altKey || ev.ctrlKey || ev.shiftKey) {
return;
}

ev.preventDefault();

if (Array.isArray(routeTo)) {
history.push(...routeTo);
} else if (typeof routeTo === 'string') {
history.push(routeTo);
} else {
history.push(routeTo);
}
},
[history, onClick, routeTo]
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@
* you may not use this file except in compliance with the Elastic License.
*/

import React, { memo } from 'react';
import React, { memo, MouseEventHandler } from 'react';
import { EuiFlyoutHeader, CommonProps, EuiButtonEmpty } from '@elastic/eui';
import styled from 'styled-components';

export type FlyoutSubHeaderProps = CommonProps & {
children: React.ReactNode;
backButton?: {
title: string;
onClick: (event: React.MouseEvent) => void;
onClick: MouseEventHandler<HTMLButtonElement | HTMLAnchorElement>;
href?: string;
};
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ import {
import React, { memo, useMemo } from 'react';
import { FormattedMessage } from '@kbn/i18n/react';
import { i18n } from '@kbn/i18n';
import { useHistory } from 'react-router-dom';
import { HostMetadata } from '../../../../../../common/types';
import { FormattedDateAndTime } from '../../formatted_date_time';
import { LinkToApp } from '../../components/link_to_app';
import { useHostListSelector, useHostLogsUrl } from '../hooks';
import { urlFromQueryParams } from '../url_from_query_params';
import { uiQueryParams } from '../../../store/hosts/selectors';
import { useNavigateByRouterEventHandler } from '../../hooks/use_navigate_by_router_event_handler';

const HostIds = styled(EuiListGroupItem)`
margin-top: 0;
Expand All @@ -34,7 +34,6 @@ const HostIds = styled(EuiListGroupItem)`
export const HostDetails = memo(({ details }: { details: HostMetadata }) => {
const { appId, appPath, url } = useHostLogsUrl(details.host.id);
const queryParams = useHostListSelector(uiQueryParams);
const history = useHistory();
const detailsResultsUpper = useMemo(() => {
return [
{
Expand Down Expand Up @@ -65,6 +64,7 @@ export const HostDetails = memo(({ details }: { details: HostMetadata }) => {
show: 'policy_response',
});
}, [details.host.id, queryParams]);
const policyStatusClickHandler = useNavigateByRouterEventHandler(policyResponseUri);

const detailsResultsLower = useMemo(() => {
return [
Expand All @@ -84,10 +84,7 @@ export const HostDetails = memo(({ details }: { details: HostMetadata }) => {
<EuiLink
data-test-subj="policyStatusValue"
href={'?' + policyResponseUri.search}
onClick={(ev: React.MouseEvent) => {
ev.preventDefault();
history.push(policyResponseUri);
}}
onClick={policyStatusClickHandler}
>
<FormattedMessage
id="xpack.endpoint.host.details.policyStatus.success"
Expand Down Expand Up @@ -127,8 +124,8 @@ export const HostDetails = memo(({ details }: { details: HostMetadata }) => {
details.endpoint.policy.id,
details.host.hostname,
details.host.ip,
history,
policyResponseUri,
policyResponseUri.search,
policyStatusClickHandler,
]);

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { HostDetails } from './host_details';
import { PolicyResponse } from './policy_response';
import { HostMetadata } from '../../../../../../common/types';
import { FlyoutSubHeader, FlyoutSubHeaderProps } from './components/flyout_sub_header';
import { useNavigateByRouterEventHandler } from '../../hooks/use_navigate_by_router_event_handler';

export const HostDetailsFlyout = memo(() => {
const history = useHistory();
Expand Down Expand Up @@ -92,24 +93,25 @@ export const HostDetailsFlyout = memo(() => {
const PolicyResponseFlyoutPanel = memo<{
hostMeta: HostMetadata;
}>(({ hostMeta }) => {
const history = useHistory();
const { show, ...queryParams } = useHostListSelector(uiQueryParams);
const detailsUri = useMemo(
() =>
urlFromQueryParams({
...queryParams,
selected_host: hostMeta.host.id,
}),
[hostMeta.host.id, queryParams]
);
const backToDetailsClickHandler = useNavigateByRouterEventHandler(detailsUri);
const backButtonProp = useMemo((): FlyoutSubHeaderProps['backButton'] => {
const detailsUri = urlFromQueryParams({
...queryParams,
selected_host: hostMeta.host.id,
});
return {
title: i18n.translate('xpack.endpoint.host.policyResponse.backLinkTitle', {
defaultMessage: 'Endpoint Details',
}),
href: '?' + detailsUri.search,
onClick: ev => {
ev.preventDefault();
history.push(detailsUri);
},
onClick: backToDetailsClickHandler,
};
}, [history, hostMeta.host.id, queryParams]);
}, [backToDetailsClickHandler, detailsUri.search]);

return (
<>
Expand Down
Loading

0 comments on commit 8c99b0a

Please sign in to comment.