|
5 | 5 | * LICENSE file in the root directory of this source tree. |
6 | 6 | */ |
7 | 7 |
|
8 | | -import React from 'react'; |
| 8 | +import React, {useRef, useEffect} from 'react'; |
| 9 | +import {useLocation} from '@docusaurus/router'; |
9 | 10 |
|
10 | 11 | import styles from './styles.module.css'; |
11 | 12 |
|
| 13 | +function programmaticFocus(el) { |
| 14 | + el.setAttribute('tabindex', '-1'); |
| 15 | + el.focus(); |
| 16 | + setTimeout(() => el.removeAttribute('tabindex'), 1000); |
| 17 | +} |
| 18 | + |
12 | 19 | function SkipToContent(): JSX.Element { |
13 | | - const handleSkip = (e: React.KeyboardEvent<HTMLButtonElement>) => { |
14 | | - if (e.keyCode !== 13) { |
15 | | - return; |
16 | | - } |
| 20 | + const containerRef = useRef(null); |
| 21 | + const location = useLocation(); |
17 | 22 |
|
18 | | - (document.activeElement as HTMLElement).blur(); |
| 23 | + const handleSkip = (e: React.MouseEvent<HTMLLinkElement>) => { |
| 24 | + e.preventDefault(); |
19 | 25 |
|
20 | | - const firstMainElement = document.querySelector('main:first-of-type'); |
| 26 | + const targetElement = |
| 27 | + document.querySelector('main:first-of-type') || |
| 28 | + document.querySelector('.main-wrapper'); |
21 | 29 |
|
22 | | - if (firstMainElement) { |
23 | | - firstMainElement.scrollIntoView(); |
| 30 | + if (targetElement) { |
| 31 | + programmaticFocus(targetElement); |
24 | 32 | } |
25 | 33 | }; |
26 | 34 |
|
| 35 | + useEffect(() => { |
| 36 | + programmaticFocus(containerRef.current); |
| 37 | + }, [location.pathname]); |
| 38 | + |
27 | 39 | return ( |
28 | | - <nav aria-label="Skip navigation links"> |
29 | | - <button |
30 | | - type="button" |
31 | | - tabIndex={0} |
32 | | - className={styles.skipToContent} |
33 | | - onKeyDown={handleSkip}> |
| 40 | + <div ref={containerRef}> |
| 41 | + <a href="#main" className={styles.skipToContent} onClick={handleSkip}> |
34 | 42 | Skip to main content |
35 | | - </button> |
36 | | - </nav> |
| 43 | + </a> |
| 44 | + </div> |
37 | 45 | ); |
38 | 46 | } |
39 | 47 |
|
|
0 commit comments