forked from martinkadlec0/Smart-RSS
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathcontentView.js
More file actions
497 lines (425 loc) · 20.1 KB
/
contentView.js
File metadata and controls
497 lines (425 loc) · 20.1 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
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
/**
* @module App
* @submodule views/contentView
*/
define(function (require) {
const BB = require('backbone');
const dateUtils = require('helpers/dateUtils');
/**
* Full view of one article (right column)
* @class ContentView
* @constructor
* @extends Backbone.View
*/
let ContentView = BB.View.extend({
/**
* Tag name of content view element
* @property tagName
* @default 'header'
* @type String
*/
tagName: 'header',
events: {
'mousedown': 'handleMouseDown',
'click .pin-button': 'handlePinClick',
'keydown': 'handleKeyDown'
},
view: '',
/**
* Changes pin state
* @method handlePinClick
* @triggered on click on pin button
* @param event {MouseEvent}
*/
handlePinClick: function (event) {
const target = event.target;
if (target.classList.contains('pinned')) {
target.classList.remove('pinned');
} else {
target.classList.add('pinned');
}
this.model.save({
pinned: target.classList.contains('pinned')
});
},
/**
* Called when new instance is created
* @method initialize
*/
initialize: function () {
this.on('attach', this.handleAttached);
bg.items.on('change:pinned', this.handleItemsPin, this);
bg.sources.on('clear-events', this.handleClearEvents, this);
},
/**
* Sets comm event listeners
* @method handleAttached
* @triggered when content view is attached to DOM
*/
handleAttached: function () {
app.on('select:article-list', function (data) {
this.handleNewSelected(bg.items.findWhere({id: data.value}));
}, this);
app.on('space-pressed', function () {
this.handleSpace();
}, this);
app.on('no-items:article-list', function () {
if (this.renderTimeout) {
clearTimeout(this.renderTimeout);
}
this.model = null;
this.hide();
}, this);
},
/**
* Next page in article or next unread article
* @method handleSpace
* @triggered when space is pressed in middle column
*/
handleSpace: function () {
const cw = document.querySelector('#content');
if (cw.offsetHeight + cw.scrollTop >= cw.scrollHeight) {
app.trigger('give-me-next');
} else {
cw.scrollBy(0, cw.offsetHeight * 0.85);
}
},
/**
* Unbinds all listeners to bg process
* @method handleClearEvents
* @triggered when tab is closed/refreshed
* @param id {Number} id of the closed tab
*/
handleClearEvents: function (id) {
if (window == null || id === tabID) {
bg.items.off('change:pinned', this.handleItemsPin, this);
bg.sources.off('clear-events', this.handleClearEvents, this);
}
},
/**
* Sets the pin button state
* @method handleItemsPin
* @triggered when the pin state of the article is changed
* @param model {Item} article that had its pin state changed
*/
handleItemsPin: function (model) {
if (model === this.model) {
const pinButton = this.el.querySelector('.pin-button');
if (this.model.get('pinned')) {
pinButton.classList.add('pinned');
} else {
pinButton.classList.remove('pinned');
}
}
},
/**
* Gets formatted date (according to settings) from given unix time
* @method getFormattedDate
* @param unixtime {Number}
*/
getFormattedDate: function (unixtime) {
const dateFormats = {normal: 'DD.MM.YYYY', iso: 'YYYY-MM-DD', us: 'MM/DD/YYYY'};
const pickedFormat = dateFormats[bg.settings.get('dateType') || 'normal'] || dateFormats['normal'];
const timeFormat = bg.settings.get('hoursFormat') === '12h' ? 'H:mm:ss a' : 'hh:mm:ss';
return dateUtils.formatDate(unixtime, pickedFormat + ' ' + timeFormat);
},
/**
* Rendering of article is delayed with timeout for 50ms to speed up quick select changes in article list.
* This property contains descriptor for that timeout.
* @property renderTimeout
* @default null
* @type Number
*/
renderTimeout: null,
/**
* Renders articles content asynchronously
* @method render
* @chainable
*/
render: function (overrideView = '') {
clearTimeout(this.renderTimeout);
this.renderTimeout = setTimeout(async () => {
if (!this.model) {
return;
}
const modelUrl = this.model.get('url');
this.show();
const source = this.model.getSource();
const openEnclosure = source.get('openEnclosure');
const sourceDefaultView = source.get('defaultView');
const defaultView = sourceDefaultView === 'global' ? bg.settings.get('defaultView') : sourceDefaultView;
const open = openEnclosure === 'yes' || openEnclosure === 'global' && bg.settings.get('openEnclosure') === 'yes';
const data = Object.create(this.model.attributes);
data.date = this.getFormattedDate(this.model.get('date'));
data.titleIsLink = bg.settings.get('titleIsLink');
data.open = open;
let content = '';
if (overrideView !== '') {
this.view = overrideView;
} else {
this.view = defaultView;
}
if (this.view === 'feed') {
content = this.model.get('content');
} else {
// const parsedContent = this.model.get('parsedContent');
// if (this.view in parsedContent) {
// content = parsedContent[this.view];
// } else {
if (this.view === 'mozilla') {
const response = await fetch(this.model.get('url'), {
method: 'GET',
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer'
});
const websiteContent = await response.text();
const parser = new DOMParser();
const websiteDocument = parser.parseFromString(websiteContent, 'text/html');
const Readability = require('../../libs/readability');
if(this.model.get('url') !== modelUrl){
return;
}
content = new Readability(websiteDocument).parse().content;
}
// }
// if (bg.settings.get('cacheParsedArticles') === 'true' && !(this.view in parsedContent)) {
// parsedContent[this.view] = content;
// this.model.set('parsedContent', parsedContent);
// }
}
const toRemove = chrome.runtime.getURL('');
const re = new RegExp(toRemove, 'g');
content = content.replace(re, '/');
while (this.el.firstChild) {
this.el.removeChild(this.el.firstChild);
}
const fragment = document.createRange().createContextualFragment(require('text!templates/contentView.html'));
fragment.querySelector('.author').textContent = data.author;
fragment.querySelector('.date').textContent = data.date;
if (data.pinned) {
fragment.querySelector('.pin-button').classList.add('pinned');
}
function createEnclosure(enclosureData) {
let newEnclosure;
switch (enclosureData.medium) {
case 'image':
newEnclosure = document
.createRange()
.createContextualFragment(require('text!templates/enclosureImage.html'));
const img = newEnclosure.querySelector('img');
img.src = enclosureData.url;
img.alt = enclosureData.name;
break;
case 'video':
newEnclosure = document
.createRange()
.createContextualFragment(require('text!templates/enclosureVideo.html'));
const video = newEnclosure.querySelector('video');
video.querySelector('source').src = enclosureData.url;
video.querySelector('source').type = enclosureData.type;
break;
case 'audio':
newEnclosure = document
.createRange()
.createContextualFragment(require('text!templates/enclosureAudio.html'));
const audio = newEnclosure.querySelector('audio');
audio.querySelector('source').src = enclosureData.url;
break;
case 'youtube':
// Do not create YouTube Preview if disabled
if (!bg.settings.get('enableYoutubePreview')) {
newEnclosure = document
.createRange()
.createContextualFragment(require('text!templates/enclosureGeneral.html'));
break;
}
newEnclosure = document
.createRange()
.createContextualFragment(require('text!templates/enclosureYoutubeCover.html'));
const videoId = /^.*\/(.*)\?(.*)$/.exec(enclosureData.url)[1];
const posterUrl = `https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`;
const videoUrl = `https://www.youtube-nocookie.com/embed/${videoId}?autoplay=1`;
const cover = newEnclosure.querySelector('.youtube-cover');
cover.style.backgroundImage = `url("${posterUrl}")`;
cover.addEventListener('click', () => {
iframeEnclosure = document
.createRange()
.createContextualFragment(require('text!templates/enclosureYoutube.html'));
const iframe = iframeEnclosure.querySelector('iframe');
iframe.src = videoUrl;
cover.replaceWith(iframeEnclosure);
iframeEnclosure.focus();
});
break;
default:
newEnclosure = document
.createRange()
.createContextualFragment(require('text!templates/enclosureGeneral.html'));
}
newEnclosure.querySelector('a').href = enclosureData.url;
newEnclosure.querySelector('a').textContent = enclosureData.name;
return newEnclosure;
}
if (data.enclosure) {
const enclosures = Array.isArray(data.enclosure) ? data.enclosure : [data.enclosure];
enclosures.forEach((enclosureData) => {
const enclosure = createEnclosure(enclosureData);
fragment.querySelector('#below-h1').appendChild(enclosure);
});
if (data.open && enclosures.length === 1) {
fragment.querySelector('.enclosure').setAttribute('open', 'open');
}
}
this.el.appendChild(fragment);
const h1 = this.el.querySelector('h1');
if (data.titleIsLink) {
const link = document.createElement('a');
link.target = '_blank';
link.tabindex = '-1';
link.href = data.url ? data.url : '#';
link.textContent = data.title;
h1.appendChild(link);
} else {
h1.textContent = data.title;
}
// first load might be too soon
const sandbox = app.content.sandbox;
const frame = sandbox.el;
frame.setAttribute('scrolling', 'no');
const resizeFrame = () => {
const scrollHeight = frame.contentDocument.body.scrollHeight;
frame.style.minHeight = '10px';
frame.style.minHeight = '70%';
frame.style.minHeight = `${scrollHeight}px`;
frame.style.height = '10px';
frame.style.height = '70%';
frame.style.height = `${scrollHeight}px`;
};
const loadContent = () => {
const body = frame.contentDocument.querySelector('body');
const articleUrl = this.model.get('url');
const articleDomain = new URL(articleUrl).origin;
let base = frame.contentDocument.querySelector('base');
base.href = articleDomain;
const shouldInvertColors = bg.settings.get('invertColors') === 'yes';
if (shouldInvertColors) {
body.classList.add('dark-theme');
} else {
body.classList.remove('dark-theme');
}
frame.contentWindow.scrollTo(0, 0);
document.querySelector('#content').scrollTo(0, 0);
frame.contentDocument.documentElement.style.fontSize = bg.settings.get('articleFontSize') + '%';
const contentElement = frame.contentDocument.querySelector('#smart-rss-content');
while (contentElement.firstChild) {
contentElement.removeChild(contentElement.firstChild);
}
let fragment;
switch (data.enclosure.medium) {
case 'youtube':
fragment = document.createRange().createContextualFragment(content.replace(/\r/g, '<br>'));
break;
default:
fragment = document.createRange().createContextualFragment(content);
}
contentElement.appendChild(fragment);
frame.contentDocument.querySelector('#smart-rss-url').href = articleUrl;
frame.contentDocument.querySelector('#full-article-url').textContent = articleUrl;
const clickHandler = (event) => {
if (event.target.matches('a')) {
event.stopPropagation();
const href = event.target.getAttribute('href');
if (!href || href[0] !== '#') {
return true;
}
event.preventDefault();
const name = href.substring(1);
const nameElement = frame.contentDocument.querySelector('[name="' + name + ']"');
const idElement = frame.contentDocument.getElementById(name);
let element = null;
if (nameElement) {
element = nameElement;
} else if (idElement) {
element = idElement;
}
if (element) {
const getOffset = function (el) {
const box = el.getBoundingClientRect();
return {
top: box.top + frame.contentWindow.pageYOffset - frame.contentDocument.documentElement.clientTop,
left: box.left + frame.contentWindow.pageXOffset - frame.contentDocument.documentElement.clientLeft
};
};
const offset = getOffset(element);
frame.contentWindow.scrollTo(offset.left, offset.top);
}
return false;
}
};
frame.contentDocument.removeEventListener('click', clickHandler);
frame.contentDocument.addEventListener('click', clickHandler);
frame.contentDocument.removeEventListener('load', resizeFrame);
frame.contentDocument.addEventListener('load', resizeFrame);
if (typeof ResizeObserver !== 'undefined') {
const resizeObserver = new ResizeObserver(resizeFrame);
resizeObserver.observe(frame.contentDocument.body);
}
[...frame.contentDocument.querySelectorAll('img, picture, iframe, video, audio')]
.forEach((element) => {
if (element.src.startsWith('https://www.youtube.com/watch?')) {
element.src = element.src.replace('https://www.youtube.com/watch?v=', 'https://www.youtube-nocookie.com/embed/');
element.removeAttribute('allowfullscreen');
element.removeAttribute('height');
element.removeAttribute('width');
element.setAttribute('allowfullscreen', 'allowfullscreen');
}
element.onload = resizeFrame;
});
resizeFrame();
};
if (sandbox.loaded) {
loadContent();
} else {
sandbox.on('load', loadContent);
}
}, 50);
return this;
},
/**
* Replaces old article model with newly selected one
* @method handleNewSelected
* @param model {Item} The new article model
*/
handleNewSelected: function (model) {
if (model === this.model) {
return;
}
this.model = model;
if (!this.model) {
// should not happen but happens
this.hide();
} else {
this.render();
}
},
/**
* Hides contents (header, iframe)
* @method hide
*/
hide: function () {
[...document.querySelectorAll('header,iframe')].forEach((element) => {
element.hidden = true;
});
},
/**
* Show contents (header, iframe)
* @method hide
*/
show: function () {
[...document.querySelectorAll('header,iframe')].forEach((element) => {
element.hidden = false;
});
}
});
return new ContentView();
});