|
| 1 | +import { type MouseEvent, useState } from 'react' |
| 2 | +import { useTranslation } from 'react-i18next' |
| 3 | + |
| 4 | +export const MAIN_CONTENT_ID = 'main-content' |
| 5 | + |
| 6 | +const hiddenStyle: React.CSSProperties = { |
| 7 | + position: 'absolute', |
| 8 | + width: 1, |
| 9 | + height: 1, |
| 10 | + margin: -1, |
| 11 | + padding: 0, |
| 12 | + overflow: 'hidden', |
| 13 | + clip: 'rect(0, 0, 0, 0)', |
| 14 | + whiteSpace: 'nowrap', |
| 15 | + border: 0, |
| 16 | +} |
| 17 | + |
| 18 | +const visibleStyle: React.CSSProperties = { |
| 19 | + position: 'fixed', |
| 20 | + top: '0.5rem', |
| 21 | + left: '50%', |
| 22 | + transform: 'translateX(-50%)', |
| 23 | + width: 'auto', |
| 24 | + height: 'auto', |
| 25 | + margin: 0, |
| 26 | + padding: '0.625rem 1rem', |
| 27 | + overflow: 'visible', |
| 28 | + clip: 'auto', |
| 29 | + whiteSpace: 'normal', |
| 30 | + zIndex: 9999, |
| 31 | + backgroundColor: 'white', |
| 32 | + color: 'var(--colors-primary-800)', |
| 33 | + fontWeight: 500, |
| 34 | + fontSize: '0.875rem', |
| 35 | + textDecoration: 'none', |
| 36 | + border: '1px solid var(--colors-primary-800)', |
| 37 | + borderRadius: 4, |
| 38 | + outline: '2px solid var(--colors-focus-ring)', |
| 39 | + outlineOffset: 2, |
| 40 | +} |
| 41 | + |
| 42 | +export const SkipLink = () => { |
| 43 | + const { t } = useTranslation() |
| 44 | + const [isFocused, setIsFocused] = useState(false) |
| 45 | + |
| 46 | + const handleClick = (e: MouseEvent<HTMLAnchorElement>) => { |
| 47 | + e.preventDefault() |
| 48 | + const main = document.getElementById(MAIN_CONTENT_ID) |
| 49 | + if (!main) return |
| 50 | + |
| 51 | + const heading = main.querySelector('h1, h2, h3') as HTMLElement | null |
| 52 | + const target = heading ?? main |
| 53 | + |
| 54 | + if (!target.hasAttribute('tabindex')) { |
| 55 | + target.setAttribute('tabindex', '-1') |
| 56 | + } |
| 57 | + target.focus() |
| 58 | + } |
| 59 | + |
| 60 | + return ( |
| 61 | + <a |
| 62 | + href={`#${MAIN_CONTENT_ID}`} |
| 63 | + style={isFocused ? visibleStyle : hiddenStyle} |
| 64 | + onFocus={() => setIsFocused(true)} |
| 65 | + onBlur={() => setIsFocused(false)} |
| 66 | + onClick={handleClick} |
| 67 | + > |
| 68 | + {t('skipLink')} |
| 69 | + </a> |
| 70 | + ) |
| 71 | +} |
0 commit comments