forked from zserge/headline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
273 lines (248 loc) · 8.57 KB
/
app.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
const DEFAULT_CORS_PROXY = url => `https://api.allorigins.win/raw?url=${encodeURIComponent(url)}`;
const DEFAULT_FEEDS = [
'https://ubports.com/blog/ubports-blog-1/feed',
'https://edwardsnowden.substack.com/feed',
];
const MAX_NEWS_PER_FEED = 1000;
const MAX_NEWS_ON_PAGE = 300;
const loading = document.querySelector('#loading');
const menu = document.querySelector('#menu');
const title = document.querySelector('#title');
const settings = document.querySelector('#settings');
const keywords = document.querySelector('#settings textarea');
const news = document.querySelector('#news');
const newsFeeds = document.querySelector('#feeds');
const feedItem = document.querySelector('#settings-feed-item');
const newsItem = document.querySelector('#news-item');
// State = {lastSeen: Date, feeds: Array<Feed>}
// Feed = {url: String, Entries: Array<Entry>}
// Entry = {title: String, link: String, timestamp: Date}
const state = (() => {
try {
// Restore from local storage
let state = JSON.parse(localStorage.getItem('state-v1'));
// Parse timestamps from JSON
state.feeds.forEach(feed => {
feed.entries.forEach(e => {
e.timestamp = new Date(e.timestamp);
});
});
return state;
} catch (e) {
// Try importing settings from the URL
try {
const settings = JSON.parse(atob(window.location.hash.substring(1)));
return {
feeds: settings.feeds.map(url => ({url, entries: []})),
keywords: settings.keywords,
};
} catch (e) {
// If anything goes wrong - use default values
return {
feeds: DEFAULT_FEEDS.map(url => ({url, entries: []})),
keywords: '',
};
}
}
})();
function save() {
localStorage.setItem('state-v1', JSON.stringify(state));
const settings = {
feeds: state.feeds.map(f => f.url),
keywords: state.keywords,
};
window.location.hash = btoa(JSON.stringify(settings));
}
let urlFilter = '';
// parseFeed converts RSS or Atom text into a list of feed entries
function parseFeed(text) {
const xml = new DOMParser().parseFromString(text, 'text/xml');
const map = (c, f) => Array.prototype.slice.call(c, 0).map(f);
const tag = (item, name) =>
(item.getElementsByTagName(name)[0] || {}).textContent;
switch (xml.documentElement.nodeName) {
case 'rss':
return map(xml.documentElement.getElementsByTagName('item'), item => ({
link: tag(item, 'link'),
title: tag(item, 'title'),
timestamp: new Date(tag(item, 'pubDate')),
}));
case 'feed':
return map(xml.documentElement.getElementsByTagName('entry'), item => ({
link: map(item.getElementsByTagName('link'), link => {
const rel = link.getAttribute('rel');
if (!rel || rel === 'alternate') {
return link.getAttribute('href');
}
})[0],
title: tag(item, 'title'),
timestamp: new Date(tag(item, 'updated')),
}));
}
return [];
}
const simplifyLink = link => link.replace(/^.*:\/\/(www\.)?/, '');
function renderSettings() {
keywords.value = state.keywords;
newsFeeds.innerHTML = '';
state.feeds.forEach(f => {
const el = document.importNode(feedItem.content, true).querySelector('li');
el.querySelector('span').innerText = simplifyLink(f.url);
el.querySelector('a').onclick = () => {
urlFilter = f.url;
menu.classList.remove('close');
menu.classList.add('back');
settings.classList.remove('shown');
title.innerText = simplifyLink(f.url);
render(urlFilter);
};
el.querySelectorAll('a')[1].onclick = () => {
if (confirm(`Remove ${f.url}?`)) {
state.feeds = state.feeds.filter(x => x.url !== f.url);
save();
// remove feed from list
renderSettings();
// remove entries from deleted feed
render(urlFilter = '');
}
};
newsFeeds.appendChild(el);
});
}
function render(urlFilter = '') {
const marks = state.keywords.split(',').map(k => k.trim()).filter(k => k.length).map(k => {
let mode = '';
if (k[0] == "/" && k[k.length - 1] == '/') {
k = k.substring(1, k.length - 1);
} else {
k = '\\b' + k.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '\\b';
mode = (k.toLowerCase() == k ? 'i' : '');
}
return new RegExp(k, mode);
});
const highlight = s => marks.some(m => m.exec(s));
const newsList = [].concat(...state.feeds.filter(f => !urlFilter || f.url == urlFilter).map(f => f.entries))
.sort((a, b) => b.timestamp - a.timestamp)
.slice(0, MAX_NEWS_ON_PAGE);
news.innerHTML = '';
newsList.forEach((n, i) => {
// Get or create a new item
let el = news.childNodes[i];
if (!el) {
el = document.importNode(newsItem.content, true).querySelector('li');
news.appendChild(el);
}
// If the day has changed between the two adjacent items - show new date delimiter
const day = i ? newsList[i - 1].timestamp.toDateString() : '';
if (n.timestamp.toDateString() !== day) {
el.querySelector('h3').innerText =
n.timestamp.toLocaleDateString(undefined, { month: 'long', day: '2-digit' });
} else {
el.querySelector('h3').innerText = '';
}
el.querySelector('a').href = n.link;
el.querySelector('span').innerHTML = n.title;
if (highlight(n.title)) {
el.querySelector('span').classList.add('marked');
} else {
el.querySelector('span').classList.remove('marked');
}
el.querySelector('em').innerText = `(${simplifyLink(n.link).split('/')[0]})`;
});
}
function onMenuClicked() {
if (menu.classList.contains('close')) {
title.innerText = '';
menu.classList.remove('close');
settings.classList.remove('shown');
} else if (menu.classList.contains('back')) {
title.innerText = '';
urlFilter = '';
menu.classList.remove('back');
render(urlFilter);
} else {
title.innerText = 'Settings';
menu.classList.add('close');
settings.classList.add('shown');
}
}
function onDoneClicked() {
onMenuClicked();
render(urlFilter);
}
function onAddFeedClicked() {
var url = prompt(`Enter feed address (full URL is recommended):`);
if (url) {
// if feed does not contain "https://" or "http://", add "http://"
// (we assume all "http://" links will be redirected to "https://" if available)
if (!url.includes("https://" || "http://")) {
var http = "http://";
url = http + url;
}
if (!state.feeds.some(f => f.url === url)) {
state.feeds.push({url, entries: []});
save();
window.location.reload();
}
}
}
function onKeywordsChanged(keywords) {
state.keywords = keywords;
save();
}
function darkMode() {
localStorage.setItem("darkmode", "1");
document.documentElement.style.setProperty('--color-text', '#fafafa');
document.documentElement.style.setProperty('--color-text-secondary', '#bdbdbd');
document.documentElement.style.setProperty('--color-text-visited', '#757575');
document.documentElement.style.setProperty('--color-background', '#000000');
document.documentElement.style.setProperty('--color-accent', '#880E4F');
}
function lightMode() {
localStorage.setItem("darkmode", "0");
document.documentElement.style.setProperty('--color-text', '#212121');
document.documentElement.style.setProperty('--color-text-secondary', '#bdbdbd');
document.documentElement.style.setProperty('--color-text-visited', '#757575');
document.documentElement.style.setProperty('--color-background', '#ffffff');
document.documentElement.style.setProperty('--color-accent', '#FFFF00');
}
function toggleDarkMode() {
if (localStorage.getItem("darkmode") == 1) {
lightMode();
} else {
darkMode();
}
}
// restore dark mode state after a reboot
function restoreDarkModeState() {
if (localStorage.getItem("darkmode") == 1) {
darkMode();
} else {
lightMode();
}
}
restoreDarkModeState();
(async () => {
// Register service worker for PWA
navigator.serviceWorker.register('sw.js');
// Render cached news
save();
renderSettings();
render(urlFilter);
// Fetch each feed and render the settings screen
for (const feed of state.feeds) {
const f = parseFeed(await fetch(DEFAULT_CORS_PROXY(feed.url)).then(res => res.text()));
feed.entries = feed.entries
.concat(
f.filter(e => feed.entries.findIndex(x => (x.link === e.link || x.title === e.title)) < 0),
)
.sort((a, b) => b.timestamp - a.timestamp)
.slice(0, MAX_NEWS_PER_FEED);
localStorage.setItem('state-v1', JSON.stringify(state));
}
// Hide loading indicator
loading.classList.add('hidden');
render(urlFilter);
// Hide "loading" message
document.getElementById("loadingmessage").style.display = 'none';
})();