-
Notifications
You must be signed in to change notification settings - Fork 67
/
Trap.js
317 lines (276 loc) Β· 8.82 KB
/
Trap.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
/* eslint-disable no-mixed-operators */
import * as React from 'react';
import PropTypes from 'prop-types';
import withSideEffect from 'react-clientside-effect';
import {
moveFocusInside, focusInside,
focusIsHidden,
expandFocusableNodes,
getFocusableNodes,
focusNextElement,
focusPrevElement,
focusFirstElement,
focusLastElement,
captureFocusRestore,
} from 'focus-lock';
import { deferAction, extractRef } from './util';
import { mediumFocus, mediumBlur, mediumEffect } from './medium';
const focusOnBody = () => (
document && document.activeElement === document.body
);
const isFreeFocus = () => focusOnBody() || focusIsHidden();
let lastActiveTrap = null;
let lastActiveFocus = null;
let tryRestoreFocus = () => null;
let lastPortaledElement = null;
let focusWasOutsideWindow = false;
let windowFocused = false;
const defaultWhitelist = () => true;
const focusWhitelisted = activeElement => (
(lastActiveTrap.whiteList || defaultWhitelist)(activeElement)
);
const recordPortal = (observerNode, portaledElement) => {
lastPortaledElement = { observerNode, portaledElement };
};
const focusIsPortaledPair = element => (
lastPortaledElement && lastPortaledElement.portaledElement === element
);
function autoGuard(startIndex, end, step, allNodes) {
let lastGuard = null;
let i = startIndex;
do {
const item = allNodes[i];
if (item.guard) {
if (item.node.dataset.focusAutoGuard) {
lastGuard = item;
}
} else if (item.lockItem) {
if (i !== startIndex) {
// we will tab to the next element
return;
}
lastGuard = null;
} else {
break;
}
} while ((i += step) !== end);
if (lastGuard) {
lastGuard.node.tabIndex = 0;
}
}
const focusWasOutside = (crossFrameOption) => {
if (crossFrameOption) {
// with cross frame return true for any value
return Boolean(focusWasOutsideWindow);
}
// in other case return only of focus went a while aho
return focusWasOutsideWindow === 'meanwhile';
};
const checkInHost = (check, el, boundary) => (
el && (
// find host equal to active element and check nested active element
(el.host === check && (!el.activeElement || boundary.contains(el.activeElement))
// dive up
|| (el.parentNode && checkInHost(check, el.parentNode, boundary))))
);
const withinHost = (activeElement, workingArea) => (
workingArea.some(area => checkInHost(activeElement, area, area))
);
const getNodeFocusables = nodes => getFocusableNodes(nodes, new Map());
const isNotFocusable = node => (
!getNodeFocusables([node.parentNode]).some(el => el.node === node)
);
const activateTrap = () => {
let result = false;
if (lastActiveTrap) {
const {
observed, persistentFocus, autoFocus, shards, crossFrame, focusOptions, noFocusGuards,
} = lastActiveTrap;
const workingNode = observed || (lastPortaledElement && lastPortaledElement.portaledElement);
// check if lastActiveFocus is still reachable
if (focusOnBody() && lastActiveFocus) {
if (
// it was removed
!document.body.contains(lastActiveFocus)
// or not focusable (this is expensive operation)!
|| isNotFocusable(lastActiveFocus)
) {
lastActiveFocus = null;
const newTarget = tryRestoreFocus();
if (newTarget) {
newTarget.focus();
}
}
}
const activeElement = document && document.activeElement;
if (workingNode) {
const workingArea = [
workingNode,
...shards.map(extractRef).filter(Boolean),
];
const shouldForceRestoreFocus = () => {
// force restoration happens when
// - focus is not inside now
// - focusWasOutside
// - there are go guards
// - the last active element was the first or the last focusable one
if (!focusWasOutside(crossFrame) || !noFocusGuards || !lastActiveFocus || windowFocused) {
return false;
}
const nodes = getNodeFocusables(workingArea);
const lastIndex = nodes.findIndex(({ node }) => node === lastActiveFocus);
return lastIndex === 0 || lastIndex === nodes.length - 1;
};
if (!activeElement || focusWhitelisted(activeElement)) {
if (
(persistentFocus || shouldForceRestoreFocus())
|| !isFreeFocus()
|| (!lastActiveFocus && autoFocus)
) {
if (
workingNode
&& !(
// active element is "inside" working area
(focusInside(workingArea) || (
// check for shadow-dom contained elements
activeElement && withinHost(activeElement, workingArea))
)
|| focusIsPortaledPair(activeElement, workingNode)
)
) {
if (document && !lastActiveFocus && activeElement && !autoFocus) {
// Check if blur() exists, which is missing on certain elements on IE
if (activeElement.blur) {
activeElement.blur();
}
document.body.focus();
} else {
result = moveFocusInside(workingArea, lastActiveFocus, { focusOptions });
lastPortaledElement = {};
}
}
focusWasOutsideWindow = false;
lastActiveFocus = document && document.activeElement;
tryRestoreFocus = captureFocusRestore(lastActiveFocus);
}
}
if (document
// element was changed by moveFocusInside
&& activeElement !== document.activeElement
// fast check for any auto-guard
&& document.querySelector('[data-focus-auto-guard]')) {
const newActiveElement = document && document.activeElement;
const allNodes = expandFocusableNodes(workingArea);
const focusedIndex = allNodes.map(({ node }) => node).indexOf(newActiveElement);
if (focusedIndex > -1) {
// remove old focus
allNodes
.filter(({ guard, node }) => guard && node.dataset.focusAutoGuard)
.forEach(({ node }) => node.removeAttribute('tabIndex'));
autoGuard(focusedIndex, allNodes.length, +1, allNodes);
autoGuard(focusedIndex, -1, -1, allNodes);
}
}
}
}
return result;
};
const onTrap = (event) => {
if (activateTrap() && event) {
// prevent scroll jump
event.stopPropagation();
event.preventDefault();
}
};
const onBlur = () => (
deferAction(activateTrap)
);
const onFocus = (event) => {
// detect portal
const source = event.target;
const currentNode = event.currentTarget;
if (!currentNode.contains(source)) {
recordPortal(currentNode, source);
}
};
const FocusWatcher = () => null;
const FocusTrap = ({ children }) => (
<div onBlur={onBlur} onFocus={onFocus}>
{children}
</div>
);
FocusTrap.propTypes = {
children: PropTypes.node.isRequired,
};
const onWindowFocus = () => {
windowFocused = true;
};
const onWindowBlur = () => {
windowFocused = false;
focusWasOutsideWindow = 'just';
// using setTimeout to set this variable after React/sidecar reaction
deferAction(() => {
focusWasOutsideWindow = 'meanwhile';
});
};
const attachHandler = () => {
document.addEventListener('focusin', onTrap);
document.addEventListener('focusout', onBlur);
window.addEventListener('focus', onWindowFocus);
window.addEventListener('blur', onWindowBlur);
};
const detachHandler = () => {
document.removeEventListener('focusin', onTrap);
document.removeEventListener('focusout', onBlur);
window.removeEventListener('focus', onWindowFocus);
window.removeEventListener('blur', onWindowBlur);
};
function reducePropsToState(propsList) {
return propsList
.filter(({ disabled }) => !disabled);
}
const focusLockAPI = {
moveFocusInside,
focusInside,
focusNextElement,
focusPrevElement,
focusFirstElement,
focusLastElement,
captureFocusRestore,
};
function handleStateChangeOnClient(traps) {
const trap = traps.slice(-1)[0];
if (trap && !lastActiveTrap) {
attachHandler();
}
const lastTrap = lastActiveTrap;
const sameTrap = lastTrap && trap && trap.id === lastTrap.id;
lastActiveTrap = trap;
if (lastTrap && !sameTrap) {
lastTrap.onDeactivation();
// return focus only of last trap was removed
if (!traps.filter(({ id }) => id === lastTrap.id).length) {
// allow defer is no other trap is awaiting restore
lastTrap.returnFocus(!trap);
}
}
if (trap) {
lastActiveFocus = null;
if (!sameTrap || lastTrap.observed !== trap.observed) {
trap.onActivation(focusLockAPI);
}
activateTrap(true);
deferAction(activateTrap);
} else {
detachHandler();
lastActiveFocus = null;
}
}
// bind medium
mediumFocus.assignSyncMedium(onFocus);
mediumBlur.assignMedium(onBlur);
mediumEffect.assignMedium(cb => cb(focusLockAPI));
export default withSideEffect(
reducePropsToState,
handleStateChangeOnClient,
)(FocusWatcher);