mirror of
https://github.com/facebook/docusaurus.git
synced 2025-05-20 12:37:01 +02:00
fix(v2): make more accessible skip link (#4162)
This commit is contained in:
parent
98453ebda0
commit
3f6e04380f
1 changed files with 25 additions and 17 deletions
|
@ -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 SkipToContent(): JSX.Element {
|
||||
const handleSkip = (e: React.KeyboardEvent<HTMLButtonElement>) => {
|
||||
if (e.keyCode !== 13) {
|
||||
return;
|
||||
function programmaticFocus(el) {
|
||||
el.setAttribute('tabindex', '-1');
|
||||
el.focus();
|
||||
setTimeout(() => el.removeAttribute('tabindex'), 1000);
|
||||
}
|
||||
|
||||
(document.activeElement as HTMLElement).blur();
|
||||
function SkipToContent(): JSX.Element {
|
||||
const containerRef = useRef(null);
|
||||
const location = useLocation();
|
||||
|
||||
const firstMainElement = document.querySelector('main:first-of-type');
|
||||
const handleSkip = (e: React.MouseEvent<HTMLAnchorElement>) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (firstMainElement) {
|
||||
firstMainElement.scrollIntoView();
|
||||
const targetElement =
|
||||
document.querySelector('main:first-of-type') ||
|
||||
document.querySelector('.main-wrapper');
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue