-
Notifications
You must be signed in to change notification settings - Fork 126
/
listenFocusOutside.ts
99 lines (83 loc) · 2.52 KB
/
listenFocusOutside.ts
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
import ReactDOM from 'react-dom';
import { isBrowser } from './client';
interface FocusOutsideEventHandler {
elements: HTMLElement[] | (() => HTMLElement[]);
callback: (event: Event) => void;
}
const handlers: FocusOutsideEventHandler[] = [];
function addHandleEvent() {
document.body.addEventListener('focusin', handleNativeFocus, { capture: true });
}
if (isBrowser) {
if (document.readyState === 'complete') {
addHandleEvent();
} else {
window.addEventListener('load', addHandleEvent);
}
}
function handleNativeFocus(event: UIEvent) {
// FIXME: not safe casting
const target: HTMLElement = (event.target || event.srcElement) as HTMLElement;
handlers.forEach(handler => {
let elements = handler.elements;
if (typeof elements === 'function') {
elements = elements();
}
if (elements.some(containsTargetOrRenderContainer(target))) {
return;
}
ReactDOM.unstable_batchedUpdates(() => handler.callback(event));
});
}
export function containsTargetOrRenderContainer(target: Element) {
return (element: Element) => {
if (!element) {
return false;
}
if (element.contains(target)) {
return true;
}
const container = findRenderContainer(target, element);
return !!container && element.contains(container);
};
}
/**
* Searches RenderContainer placed in "rootNode" for "node"
*/
function findRenderContainer(node: Element, rootNode: Element, container?: Element): Element | null {
const currentNode = node.parentNode;
if (
!currentNode ||
node === rootNode ||
currentNode === rootNode ||
currentNode === document.body ||
currentNode === document.documentElement ||
!(currentNode instanceof Element)
) {
return container ? container : null;
}
const newContainerId = currentNode.getAttribute('data-rendered-container-id');
if (newContainerId) {
const nextNode = document.querySelector(`[data-render-container-id~="${newContainerId}"]`);
if (!nextNode) {
throw Error(`Origin node for container with id ${newContainerId} was not found`);
}
return findRenderContainer(nextNode, rootNode, nextNode);
}
return findRenderContainer(currentNode, rootNode, container);
}
export function listen(elements: HTMLElement[] | (() => HTMLElement[]), callback: (event: Event) => void) {
const handler = {
elements,
callback,
};
handlers.push(handler);
return {
remove() {
const index = handlers.indexOf(handler);
if (index > -1) {
handlers.splice(index, 1);
}
},
};
}