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

[EuiSkipLink] Allow consumer onClicks to be called even if no valid destination or fallback destination exists #6355

Merged
merged 2 commits into from
Nov 14, 2022
Merged
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
22 changes: 22 additions & 0 deletions src/components/accessibility/skip_link/skip_link.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,28 @@ describe('EuiSkipLink', () => {
expect(onClick).toHaveBeenCalled();
});

test('is called even when no valid destination exists', () => {
const onClick = jest.fn(() =>
document.querySelector('button')!.focus()
);
const { getByText } = render(
<>
<EuiSkipLink
destinationId=""
fallbackDestination=""
onClick={onClick}
>
Test
</EuiSkipLink>
<button />
</>
);
fireEvent.click(getByText('Test'));

expect(onClick).toHaveBeenCalled();
expect(document.activeElement?.tagName.toLowerCase()).toEqual('button');
});

test('does not override overrideLinkBehavior', () => {
const onClick = jest.fn();
const { getByText } = render(
Expand Down
13 changes: 8 additions & 5 deletions src/components/accessibility/skip_link/skip_link.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,16 +94,19 @@ export const EuiSkipLink: FunctionComponent<EuiSkipLinkProps> = ({
setHasValidId(false);

// If no valid element via ID is available, use the fallback query selectors
const fallbackEl = document.querySelector<HTMLElement>(fallbackDestination);
if (fallbackEl) {
setDestinationEl(fallbackEl);
if (fallbackDestination) {
const fallbackEl = document.querySelector<HTMLElement>(
fallbackDestination
);
if (fallbackEl) {
setDestinationEl(fallbackEl);
}
}
}, [destinationId, fallbackDestination]);

const onClick = useCallback(
(e: React.MouseEvent<HTMLAnchorElement>) => {
if (overrideLinkBehavior || !hasValidId) {
if (!destinationEl) return;
if ((overrideLinkBehavior || !hasValidId) && destinationEl) {
e.preventDefault();

// Scroll to the top of the destination content only if it's ~mostly out of view
Expand Down
3 changes: 3 additions & 0 deletions upcoming_changelogs/6355.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
**Bug fixes**

- `EuiSkipLink` now correctly calls `onClick` even when `fallbackDestination` is invalid