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.
|
* 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';
|
import styles from './styles.module.css';
|
||||||
|
|
||||||
|
function programmaticFocus(el) {
|
||||||
|
el.setAttribute('tabindex', '-1');
|
||||||
|
el.focus();
|
||||||
|
setTimeout(() => el.removeAttribute('tabindex'), 1000);
|
||||||
|
}
|
||||||
|
|
||||||
function SkipToContent(): JSX.Element {
|
function SkipToContent(): JSX.Element {
|
||||||
const handleSkip = (e: React.KeyboardEvent<HTMLButtonElement>) => {
|
const containerRef = useRef(null);
|
||||||
if (e.keyCode !== 13) {
|
const location = useLocation();
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
(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) {
|
if (targetElement) {
|
||||||
firstMainElement.scrollIntoView();
|
programmaticFocus(targetElement);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
programmaticFocus(containerRef.current);
|
||||||
|
}, [location.pathname]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<nav aria-label="Skip navigation links">
|
<div ref={containerRef}>
|
||||||
<button
|
<a href="#main" className={styles.skipToContent} onClick={handleSkip}>
|
||||||
type="button"
|
|
||||||
tabIndex={0}
|
|
||||||
className={styles.skipToContent}
|
|
||||||
onKeyDown={handleSkip}>
|
|
||||||
Skip to main content
|
Skip to main content
|
||||||
</button>
|
</a>
|
||||||
</nav>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue