forked from mozilla-mobile/android-components
-
Notifications
You must be signed in to change notification settings - Fork 0
/
readerview.js
305 lines (261 loc) · 9.37 KB
/
readerview.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
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
/* Avoid adding ID selector rules in this style sheet, since they could
* inadvertently match elements in the article content. */
const supportedProtocols = ["http:", "https:"];
const blockedHosts = ["amazon.com", "github.com", "mail.google.com", "pinterest.com", "reddit.com", "twitter.com", "youtube.com"];
class ReaderView {
static isReaderable() {
if (!supportedProtocols.includes(location.protocol)) {
return false;
}
if (blockedHosts.some(blockedHost => location.hostname.endsWith(blockedHost))) {
return false;
}
if (location.pathname == "/") {
return false;
}
return isProbablyReaderable(document);
}
static get MIN_FONT_SIZE() {
return 1;
}
static get MAX_FONT_SIZE() {
return 9;
}
constructor(document) {
this.document = document;
this.originalBody = document.body.outerHTML;
}
show({fontSize = 4, fontType = "sans-serif", colorScheme = "light"} = {}) {
var documentClone = document.cloneNode(true);
var result = new Readability(documentClone).parse();
result.language = document.documentElement.lang;
var article = Object.assign(
result,
{url: location.hostname},
{readingTime: this.getReadingTime(result.length, result.language)},
{byline: this.getByline()},
{dir: this.getTextDirection(result)}
);
document.body.outerHTML = this.createHtml(article);
this.setFontSize(fontSize);
this.setFontType(fontType);
this.setColorScheme(colorScheme);
}
hide() {
document.body.outerHTML = this.originalBody;
}
/**
* Allows adjusting the font size in discrete steps between ReaderView.MIN_FONT_SIZE
* and ReaderView.MAX_FONT_SIZE.
*
* @param changeAmount e.g. +1, or -1.
*/
changeFontSize(changeAmount) {
var size = Math.max(ReaderView.MIN_FONT_SIZE, Math.min(ReaderView.MAX_FONT_SIZE, this.fontSize + changeAmount));
this.setFontSize(size);
}
/**
* Sets the font size.
*
* @param fontSize must be value between ReaderView.MIN_FONT_SIZE
* and ReaderView.MAX_FONT_SIZE.
*/
setFontSize(fontSize) {
let size = (10 + 2 * fontSize) + "px";
let readerView = document.getElementById("mozac-readerview-container");
readerView.style.setProperty("font-size", size);
this.fontSize = fontSize;
}
/**
* Sets the font type.
*
* @param fontType the font type to use.
*/
setFontType(fontType) {
if (this.fontType === fontType) {
return;
}
let bodyClasses = document.body.classList;
if (this.fontType) {
bodyClasses.remove(this.fontType)
}
this.fontType = fontType
bodyClasses.add(this.fontType)
}
/**
* Sets the color scheme
*
* @param colorScheme the color scheme to use, must be either light, dark
* or sepia.
*/
setColorScheme(colorScheme) {
if(!['light', 'sepia', 'dark'].includes(colorScheme)) {
console.error(`Invalid color scheme specified: ${colorScheme}`)
return;
}
if (this.colorScheme === colorScheme) {
return;
}
let bodyClasses = document.body.classList;
if (this.colorScheme) {
bodyClasses.remove(this.colorScheme)
}
this.colorScheme = colorScheme
bodyClasses.add(this.colorScheme)
}
createHtml(article) {
return `
<body class="mozac-readerview-body">
<div id="mozac-readerview-container" class="container" dir=${article.dir}>
<div class="header">
<a class="domain">${article.url}</a>
<div class="domain-border"></div>
<h1>${article.title}</h1>
<div class="credits">${article.byline}</div>
<div>
<div>${article.readingTime}</div>
</div>
</div>
<hr>
<div class="content">
<div class="mozac-readerview-content">${article.content}</div>
</div>
</div>
</body>
`
}
/**
* Returns the estimated reading time as localized string.
*
* @param length of the article (number of chars).
* @param optional language of the article, defaults to en.
*/
getReadingTime(length, lang = "en") {
const readingSpeed = this.getReadingSpeedForLanguage(lang);
const charactersPerMinuteLow = readingSpeed.cpm - readingSpeed.variance;
const charactersPerMinuteHigh = readingSpeed.cpm + readingSpeed.variance;
const readingTimeMinsSlow = Math.ceil(length / charactersPerMinuteLow);
const readingTimeMinsFast = Math.ceil(length / charactersPerMinuteHigh);
if (readingTimeMinsSlow == readingTimeMinsFast) {
return moment.duration(readingTimeMinsFast, 'minutes').locale(lang).humanize();
}
return `${readingTimeMinsFast} - ${moment.duration(readingTimeMinsSlow, 'minutes').locale(lang).humanize()}`;
}
/**
* Returns the reading speed of a selection of languages with likely variance.
*
* Reading speed estimated from a study done on reading speeds in various languages.
* study can be found here: http://iovs.arvojournals.org/article.aspx?articleid=2166061
*
* @return object with characters per minute and variance. Defaults to English
* if no suitable language is found in the collection.
*/
getReadingSpeedForLanguage(lang) {
const readingSpeed = new Map([
[ "en", {cpm: 987, variance: 118 } ],
[ "ar", {cpm: 612, variance: 88 } ],
[ "de", {cpm: 920, variance: 86 } ],
[ "es", {cpm: 1025, variance: 127 } ],
[ "fi", {cpm: 1078, variance: 121 } ],
[ "fr", {cpm: 998, variance: 126 } ],
[ "he", {cpm: 833, variance: 130 } ],
[ "it", {cpm: 950, variance: 140 } ],
[ "jw", {cpm: 357, variance: 56 } ],
[ "nl", {cpm: 978, variance: 143 } ],
[ "pl", {cpm: 916, variance: 126 } ],
[ "pt", {cpm: 913, variance: 145 } ],
[ "ru", {cpm: 986, variance: 175 } ],
[ "sk", {cpm: 885, variance: 145 } ],
[ "sv", {cpm: 917, variance: 156 } ],
[ "tr", {cpm: 1054, variance: 156 } ],
[ "zh", {cpm: 255, variance: 29 } ],
]);
return readingSpeed.get(lang) || readingSpeed.get("en");
}
/**
* Attempts to find author information in the meta elements of the current page.
*/
getByline() {
var metadata = {};
var values = {};
var metaElements = [...document.getElementsByTagName("meta")];
// property is a space-separated list of values
var propertyPattern = /\s*(dc|dcterm|og|twitter)\s*:\s*(author|creator|description|title|site_name)\s*/gi;
// name is a single value
var namePattern = /^\s*(?:(dc|dcterm|og|twitter|weibo:(article|webpage))\s*[\.:]\s*)?(author|creator|description|title|site_name)\s*$/i;
// Find description tags.
metaElements.forEach((element) => {
var elementName = element.getAttribute("name");
var elementProperty = element.getAttribute("property");
var content = element.getAttribute("content");
if (!content) {
return;
}
var matches = null;
var name = null;
if (elementProperty) {
matches = elementProperty.match(propertyPattern);
if (matches) {
for (var i = matches.length - 1; i >= 0; i--) {
// Convert to lowercase, and remove any whitespace
// so we can match below.
name = matches[i].toLowerCase().replace(/\s/g, "");
// multiple authors
values[name] = content.trim();
}
}
}
if (!matches && elementName && namePattern.test(elementName)) {
name = elementName;
if (content) {
// Convert to lowercase, remove any whitespace, and convert dots
// to colons so we can match below.
name = name.toLowerCase().replace(/\s/g, "").replace(/\./g, ":");
values[name] = content.trim();
}
}
});
return values["dc:creator"] || values["dcterm:creator"] || values["author"] || "";
}
/**
* Attempts to read the optional text direction from the article and uses
* language mapping to detect rtl, if missing.
*/
getTextDirection(article) {
if (article.dir) {
return article.dir
}
if (["ar", "fa", "he", "ug", "ur"].includes(article.language)) {
return "rtl";
}
return "ltr";
}
}
let port = browser.runtime.connectNative("mozacReaderview");
port.onMessage.addListener((message) => {
switch (message.action) {
case 'show':
readerView.show({fontSize: 3, fontType: "serif", colorScheme: "light"});
break;
case 'hide':
readerView.hide();
break;
case 'checkReaderable':
port.postMessage({readerable: ReaderView.isReaderable()});
break;
default:
console.error(`Received invalid action ${message.action}`);
}
});
// TODO remove hostname check (for testing purposes only)
// e.g. https://blog.mozilla.org/firefox/reader-view
if (ReaderView.isReaderable() && location.hostname.endsWith("blog.mozilla.org")) {
// TODO send message to app to inform that readerview is available
// For now we show reader view for every page on blog.mozilla.org
let readerView = new ReaderView(document);
// TODO Parameters need to be passed down in message to display readerview
readerView.show({fontSize: 3, fontType: "serif", colorScheme: "light"});
}