-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathextension.js
More file actions
80 lines (69 loc) · 2.22 KB
/
extension.js
File metadata and controls
80 lines (69 loc) · 2.22 KB
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
const getFsViewName = (entry) => {
return entry.target.attributes.getNamedItem('data-fs-view').value;
};
const getFsThreshold = (entry) => {
const item = entry.target.attributes.getNamedItem('data-fs-view-threshold');
// TODO: validate item.value before parsing
return item ? parseInt(item.value) : undefined;
}
const fireEvent = (entry, count) => {
// TODO: validate that name exists
// if not, console.warn about it and return
FS.event(`Viewed ${getFsViewName(entry)}`, {
numberOfViews: count,
});
console.log(`sent event ${getFsViewName(entry)} at ${(new Date()).getTime()} with count ${count}`);
};
const makeIntersectedCallback = () => {
let count = 0;
let inView = false;
let timeoutHandle;
return entries => {
for (const entry of entries) {
inView = entry.isIntersecting;
if (inView) {
console.log('intersecting');
const delay = getFsThreshold(entry) || 500;
timeoutHandle = window.setTimeout(() => {
if (inView) { // this test might not be needed since the timeout is being cleared
count++;
fireEvent(entry, count);
}
}, delay);
} else {
window.clearTimeout(timeoutHandle);
}
}
};
}
const attachObserver = (target) => {
if (IntersectionObserver) {
const observer = new IntersectionObserver(makeIntersectedCallback(), {
threshold: [ 0.8 ]
});
observer.observe(target);
} else {
console.warn('The IntersectionObserver API is not supported by this browser');
}
}
const observeFsView = (root) => {
if (root.getAttribute('data-fs-view')) {
attachObserver(root);
}
const targets = root.querySelectorAll('[data-fs-view]');
targets.forEach((target) => {
attachObserver(target);
});
};
const initExtension = () => {
const body = document.getElementsByTagName('body')[0];
observeFsView(body);
const observer = new MutationObserver((mutationsList) => {
for (const mutation of mutationsList) {
for (const addedNode of mutation.addedNodes) {
observeFsView(addedNode);
}
}
});
observer.observe(body, { childList: true, subtree: true });
}