Skip to content

Commit

Permalink
[EuiSkipLink] Allow consumer onClicks to be called even if no valid…
Browse files Browse the repository at this point in the history
… destination or fallback destination exists (#6355)

* Allow consumers to skip/pass empty strings for both destinationId and fallbackDestination and call their own custom `onClick` scroll/focus logic

* changelog
  • Loading branch information
Constance authored Nov 14, 2022
1 parent cae53d2 commit 2e657f4
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 5 deletions.
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

0 comments on commit 2e657f4

Please sign in to comment.