-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
79 lines (64 loc) · 1.56 KB
/
index.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
import moveFocusInside, {focusInside, focusIsHidden} from 'focus-lock';
let lastActiveTrap = 0;
let lastActiveFocus = null;
const focusOnBody = () => (
document && document.activeElement === document.body
);
const isFreeFocus = () => focusOnBody() || focusIsHidden();
const activateTrap = () => {
let result = false;
if (lastActiveTrap) {
const observed = lastActiveTrap;
if(!isFreeFocus()) {
if (observed && !focusInside(observed)) {
result = moveFocusInside(observed, lastActiveFocus);
}
lastActiveFocus = document.activeElement;
}
}
return result;
};
const reducePropsToState = (propsList) => {
return propsList
.filter(node => node)
.slice(-1)[0];
};
const handleStateChangeOnClient = (trap) => {
lastActiveTrap = trap;
if (trap) {
activateTrap();
}
};
let instances = [];
const emitChange = (event) => {
if (handleStateChangeOnClient(reducePropsToState(instances))) {
event && event.preventDefault();
return true;
}
return false;
};
const attachHandler = () => {
document.addEventListener('focusin', emitChange);
};
const detachHandler = () => {
document.removeEventListener('focusin', emitChange);
};
const focusLock = {
on(domNode){
if (instances.length === 0) {
attachHandler();
}
if (instances.indexOf(domNode) < 0) {
instances.push(domNode);
emitChange();
}
},
off(domNode){
instances = instances.filter(node => node !== domNode);
emitChange();
if (instances.length === 0) {
detachHandler();
}
}
};
export default focusLock;