-
Notifications
You must be signed in to change notification settings - Fork 7
/
spree.js
696 lines (519 loc) · 20.4 KB
/
spree.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
/*Rendered nonfunctional as of 1/6/15 by request of Jamie Locke of Spritz Technology, Inc.*/
/*Uncommenting the call/listener to main would result in an ...apparently... infringing program... so beware!*/
/*What this tells about technology patents and the diligent 3 years of work Spritz did developing their serial reader I'll leave unsaid.*/
(function(W,D){
function main(){
/**DOM Handles**/
var body = D.body;
var mainContainer;
var globalNode;
var controls;
var controlPane;
var wpmDiv;
var colorSquares;
/**Counts, indexes, offsets**/
var wordCount=0;
var gap = 100;
var parentY=0;
var colorIndex = 0;
var textNodeIndex=0;
/**Flags**/
var active = 0;
var paused=0;
var stopSpree=0;
/**Tracking Arrays**/
var paragraph=[];
var leftovers=[];
/**Style shortcuts and global colors**/
var containerText = "<div class='spreeaftwrap'><span class='spreeText' style='margin-left:-50px'>Infringer!</span></div>";
var borderStyle;
var cssText;
var colors = ["#FFA500","#99793D","#FF6200","#40FFCE","#00FF76","#FFCF40","#1500FF","#773D99","#A000FF","#FF8700","#5E3D99","#444444","#00B5FF","#998B3D","#00F8FF","#FF0F26"];
var backgroundColors = ["#ffd530", "#c9a96d", "#ff9230", "#70fffe", "#30ffa6", "#ffff70", "#4530ff", "#a76dc9", "#d030ff", "#ffb730", "#8e6dc9", "#747474", "#30e5ff", "#c9bb6d", "#30ffff", "#ff3f56"];
var pauseWord = " (code) ";
/**Convenience**/
var innerHeight;
var indexOf = Array.prototype.indexOf;
/**Get a function that manages UI state in its closure**/
var toggleControls=function(){
var showing = 0;
var firstCall = 1;
return function (force){
if(firstCall){
buildControlPane();
firstCall = 0;
}
if(showing||force){
controls.innerText = "Controls \u25BE";
controlPane.style.cssText ="width:0;height:0;";
showing = 0;
}else{
controls.innerText = "Controls \u25B4";
controlPane.style.cssText = "width:140px;height:140px";
showing = 1;
}
}
}();
/**Dynamically add styles. Allows full app to work as a bookmarklet**/
/**without external requests. Ugly, but functional.**/
var spreeSheet = (function() {
var style = D.createElement("style");
style.appendChild(D.createTextNode(""));
D.head.appendChild(style);
var sheet = style.sheet;
sheet.addRule("#spreeCon","color:#444;width:600px;height:100px;top:50%;left:50%;margin:-50px 0 0 -300px;box-shadow:0 4px 6px -4px #666, 0 1px 2px 0 #666;text-align:left;font-size:36px;line-height:100px;font-weight:300;padding:0;",0);
sheet.addRule(".spreeaftwrap","float:right;font-size:36px;border:0;width:350px;line-height:100px;display:inline-block;background:#fffefc;",1);
sheet.addRule(".spreeaftwrap >span","float:left;line-height:100px;font-size:36px;",2);
sheet.addRule("#spreewpm","top:10px;left:10px;",3);
sheet.addRule("#spreeControls","top:10px;right:10px;-webkit-touch-callout: none;-webkit-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;",4);
sheet.addRule('#spreeControls:hover','cursor:pointer',5)
sheet.addRule(".spreeaftwrap>span:before",'content: "";border-left: 2px solid transparent;border-right:2px solid transparent; border-top:25px solid #666;height: 0;width:0;position:absolute;left: 247px;',6)
sheet.addRule(".spreeaftwrap>span:after",'content: "";border-left: 2px solid transparent;border-right:2px solid transparent; border-bottom:25px solid #666;height:0;width:0;position:absolute;left: 248px;bottom:0px;',7)
sheet.addRule(".spreeHL","background-color:#ffd530;",8);
sheet.insertRule("@media screen and (max-width : 600px){.spreeCon{margin:-50px 0 0 0; width:100%;left:0}.spreeaftwrap{width:60%;}.spreeaftwrap>span:before,.spreeaftwrap>span:after{left:39.4%;}}",9);
sheet.addRule(".spreeCon >span","line-height:100px",10);
sheet.addRule("#spreeControlPane","top:33px;right:10px;width:0;height:0;overflow:hidden;padding:0;box-shadow:0px 2px 1px -1px #666;-webkit-transition: height 0.1s ease-out,width 0.1s ease-out;-moz-transition: height 0.1s ease-out,width 0.1s ease-out;-o-transition: height 0.1s ease-out,width 0.1s ease-out;transition: height 0.1s ease-out,width 0.1s ease-out;",11);
sheet.addRule(".spreeAtop","position:fixed;background:#fffefc;text-align:center;box-shadow:0 1px 1px 0 #666;z-index:591233;padding:2px 4px;width:auto;height:auto;font-size:14px;font-family:Helvetica;",12)
sheet.addRule(".spreeColor","width:35px;height:35px;float:left;",13);
sheet.addRule("#colorDiv","width:140px;height:140px;background:#fffefc;float:right;margin:0;padding:0;border:0;",14)
sheet.addRule("#colorDiv:hover","cursor:pointer;",15);
sheet.addRule(".spreeColor:active","opacity:0.7",16);
sheet.addRule(".spreeText","color:#ffa500;",17);
return sheet;
})();
/**If using the extension, pull in saved settings**/
if(chrome&&chrome.storage){
chrome.storage.sync.get(null,function(obj){
if(obj.gap) gap = obj.gap;
if(obj.colorIndex) colorIndex = obj.colorIndex;
});
}
/**Added main listener, entry point into app**/
W.addEventListener("mousedown",function(e){
var node = e.target;
var tag = node.tagName;
/**Activate on alt-click, on sensible elements**/
if( e.altKey === true &&
active === 0 &&
tag !== "HTML" &&
tag !== "SELECT" &&
tag !== "INPUT" &&
tag !== "TEXTAREA" &&
(e.button===0||(document.all&&e.button===1))
){
stopSpree=0;
active=1;
/**query window/node state**/
parentY = getYOffset(node.offsetParent, 0);
innerHeight = W.innerHeight;
/**apply preferences before display**/
setBorderStyle(node);
setColor(colorIndex);
/**initialize UI widgets on first activation, otherwise show them**/
if(mainContainer){
showPane(mainContainer);
showPane(controls);
showPane(controlPane);
showPane(wpmDiv);
}else{
initializeUI();
}
/**show speed and kick off word display**/
updateWpm(60000/(gap+50));
setTimeout(function(){spree(node,mainContainer)},500);
/**add listeners for ui and interrupts**/
W.addEventListener("keydown",key);
controls.addEventListener("mousedown",mouse);
}
});
/**create each UI component, saving them in app-wide variables **/
function initializeUI(){
mainContainer = addPane({
id: "spreeCon",
className: "spreeAtop spreeText",
innerHTML: containerText
});
controls = addPane({
id:'spreeControls',
className:'spreeAtop spreeText',
innerText :"Controls \u25BE"
});
controlPane = addPane({
id:'spreeControlPane',
className:'spreeAtop spreeText'
});
wpmDiv = addPane({
id:'spreewpm',
className:'spreeAtop spreeText'
});
/**Convenience function for adding UI elements to the body**/
function addPane(obj){
var elem = D.createElement('div');
for(var prop in obj){
if(obj.hasOwnProperty(prop)){
elem[prop] = obj[prop];
}
}
body.appendChild(elem);
return elem;
}
}
/**reattach pre-generated nodes to the DOM**/
function showPane(node){
body.appendChild(node);
return node;
}
/**Apply paragraph-focusing border. Color set to color choice.**/
function setBorderStyle(node){
var s = W.getComputedStyle(node)
, pd = +s.paddingLeft.slice(0,-2)
, brd = +s.borderLeft.split(" ")[0].slice(0,-2)
, mrg = +s.marginLeft.slice(0,-2)
;
borderStyle="margin-left:"+(pd+brd+mrg-13)+"px;padding-left:10px;border-left:3px solid "+colors[colorIndex]+";"
}
/**Word display function. Heart of the functionality**/
function spree(node,box){
/**Walk the DOM for text nodes and store their values**/
fillParagraph(node);
var nextParagraph = node.nextElementSibling;
/**Empty paragraph, move on or stop**/
if(!paragraph.length){
if(nextParagraph) return setTimeout(function(){spree(nextParagraph,box)});
else return
}
var nodesInParagraph = paragraph.length-1;
var words = paragraph[textNodeIndex].words;
var nodeWordLength = words.length;
/**Update globals**/
wordCount=0;
globalNode = node;
cssText = node.style.cssText;
node.style.cssText = borderStyle;
/**Scroll page when an offpage node is reached**/
if(node.offsetTop+node.clientHeight+parentY >innerHeight+W.scrollY){
W.scrollTo(0,node.offsetTop+parentY-50);
}
/**Word display recursive loop**/
(function addWord(){
if(stopSpree)return;
if(paused){
/**pass closure to be called when unpaused**/
togglePause.callback=addWord;
return;
}
/**Get next word, from this node, next node or from a split word**/
if(textNodeIndex < nodesInParagraph || wordCount < nodeWordLength || leftovers.length){
var word;
var offset=0;
/**use leftover bits of previously split words first**/
if(leftovers.length)
word = leftovers.shift();
else{
if(wordCount === nodeWordLength){
words = paragraph[++textNodeIndex].words;
nodeWordLength = words.length;
wordCount = 0;
}
word = words[wordCount++];
}
if(word.length > 20)
word = splitWord(word);
/**Add word and set offset modifiers**/
if(word.length){
createText(word,box);
var first = word[0];
var last = word[word.length-1];
if(first===first.toUpperCase())offset += gap/1.5;
if(last===','||last===';')offset+=gap/5;
else if(last==='.'||last==='?'||last==='!')offset+=gap/2.5;
}
/**Set delay until the next word's display and propagate to wpm calculation**/
var delay=gap+offset+word.length*8;
checkWpm(delay);
setTimeout(addWord,delay);
}else{
/**Clean shared variables, break from addWord loop, and run spree on the next paragraph**/
cleanup();
if(nextParagraph)
setTimeout(function(){spree(nextParagraph,box)},0);
}
})();
}
/**recursively find text nodes and add them to the paragraph array**/
/**The objects in the paragraph array track the words, whitespace, and the node**/
function fillParagraph(node){
var tag = node.tagName;
if(tag == "PRE")paragraph.push({words:[pauseWord],gaps:["",""],node:node})
if(tag=="IMG"||tag=="SCRIPT"||tag=="EMBED"||tag=="PRE"||tag=="VIDEO"||tag=="TABLE"||tag=="FORM"||tag=="FIGURE") return;
var nodes = node.childNodes;
var len=nodes.length;
if(len){
for(var i=0; i<len; i++)
fillParagraph(nodes[i])
}else{
if(node.nodeType === 3){
paragraph.push({
words:node.nodeValue.split(/\s+/),
gaps:node.nodeValue.split(/\S+/),
node:node
});
}
}
}
/**Recursively sum offset top values until body/html is reached**/
/**Get the 'absolute' position for elements positioned in any way**/
function getYOffset(node,val){
if (node === body||node===null)return val;
return getYOffset(node.offsetParent,val+node.offsetTop);
}
/**Process word for display, allows for focal letter**/
function createText(word,box){
var pausing = word === pauseWord;
var focus=word.length/3>>0;
var pre = D.createElement('span');
var foc = D.createElement('span');
var aft = D.createElement('span');
var wrap = D.createElement('div');
pre.style.float="right";
foc.className = "spreeText";
wrap.className='spreeaftwrap';
if(pausing){
foc.innerText = word;
}else{
pre.innerText=word.slice(0,focus);
foc.innerText=word[focus];
aft.innerText=word.slice(focus+1);
}
wrap.appendChild(foc);
wrap.appendChild(aft);
box.innerHTML='';
box.appendChild(wrap);
box.appendChild(pre);
var center = foc.offsetWidth/-2;
foc.style.marginLeft=center+"px";
pre.style.marginRight=-center+"px";
if(pausing) togglePause(0)
}
/**Pausing logic. Call the last set callback, which has node/text in its closure**/
/**Call the in-page word highlighter if the user initiated the pause**/
function togglePause(userPause){
if(paused){
paused=0;
if(userPause)clearHighlight();
togglePause.callback();
}else{
paused = 1;
if(userPause)highlight();
}
}
togglePause.callback=function(){};
/**Split long words into multiple, hyphenated words**/
/**Return the first, and process the remain bits before any new words**/
function splitWord(word){
var start =0
, end = 10
, len = word.length
, newWord
, subWord
;
while(start < len){
subWord = word.slice(start,end);
if(end<len) subWord+="-"
if(start===0)newWord = subWord;
else leftovers.push(subWord)
start+=10;
end+=10
}
return newWord
}
/**Set speed on up/down, saving it if this is the extension**/
function setSpeed(code){
var factor = gap/5;
if(code===38)gap-=factor;
else gap+=factor;
if(gap<10)gap=10;
if(chrome&&chrome.storage){
chrome.storage.sync.set({gap:gap})
}
var wpm = 60000/(gap+50);
updateWpm(wpm);
}
/**Reflect new WPM in the UI**/
function updateWpm(wpm){
wpmDiv.innerText='~'+wpm.toString().slice(0,6)+" wpm";
}
/**On left arrow, move back ten words, or to the start of the paragraph**/
function rewind(){
wordCount-=10;
if (wordCount < 0) wordCount = 0;
}
/**Every 50 words, update the wpm display with the average wpm for the block**/
function checkWpm(delay){
var wpmArr = checkWpm.arr;
wpmArr.push(delay);
if (wpmArr.length === 50){
var sum=0;
for(var i=0; i<50; i++){
sum+=wpmArr[i];
}
updateWpm(60000/(sum/50));
wpmArr.length=0;
}
}
checkWpm.arr=[];
/**Generate control pane from the list of colors and hook up listeners**/
function buildControlPane(){
var colorDiv = D.createElement('div');
colorDiv.id = "colorDiv";
colors.forEach(function(v){
var node = D.createElement('div')
node.className = "spreeColor";
node.style.backgroundColor = v;
colorDiv.appendChild(node);
});
controlPane.appendChild(colorDiv);
colorSquares = colorDiv.children;
controlPane.addEventListener("mouseover",mouseOverColorSet);
controlPane.addEventListener("mousedown",mouseDownColorSet);
controlPane.addEventListener("mouseout",mouseOutColorSet);
}
/**Get and set the color from the list at the same index as the target node**/
function mouseOverColorSet(e){
setColor(indexOf.call(colorSquares,e.target))
}
/**Save the targeted color globally and remember it if in the extension**/
function mouseDownColorSet(e){
colorIndex = indexOf.call(colorSquares,e.target);
if(chrome&&chrome.storage){
chrome.storage.sync.set({colorIndex:colorIndex});
}
}
/**If leaving the box of colors, reapply the saved color**/
function mouseOutColorSet(e){
if(!e.toElement||e.toElement.className !== "spreeColor"){
setColor(colorIndex);
}
}
/**Apply color change to UI elements**/
function setColor(index){
if(index !== -1){
var rules = spreeSheet.rules;
rules[17].style.color = colors[index];
rules[8].style.backgroundColor = backgroundColors[index];
borderStyle = borderStyle.slice(0,-8) + colors[index] +';';
setParagraphBorder(borderStyle);
}
}
/**Highlight the current word on the page when the user pauses**/
function highlight(){
var textObj = paragraph[textNodeIndex];
if(!textObj) return;
var words=textObj.words;
var gaps = textObj.gaps;
var node = textObj.node;
if(!node) return;
var hlInd = wordCount-1;
var firstPart = '';
var secondPart = '';
/**Copy the text of the paragraph before current word**/
for(var ind=0;ind<hlInd;ind++){
firstPart += gaps[ind] + words[ind];
}
firstPart+=gaps[hlInd]
/**Copy the text of the paragraph after the current word**/
for(ind = hlInd+1;ind<gaps.length;ind++){
var addition = gaps[ind];
if (words[ind]) addition += words[ind]
secondPart+=addition;
}
/**Create new nodes from the copied text**/
var firstNode=D.createTextNode(firstPart);
var secondNode=D.createTextNode(secondPart);
/**Make the highlighted node**/
var hlWord = textObj.words[hlInd];
var hlNode=D.createElement('span');
hlNode.className='spreeHL';
hlNode.innerText=hlWord;
/**Replace the old node with our newly made nodes**/
var parNode = node.parentNode;
parNode.insertBefore(firstNode,node);
parNode.insertBefore(hlNode,node);
parNode.insertBefore(secondNode,node);
parNode.removeChild(node);
}
/**Replace a highlighted paragraph with its normal form**/
function clearHighlight(){
var hlNode = D.getElementsByClassName("spreeHL")[0];
if(!hlNode)return;
var node = paragraph[textNodeIndex].node;
var firstNode = hlNode.previousSibling;
var secondNode = hlNode.nextSibling;
var parNode = hlNode.parentNode;
parNode.insertBefore(node,firstNode);
parNode.removeChild(firstNode);
parNode.removeChild(hlNode);
parNode.removeChild(secondNode);
}
/**Set paragraph border, global to allow for easy use in cleanup**/
function setParagraphBorder(css){
if(globalNode) globalNode.style.cssText=css;
}
/**Set the starting text to "Spree...".. to give the reader a warmup time**/
function setStartText(){
mainContainer.innerHTML="<div class='spreeaftwrap'><span class='spreeText' style='margin-left:-50px'>Spree...</span></div>"
}
/**Wipe references to the current node and clear the paragraph array**/
function cleanup(){
setParagraphBorder(cssText);
globalNode = null;
paragraph.length = 0;
textNodeIndex = 0;
}
/**Stop spree**/
function stop(){
stopSpree=1;
active = 0;
parentY=0;
paused=0;
/**Remove UI elements from the DOM**/
body.removeChild(mainContainer);
body.removeChild(wpmDiv);
body.removeChild(controls);
body.removeChild(controlPane);
/**Reset controls/components/variables**/
clearHighlight();
setStartText();
toggleControls(1);
cleanup();
/**Remove listeners**/
W.removeEventListener("keydown",key);
controls.removeEventListener("mousedown",mouse);
}
/**Keydown handler, up/down for speed, left to rewind, space to pause, ignore alt**/
function key(e){
e.preventDefault();
var code = e.keyCode;
if(code===18) return;
if(code===38||code===40)return setSpeed(code);
if(code===32)return togglePause(1);
if(code===37)return rewind();
stop();
}
/**Mousedown handler to toggle controls**/
function mouse(){
toggleControls(0);
W.addEventListener("mousedown",tog);
}
/**Force the controls closed with a mousedown anywhere after they have been open**/
function tog(e){
if(e.target !== controls && e.target.className !== "spreeColor"){
toggleControls(1);
W.removeEventListener("mousedown",tog)
}
}
} /**Exit main**/
/**Run main once the DOM has loaded**/
//if(D.readyState === "loaded"||D.readyState === "complete") main();
//else W.addEventListener("DOMContentLoaded",main);
})(window,document);