-
Notifications
You must be signed in to change notification settings - Fork 0
/
disco.js
61 lines (53 loc) · 1.56 KB
/
disco.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
let observer;
let observed = new Set();
let observedSelectors;
/**
* Observe a node, array of nodes or an element selector for dis-connected events.
* @param {...(Node|String)} nodesOrSelectors
*/
export function observe(...nodesOrSelectors) {
if (!observer) {
observer = new MutationObserver(onChanges);
observer.observe(document, { subtree: true, childList: true });
}
nodesOrSelectors.forEach(s => observed.add(s));
}
function onChanges(mutationList) {
observedSelectors = [...observed].filter(s => typeof s === 'string');
mutationList.forEach(({ removedNodes, addedNodes }) => {
dispatchAll('disconnected', removedNodes);
dispatchAll('connected', addedNodes);
});
}
function dispatchAll(type, nodes) {
Array.from(nodes).forEach(node => dispatchTarget(type, node));
}
function dispatchTarget(type, node) {
if (node.nodeType !== 1) return;
// Prevent firing out of the observe scope.
if (observed.has(node) || observedSelectors.some(s => node.matches(s))) {
node.dispatchEvent(new Event(type));
}
node = node.firstChild;
while (node) {
dispatchTarget(type, node);
node = node.nextSibling;
}
}
/**
* Unobserve for dis-connected events.
* Passing no argument will unobserve all previously observed scopes.
*
* @param {...(Node|String)} [nodesOrSelectors]
*/
export function unobserve(...nodesOrSelectors) {
if (nodesOrSelectors.length) {
nodesOrSelectors.forEach(s => observed.delete(s));
} else {
observed.clear();
}
if (observer && !observed.size) {
observer.disconnect();
observer = null;
}
}