-
Notifications
You must be signed in to change notification settings - Fork 8.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Endpoint] Hook to handle events needing navigation via Router (#63863)
* 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
1 parent
5501fb4
commit ed91275
Showing
11 changed files
with
244 additions
and
84 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
90 changes: 90 additions & 0 deletions
90
...int/public/applications/endpoint/view/hooks/use_navigate_by_router_event_handler.test.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | ||
}); | ||
}); | ||
}); |
70 changes: 70 additions & 0 deletions
70
.../endpoint/public/applications/endpoint/view/hooks/use_navigate_by_router_event_handler.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | ||
); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.