-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathfocus-trap-react.js
229 lines (194 loc) · 7.12 KB
/
focus-trap-react.js
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
const React = require('react');
const ReactDOM = require('react-dom');
const PropTypes = require('prop-types');
const { createFocusTrap } = require('focus-trap');
// TODO: These issues are related to older React features which we'll likely need
// to fix in order to move the code forward to the next major version of React.
// @see https://github.com/davidtheclark/focus-trap-react/issues/77
/* eslint-disable react/no-find-dom-node */
class FocusTrap extends React.Component {
constructor(props) {
super(props);
// We need to hijack the returnFocusOnDeactivate option,
// because React can move focus into the element before we arrived at
// this lifecycle hook (e.g. with autoFocus inputs). So the component
// captures the previouslyFocusedElement in componentWillMount,
// then (optionally) returns focus to it in componentWillUnmount.
this.tailoredFocusTrapOptions = {
returnFocusOnDeactivate: false,
};
// because of the above, we maintain our own flag for this option, and
// default it to `true` because that's focus-trap's default
this.returnFocusOnDeactivate = true;
const { focusTrapOptions } = props;
for (const optionName in focusTrapOptions) {
if (!Object.prototype.hasOwnProperty.call(focusTrapOptions, optionName)) {
continue;
}
if (optionName === 'returnFocusOnDeactivate') {
this.returnFocusOnDeactivate = !!focusTrapOptions[optionName];
continue;
}
this.tailoredFocusTrapOptions[optionName] = focusTrapOptions[optionName];
}
// elements from which to create the focus trap on mount; if a child is used
// instead of the `containerElements` prop, we'll get the child's related
// element when the trap renders and then is declared 'mounted'
this.focusTrapElements = props.containerElements || [];
// now we remember what the currently focused element is, not relying on focus-trap
this.updatePreviousElement();
}
/** Update the previously focused element with the currently focused element. */
updatePreviousElement() {
if (typeof document !== 'undefined') {
this.previouslyFocusedElement = document.activeElement;
}
}
/** Returns focus to the element that had focus when the trap was activated. */
returnFocus() {
if (this.previouslyFocusedElement && this.previouslyFocusedElement.focus) {
this.previouslyFocusedElement.focus();
}
}
setupFocusTrap() {
if (!this.focusTrap) {
const focusTrapElementDOMNodes = this.focusTrapElements.map(
// NOTE: `findDOMNode()` does not support CSS selectors; it'll just return
// a new text node with the text wrapped in it instead of treating the
// string as a selector and resolving it to a node in the DOM
ReactDOM.findDOMNode
);
const nodesExist = focusTrapElementDOMNodes.some(Boolean);
if (nodesExist) {
// eslint-disable-next-line react/prop-types -- _createFocusTrap is an internal prop
this.focusTrap = this.props._createFocusTrap(
focusTrapElementDOMNodes,
this.tailoredFocusTrapOptions
);
if (this.props.active) {
this.focusTrap.activate();
}
if (this.props.paused) {
this.focusTrap.pause();
}
}
}
}
componentDidMount() {
this.setupFocusTrap();
}
componentDidUpdate(prevProps) {
if (this.focusTrap) {
if (prevProps.containerElements !== this.props.containerElements) {
this.focusTrap.updateContainerElements(this.props.containerElements);
}
if (prevProps.active && !this.props.active) {
// NOTE: we never let the trap return the focus since we do that ourselves
this.focusTrap.deactivate({ returnFocus: false });
if (this.returnFocusOnDeactivate) {
this.returnFocus();
}
return; // un/pause does nothing on an inactive trap
}
if (!prevProps.active && this.props.active) {
this.updatePreviousElement();
this.focusTrap.activate();
}
if (prevProps.paused && !this.props.paused) {
this.focusTrap.unpause();
} else if (!prevProps.paused && this.props.paused) {
this.focusTrap.pause();
}
} else if (prevProps.containerElements !== this.props.containerElements) {
this.focusTrapElements = this.props.containerElements;
this.setupFocusTrap();
}
}
componentWillUnmount() {
if (this.focusTrap) {
// NOTE: we never let the trap return the focus since we do that ourselves
this.focusTrap.deactivate({ returnFocus: false });
}
if (this.returnFocusOnDeactivate) {
this.returnFocus();
}
}
render() {
const child = this.props.children
? React.Children.only(this.props.children)
: undefined;
if (child) {
if (child.type && child.type === React.Fragment) {
throw new Error(
'A focus-trap cannot use a Fragment as its child container. Try replacing it with a <div> element.'
);
}
const composedRefCallback = (element) => {
const { containerElements } = this.props;
if (child) {
if (typeof child.ref === 'function') {
child.ref(element);
} else if (child.ref) {
child.ref.current = element;
}
}
this.focusTrapElements = containerElements
? containerElements
: [element];
};
const childWithRef = React.cloneElement(child, {
ref: composedRefCallback,
});
return childWithRef;
}
return null;
}
}
// support server-side rendering where `Element` will not be defined
const ElementType = typeof Element === 'undefined' ? Function : Element;
FocusTrap.propTypes = {
active: PropTypes.bool,
paused: PropTypes.bool,
focusTrapOptions: PropTypes.shape({
onActivate: PropTypes.func,
onDeactivate: PropTypes.func,
initialFocus: PropTypes.oneOfType([
PropTypes.instanceOf(ElementType),
PropTypes.string,
PropTypes.func,
]),
fallbackFocus: PropTypes.oneOfType([
PropTypes.instanceOf(ElementType),
PropTypes.string,
PropTypes.func,
]),
escapeDeactivates: PropTypes.bool,
clickOutsideDeactivates: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.func,
]),
returnFocusOnDeactivate: PropTypes.bool,
setReturnFocus: PropTypes.oneOfType([
PropTypes.instanceOf(ElementType),
PropTypes.string,
PropTypes.func,
]),
allowOutsideClick: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
preventScroll: PropTypes.bool,
}),
containerElements: PropTypes.arrayOf(PropTypes.instanceOf(ElementType)),
children: PropTypes.oneOfType([
PropTypes.element, // React element
PropTypes.instanceOf(ElementType), // DOM element
]),
// NOTE: _createFocusTrap is internal, for testing purposes only, so we don't
// specify it here. It's expected to be set to the function returned from
// require('focus-trap'), or one with a compatible interface.
};
FocusTrap.defaultProps = {
active: true,
paused: false,
focusTrapOptions: {},
_createFocusTrap: createFocusTrap,
};
module.exports = FocusTrap;