forked from reservedwords/NewsHacker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
popup.js
59 lines (50 loc) · 1.5 KB
/
popup.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
function makeLink(hit) {
const listItem = document.createElement('li');
const hyperlink = document.createElement('a');
hyperlink.setAttribute('href', `https://news.ycombinator.com/item?id=${hit.objectID}`);
hyperlink.setAttribute('target', '_blank');
hyperlink.setAttribute('rel', 'noopener noreferrer');
hyperlink.textContent = hit.title;
listItem.appendChild(hyperlink);
return listItem;
}
function show(id) {
document.getElementById(id).classList.remove('hide');
}
function hide(id) {
document.getElementById(id).classList.add('hide');
}
function showThreads(threads) {
if(threads.length == 0) {
show('no-match');
return;
}
const threadLinks = threads
.filter(thread => thread.num_comments > 0)
.map(makeLink);
threadLinks.forEach(link => {
document.getElementById('hits').appendChild(link);
});
}
function showError(error) {
const errorMessage = 'An unknown error occurred';
if(error) {
errorMessage = `Error: ${error}`
}
show('error');
document.getElementById('error').textContent = errorMessage;
}
function connect() {
show('loading');
const port = chrome.extension.connect({name: 'MainChannel'});
port.onMessage.addListener(function(msg) {
hide('loading');
if(msg.success) {
showThreads(msg.threads);
return;
}
showError(msg.error);
return;
});
}
document.addEventListener('DOMContentLoaded', connect);