|
| 1 | +/* |
| 2 | + * Wire |
| 3 | + * Copyright (C) 2025 Wire Swiss GmbH |
| 4 | + * |
| 5 | + * This program is free software: you can redistribute it and/or modify |
| 6 | + * it under the terms of the GNU General Public License as published by |
| 7 | + * the Free Software Foundation, either version 3 of the License, or |
| 8 | + * (at your option) any later version. |
| 9 | + * |
| 10 | + * This program is distributed in the hope that it will be useful, |
| 11 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | + * GNU General Public License for more details. |
| 14 | + * |
| 15 | + * You should have received a copy of the GNU General Public License |
| 16 | + * along with this program. If not, see http://www.gnu.org/licenses/. |
| 17 | + * |
| 18 | + */ |
| 19 | + |
| 20 | +import {useEffect} from 'react'; |
| 21 | + |
| 22 | +import {useLocation} from 'react-router-dom'; |
| 23 | + |
| 24 | +export function useRouteA11y(screenKey?: string) { |
| 25 | + const location = useLocation(); |
| 26 | + |
| 27 | + useEffect(() => { |
| 28 | + const focusTarget: HTMLElement | null = |
| 29 | + document.querySelector<HTMLElement>('[data-page-title]') || |
| 30 | + document.querySelector<HTMLElement>('main,[role="main"]') || |
| 31 | + document.querySelector<HTMLElement>('h1'); |
| 32 | + |
| 33 | + if (!focusTarget) { |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + // scroll to top on each route change |
| 38 | + window.scrollTo({top: 0, left: 0}); |
| 39 | + |
| 40 | + const element = focusTarget; |
| 41 | + element.setAttribute('tabindex', '-1'); |
| 42 | + element.classList.add('sr-only-focus'); |
| 43 | + element.focus({preventScroll: true}); |
| 44 | + |
| 45 | + // remove tabindex after blur |
| 46 | + const handleBlur = () => { |
| 47 | + element.classList.remove('sr-only-focus'); |
| 48 | + element.removeAttribute('tabindex'); |
| 49 | + element.removeEventListener('blur', handleBlur); |
| 50 | + }; |
| 51 | + element.addEventListener('blur', handleBlur); |
| 52 | + }, [location.key, screenKey]); |
| 53 | +} |
0 commit comments