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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
import React, { useImperativeHandle, useState } from 'react';
import { useLocation } from 'react-router';
import { sprintf } from 'sprintf-js';
import styled from 'styled-components';
import { messages } from '../../shared/gettext';
const FOCUS_FALLBACK_CLASS = 'focus-fallback';
const PageChangeAnnouncer = styled.div({
width: 0,
height: 0,
overflow: 'hidden',
});
export interface IFocusHandle {
resetFocus(): void;
}
interface IFocusProps {
children?: React.ReactElement;
}
function Focus(props: IFocusProps, ref: React.Ref<IFocusHandle>) {
const location = useLocation();
const [title, setTitle] = useState<string>();
useImperativeHandle(
ref,
() => ({
resetFocus: () => {
const pageName = location.pathname.slice(location.pathname.lastIndexOf('/') + 1);
const titleElement = document.getElementsByTagName('h1')[0];
const titleContent = titleElement?.textContent ?? pageName;
setTitle(titleContent);
const focusElement =
titleElement ?? document.getElementsByClassName(FOCUS_FALLBACK_CLASS)[0];
if (focusElement) {
focusElement.setAttribute('tabindex', '-1');
focusElement.focus();
}
},
}),
[location.pathname],
);
return (
<>
{title && (
<PageChangeAnnouncer aria-live="polite">
{
// TRANSLATORS: This string is used to notify users of screenreaders that the view has
// TRANSLATORS: changed, usually as a result of pressing a navigation button.
// TRANSLATORS: Available placeholders:
// TRANSLATORS: %(title)s - page title
sprintf(messages.pgettext('accessibility', '%(title)s, View loaded'), { title })
}
</PageChangeAnnouncer>
)}
{props.children}
</>
);
}
export default React.memo(React.forwardRef(Focus));
interface IFocusFallbackProps {
children: React.ReactElement;
}
export function FocusFallback(props: IFocusFallbackProps) {
return React.cloneElement(props.children, {
className: `${props.children.props.className} ${FOCUS_FALLBACK_CLASS}`,
});
}
|