-
Notifications
You must be signed in to change notification settings - Fork 8.3k
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
[Endpoint] Hook to handle events needing navigation via Router #63863
Merged
paul-tavares
merged 12 commits into
elastic:master
from
paul-tavares:task/EMT-230-react-router-click-handler-hook
Apr 21, 2020
Merged
Changes from 11 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
0b144da
new hook providing generic event handler for use with react router
paul-tavares e8e799c
Refactor of Header Naviagtion to use useNavigateByRouterEventHandler
paul-tavares 4643efe
Policy list refactor to use useNavigateByRouterEventHandler hook
paul-tavares bac8e2c
Policy list Policy name link to use useNavigateByRouterEventHandler hook
paul-tavares 87d72af
Host list use of useNavigateByRouteEventHandler
paul-tavares f718e05
Added test plan for new hook
paul-tavares 535b196
Merge remote-tracking branch 'upstream/master' into task/EMT-230-reac…
paul-tavares 42a0af6
Refactor latest Host components to use useNavigateByRouterEventHandle…
paul-tavares a2f5b8d
Fix test cases for policy details
paul-tavares 585b511
Finish tests for router event handler hook
paul-tavares d863ed7
Merge remote-tracking branch 'upstream/master' into task/EMT-230-reac…
paul-tavares 7c2572e
remove unnecessary sleep from test
paul-tavares File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
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.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe you could add a type parameter to this hook like:
TargetElement extends HTMLButtonElement | HTMLAnchorElement
and then define
onClick
like:onClick?: MouseEventHandler<TargetElement>
and then the return type of the hook could beMouseEventHandler<TargetElement>
I think this would allow
onClick
to have button or link specific logic (if needed)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🤔 isn't that the same that I already have defined above in the
EventHandlerCallback
type?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't see the difference here with what @paul-tavares did vs @oatkiller suggestion. Maybe we could reuse
TargetElement
if we defined it outside of the the generic types forMouseEventHandler
. But we could do that later if needed