-
-
Notifications
You must be signed in to change notification settings - Fork 32.4k
/
FocusTrap.js
404 lines (352 loc) · 12 KB
/
FocusTrap.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
/* eslint-disable consistent-return, jsx-a11y/no-noninteractive-tabindex */
import * as React from 'react';
import PropTypes from 'prop-types';
import {
exactProp,
elementAcceptingRef,
unstable_useForkRef as useForkRef,
unstable_ownerDocument as ownerDocument,
} from '@mui/utils';
// Inspired by https://github.com/focus-trap/tabbable
const candidatesSelector = [
'input',
'select',
'textarea',
'a[href]',
'button',
'[tabindex]',
'audio[controls]',
'video[controls]',
'[contenteditable]:not([contenteditable="false"])',
].join(',');
function getTabIndex(node) {
const tabindexAttr = parseInt(node.getAttribute('tabindex'), 10);
if (!Number.isNaN(tabindexAttr)) {
return tabindexAttr;
}
// Browsers do not return `tabIndex` correctly for contentEditable nodes;
// https://bugs.chromium.org/p/chromium/issues/detail?id=661108&q=contenteditable%20tabindex&can=2
// so if they don't have a tabindex attribute specifically set, assume it's 0.
// in Chrome, <details/>, <audio controls/> and <video controls/> elements get a default
// `tabIndex` of -1 when the 'tabindex' attribute isn't specified in the DOM,
// yet they are still part of the regular tab order; in FF, they get a default
// `tabIndex` of 0; since Chrome still puts those elements in the regular tab
// order, consider their tab index to be 0.
if (
node.contentEditable === 'true' ||
((node.nodeName === 'AUDIO' || node.nodeName === 'VIDEO' || node.nodeName === 'DETAILS') &&
node.getAttribute('tabindex') === null)
) {
return 0;
}
return node.tabIndex;
}
function isNonTabbableRadio(node) {
if (node.tagName !== 'INPUT' || node.type !== 'radio') {
return false;
}
if (!node.name) {
return false;
}
const getRadio = (selector) => node.ownerDocument.querySelector(`input[type="radio"]${selector}`);
let roving = getRadio(`[name="${node.name}"]:checked`);
if (!roving) {
roving = getRadio(`[name="${node.name}"]`);
}
return roving !== node;
}
function isNodeMatchingSelectorFocusable(node) {
if (
node.disabled ||
(node.tagName === 'INPUT' && node.type === 'hidden') ||
isNonTabbableRadio(node)
) {
return false;
}
return true;
}
function defaultGetTabbable(root) {
const regularTabNodes = [];
const orderedTabNodes = [];
Array.from(root.querySelectorAll(candidatesSelector)).forEach((node, i) => {
const nodeTabIndex = getTabIndex(node);
if (nodeTabIndex === -1 || !isNodeMatchingSelectorFocusable(node)) {
return;
}
if (nodeTabIndex === 0) {
regularTabNodes.push(node);
} else {
orderedTabNodes.push({
documentOrder: i,
tabIndex: nodeTabIndex,
node,
});
}
});
return orderedTabNodes
.sort((a, b) =>
a.tabIndex === b.tabIndex ? a.documentOrder - b.documentOrder : a.tabIndex - b.tabIndex,
)
.map((a) => a.node)
.concat(regularTabNodes);
}
function defaultIsEnabled() {
return true;
}
/**
* Utility component that locks focus inside the component.
*/
function FocusTrap(props) {
const {
children,
disableAutoFocus = false,
disableEnforceFocus = false,
disableRestoreFocus = false,
getTabbable = defaultGetTabbable,
isEnabled = defaultIsEnabled,
open,
} = props;
const ignoreNextEnforceFocus = React.useRef();
const sentinelStart = React.useRef(null);
const sentinelEnd = React.useRef(null);
const nodeToRestore = React.useRef(null);
const reactFocusEventTarget = React.useRef(null);
// This variable is useful when disableAutoFocus is true.
// It waits for the active element to move into the component to activate.
const activated = React.useRef(false);
const rootRef = React.useRef(null);
const handleRef = useForkRef(children.ref, rootRef);
const lastKeydown = React.useRef(null);
React.useEffect(() => {
// We might render an empty child.
if (!open || !rootRef.current) {
return;
}
activated.current = !disableAutoFocus;
}, [disableAutoFocus, open]);
React.useEffect(() => {
// We might render an empty child.
if (!open || !rootRef.current) {
return;
}
const doc = ownerDocument(rootRef.current);
if (!rootRef.current.contains(doc.activeElement)) {
if (!rootRef.current.hasAttribute('tabIndex')) {
if (process.env.NODE_ENV !== 'production') {
console.error(
[
'MUI: The modal content node does not accept focus.',
'For the benefit of assistive technologies, ' +
'the tabIndex of the node is being set to "-1".',
].join('\n'),
);
}
rootRef.current.setAttribute('tabIndex', -1);
}
if (activated.current) {
rootRef.current.focus();
}
}
return () => {
// restoreLastFocus()
if (!disableRestoreFocus) {
// In IE11 it is possible for document.activeElement to be null resulting
// in nodeToRestore.current being null.
// Not all elements in IE11 have a focus method.
// Once IE11 support is dropped the focus() call can be unconditional.
if (nodeToRestore.current && nodeToRestore.current.focus) {
ignoreNextEnforceFocus.current = true;
nodeToRestore.current.focus();
}
nodeToRestore.current = null;
}
};
// Missing `disableRestoreFocus` which is fine.
// We don't support changing that prop on an open FocusTrap
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
React.useEffect(() => {
// We might render an empty child.
if (!open || !rootRef.current) {
return;
}
const doc = ownerDocument(rootRef.current);
const contain = (nativeEvent) => {
const { current: rootElement } = rootRef;
// Cleanup functions are executed lazily in React 17.
// Contain can be called between the component being unmounted and its cleanup function being run.
if (rootElement === null) {
return;
}
if (
!doc.hasFocus() ||
disableEnforceFocus ||
!isEnabled() ||
ignoreNextEnforceFocus.current
) {
ignoreNextEnforceFocus.current = false;
return;
}
if (!rootElement.contains(doc.activeElement)) {
// if the focus event is not coming from inside the children's react tree, reset the refs
if (
(nativeEvent && reactFocusEventTarget.current !== nativeEvent.target) ||
doc.activeElement !== reactFocusEventTarget.current
) {
reactFocusEventTarget.current = null;
} else if (reactFocusEventTarget.current !== null) {
return;
}
if (!activated.current) {
return;
}
let tabbable = [];
if (
doc.activeElement === sentinelStart.current ||
doc.activeElement === sentinelEnd.current
) {
tabbable = getTabbable(rootRef.current);
}
if (tabbable.length > 0) {
const isShiftTab = Boolean(
lastKeydown.current?.shiftKey && lastKeydown.current?.key === 'Tab',
);
const focusNext = tabbable[0];
const focusPrevious = tabbable[tabbable.length - 1];
if (isShiftTab) {
focusPrevious.focus();
} else {
focusNext.focus();
}
} else {
rootElement.focus();
}
}
};
const loopFocus = (nativeEvent) => {
lastKeydown.current = nativeEvent;
if (disableEnforceFocus || !isEnabled() || nativeEvent.key !== 'Tab') {
return;
}
// Make sure the next tab starts from the right place.
// doc.activeElement referes to the origin.
if (doc.activeElement === rootRef.current && nativeEvent.shiftKey) {
// We need to ignore the next contain as
// it will try to move the focus back to the rootRef element.
ignoreNextEnforceFocus.current = true;
sentinelEnd.current.focus();
}
};
doc.addEventListener('focusin', contain);
doc.addEventListener('keydown', loopFocus, true);
// With Edge, Safari and Firefox, no focus related events are fired when the focused area stops being a focused area.
// e.g. https://bugzilla.mozilla.org/show_bug.cgi?id=559561.
// Instead, we can look if the active element was restored on the BODY element.
//
// The whatwg spec defines how the browser should behave but does not explicitly mention any events:
// https://html.spec.whatwg.org/multipage/interaction.html#focus-fixup-rule.
const interval = setInterval(() => {
if (doc.activeElement.tagName === 'BODY') {
contain();
}
}, 50);
return () => {
clearInterval(interval);
doc.removeEventListener('focusin', contain);
doc.removeEventListener('keydown', loopFocus, true);
};
}, [disableAutoFocus, disableEnforceFocus, disableRestoreFocus, isEnabled, open, getTabbable]);
const onFocus = (event) => {
if (nodeToRestore.current === null) {
nodeToRestore.current = event.relatedTarget;
}
activated.current = true;
reactFocusEventTarget.current = event.target;
const childrenPropsHandler = children.props.onFocus;
if (childrenPropsHandler) {
childrenPropsHandler(event);
}
};
const handleFocusSentinel = (event) => {
if (nodeToRestore.current === null) {
nodeToRestore.current = event.relatedTarget;
}
activated.current = true;
};
return (
<React.Fragment>
<div
tabIndex={open ? 0 : -1}
onFocus={handleFocusSentinel}
ref={sentinelStart}
data-testid="sentinelStart"
/>
{React.cloneElement(children, { ref: handleRef, onFocus })}
<div
tabIndex={open ? 0 : -1}
onFocus={handleFocusSentinel}
ref={sentinelEnd}
data-testid="sentinelEnd"
/>
</React.Fragment>
);
}
FocusTrap.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* A single child content element.
*/
children: elementAcceptingRef,
/**
* If `true`, the focus trap will not automatically shift focus to itself when it opens, and
* replace it to the last focused element when it closes.
* This also works correctly with any focus trap children that have the `disableAutoFocus` prop.
*
* Generally this should never be set to `true` as it makes the focus trap less
* accessible to assistive technologies, like screen readers.
* @default false
*/
disableAutoFocus: PropTypes.bool,
/**
* If `true`, the focus trap will not prevent focus from leaving the focus trap while open.
*
* Generally this should never be set to `true` as it makes the focus trap less
* accessible to assistive technologies, like screen readers.
* @default false
*/
disableEnforceFocus: PropTypes.bool,
/**
* If `true`, the focus trap will not restore focus to previously focused element once
* focus trap is hidden or unmounted.
* @default false
*/
disableRestoreFocus: PropTypes.bool,
/**
* Returns an array of ordered tabbable nodes (i.e. in tab order) within the root.
* For instance, you can provide the "tabbable" npm dependency.
* @param {HTMLElement} root
*/
getTabbable: PropTypes.func,
/**
* This prop extends the `open` prop.
* It allows to toggle the open state without having to wait for a rerender when changing the `open` prop.
* This prop should be memoized.
* It can be used to support multiple focus trap mounted at the same time.
* @default function defaultIsEnabled() {
* return true;
* }
*/
isEnabled: PropTypes.func,
/**
* If `true`, focus is locked.
*/
open: PropTypes.bool.isRequired,
};
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line
FocusTrap['propTypes' + ''] = exactProp(FocusTrap.propTypes);
}
export default FocusTrap;