-
Notifications
You must be signed in to change notification settings - Fork 0
/
hide-recent-subreddits.js
82 lines (70 loc) · 2.82 KB
/
hide-recent-subreddits.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
(function() {
function getElement(elementName) {
let retries = 0;
return new Promise((resolve, _) => {
function findElement() {
const element = document.querySelector(elementName);
if (element) {
resolve(element);
} else if (retries < 5) {
retries = retries + 1;
setTimeout(findElement, 100);
} else {
resolve(null);
}
}
findElement();
})
}
function makeNodeHidden(node) {
node.style.visibility = 'hidden';
node.style.display = 'none';
}
function makeNodeVisible(node) {
node.style.removeProperty('visibility');
node.style.removeProperty('display');
}
async function updateRecentPagesVisibility(redditRecentPages, isVisible) {
redditRecentPages = redditRecentPages ?? await getElement('reddit-recent-pages');
if (!redditRecentPages) {
return;
}
if (isVisible) {
makeNodeVisible(redditRecentPages);
// We also need to hide the <hr /> tag under the
// <reddit-recent-page>, otherwise there'll be
// one extra <hr /> tag.
makeNodeVisible(redditRecentPages.nextElementSibling);
} else {
makeNodeHidden(redditRecentPages);
makeNodeHidden(redditRecentPages.nextElementSibling);
}
}
async function updateVisibility(nodeName, node) {
const storage = await browser.storage.local.get('visibility');
const isVisible = storage.visibility === 'visible';
console.info(`${(new Date()).toLocaleString()}: Change visibility for ${nodeName} to ${storage.visibility}`);
if (nodeName === 'REDDIT-RECENT-PAGES') {
updateRecentPagesVisibility(node, isVisible);
}
}
const observe = (observeWindow, observeNodeName, options) => {
const observer = new MutationObserver(async (mutations) => {
for (const mutation of mutations) {
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
for (const node of mutation.addedNodes) {
if (node.nodeType === Node.ELEMENT_NODE && node.nodeName === observeNodeName) {
updateVisibility(observeNodeName, node);
return;
}
}
}
}
});
observer.observe(observeWindow, Object.assign({ childList: true, subtree: true }, options));
};
observe(document.querySelector('reddit-sidebar-nav'), 'REDDIT-RECENT-PAGES');
browser.storage.onChanged.addListener(async () => {
await updateVisibility('REDDIT-RECENT-PAGES');
});
})();