-
Notifications
You must be signed in to change notification settings - Fork 725
/
Copy pathBridge.js
executable file
·1139 lines (909 loc) · 34.6 KB
/
Bridge.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
//
// Bridge.js
// FolioReaderKit
//
// Created by Heberti Almeida on 06/05/15.
// Copyright (c) 2015 Folio Reader. All rights reserved.
//
var thisHighlight;
var audioMarkClass;
var wordsPerMinute = 180;
document.addEventListener("DOMContentLoaded", function(event) {
// var lnk = document.getElementsByClassName("lnk");
// for (var i=0; i<lnk.length; i++) {
// lnk[i].setAttribute("onclick","return callVerseURL(this);");
// }
});
// Generate a GUID
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
var guid = s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
return guid.toUpperCase();
}
// Get All HTML
function getHTML() {
Highlight.getHtmlAndSaveHighlight(document.documentElement.outerHTML);
//return document.documentElement.outerHTML;
}
// Class manipulation
function hasClass(ele,cls) {
return !!ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
if (!hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
if (hasClass(ele,cls)) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
}
// Font name class
function setFontName(cls) {
var elm = document.documentElement;
removeClass(elm, "andada");
removeClass(elm, "lato");
removeClass(elm, "lora");
removeClass(elm, "raleway");
addClass(elm, cls);
}
// Toggle night mode
function nightMode(enable) {
var elm = document.documentElement;
if(enable) {
addClass(elm, "nightMode");
} else {
removeClass(elm, "nightMode");
}
}
// Set font size
function setFontSize(cls) {
var elm = document.documentElement;
removeClass(elm, "textSizeOne");
removeClass(elm, "textSizeTwo");
removeClass(elm, "textSizeThree");
removeClass(elm, "textSizeFour");
removeClass(elm, "textSizeFive");
addClass(elm, cls);
}
// Menu colors
function setHighlightStyle(style) {
Highlight.getUpdatedHighlightId(thisHighlight.id, style);
}
function removeThisHighlight() {
return thisHighlight.id;
}
function removeHighlightById(elmId) {
var elm = document.getElementById(elmId);
elm.outerHTML = elm.innerHTML;
return elm.id;
}
function getHighlightContent() {
return thisHighlight.textContent
}
function getBodyText() {
return document.body.innerText;
}
// Method that returns only selected text plain
var getSelectedText = function() {
return window.getSelection().toString();
}
// Method that gets the Rect of current selected text
// and returns in a JSON format
var getRectForSelectedText = function(elm) {
if (typeof elm === "undefined") elm = window.getSelection().getRangeAt(0);
var rect = elm.getBoundingClientRect();
return "{{" + rect.left + "," + rect.top + "}, {" + rect.width + "," + rect.height + "}}";
}
// Method that call that a hightlight was clicked
// with URL scheme and rect informations
var callHighlightURL = function(elm) {
event.stopPropagation();
var URLBase = "highlight://";
var currentHighlightRect = getRectForSelectedText(elm);
thisHighlight = elm;
window.location = URLBase + encodeURIComponent(currentHighlightRect);
}
// Reading time
function getReadingTime() {
var text = document.body.innerText;
var totalWords = text.trim().split(/\s+/g).length;
var wordsPerSecond = wordsPerMinute / 60; //define words per second based on words per minute
var totalReadingTimeSeconds = totalWords / wordsPerSecond; //define total reading time in seconds
var readingTimeMinutes = Math.round(totalReadingTimeSeconds / 60);
return readingTimeMinutes;
}
/**
Get Vertical or Horizontal paged #anchor offset
*/
var getAnchorOffset = function(target, horizontal) {
var elem = document.getElementById(target);
if (!elem) {
elem = document.getElementsByName(target)[0];
}
if (horizontal) {
return document.body.clientWidth * Math.floor(elem.offsetTop / window.innerHeight);
}
return elem.offsetTop;
}
function scrollAnchor(id) {
window.location.hash = id;
}
function findElementWithID(node) {
if( !node || node.tagName == "BODY")
return null
else if( node.id )
return node
else
return findElementWithID(node)
}
function findElementWithIDInView() {
if(audioMarkClass) {
// attempt to find an existing "audio mark"
var el = document.querySelector("."+audioMarkClass)
// if that existing audio mark exists and is in view, use it
if( el && el.offsetTop > document.body.scrollTop && el.offsetTop < (window.innerHeight + document.body.scrollTop))
return el
}
// @NOTE: is `span` too limiting?
var els = document.querySelectorAll("span[id]")
for(indx in els) {
var element = els[indx];
// Horizontal scroll
if (document.body.scrollTop == 0) {
var elLeft = document.body.clientWidth * Math.floor(element.offsetTop / window.innerHeight);
// document.body.scrollLeft = elLeft;
if (elLeft == document.body.scrollLeft) {
return element;
}
// Vertical
} else if(element.offsetTop > document.body.scrollTop) {
return element;
}
}
return null
}
/**
Play Audio - called by native UIMenuController when a user selects a bit of text and presses "play"
*/
function playAudio() {
var sel = getSelection();
var node = null;
// user selected text? start playing from the selected node
if (sel.toString() != "") {
node = sel.anchorNode ? findElementWithID(sel.anchorNode.parentNode) : null;
// find the first ID'd element that is within view (it will
} else {
node = findElementWithIDInView()
}
playAudioFragmentID(node ? node.id : null)
}
/**
Play Audio Fragment ID - tells page controller to begin playing audio from the following ID
*/
function playAudioFragmentID(fragmentID) {
var URLBase = "play-audio://";
window.location = URLBase + (fragmentID?encodeURIComponent(fragmentID):"")
}
function bodyOrHtml() {
if ('scrollingElement' in document) {
return document.scrollingElement;
}
// Fallback for legacy browsers
if (navigator.userAgent.indexOf('WebKit') != -1) {
return document.body;
}
return document.documentElement;
}
/**
Go To Element - scrolls the webview to the requested element
*/
function goToElement(element) {
var scrollingElement = bodyOrHtml();
var top = scrollingElement.scrollTop;
var elementTop = element.offsetTop - 20;
var bottom = window.innerHeight + top;
var elementBottom = element.offsetHeight + element.offsetTop + 60;
//console.log(window);
//console.log("-> top = " + top);
//console.log("-> elementTop = " + elementTop);
//console.log("-> bottom = " + bottom);
//console.log("-> elementBottom = " + elementBottom);
if (FolioPageFragment.getDirection() == "VERTICAL" &&
(elementBottom > bottom || elementTop < top)) {
var newScrollTop = elementTop;
//console.log("-> newScrollTop = " + newScrollTop);
scrollingElement.scrollTop = newScrollTop;
} else if (FolioPageFragment.getDirection() == "HORIZONTAL" && top == 0) {
var clientWidth = document.documentElement.clientWidth;
var pageIndex = Math.floor(element.offsetLeft / clientWidth);
var newScrollLeft = clientWidth * pageIndex;
//console.log("-> newScrollLeft = " + newScrollLeft);
scrollingElement.scrollLeft = newScrollLeft;
WebViewPager.setCurrentPage(pageIndex);
}
return element;
}
/**
Remove All Classes - removes the given class from all elements in the DOM
*/
function removeAllClasses(className) {
var els = document.body.getElementsByClassName(className)
if( els.length > 0 )
for( i = 0; i <= els.length; i++) {
els[i].classList.remove(className);
}
}
//For testing purpose only
function sleep(seconds)
{
var e = new Date().getTime() + (seconds * 1000);
while (new Date().getTime() <= e) {}
}
// Mock objects for testing purpose
/*var FolioPageFragment = {
setHorizontalPageCount : function(pageCount) {
console.warn("-> Mock call to FolioPageFragment.setHorizontalPageCount(" + pageCount + ")");
},
storeFirstVisibleSpan : function(usingId, value) {
console.warn("-> Mock call to FolioPageFragment.storeFirstVisibleSpan(" + usingId + ", " + value + ")");
},
getDirection : function() {
//var direction = "VERTICAL";
var direction = "HORIZONTAL";
console.warn("-> Mock call to FolioPageFragment.getDirection(), return " + direction);
return direction;
}
};
var FolioWebView = {
setCompatMode : function(compatMode) {
console.warn("-> Mock call to FolioWebView.setCompatMode(" + compatMode + ")");
}
};
var WebViewPager = {
setCurrentPage : function(pageIndex) {
console.warn("-> Mock call to WebViewPager.setCurrentPage(" + pageIndex + ")");
},
setPageToLast : function() {
console.warn("-> Mock call to WebViewPager.setPageToLast()");
},
setPageToFirst : function() {
console.warn("-> Mock call to WebViewPager.setPageToFirst()");
}
};
var LoadingView = {
show : function() {
console.warn("-> Mock call to LoadingView.show()");
},
hide : function() {
console.warn("-> Mock call to LoadingView.hide()");
},
visible : function() {
console.warn("-> Mock call to LoadingView.visible()");
},
invisible : function() {
console.warn("-> Mock call to LoadingView.invisible()");
}
};*/
// Testing purpose calls
function test() {
getCompatMode();
wrappingSentencesWithinPTags();
if (FolioPageFragment.getDirection() == "HORIZONTAL")
initHorizontalDirection();
}
function scrollToLast() {
console.log("-> scrollToLast");
var direction = FolioPageFragment.getDirection();
var scrollingElement = bodyOrHtml();
if (direction == "VERTICAL") {
scrollingElement.scrollTop =
scrollingElement.scrollHeight - document.documentElement.clientHeight;
} else if (direction == "HORIZONTAL") {
scrollingElement.scrollLeft =
scrollingElement.scrollWidth - document.documentElement.clientWidth;
WebViewPager.setPageToLast();
}
LoadingView.hide();
}
function scrollToFirst() {
console.log("-> scrollToFirst");
var direction = FolioPageFragment.getDirection();
var scrollingElement = bodyOrHtml();
if (direction == "VERTICAL") {
scrollingElement.scrollTop = 0;
} else if (direction == "HORIZONTAL") {
scrollingElement.scrollLeft = 0;
WebViewPager.setPageToFirst();
}
LoadingView.hide();
}
function getCompatMode() {
FolioWebView.setCompatMode(document.compatMode);
}
var scrollWidth;
var horizontalInterval;
var horizontalIntervalPeriod = 1000;
var horizontalIntervalCounter = 0;
var horizontalIntervalLimit = 3000;
function horizontalRecheck() {
horizontalIntervalCounter += horizontalIntervalPeriod;
if (window.scrollWidth != document.documentElement.scrollWidth) {
// Rare condition
// This might happen when document.documentElement.scrollWidth gives incorrect value
// when the webview is busy re-drawing contents.
//console.log("-> horizontalIntervalCounter = " + horizontalIntervalCounter);
console.warn("-> scrollWidth changed from " + window.scrollWidth + " to " +
document.documentElement.scrollWidth);
postInitHorizontalDirection();
}
if (horizontalIntervalCounter >= horizontalIntervalLimit)
clearInterval(horizontalInterval);
}
function initHorizontalDirection() {
preInitHorizontalDirection();
postInitHorizontalDirection();
horizontalInterval = setInterval(horizontalRecheck, horizontalIntervalPeriod);
}
function preInitHorizontalDirection() {
//console.log(window);
//console.log("-> " + document.getElementsByTagName('title')[0].innerText);
var htmlElement = document.getElementsByTagName('html')[0];
var bodyElement = document.getElementsByTagName('body')[0];
// Required when initHorizontalDirection() is called multiple times.
// Currently it is called only once per page.
htmlElement.style.width = null;
bodyElement.style.width = null;
htmlElement.style.height = null;
bodyElement.style.height = null;
var bodyStyle = bodyElement.currentStyle || window.getComputedStyle(bodyElement);
var paddingTop = parseInt(bodyStyle.paddingTop, 10);
var paddingRight = parseInt(bodyStyle.paddingRight, 10);
var paddingBottom = parseInt(bodyStyle.paddingBottom, 10);
var paddingLeft = parseInt(bodyStyle.paddingLeft, 10);
//console.log("-> padding = " + paddingTop + ", " + paddingRight + ", " + paddingBottom + ", " + paddingLeft);
//document.documentElement.clientWidth is window.innerWidth excluding x scrollbar width
var pageWidth = document.documentElement.clientWidth - (paddingLeft + paddingRight);
//document.documentElement.clientHeight is window.innerHeight excluding y scrollbar height
var pageHeight = document.documentElement.clientHeight - (paddingTop + paddingBottom);
bodyElement.style.webkitColumnGap = (paddingLeft + paddingRight) + 'px';
bodyElement.style.webkitColumnWidth = pageWidth + 'px';
//console.log("-> window.innerWidth = " + window.innerWidth);
//console.log("-> window.innerHeight = " + window.innerHeight);
//console.log("-> clientWidth = " + document.documentElement.clientWidth);
//console.log("-> clientHeight = " + document.documentElement.clientHeight);
//console.log("-> bodyElement.offsetWidth = " + bodyElement.offsetWidth);
//console.log("-> bodyElement.offsetHeight = " + bodyElement.offsetHeight);
//console.log("-> pageWidth = " + pageWidth);
//console.log("-> pageHeight = " + pageHeight);
htmlElement.style.height = (pageHeight + (paddingTop + paddingBottom)) + 'px';
bodyElement.style.height = pageHeight + 'px';
}
function postInitHorizontalDirection() {
var htmlElement = document.getElementsByTagName('html')[0];
var bodyElement = document.getElementsByTagName('body')[0];
var bodyStyle = bodyElement.currentStyle || window.getComputedStyle(bodyElement);
var paddingTop = parseInt(bodyStyle.paddingTop, 10);
var paddingRight = parseInt(bodyStyle.paddingRight, 10);
var paddingBottom = parseInt(bodyStyle.paddingBottom, 10);
var paddingLeft = parseInt(bodyStyle.paddingLeft, 10);
var clientWidth = document.documentElement.clientWidth;
var scrollWidth = document.documentElement.scrollWidth;
//console.log("-> document.documentElement.offsetWidth = " + document.documentElement.offsetWidth);
if (scrollWidth > clientWidth
&& scrollWidth > document.documentElement.offsetWidth) {
scrollWidth += paddingRight;
}
var newBodyWidth = scrollWidth - (paddingLeft + paddingRight);
window.scrollWidth = scrollWidth;
htmlElement.style.width = scrollWidth + 'px';
bodyElement.style.width = newBodyWidth + 'px';
// pageCount deliberately rounded instead of ceiling to avoid any unexpected error
var pageCount = Math.round(scrollWidth / clientWidth);
var pageCountFloat = scrollWidth / clientWidth;
if (pageCount != pageCountFloat) {
console.warn("-> pageCount = " + pageCount + ", pageCountFloat = " + pageCountFloat
+ ", Something wrong in pageCount calculation");
}
//console.log("-> scrollWidth = " + scrollWidth);
//console.log("-> newBodyWidth = " + newBodyWidth);
//console.log("-> pageCount = " + pageCount);
FolioPageFragment.setHorizontalPageCount(pageCount);
}
/**
Audio Mark ID - marks an element with an ID with the given class and scrolls to it
*/
function audioMarkID(className, id) {
if (audioMarkClass)
removeAllClasses(audioMarkClass);
audioMarkClass = className
var el = document.getElementById(id);
goToElement(el);
el.classList.add(className)
}
function setMediaOverlayStyle(style){
document.documentElement.classList.remove("mediaOverlayStyle0", "mediaOverlayStyle1", "mediaOverlayStyle2")
document.documentElement.classList.add(style)
}
function setMediaOverlayStyleColors(color, colorHighlight) {
var stylesheet = document.styleSheets[document.styleSheets.length-1];
// stylesheet.insertRule(".mediaOverlayStyle0 span.epub-media-overlay-playing { background: "+colorHighlight+" !important }")
// stylesheet.insertRule(".mediaOverlayStyle1 span.epub-media-overlay-playing { border-color: "+color+" !important }")
// stylesheet.insertRule(".mediaOverlayStyle2 span.epub-media-overlay-playing { color: "+color+" !important }")
}
var currentIndex = -1;
function findSentenceWithIDInView(els) {
// @NOTE: is `span` too limiting?
for(indx in els) {
var element = els[indx];
// Horizontal scroll
if (document.body.scrollTop == 0) {
var elLeft = document.body.clientWidth * Math.floor(element.offsetTop / window.innerHeight);
// document.body.scrollLeft = elLeft;
if (elLeft == document.body.scrollLeft) {
currentIndex = indx;
return element;
}
// Vertical
} else if(element.offsetTop > document.body.scrollTop) {
currentIndex = indx;
return element;
}
}
return null
}
function findNextSentenceInArray(els) {
if(currentIndex >= 0) {
currentIndex ++;
return els[currentIndex];
}
return null
}
function resetCurrentSentenceIndex() {
currentIndex = -1;
}
function rewindCurrentIndex() {
currentIndex = currentIndex-1;
}
function getSentenceWithIndex(className) {
var sentence;
var sel = getSelection();
var node = null;
var elements = document.querySelectorAll("span.sentence");
// Check for a selected text, if found start reading from it
if (sel.toString() != "") {
console.log(sel.anchorNode.parentNode);
node = sel.anchorNode.parentNode;
if (node.className == "sentence") {
sentence = node
for(var i = 0, len = elements.length; i < len; i++) {
if (elements[i] === sentence) {
currentIndex = i;
break;
}
}
} else {
sentence = findSentenceWithIDInView(elements);
}
} else if (currentIndex < 0) {
sentence = findSentenceWithIDInView(elements);
} else {
sentence = findNextSentenceInArray(elements);
}
var text = sentence.innerText || sentence.textContent;
goToElement(sentence);
if (audioMarkClass){
removeAllClasses(audioMarkClass);
}
audioMarkClass = className;
sentence.classList.add(className)
return text;
}
function wrappingSentencesWithinPTags(){
currentIndex = -1;
"use strict";
var rxOpen = new RegExp("<[^\\/].+?>"),
rxClose = new RegExp("<\\/.+?>"),
rxSupStart = new RegExp("^<sup\\b[^>]*>"),
rxSupEnd = new RegExp("<\/sup>"),
sentenceEnd = [],
rxIndex;
sentenceEnd.push(new RegExp("[^\\d][\\.!\\?]+"));
sentenceEnd.push(new RegExp("(?=([^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*?$)"));
sentenceEnd.push(new RegExp("(?![^\\(]*?\\))"));
sentenceEnd.push(new RegExp("(?![^\\[]*?\\])"));
sentenceEnd.push(new RegExp("(?![^\\{]*?\\})"));
sentenceEnd.push(new RegExp("(?![^\\|]*?\\|)"));
sentenceEnd.push(new RegExp("(?![^\\\\]*?\\\\)"));
//sentenceEnd.push(new RegExp("(?![^\\/.]*\\/)")); // all could be a problem, but this one is problematic
rxIndex = new RegExp(sentenceEnd.reduce(function (previousValue, currentValue) {
return previousValue + currentValue.source;
}, ""));
function indexSentenceEnd(html) {
var index = html.search(rxIndex);
if (index !== -1) {
index += html.match(rxIndex)[0].length - 1;
}
return index;
}
function pushSpan(array, className, string, classNameOpt) {
if (!string.match('[a-zA-Z0-9]+')) {
array.push(string);
} else {
array.push('<span class="' + className + '">' + string + '</span>');
}
}
function addSupToPrevious(html, array) {
var sup = html.search(rxSupStart),
end = 0,
last;
if (sup !== -1) {
end = html.search(rxSupEnd);
if (end !== -1) {
last = array.pop();
end = end + 6;
array.push(last.slice(0, -7) + html.slice(0, end) + last.slice(-7));
}
}
return html.slice(end);
}
function paragraphIsSentence(html, array) {
var index = indexSentenceEnd(html);
if (index === -1 || index === html.length) {
pushSpan(array, "sentence", html, "paragraphIsSentence");
html = "";
}
return html;
}
function paragraphNoMarkup(html, array) {
var open = html.search(rxOpen),
index = 0;
if (open === -1) {
index = indexSentenceEnd(html);
if (index === -1) {
index = html.length;
}
pushSpan(array, "sentence", html.slice(0, index += 1), "paragraphNoMarkup");
}
return html.slice(index);
}
function sentenceUncontained(html, array) {
var open = html.search(rxOpen),
index = 0,
close;
if (open !== -1) {
index = indexSentenceEnd(html);
if (index === -1) {
index = html.length;
}
close = html.search(rxClose);
if (index < open || index > close) {
pushSpan(array, "sentence", html.slice(0, index += 1), "sentenceUncontained");
} else {
index = 0;
}
}
return html.slice(index);
}
function sentenceContained(html, array) {
var open = html.search(rxOpen),
index = 0,
close,
count;
if (open !== -1) {
index = indexSentenceEnd(html);
if (index === -1) {
index = html.length;
}
close = html.search(rxClose);
if (index > open && index < close) {
count = html.match(rxClose)[0].length;
pushSpan(array, "sentence", html.slice(0, close + count), "sentenceContained");
index = close + count;
} else {
index = 0;
}
}
return html.slice(index);
}
function anythingElse(html, array) {
pushSpan(array, "sentence", html, "anythingElse");
return "";
}
function guessSenetences() {
var paragraphs = document.getElementsByTagName("p");
Array.prototype.forEach.call(paragraphs, function (paragraph) {
var html = paragraph.innerHTML,
length = html.length,
array = [],
safety = 100;
while (length && safety) {
html = addSupToPrevious(html, array);
if (html.length === length) {
if (html.length === length) {
html = paragraphIsSentence(html, array);
if (html.length === length) {
html = paragraphNoMarkup(html, array);
if (html.length === length) {
html = sentenceUncontained(html, array);
if (html.length === length) {
html = sentenceContained(html, array);
if (html.length === length) {
html = anythingElse(html, array);
}
}
}
}
}
}
length = html.length;
safety -= 1;
}
paragraph.innerHTML = array.join("");
});
}
guessSenetences();
}
function isElementVisible(element, isHorizontal) {
var rect = element.getBoundingClientRect();
if(isHorizontal)
return rect.left > 0;
else
return rect.top > 0;
}
/**
Gets the first visible span from the displayed chapter and if it has id then usingId is true with
value as span id else usingId is false with value as span index. usingId and value is forwarded to
FolioPageFragment#storeFirstVisibleSpan(boolean, String) JavascriptInterface.
@param {boolean} isHorizontal - scrolling type of DirectionalViewpager#mDirection
*/
function getFirstVisibleSpan(isHorizontal) {
var spanCollection = document.getElementsByTagName("span");
if (spanCollection.length == 0) {
FolioPageFragment.storeFirstVisibleSpan(false, 0);
return;
}
var spanIndex = 0;
var spanElement;
for (var i = 0 ; i < spanCollection.length ; i++) {
if (isElementVisible(spanCollection[i], isHorizontal)) {
spanIndex = i;
spanElement = spanCollection[i];
break;
}
}
var usingId = spanElement.id ? true : false;
var value = usingId ? spanElement.id : spanIndex;
FolioPageFragment.storeFirstVisibleSpan(usingId, value);
}
/**
Scrolls the web page to particular span using id or index
@param {boolean} usingId - if span tag has id then true or else false
@param {number} value - if usingId true then span id else span index
*/
function scrollToSpan(usingId, value) {
if (usingId) {
var spanElement = document.getElementById(value);
if (spanElement)
goToElement(spanElement);
} else {
var spanCollection = document.getElementsByTagName("span");
if (spanCollection.length == 0 || value < 0 || value >= spanCollection.length
|| value == null) {
LoadingView.hide();
return;
}
goToElement(spanCollection[value]);
}
LoadingView.hide();
}
// Class based onClick listener
function addClassBasedOnClickListener(schemeName, querySelector, attributeName, selectAll) {
if (selectAll) {
// Get all elements with the given query selector
var elements = document.querySelectorAll(querySelector);
for (elementIndex = 0; elementIndex < elements.length; elementIndex++) {
var element = elements[elementIndex];
addClassBasedOnClickListenerToElement(element, schemeName, attributeName);
}
} else {
// Get the first element with the given query selector
var element = document.querySelector(querySelector);
addClassBasedOnClickListenerToElement(element, schemeName, attributeName);
}
}
function addClassBasedOnClickListenerToElement(element, schemeName, attributeName) {
// Get the content from the given attribute name
var attributeContent = element.getAttribute(attributeName);
// Add the on click logic
element.setAttribute("onclick", "onClassBasedListenerClick(\"" + schemeName + "\", \"" + encodeURIComponent(attributeContent) + "\");");
}
var onClassBasedListenerClick = function(schemeName, attributeContent) {
// Prevent the browser from performing the default on click behavior
event.preventDefault();
// Don't pass the click event to other elemtents
event.stopPropagation();
// Create parameters containing the click position inside the web view.
var positionParameterString = "/clientX=" + event.clientX + "&clientY=" + event.clientY;
// Set the custom link URL to the event
window.location = schemeName + "://" + attributeContent + positionParameterString;
}
function getHighlightString(style) {
var range = window.getSelection().getRangeAt(0);
var selectionContents = range.extractContents();
var elm = document.createElement("highlight");
var id = guid();
elm.appendChild(selectionContents);
elm.setAttribute("id", id);
elm.setAttribute("onclick","callHighlightURL(this);");
elm.setAttribute("class", style);
range.insertNode(elm);
thisHighlight = elm;
var params = [];
params.push({id: id, rect: getRectForSelectedText(elm)});
Highlight.getHighlightJson(JSON.stringify(params));
}
function goToHighlight(highlightId){
var element = document.getElementById(highlightId.toString());
if (element)
goToElement(element);
LoadingView.hide();
}
function goToAnchor(anchorId) {
var element = document.getElementById(anchorId);
if (element)
goToElement(element);
LoadingView.hide();
}
$(function(){
window.ssReader = Class({
$singleton: true,
init: function() {
rangy.init();
this.highlighter = rangy.createHighlighter();
this.highlighter.addClassApplier(rangy.createClassApplier("highlight_yellow", {
ignoreWhiteSpace: true,
tagNames: ["span", "a"]
}));
this.highlighter.addClassApplier(rangy.createClassApplier("highlight_green", {
ignoreWhiteSpace: true,
tagNames: ["span", "a"]
}));
this.highlighter.addClassApplier(rangy.createClassApplier("highlight_blue", {
ignoreWhiteSpace: true,
tagNames: ["span", "a"]
}));
this.highlighter.addClassApplier(rangy.createClassApplier("highlight_pink", {
ignoreWhiteSpace: true,
tagNames: ["span", "a"]
}));
this.highlighter.addClassApplier(rangy.createClassApplier("highlight_underline", {
ignoreWhiteSpace: true,
tagNames: ["span", "a"]
}));
},
setFontAndada: function(){
this.setFont("andada");
},
setFontLato: function(){
this.setFont("lato");
},
setFontPtSerif: function(){
this.setFont("pt-serif");
},