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

fix(v2): make more accessible skip link #4162

Merged
merged 1 commit into from
Feb 3, 2021
Merged
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
42 changes: 25 additions & 17 deletions packages/docusaurus-theme-classic/src/theme/SkipToContent/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,43 @@
* LICENSE file in the root directory of this source tree.
*/

import React from 'react';
import React, {useRef, useEffect} from 'react';
import {useLocation} from '@docusaurus/router';

import styles from './styles.module.css';

function programmaticFocus(el) {
el.setAttribute('tabindex', '-1');
el.focus();
setTimeout(() => el.removeAttribute('tabindex'), 1000);
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

didn't know this was possible, nice trick
is it safe in all cases to use? (seems to work for Chrome + Safari at least)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think yes, it's safe.


function SkipToContent(): JSX.Element {
const handleSkip = (e: React.KeyboardEvent<HTMLButtonElement>) => {
if (e.keyCode !== 13) {
return;
}
const containerRef = useRef(null);
const location = useLocation();

(document.activeElement as HTMLElement).blur();
const handleSkip = (e: React.MouseEvent<HTMLAnchorElement>) => {
e.preventDefault();

const firstMainElement = document.querySelector('main:first-of-type');
const targetElement =
document.querySelector('main:first-of-type') ||
document.querySelector('.main-wrapper');

if (firstMainElement) {
firstMainElement.scrollIntoView();
if (targetElement) {
programmaticFocus(targetElement);
}
};

useEffect(() => {
programmaticFocus(containerRef.current);
}, [location.pathname]);

return (
<nav aria-label="Skip navigation links">
<button
type="button"
tabIndex={0}
className={styles.skipToContent}
onKeyDown={handleSkip}>
<div ref={containerRef}>
<a href="#main" className={styles.skipToContent} onClick={handleSkip}>
Skip to main content
</button>
</nav>
</a>
</div>
);
}

Expand Down