-
Notifications
You must be signed in to change notification settings - Fork 0
/
undistracted.js
1719 lines (1475 loc) · 69.8 KB
/
undistracted.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
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name Undistracted
// @namespace http://your.homepage/
// @version 0.2
// @description Read the article, and get on with your life.
// @author You
// @include *
// @grant none
// @noframe
// ==/UserScript==
var DBG = true;
var dbg = (DBG === true && typeof console !== 'undefined') ? function(s) {
// console.log("Readability: " + s);
console.log.apply(console, arguments);
} : function() {};
var info = (DBG === true&& typeof console !== 'undefined') ? function() {
console.info.apply(console, arguments);
} : function() {};
var trace = (DBG === true&& typeof console !== 'undefined') ? function() {
console.trace.apply(console, arguments);
} : function() {};
var dir = (DBG === true && typeof console !== 'undefined') ? function() {
console.dir.apply(console, arguments);
} : function() {};
var readability = {
convertLinksToFootnotes: true,
biggestFrame: false,
wholePageCache: null,
bodyCache: null,
flags: 0x1 | 0x2 | 0x4,
/* Start with all flags set. */
/* constants */
FLAG_STRIP_UNLIKELYS: 0x1,
FLAG_WEIGHT_CLASSES: 0x2,
FLAG_CLEAN_CONDITIONALLY: 0x4,
maxPages: 10,
/* The maximum number of pages to loop through before we call it quits and just show a link. */
parsedPages: {},
/* The list of pages we've parsed in this call of readability, for autopaging. As a key store for easier searching. */
pageETags: {},
/* A list of the ETag headers of pages we've parsed, in case they happen to match, we'll know it's a duplicate. */
/**
* All of the regular expressions in use within readability.
* Defined up here so we don't instantiate them repeatedly in loops.
**/
regexps: {
unlikelyCandidates: /combx|comment|community|disqus|extra|foot|header|menu|remark|rss|shoutbox|sidebar|sponsor|ad-break|agegate|pagination|pager|popup|tweet|twitter|aside|nocontent/i,
okMaybeItsACandidate: /and|article|body|column|main|shadow|canvas|svg|figure/i,
stripFromText: /img|a/i,
positive: /article|body|content|entry|hentry|main|page|pagination|post|text|blog|story|code|svg|canvas|figure/i,
negative: /combx|comment|com-|contact|header|foot|footer|footnote|masthead|meta|outbrain|promo|related|scroll|shoutbox|sidebar|sponsor|shopping|tags|tool|widget|nocontent|share|bookmark/i,
extraneous: /print|archive|comment|discuss|e[\-]?mail|share|reply|all|login|sign|single/i,
divToPElements: /<(a|blockquote|dl|div|img|ol|p|pre|table|ul)/i,
replaceBrs: /(<br[^>]*>[ \n\r\t]*){2,}/gi,
replaceFonts: /<(\/?)font[^>]*>/gi,
trim: /^\s+|\s+$/g,
normalize: /\s{2,}/g,
killBreaks: /(<br\s*\/?>(\s| ?)*){1,}/g,
videos: /http:\/\/(www\.)?(youtube|vimeo)\.com/i,
skipFootnoteLink: /^\s*(\[?[a-z0-9]{1,2}\]?|^|edit|citation needed)\s*$/i,
nextLink: /(next|weiter|continue|>([^\|]|$)|»([^\|]|$))/i, // Match: next, continue, >, >>, » but not >|, »| as those usually mean last.
prevLink: /(prev|earl|old|new|<|«)/i,
likelyURLpath: /[-_]/
},
nextPageLink: null,
/**
* Runs readability.
*
* Workflow:
* 1. Prep the document by removing script tags, css, etc.
* 2. Build readability's DOM tree.
* 3. Grab the article content from the current dom tree.
* 4. Replace the current DOM tree with the new one.
* 5. Read peacefully.
*
* @return void
**/
init: function() {
/**
* Don't use this on root page (NOT UNIVERSAL)
**/
info("Started Readability~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" );
if (/\b(google.com|facebook.com|twitter.com|dropbox.com|quizlet.com|youtube.com|amazon.com)\b/i.test(window.document.location.hostname)) return null;
if (localStorage.getItem("lens-user-never-again-GH3UEgL6CbcpK4hNtQeR8Fc") === "n") return null;
// readability.flags = localStorage.getItem("lens-flag-GH3UEgL6CbcpK4hNtQeR8Fc") || readability.flags;
// don't use on forums
var linksOnSameDomain = function(query){
links = document.querySelectorAll(query);
var total = 0;
for (var i = 0; i < links.length; i++) {
try {
if (links.href.split('/')[2] === location.hostname){
total+=1;
}
} catch (err) {}
}
return total;
};
if (linksOnSameDomain("a[href*='forum']") > 5 || linksOnSameDomain("a[href*='thread']") > 5) {
info("forum");
return null;
}
// don't use of stackoverflow like pages, may want to try to find something more general (like textarea) although comments...
if (document.querySelector("html[itemtype='http://schema.org/QAPage']") !== null) {
info("page like stackoverflow");
return null;
}
readability.createBodyIfNeeded();
if(document.body && !readability.bodyCache) {
readability.wholePageCache = document.cloneNode(true);
readability.wholePageCache.normalize();
readability.bodyCache = readability.wholePageCache.querySelector("body");
}
readability.removeScripts(readability.wholePageCache);
/* Make sure this document is added to the list of parsed pages first, so we don't double up on the first page */
readability.parsedPages[window.location.href.replace(/\/$/, '')] = true;
/* Pull out any possible next page link first */
var nextPageLink = readability.findNextPageLink(readability.bodyCache);
readability.nextPageLink = nextPageLink;
var articleTools = readability.getArticleTools();
var articleTitle = readability.getArticleTitle();
var articleContent = readability.grabArticle(readability.bodyCache);
if (!articleContent) {
info("unable to extract main content");
return;
}
// Clean memory
readability.bodyCache.innerHTML = "";
readability.bodyCache = null;
readability.wholePageCache.innerHTML = "";
readability.wholePageCache = null;
readability["readability-content"] = articleContent;
var styles = document.styleSheets;
for (var i = 0; i< styles.length; i++){
styles[i].disabled = true;
styles[i].ownerNode.dataset.lensDisabled = true;
}
var articleFooter = readability.getArticleFooter();
readability.readFooter = articleFooter;
/* Build readability's DOM tree */
var style = document.createElement("LINK");
style.href = chrome.extension.getURL("/css/lens.css");
style.rel = "stylesheet";
// var style = document.createElement("style");
// style.type = "text/css";
// style.innerHTML = '.lensLink {box-sizing: border-box; color: rgba(0, 0, 0, 0.439216); cursor: pointer; display: inline-block; height: 38px; letter-spacing: -0.280000001192093px; position: relative; text-align: center; text-decoration: none; background-color:white; text-rendering: optimizeLegibility; vertical-align: middle; white-space: nowrap; -webkit-perspective-origin: 50% 50%; -moz-perspective-origin: 50% 50%; -o-perspective-origin: 50% 50%; perspective-origin: 50% 50%; -webkit-transform-origin: 50% 50%; -moz-transform-origin: 50% 50%; -o-transform-origin: 50% 50%; -ms-transform-origin: 50% 50%; transform-origin: 50% 50%; border: 1px solid rgba(0, 0, 0, 0.14902); border-radius: 13986px 13986px 13986px 13986px; font: normal normal normal normal 14px/37px "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Geneva, Verdana, sans-serif; margin: 0 8px 0 0; outline: rgba(0, 0, 0, 0.439216) none 0; padding: 0 16px; transition: border-color 0.1s ease 0s, color 0.1s ease 0s; } .tools{padding: 10px 10px; padding-bottom: 0; } .lensLink:focus, .lensLink:active, .lensLink:hover {color: rgba(0,0,0,0.6); border-color: rgba(0,0,0,0.3); } img {max-width: 100%; } body, td, input, select, textarea, button {color: hsl(273, 10%, 20%); } h1 {font-size: 1.25em; } h2 {font-size: 1.125em; } h3 {font-size: 1.05em; } a {text-decoration: none; color: #35C; } a:hover {text-decoration: underline; background-color: #fafafa; } blockquote {border-left: 5px solid #eaeef1; color: #555; margin-left: 0; margin-right: 0; padding: 0 20px; } hr {height: 0px; border: none; border-top: 1px solid #ddd; } br {clear: left; } #article {display: inline-block; font: 19px Georgia, Times, "Times New Roman", serif; line-height: 160%; text-align: justify; text-shadow: none; } #article.rtl {direction: rtl; text-align: right; } .page {border: 1px solid #C3C3C3; background-color: #fdfdfd; padding: 45px 70px; margin: 12px 12px 0 12px; -webkit-user-select: auto; } .page:first-of-type {margin-top: 20px; } .page:last-of-type {margin-bottom: 20px; } .page table {font-size: 0.9em; text-align: left; } .page.rtl table {text-align: right; } #title {display: none; font-weight: bold; font-size: 1.33em; line-height: 1.25em; margin-bottom: 1.5em; padding: 45px 70px; padding-bottom: 0; } .page:first-of-type #title {display: block; } .content {word-wrap: break-word; } .content pre, .content xmp, .content plaintext, .content listing {white-space: normal; } .content pre, .content code {border: 1px dashed #d3c8cf; border-left: 5px solid #f5edf2; padding: 5px 5px 5px 10px; } .content img {float: left; margin: 12px 12px 12px 0px; max-width: 100%; height: auto; } .content.disableImages img {display: none !important; } .content .tinyImage {float: none; margin: 0; } .content .largeImage {float: none; margin: 1em auto; display: block; clear: both; /*-webkit-box-shadow: rgba(0, 0, 0, 0.05) 0px 0px 20px;*/; } .content a img {border: none; } .content .float {margin: 8px 0; font-size: 70%; line-height: 1.4; text-align: left; } #article.rtl .content .float {text-align: right; } .content .float.left {float: left; margin-right: 20px; } .content .float.right {float: right; margin-left: 20px !important; } .content .float.full-width {float: none; display: block; } ::-webkit-scrollbar:horizontal, ::-webkit-scrollbar-track:disabled {display: none; } ::-webkit-scrollbar-thumb {-webkit-border-image: url("https://i.imgur.com/JiF4KuF.png") 19 0 19 0; /*-webkit-border-image: url("chrome-extension://__MSG_@@extension_id__/assets/images/scrollbar-thumb.png") 19 0 19 0;*/ border-width: 19px 0; min-height: 40px; } ::-webkit-scrollbar-track {margin-top: 20; margin-bottom: 20; -webkit-border-image: url("https://i.imgur.com/wLYCOTH.png") 21 0 21 0; /*-webkit-border-image: url("chrome-extension://__MSG_@@extension_id__/assets/images/scrollbar-track.png") 21 0 21 0;*/ border-width: 21px 0; } ::-webkit-scrollbar {width: 21px; } @media print {body {background: #fff !important; } #controls, .footer, .loader {display: none !important; } #articleContainer {width: auto !important; height: auto !important; } #article, .page, .contentWrapper {border: none; margin: 0 ; padding: 0 ; font-size: 12pt; } .page {background: #fff !important; } .page, a:link, a:visited {color: #000 !important; } a:link, a:visited {color: #520 !important; background: transparent; text-decoration: underline; } .content a:link:after, .content a:visited:after {/*opt*/content: " (" attr(href) ") "; font-size: 80%; color: #853 !important; } .page:last-of-type .articleInfo {display: block !important; } .page .pageNumber {float: none; background: #fafafa; color: #000; border: solid 2px #eee; border-left: none; border-right: none; border-radius: 0px; margin-top: 15px; margin-bottom: 15px; } }';
var body = document.createElement("DIV");
body.id = "article";
body.appendChild(style);
/* Apply user-selected styling */
// readability.wholePageCache.dir = readability.getSuggestedDirection(articleTitle.innerHTML);
readability.postProcessContent(articleContent);
/* Glue the structure of our document together. */
var page = articleContent.firstChild;
page.insertBefore(articleTitle, page.firstChild);
page.insertBefore(articleTools, page.firstChild);
body.appendChild(articleContent);
articleContent.appendChild(articleFooter);
articleFooter.classList.add("page");
var oldBodyOverflow = document.body.style.overflow;
document.body.style.visibility = "hidden";
document.body.style.overflow = "hidden";
picoModal({
content: body,
closeButton: false
}).afterClose(function(modal){
style.disabled = true;
var styles = document.styleSheets;
for (var i = 0; i< styles.length; i++){
if (styles[i].ownerNode.dataset.lensDisabled){
styles[i].disabled = false;
} else {
styles[i].disabled = true;
}
}
document.body.style.visibility = "visible";
document.body.style.overflow = oldBodyOverflow;
modal.destroy();
}).afterShow(function(){
window.scrollTo(0, 0);
body.focus();
body.click();
}).show();
if (nextPageLink) {
// *
// * Append any additional pages after a small timeout so that people
// * can start reading without having to wait for this to finish processing.
// *
window.setTimeout(function() {
readability.appendNextPage(nextPageLink);
}, 0);
}
},
/**
* Run any post-process modifications to article content as necessary.
*
* @param Element
* @return void
**/
postProcessContent: function(articleContent) {
readability.addFootnotes(articleContent);
// readability.fixImageFloats(articleContent);
},
/**
* Some content ends up looking ugly if the image is too large to be floated.
* If the image is wider than a threshold (currently 55%), no longer float it,
* center it instead.
*
* @param Element
* @return void
**/
// fixImageFloats: function(articleContent) {
// var imageWidthThreshold = Math.min(articleContent.offsetWidth, 800) * 0.55,
// images = articleContent.getElementsByTagName('img');
// for (var i = 0, il = images.length; i < il; i += 1) {
// var image = images[i];
// if (image.offsetWidth > imageWidthThreshold) {
// image.className += " blockImage";
// }
// }
// },
/**
* Get the article tools Element that has buttons like reload, print, email.
*
* @return void
**/
getArticleTools: function() {
var articleTools = document.createElement("DIV");
articleTools.className = "tools";
var close = document.createElement("A");
close.className = "pico-close lensLink ";
close.text = "Close";
var neverAgain = document.createElement("A");
neverAgain.className = "lensLink";
neverAgain.text = "Never on this Domain";
neverAgain.onclick = function(){
localStorage.setItem("lens-user-never-again-GH3UEgL6CbcpK4hNtQeR8Fc", "n");
close.click();
};
articleTools.appendChild(close);
articleTools.appendChild(neverAgain);
return articleTools;
},
/**
* retuns the suggested direction of the string
*
* @return "rtl" || "ltr"
**/
// getSuggestedDirection: function(text) {
// function sanitizeText() {
// return text.replace(/@\w+/, "");
// }
// function countMatches(match) {
// var matches = text.match(new RegExp(match, "g"));
// return matches !== null ? matches.length : 0;
// }
// function isRTL() {
// var count_heb = countMatches("[\\u05B0-\\u05F4\\uFB1D-\\uFBF4]");
// var count_arb = countMatches("[\\u060C-\\u06FE\\uFB50-\\uFEFC]");
// // if 20% of chars are Hebrew or Arbic then direction is rtl
// return (count_heb + count_arb) * 100 / text.length > 20;
// }
// text = sanitizeText(text);
// return isRTL() ? "rtl" : "ltr";
// },
/**
* Get the article title as an H1.
*
* @return void
**/
getArticleTitle: function() {
var curTitle = "",
origTitle = "";
try {
curTitle = origTitle = document.title;
if (typeof curTitle !== "string") { /* If they had an element with id "title" in their HTML */
curTitle = origTitle = readability.getInnerText(document.getElementsByTagName('title')[0]);
}
} catch (e) {}
if (curTitle.match(/ [\|\-] /)) {
curTitle = origTitle.replace(/(.*)[\|\-] .*/gi, '$1');
if (curTitle.split(' ').length < 3) {
curTitle = origTitle.replace(/[^\|\-]*[\|\-](.*)/gi, '$1');
}
} else if (curTitle.indexOf(': ') !== -1) {
curTitle = origTitle.replace(/.*:(.*)/gi, '$1');
if (curTitle.split(' ').length < 3) {
curTitle = origTitle.replace(/[^:]*[:](.*)/gi, '$1');
}
} else if (curTitle.length > 150 || curTitle.length < 15) {
var hOnes = document.getElementsByTagName('h1');
if (hOnes.length === 1) {
curTitle = readability.getInnerText(hOnes[0]);
}
}
curTitle = curTitle.replace(readability.regexps.trim, "");
if (curTitle.split(' ').length <= 4) {
curTitle = origTitle;
}
var articleTitle = document.createElement("H1");
articleTitle.innerHTML = curTitle;
return articleTitle;
},
/**
* Get the footer with the readability mark etc.
*
* @return void
**/
getArticleFooter: function() {
var articleFooter = document.createElement("DIV");
articleFooter.id = "readFooter";
articleFooter.innerHTML = [
"<div id='rdb-footer-print'>Excerpted from <cite>" + document.title + "</cite><br />" + window.location.href + "</div>",
"</div>"
].join('');
return articleFooter;
},
/**
* Prepare the HTML document for readability to scrape it.
* This includes things like stripping javascript, CSS, and handling terrible markup.
*
* @return void
**/
createBodyIfNeeded: function() {
/**
* In some cases a body element can't be found (if the HTML is totally hosed for example)
* so we create a new body node and append it to the document.
*/
if (document.body === null) {
var body = document.createElement("body");
try {
document.body = body;
} catch (e) {
document.documentElement.appendChild(body);
dbg(e);
}
}
},
/**
* For easier reading, convert this document to have footnotes at the bottom rather than inline links.
* @see http://www.roughtype.com/archives/2010/05/experiments_in.php
*
* @return void
**/
addFootnotes: function(articleContent) {
var footnotesWrapper = readability['readability-footnotes'],
articleFootnotes = readability['readability-footnotes-list'];
if (!footnotesWrapper) {
footnotesWrapper = document.createElement("DIV");
readability['readability-footnotes'] = footnotesWrapper;
footnotesWrapper.id = 'readability-footnotes';
footnotesWrapper.innerHTML = '<h3>References</h3>';
footnotesWrapper.style.display = 'none'; /* Until we know we have footnotes, don't show the references block. */
articleFootnotes = document.createElement('ol');
articleFootnotes.id = 'readability-footnotes-list';
readability['readability-footnotes-list'] = articleFootnotes;
footnotesWrapper.appendChild(articleFootnotes);
readability.readFooter.appendChild(footnotesWrapper);
}
var articleLinks = articleContent.getElementsByTagName('a');
var linkCount = articleFootnotes.getElementsByTagName('li').length;
for (var i = 0; i < articleLinks.length; i += 1) {
var articleLink = articleLinks[i],
footnoteLink = articleLink.cloneNode(true),
refLink = document.createElement('a'),
footnote = document.createElement('li'),
linkDomain = footnoteLink.host ? footnoteLink.host : document.location.host,
linkText = readability.getInnerText(articleLink);
if(articleLink.className && articleLink.className.indexOf('readability-DoNotFootnote') !== -1 || linkText.match(readability.regexps.skipFootnoteLink)) {
continue;
}
linkCount += 1;
/** Add a superscript reference after the article link */
refLink.href = '#readabilityFootnoteLink-' + linkCount;
refLink.innerHTML = '<small><sup>[' + linkCount + ']</sup></small>';
refLink.className = 'readability-DoNotFootnote';
try {
refLink.style.color = 'inherit';
} catch (e) {} /* IE7 doesn't like inherit. */
if (articleLink.parentNode.lastChild === articleLink) {
articleLink.parentNode.appendChild(refLink);
} else {
articleLink.parentNode.insertBefore(refLink, articleLink.nextSibling);
}
articleLink.id = 'readabilityLink-' + linkCount;
try {
articleLink.style.color = 'inherit';
} catch (err) {} /* IE7 doesn't like inherit. */
footnote.innerHTML = "<small><sup><a href='#readabilityLink-" + linkCount + "' title='Jump to Link in Article'>^</a></sup></small> ";
footnoteLink.innerHTML = (footnoteLink.title ? footnoteLink.title : linkText);
footnoteLink.id = 'readabilityFootnoteLink-' + linkCount;
footnote.appendChild(footnoteLink);
footnote.innerHTML = footnote.innerHTML + "<small> (" + linkDomain + ")</small>";
articleFootnotes.appendChild(footnote);
}
if (linkCount > 0) {
footnotesWrapper.style.display = 'block';
}
},
/**
* Prepare the article node for display. Clean out any inline styles,
* iframes, forms, strip extraneous <p> tags, etc.
*
* @param Element
* @return void
**/
prepArticle: function(articleContent) {
// readability.cleanStyles(articleContent);
// readability.killBreaks(articleContent);
/* Clean out junk from the article content */
readability.cleanConditionally(articleContent, "form");
readability.cleanConditionally(articleContent, "input");
readability.clean(articleContent, "h1");
// readability.clean(articleContent, "object");
/**
* If there is only one h2, they are probably using it
* as a header and not a subheader, so remove it since we already have a header.
***/
// if (articleContent.getElementsByTagName('h2').length === 1) {
// readability.clean(articleContent, "h2");
// }
// readability.clean(articleContent, "iframe");
readability.cleanHeaders(articleContent);
/* Do these last as the previous stuff may have removed junk that will affect these */
// readability.cleanConditionally(articleContent, "table");
readability.cleanConditionally(articleContent, "ul");
readability.cleanConditionally(articleContent, "div");
},
/**
* Initialize a node with the readability object. Also checks the
* className/id for special names to add to its score.
*
* @param Element
* @return void
**/
initializeNode: function(node) {
node.readability = {
"contentScore": 0
};
switch (node.tagName) {
case 'DIV':
node.readability.contentScore += 5;
break;
case 'PRE':
case 'TD':
case 'BLOCKQUOTE':
node.readability.contentScore += 3;
break;
case 'ADDRESS':
case 'OL':
case 'UL':
case 'DL':
case 'DD':
case 'DT':
case 'LI':
case 'FORM':
node.readability.contentScore -= 3;
break;
case 'H1':
case 'H2':
case 'H3':
case 'H4':
case 'H5':
case 'H6':
case 'TH':
node.readability.contentScore -= 5;
break;
}
node.readability.contentScore += readability.getClassWeight(node);
},
inCodeBlock: function(node, depth) {
depth = depth || 10;
for (var i = 0; node !==null && i < depth && node.parentNode !== null; i+=1){
if (node.tagName === "PRE" || node.tagName === "CODE") {
return true;
}
node = node.parentNode;
}
return false;
},
getLargestContent: function(element){
var text = "";
var container = document.createElement("DIV");
var children = [];
var min_length = 500;
var length = 0;
element.textContent.split(/\n{4,}/g).forEach(function(el){
el = el.replace(/\s+/g," ");
if(el.length > min_length){
container.innerHTML = el;
children = container.children;
for (var i = children.length-1; i >= 0 ; i--) {
if (children[i].tagName.search(readability.stripFromText) !== -1){
container.removeChild(children[i]);
}
}
el = container.textContent;
if (el.length > length){
text = el;
}
}
});
return text;
},
/***
* grabArticle - Using a variety of metrics (content score, classname, element types), find the content that is
* most likely to be the stuff a user wants to read. Then return it wrapped up in a div.
*
* @param page a document to run upon. Needs to be a full document, complete with body.
* @return Element
**/
grabArticle: function(page) {
var stripUnlikelyCandidates = readability.flagIsActive(readability.FLAG_STRIP_UNLIKELYS),
isPaging = (page !== null) ? true : false;
page = page ? page : document.body;
var pageCacheHtml = page.innerHTML;
var allElements = page.getElementsByTagName('*');
/**
* First, node prepping. Trash nodes that look cruddy (like ones with the class name "comment", etc), and turn divs
* into P tags where they have been used inappropriately (as in, where they contain no other block level elements.)
*
* Note: Assignment from index for performance. See http://www.peachpit.com/articles/article.aspx?p=31567&seqNum=5
* Then again js engines are getting highly unpredictable
**/
var node = null;
var nodesToScore = [];
for (var nodeIndex = 0; (node = allElements[nodeIndex]); nodeIndex += 1) {
/* Remove unlikely candidates */
if (stripUnlikelyCandidates) {
var unlikelyMatchString = node.className +" "+ node.id ;
// class/id in unlikelyCandidates but not in okMaybeItsACandidate
if (
unlikelyMatchString.search(readability.regexps.unlikelyCandidates) !== -1 &&
unlikelyMatchString.search(readability.regexps.okMaybeItsACandidate) === -1 &&
node.tagName !== "BODY"
) {
dbg("Removing unlikely candidate - " + unlikelyMatchString);
if (node.parentNode !== null && !readability.inCodeBlock(node)){
node.parentNode.removeChild(node);
nodeIndex -= 1;
continue;
}
}
}
if (node.tagName === "P" || node.tagName === "TD" || node.tagName === "PRE") {
nodesToScore[nodesToScore.length] = node;
}
/* Turn all divs that don't have children block level elements into p's */
if (node.tagName === "DIV") {
if (node.innerHTML.search(readability.regexps.divToPElements) === -1) {
var newNode = document.createElement('p');
try {
newNode.innerHTML = node.innerHTML;
node.parentNode.replaceChild(newNode, node);
nodeIndex -= 1;
nodesToScore[nodesToScore.length] = node;
} catch (e) {
dbg("Could not alter div to p, probably an IE restriction, reverting back to div.: " + e);
}
}
}
}
var beforeLength = 0;
[].slice.call(page.querySelectorAll("p,td,pre")).forEach(function(el){
beforeLength += el.textContent.length;
});
if (beforeLength< 300) {
info("beforeLength is smaller than 300, stopping");
info(beforeLength);
return;
}
/**
* Loop through all paragraphs, and assign a score to them based on how content-y they look.
* Then add their score to their parent node.
*
* A score is determined by things like number of commas, class names, etc. Maybe eventually link density.
**/
var candidates = [];
for (var pt = 0; pt < nodesToScore.length; pt += 1) {
node = nodesToScore[pt];
var parentNode = node.parentNode;
var grandParentNode = parentNode ? parentNode.parentNode : null;
var innerText = readability.getInnerText(node);
if (!parentNode || typeof(parentNode.tagName) === 'undefined') {
continue;
}
/* If this paragraph is less than 25 characters, don't even count it. */
if (innerText.length < 25) {
// dbg("paragraph not scored %o", node);
continue;
}
/* Initialize readability data for the parent. */
if (typeof parentNode.readability === 'undefined') {
readability.initializeNode(parentNode);
candidates.push(parentNode);
}
/* Initialize readability data for the grandparent. */
if (grandParentNode && typeof(grandParentNode.readability) === 'undefined' && typeof(grandParentNode.tagName) !== 'undefined') {
readability.initializeNode(grandParentNode);
candidates.push(grandParentNode);
}
var contentScore = 0;
/* Add a point for the paragraph itself as a base. */
contentScore += 1;
/* Add points for any commas within this paragraph */
contentScore += innerText.split(',').length;
/* For every 100 characters in this paragraph, add another point. Up to 3 points. */
contentScore += Math.min(Math.floor(innerText.length / 100), 3);
/* Add the score to the parent. The grandparent gets half. */
parentNode.readability.contentScore += contentScore;
if (grandParentNode) {
grandParentNode.readability.contentScore += contentScore / 2;
}
}
/**
* After we've calculated scores, loop through all of the possible candidate nodes we found
* and find the one with the highest score.
**/
var topCandidate = null;
for (var c = 0, cl = candidates.length; c < cl; c += 1) {
/**
* Scale the final candidates score based on link density. Good content should have a
* relatively small link density (5% or less) and be mostly unaffected by this operation.
**/
candidates[c].readability.contentScore = candidates[c].readability.contentScore * (1 - readability.getLinkDensity(candidates[c]));
// dbg('Candidate: ' + candidates[c] + " (" + candidates[c].className + ":" + candidates[c].id + ") with score " + candidates[c].readability.contentScore);
if (!topCandidate || candidates[c].readability.contentScore > topCandidate.readability.contentScore) {
topCandidate = candidates[c];
}
}
/**
* If we still have no top candidate, just use the body as a last resort.
* We also have to copy the body node so it is something we can modify.
**/
if (topCandidate === null || topCandidate.tagName === "BODY") {
topCandidate = document.createElement("DIV");
topCandidate.innerHTML = page.innerHTML;
page.innerHTML = "";
page.appendChild(topCandidate);
readability.initializeNode(topCandidate);
}
/**
* Now that we have the top candidate, look through its siblings for content that might also be related.
* Things like preambles, content split by ads that we removed, etc.
**/
var articleContent = document.createElement("DIV");
// IMPORTANT
var siblingScoreThreshold = Math.max(10, topCandidate.readability.contentScore * 0.2);
var siblingNodes = topCandidate.parentNode.childNodes;
// TODO: Is it useful to filter the sibling of top candidate?
for (var s = 0, sl = siblingNodes.length; s < sl; s += 1) {
var siblingNode = siblingNodes[s];
var append = false;
if (siblingNode === topCandidate) {
append = true;
}
var contentBonus = 0;
/* Give a bonus if sibling nodes and top candidates have the example same classname */
if (siblingNode.className === topCandidate.className && topCandidate.className !== "") {
contentBonus += topCandidate.readability.contentScore * 0.2;
}
if (typeof siblingNode.readability !== 'undefined' && (siblingNode.readability.contentScore + contentBonus) >= siblingScoreThreshold) {
append = true;
}
if (siblingNode.nodeName === "P") {
var linkDensity = readability.getLinkDensity(siblingNode);
var nodeContent = readability.getInnerText(siblingNode);
var nodeLength = nodeContent.length;
if (nodeLength > 80 && linkDensity < 0.25) {
append = true;
} else if (nodeLength < 80 && linkDensity === 0 && nodeContent.search(/\.( |$)/) !== -1) {
append = true;
}
}
if (append) {
var nodeToAppend = null;
if (siblingNode.nodeName !== "DIV" && siblingNode.nodeName !== "P") {
/* We have a node that isn't a common block level element, like a form or td tag. Turn it into a div so it doesn't get filtered out later by accident. */
dbg("Altering siblingNode of " + siblingNode.nodeName + ' to div.');
nodeToAppend = document.createElement("DIV");
try {
nodeToAppend.id = siblingNode.id;
nodeToAppend.innerHTML = siblingNode.innerHTML;
} catch (er) {
dbg("Could not alter siblingNode to div, probably an IE restriction, reverting back to original.");
nodeToAppend = siblingNode;
s -= 1;
sl -= 1;
}
} else {
nodeToAppend = siblingNode;
s -= 1;
sl -= 1;
}
/* Append sibling and subtract from our list because it removes the node when you append to another node */
articleContent.appendChild(nodeToAppend);
} else {
dbg("Sibling not appended: %o has score %s with threshold", siblingNode, (siblingNode.readability ? siblingNode.readability.contentScore : 'Unknown'), siblingScoreThreshold);
}
}
/**
* So we have all of the content that we need. Now we clean it up for presentation.
**/
readability.prepArticle(articleContent);
if (readability.curPageNum === 1) {
articleContent.innerHTML = '<div id="readability-page-1" class="page"><div class="content">' + articleContent.innerHTML + '</div></div>';
}
/**
* Now that we've gone through the full algorithm, check to see if we got any meaningful content.
* If we didn't, we may need to re-run grabArticle with different flags set. This gives us a higher
* likelihood of finding the content, and the sieve approach gives us a higher likelihood of
* finding the -right- content.
**/
var afterLength = 0;
[].slice.call(articleContent.querySelectorAll("p,td,pre")).forEach(function(el){
afterLength += el.textContent.length;
});
info("Article before, after, ratio: "+ beforeLength + ", " + afterLength + ", " + afterLength/beforeLength);
if (afterLength < 900 || afterLength/beforeLength < 0.50) {
page.innerHTML = pageCacheHtml;
// if (readability.flagIsActive(readability.FLAG_STRIP_UNLIKELYS)) {
// readability.removeFlag(readability.FLAG_STRIP_UNLIKELYS);
// if(readability.curPageNum === 1){
// localStorage.setItem("lens-flag-GH3UEgL6CbcpK4hNtQeR8Fc", readability.flags);
// }
// return readability.grabArticle(page);
// } else if (readability.flagIsActive(readability.FLAG_WEIGHT_CLASSES)) {
// readability.removeFlag(readability.FLAG_WEIGHT_CLASSES);
// if(readability.curPageNum === 1){
// localStorage.setItem("lens-flag-GH3UEgL6CbcpK4hNtQeR8Fc", readability.flags);
// }
// return readability.grabArticle(page);
// } else
// if (readability.flagIsActive(readability.FLAG_CLEAN_CONDITIONALLY)) {
// readability.removeFlag(readability.FLAG_CLEAN_CONDITIONALLY);
// if(readability.curPageNum === 1){
// localStorage.setItem("lens-flag-GH3UEgL6CbcpK4hNtQeR8Fc", readability.flags);
// }
// return readability.grabArticle(page);
// }
// else {
// if(readability.curPageNum === 1){
// // TODO - turn off for the whole domain or just the host/path?
// localStorage.setItem("lens-works-GH3UEgL6CbcpK4hNtQeR8Fc", "n");
// }
// return null;
// }
return null;
}
return articleContent;
},
getEditDistance: function(a, b){
var total = Math.abs(a.length - b.length);
for (var i = 0; i < Math.min(a.length, b.length); i++){
if (a[i]!=b[i]) {
total++;
}
}
return total;
},
/**
* Removes script tags from the document.
*
* @param Element
**/
removeScripts: function(element) {
var scripts = element.querySelectorAll('script,style,link,noscript');
for (var i = scripts.length - 1; i >= 0; i -= 1) {
scripts[i].nodeValue = "";
scripts[i].removeAttribute('src');
scripts[i].removeAttribute('rel');
scripts[i].removeAttribute('href');
if (scripts[i].parentNode) {
scripts[i].parentNode.removeChild(scripts[i]);
}
}
},
/**
* Get the inner text of a node - cross browser compatibly.
* This also strips out any excess whitespace to be found.
*
* @param Element
* @return string
**/
getInnerText: function(e, normalizeSpaces) {
var textContent = "";
if (typeof(e.textContent) === "undefined" && typeof(e.innerText) === "undefined") {
return "";
}
normalizeSpaces = (typeof normalizeSpaces === 'undefined') ? true : normalizeSpaces;
if (navigator.appName === "Microsoft Internet Explorer") {
textContent = e.innerText.replace(readability.regexps.trim, "");
} else {
textContent = e.textContent.replace(readability.regexps.trim, "");
}
if (normalizeSpaces) {
return textContent.replace(readability.regexps.normalize, " ");
} else {
return textContent;
}
},
/**
* Get the number of times a string s appears in the node e.
*
* @param Element
* @param string - what to split on. Default is ","
* @return number (integer)
**/
getCharCount: function(e, s) {
s = s || ",";
return readability.getInnerText(e).split(s).length - 1;
},
/**
* Remove the style attribute on every e and under.
* TODO: Test if getElementsByTagName(*) is faster.
*
* @param Element
* @return void
**/
cleanStyles: function(e) {
e = e || document;
var cur = e.firstChild;
if (!e) {
return;
}
// Remove any root styles, if we're able.
if (typeof e.removeAttribute === 'function' && e.className !== 'readability-styled') {
e.removeAttribute('style');
}
// Go until there are no more child nodes
while (cur !== null) {
if (cur.nodeType === 1) {
// Remove style attribute(s) :
if (cur.className !== "readability-styled") {
cur.removeAttribute("style");
}
readability.cleanStyles(cur);
}
cur = cur.nextSibling;
}
},
/**
* Get the density of links as a percentage of the content
* This is the amount of text that is inside a link divided by the total text in the node.
*
* @param Element
* @return number (float)
**/
getLinkDensity: function(e) {
var links = e.getElementsByTagName("a");
var textLength = readability.getInnerText(e).length;
var linkLength = 0;
for (var i = 0, il = links.length; i < il; i += 1) {
linkLength += readability.getInnerText(links[i]).length;
}
return linkLength / textLength;
},
/**
* Find a cleaned up version of the current URL, to use for comparing links for possible next-pageyness.
*
* @author Dan Lacy
* @return string the base url
**/