forked from riccardo-forina/use-patternfly
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseA11yRoute.ts
49 lines (45 loc) · 1.45 KB
/
useA11yRoute.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import * as React from 'react';
import { useRouteMatch } from 'react-router';
import { LastLocationType, useLastLocation } from 'react-router-last-location';
export function accessibleRouteChangeHandler(id: string, timeout = 50) {
return window.setTimeout(() => {
const mainContainer = document.getElementById(id);
if (mainContainer) {
mainContainer.focus();
}
}, timeout);
}
export const useA11yRouteContainerId = () => {
const { path } = useRouteMatch()!;
return `route-content-${path}`;
};
/**
* a custom hook for sending focus to the primary content container
* after a view has loaded so that subsequent press of tab key
* sends focus directly to relevant content
*/
export const useA11yRouteChange = () => {
const id = useA11yRouteContainerId();
const lastNavigation = useLastLocation();
const previousNavigation = React.useRef<LastLocationType | null>();
React.useEffect(() => {
let routeFocusTimer: number;
let isStale = true;
if (lastNavigation !== null) {
previousNavigation.current = lastNavigation;
isStale = false;
routeFocusTimer = accessibleRouteChangeHandler(id, 50);
}
return () => {
if (routeFocusTimer && isStale) {
clearTimeout(routeFocusTimer);
}
};
}, [id, lastNavigation, previousNavigation]);
};
export const useA11yRouteContainer = () => {
useA11yRouteChange();
const id = useA11yRouteContainerId();
const tabIndex = -1;
return { id, tabIndex };
};