forked from booktype/BookJS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbook.js
1642 lines (1399 loc) · 65.6 KB
/
book.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
/*!
* BookJS
* Copyright 2012-13 Steven Levithan, and Johannes Wilm. Freely available
* under the AGPL. For further details see LICENSE.txt
*
* Using this library you can turn an HTML element into a series
* of pages using CSS Regions. If the browser doesn't support CSS Regions,
* everything will be flown into one large page container that looks like a
* very long page.
*
*
* HOWTO
*
* In order to use this library, link to this javascript file within your html
* code.
* If you need to set custom options, set them before including this javascript
* file by defining an object named paginationConfig and setting the
* customization options as keys within this object. If you want to style the
* output in a specific way, customize the pagination.css file and include it, like
* this:
*
* <link href="pagination.css" rel="stylesheet" type="text/css" />
* <script type="text/javascript">
* paginationConfig = {
* 'sectionStartMarker': 'h3',
* 'columns': 3,
* 'autoStart': false,
* }
* </script>
* <script src="pagination.js" type="text/javascript"></script>
*
* OPTIONS
*
* The following options are available to customize the pagination behavior. In
* the descriptions below you can see the default values for these options. You
* only need to specify the options if you want to deviate from the default
* value.
*
* sectionStartMarker: 'h1' -- This is the HTML element we look for to find where
* a new section starts.
*
* sectionTitleMarker: 'h1' -- Within the newly found section, we look for the
* first instance of this element to determine the title of the section.
*
* chapterStartMarker: 'h2' -- This is the HTML element we look for to find where
* a new chapter starts.
*
* chapterTitleMarker: 'h2' -- Within the newly found chapter, we look for the
* first instance of this element to determine the title of the chapter.
*
* flowElement: 'document.body' -- This specifies element the container element
* of the content we will flow into pages. You can use any javascript selector
* here, such as "document.getElementById('contents')" .
*
* alwaysEven: false -- This determines whether each section and chapter should
* have an even number of pages (2, 4, 6, 8, ...).
*
* columns: 1 -- This specifies the number of number of columns used for the
* body text.
*
* enableFrontmatter: true -- This resolves whether a table of contents, page\
* headers and other frontmatter contents should be added upon page creation.
* Note: divideContents has to be true if one wants the frontmatter to render.
*
* bulkPagesToAdd: 50 -- This is the initial number of pages of each flowable
* part (section, chapter). After this number is added, adjustments are made by
* adding another bulk of pages or deleting pages individually. It takes much
* less time to delete pages than to add them individually, so it is a point to
* overshoot the target value. For larger chapters add many pages at a time so
* there is less time spent reflowing text.
*
* pagesToAddIncrementRatio: 1.4 -- This is the ratio of how the bulk of pages
* incremented. If the initial bulkPagestoAdd is 50 and those initial 50 pages
* were not enough space to fit the contents of that chapter, then next
* 1.4 * 50 = 70 are pages, for a total of 50+70 = 120 pages, etc. . 1.4 seems
* to be the fastest in most situations.
*
* frontmatterContents: none -- These are the HTML contents that are added to
* the frontmatter before the table of contents. This would usually be a title
* page and a copyright page, including page breaks.
*
* autoStart: true -- This controls whether pagination should be executed
* automatically upon page load. If it is set to false, pagination has to be
* initiated manually. See below under "methods."
*
* numberPages: true -- This controls whether page numbers should be used. If
* page numbers are not used, the table of contents is automatically left out.
*
* divideContents: true -- This controls whether the contents are divdided up
* according to sections and chapters before flowing. CSS Regions take a long
* time when more than 20-30 pages are involved, which is why it usually makes
* sense to divide the contents up. However, if the contents to be flown takes
* up less space than this, there is no need to do this division. The added
* benefit of not doing it is that the original DOM of the part that contains
* the conents will not be modified. Only the container element that holds the
* contents will be assigned another CSS class. Note: divideContents has to be
* true if one wants the frontmatter to render.
*
* maxPageNumber: 10000 -- This controls the maximum amount of pages. If more
* pages than this are added, BookJS will die. Notice that pages are added
* incrementally, so you won't be able to control the exact number of pages.
* You should always set this to something much larger than what you will ever
* expect that you book will need.
*
* topfloatSelector: '.pagination-topfloat' -- This is the CSS selector used
* for finding top floats within the HTML code. Top floats are placed on the
* page either of the reference or the one following it. In editing
* environments, the top float should be inserted inside two additional
* elements, like this:
*
* <span class='pagination-topfloat'><span><span>This is the top float contents
* </span></span></span>
*
* footnoteSelector: '.pagination-footnote' -- This is the CSS selector used
* for finding footnotes within the HTML code. Footnotes are automatically
* moved if the page of their reference changes. In editing environments, the
* footnote should be inserted inside two additional elements, like this:
*
* <span class='pagination-footnote'><span><span>This is a footnote</span>
* </span></span>.
*
* Page style options
*
* These settings provide a way to do simple styling of the page. These
* settings are different from the baove ones in that they can be overriden
* through CSS to provide more advanced designs (see the above note on
* pagination.css).
*
* outerMargin: .5 (inch)-- This controls the margin on the outer part of the
* page.
*
* innerMargin: .8 (inch)-- This controls the margin on the inenr part of the
* page.
*
* contentsTopMargin: .8 (inch)-- This controls the margin between the top of
* the page and the top of the contents.
*
* headerTopMargin: .3 (inch) -- This controls the margin between the top of
* the page and the top of the page headers.
*
* contentsBottomMargin: .8 (inch) -- This controls the margin between the
* bottom of the page and the bottom of the contents.
*
* pagenumberBottomMargin: .3 (inch) -- This controls the margin between the
* bottom of the page and the bottom of the page number.
*
* pageHeight: 8.3 (inch) -- This controls the height of the page.
*
* pageWidth: 5.8 (inch) -- This controls the width of the page.
*
* columnSeparatorWidth: .09 (inch) -- This is the space between columns.
*
* lengthUnit: 'in' (inch) -- Use this to specify the unit used in all the page
* style options. It can be any unit supported by CSS.
*
* METHODS
*
* Changing the page style after initialization
*
* At times the user might want to change the page design or page size after
* BookJS has started -- for example to look at the same text in different page
* sizes. To do this, he has to change all the page style options which are now
* located inside paginationConfig and run pagination.setPageStyle(). Like
* this:
*
* paginationConfig['pageHeight'] = 11;
* paginationConfig['pageWidth'] = 8;
* pagination.setPageStyle();
*
* Initializing page flowing after loading
*
* If one chooses not to flow the pages automatically upon page loading, it has
* to be initiated manually by calling pagination.applyBookLayout() or
* pagination.applySimpleBookLayout() in case CSS Regions are not present.
*
* Check whether CSS regions are present.
*
* pagination._cssRegionCheck() will return true or false, depending on whether
* CSS Regions are present or not.
*
*/ (function () {
var exports = this,
defaults,
pagination = {};
// pagination is the object that contains the namespace used by BookJS.
defaults = {
// pagination.config starts out with default config options.
'sectionStartMarker': 'h1',
'sectionTitleMarker': 'h1',
'chapterStartMarker': 'h2',
'chapterTitleMarker': 'h2',
'flowElement': 'document.body',
'alwaysEven': false,
'columns': 1,
'enableFrontmatter': true,
'bulkPagesToAdd': 50,
'pagesToAddIncrementRatio': 1.4,
'frontmatterContents': '',
'autoStart': true,
'numberPages': true,
'divideContents': true,
'footnoteSelector': '.pagination-footnote',
'topfloatSelector': '.pagination-topfloat',
'marginnoteSelector': '.pagination-marginnote',
'maxPageNumber': 10000,
'columnSeparatorWidth': 0.09,
'outerMargin': 0.5,
'innerMargin': 0.8,
'contentsTopMargin': 0.8,
'headerTopMargin': 0.3,
'contentsBottomMargin': 0.8,
'pagenumberBottomMargin': 0.3,
'pageHeight': 8.3,
'pageWidth': 5.8,
'lengthUnit': 'in'
};
// help functions
pagination.romanize = function () {
// Create roman numeral representations of numbers.
var digits = String(+this.value).split(""),
key = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM",
"",
"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", "",
"I", "II",
"III", "IV", "V", "VI", "VII", "VIII", "IX"
],
roman = "",
i = 3;
while (i--) {
roman = (key[+digits.pop() + (i * 10)] || "") + roman;
}
return new Array(+digits.join("") + 1).join("M") + roman;
};
pagination.createRandomId = function (base) {
// Create a random CSS Id that is not in use already.
var randomId, stillSearchingForUniqueId = true;
while (stillSearchingForUniqueId) {
randomId = base + Math.floor(Math.random() * 100000);
if (!document.getElementById(randomId)) {
stillSearchingForUniqueId = false;
}
}
return randomId;
};
pagination.pageStyleSheet = document.createElement('style');
pagination.initiate = function () {
/* Initiate BookJS by importing user set config options and setting basic
* CSS style.
*/
this.setStyle();
this.setPageStyle();
document.head.insertBefore(
pagination.pageStyleSheet,
document.head.firstChild);
};
pagination.config = function (configKey) {
/* Return configuration variables either from paginationConfig if present,
* or using default values.
*/
var returnValue;
if (paginationConfig && paginationConfig.hasOwnProperty(configKey)) {
returnValue = paginationConfig[configKey];
} else if (defaults.hasOwnProperty(configKey)) {
returnValue = defaults[configKey];
} else {
returnValue = false;
}
return returnValue;
};
pagination.setStyle = function () {
/* Set style for the regions and pages used by BookJS and add it to the
* head of the DOM.
*/
var stylesheet = document.createElement('style');
stylesheet.innerHTML =
".pagination-contents-container {display: -webkit-flex; " +
"-webkit-flex-direction: column; position: absolute;}" +
"\n.pagination-contents {display: -webkit-flex; -webkit-flex: 1;}"
/* There seems to be a bug in the new flexbox model code which requires the
* height to be set to an arbitrary value (which is ignored).
*/ + "\n.pagination-contents {height: 0px;}" +
"\n.pagination-contents-column {-webkit-flex: 1;}" + "\nbody {" +
"counter-reset: pagination-footnote pagination-footnote-reference;}" +
"\n.pagination-footnote::before {" +
"counter-increment: pagination-footnote-reference; " +
"content: counter(pagination-footnote-reference);}" +
"\n.pagination-footnote > * > *:first-child::before {" +
"counter-increment: pagination-footnote;" +
"content: counter(pagination-footnote);}" +
"\n.pagination-footnote > * > * {display: block;}" +
"\n.pagination-page {page-break-after: always; position: relative;}" +
"\nimg {-webkit-region-break-before: always; " +
"-webkit-region-break-after: always;}" +
"\n.pagination-pagenumber, .pagination-header {position: absolute;}" +
"\n.pagination-pagebreak {-webkit-region-break-after: always;}" +
"\n.pagination-simple {height: auto; position-relative;}" +
"\n.pagination-page {margin-left:auto; margin-right:auto;}";
document.head.appendChild(stylesheet);
};
pagination.setPageStyle = function () {
// Set style for a particular page size.
var unit = pagination.config('lengthUnit'),
contentsWidthNumber = pagination.config('pageWidth') - pagination.config(
'innerMargin') - pagination.config('outerMargin'),
contentsWidth = contentsWidthNumber + unit,
contentsColumnSeparatorWidthNumber = pagination.config('columnSeparatorWidth'),
contentsColumnSeparatorWidth = contentsColumnSeparatorWidthNumber + unit,
columnWidth = contentsWidthNumber / pagination.config('columns') -
(contentsColumnSeparatorWidthNumber * (pagination.config('columns') - 1))
+ unit,
contentsHeightNumber = pagination.config('pageHeight') - pagination
.config('contentsTopMargin') - pagination.config(
'contentsBottomMargin'),
contentsHeight = contentsHeightNumber + unit,
pageWidth = pagination.config('pageWidth') + unit,
pageHeight = pagination.config('pageHeight') + unit,
contentsBottomMargin = pagination.config('contentsBottomMargin') +
unit,
innerMargin = pagination.config('innerMargin') + unit,
outerMargin = pagination.config('outerMargin') + unit,
pagenumberBottomMargin = pagination.config('pagenumberBottomMargin') +
unit,
headerTopMargin = pagination.config('headerTopMargin') + unit,
imageMaxHeight = contentsHeightNumber - .1 + unit,
imageMaxWidth = contentsWidthNumber - .1 + unit;
pagination.pageStyleSheet.innerHTML =
".pagination-page {height:" + pageHeight + "; width:" + pageWidth +
";" + "background-color: #fff;}" + "\n@page {size:" + pageWidth +
" " + pageHeight + ";}" + "\nbody {background-color: #efefef;}"
// A .page.simple is employed when CSS Regions are not accessible
+ "\n.pagination-simple {padding: 1in;}"
// To give the appearance on the screen of pages, add a space of .2in
+ "\n@media screen{.pagination-page {border:solid 1px #000; " +
"margin-bottom:.2in;}}" +
"\n.pagination-contents-container {height:" + contentsHeight + ";" +
"width:" + contentsWidth + ";" + "bottom:" + contentsBottomMargin +
";}"
// Images should at max size be slightly smaller than the contentsWidth.
+ "\nimg {max-height: " + imageMaxHeight + ";max-width: " +
imageMaxWidth + ";}" + "\n.pagination-pagenumber {bottom:" +
pagenumberBottomMargin + ";}" + "\n.pagination-header {top:" +
headerTopMargin + ";}" +
"\n#pagination-toc-title:before {content:'Contents';}" +
"\n.pagination-page:nth-child(odd) .pagination-contents-container, " +
".pagination-page:nth-child(odd) .pagination-pagenumber," +
".pagination-page:nth-child(odd) .pagination-header {" + "right:" +
outerMargin + ";left:" + innerMargin + ";}" +
"\n.pagination-page:nth-child(even) .pagination-contents-container, " +
".pagination-page:nth-child(even) .pagination-pagenumber," +
".pagination-page:nth-child(even) .pagination-header {" + "right:" +
innerMargin + ";left:" + outerMargin + ";}" +
"\n.pagination-page:nth-child(odd) .pagination-pagenumber," +
".pagination-page:nth-child(odd) .pagination-header {" +
"text-align:right;}" +
"\n.pagination-page:nth-child(even) .pagination-pagenumber," +
".pagination-page:nth-child(even) .pagination-header {" +
"text-align:left;}" +
"\n.pagination-footnote > * > * {font-size: 0.7em; margin:.25em;}" +
"\n.pagination-footnote > * > *::before, .pagination-footnote::before " +
"{position: relative; top: -0.5em; font-size: 80%;}" +
"\n.pagination-toc-entry .pagination-toc-pagenumber {float:right}"
/* This seems to be a bug in Webkit. But unless we set the width of the
* original element that is being flown, some elements extend beyond the
* contentsContainer's width.
*/
+ "\n.pagination-contents-item {width:" + columnWidth + ";}" +
"\n.pagination-frontmatter-contents {width:" + contentsWidth + ";}"
+ "\n.pagination-contents-column-separator {width:" + contentsColumnSeparatorWidth + ";}" +
// Footnotes in non-CSS Regions browsers will render as right margin notes.
"\n.pagination-simple .pagination-footnote > span {" +
"position: absolute; right: 0in; width: 1in;}";
};
pagination.pageCounterCreator = function (cssClass, show) {
/* Create a pagecounter. cssClass is the CSS class employed by this page
* counter to mark all page numbers associated with it. If a show function
* is specified, use this instead of the built-in show function.
*/
this.cssClass = cssClass;
if (show !== undefined) {
this.show = show;
}
};
pagination.pageCounterCreator.prototype.value = 0;
// The initial value of any page counter is 0.
pagination.pageCounterCreator.prototype.needsUpdate = false;
/* needsUpdate controls whether a given page counter should be updated.
* Initially this is not the case.
*/
pagination.pageCounterCreator.prototype.show = function () {
/* Standard show function for page counter is to show the value itself
* using arabic numbers.
*/
return this.value;
};
pagination.pageCounterCreator.prototype.incrementAndShow = function () {
/* Increment the page count by one and return the reuslt page count
* using the show function.
*/
this.value++;
return this.show();
};
pagination.pageCounterCreator.prototype.numberPages = function () {
/* If the pages associated with this page counter need to be updated,
* go through all of them from the start of the book and number them,
* thereby potentially removing old page numbers.
*/
var pagenumbersToNumber, i;
this.value = 0;
this.needsUpdate = false;
pagenumbersToNumber = document.querySelectorAll(
'.pagination-page .pagination-pagenumber.pagination-' + this.cssClass);
for (i = 0; i < pagenumbersToNumber.length; i++) {
pagenumbersToNumber[i].innerHTML = this.incrementAndShow();
}
};
pagination.pageCounters = {};
/* pagination.pageCounters contains all the page counters we use in a book --
* typically these are two -- roman for the frontmatter and arab for the main
* body contents.
*/
pagination.pageCounters.arab = new pagination.pageCounterCreator(
'arabic');
// arab is the page counter used by the main body contents.
pagination.pageCounters.roman = new pagination.pageCounterCreator(
'roman',
pagination.romanize);
// roman is the page counter used by the frontmatter.
pagination.createPages = function (num, flowName, pageCounterClass, columns) {
// Create the DOM structure of num number of pages.
var page, contents, footnotes, contentsContainer, column, columnSeparator, topfloats, header, chapterheader, sectionheader, pagenumberfield, i, j,
tempRoot = document.createDocumentFragment();
for (i = 0; i < num; i++) {
page = document.createElement('div');
page.classList.add('pagination-page');
page.id = pagination.createRandomId('pagination-page-');
header = document.createElement('div');
header.classList.add('pagination-header');
chapterheader = document.createElement('span');
chapterheader.classList.add('pagination-header-chapter');
header.appendChild(chapterheader);
sectionheader = document.createElement('span');
sectionheader.classList.add('pagination-header-section');
header.appendChild(sectionheader);
page.appendChild(header);
if (pagination.config('numberPages')) {
pagenumberfield = document.createElement('div');
pagenumberfield.classList.add('pagination-pagenumber');
pagenumberfield.classList.add('pagination-' + pageCounterClass);
page.appendChild(pagenumberfield);
}
// If flowName is given, create a page with content flow.
if (flowName) {
contentsContainer = document.createElement('div');
contentsContainer.classList.add('pagination-contents-container');
topfloats = document.createElement('div');
topfloats.classList.add('pagination-topfloats');
contents = document.createElement('div');
contents.classList.add('pagination-contents');
for (j = 0; j < columns; j++) {
column = document.createElement('div');
column.classList.add('pagination-contents-column');
contents.appendChild(column);
if ((columns - j) > 1) {
columnSeparator = document.createElement('div');
columnSeparator.classList.add('pagination-contents-column-separator');
contents.appendChild(columnSeparator);
}
}
footnotes = document.createElement('div');
footnotes.classList.add('pagination-footnotes');
contentsContainer.appendChild(topfloats);
contentsContainer.appendChild(contents);
contentsContainer.appendChild(footnotes);
page.appendChild(contentsContainer);
// If no flowName is given, an empty page is created.
} else {
page.classList.add('pagination-empty');
}
tempRoot.appendChild(page);
}
return tempRoot;
};
pagination.events = {};
// pagination.events represents all the events created specifically by BookJS.
pagination.events.bodyLayoutUpdated = document.createEvent('Event');
pagination.events.bodyLayoutUpdated.initEvent(
'bodyLayoutUpdated',
true,
true);
/* bodyLayoutUpdated is emitted when pages have been added or removed from any
* body flowObject.
*/
pagination.events.layoutFlowFinished = document.createEvent('Event');
pagination.events.layoutFlowFinished.initEvent(
'layoutFlowFinished',
true,
true);
/* layoutFlowFinished is emitted the first time the flow of the entire book has
* been created.
*/
pagination.events.pageLayoutUpdate = document.createEvent('Event');
pagination.events.pageLayoutUpdate.initEvent(
'pageLayoutUpdate',
true,
true);
/* pageLayoutUpdate is emitted when new pages have to added or excess pages be
* removed.
*/
pagination.events.escapesNeedMove = document.createEvent('Event');
pagination.events.escapesNeedMove.initEvent(
'escapesNeedMove',
true,
true);
/* escapesNeedMove is emitted when at least one reference to a an escape
* node (footnote, top float) no longer is on the page where it used to be.
*/
pagination.events.redoEscapes = document.createEvent('Event');
pagination.events.redoEscapes.initEvent(
'redoEscapes',
true,
true);
/* redoEscapes is being listened to by BookJS to see when escape nodes
* (footnotes, top floats) need to be refound and redrawn. This can be used
* by editors that need to add new footnotes or top floats.
*/
pagination.headersAndToc = function (bodyObjects) {
/* Go through all pages of all flowObjects and add page headers and
* calculate the table fo contents (TOC) for the frontmatter. This has to
* be done after all pages representing the body of the text have been
* flown and has to redone when there are changes to the body contents that
* can influence the TOC (such as page creation or deletion).
*/
var currentChapterTitle = '', currentSectionTitle = '', pages, chapterHeader, sectionHeader, tocDiv, tocItemDiv, tocItemPnText, tocTitleH1, tocItemPnSpan, tocItemTextSpan,
i, j;
if (pagination.config('numberPages')) {
tocDiv = document.createElement('div');
tocDiv.id = 'pagination-toc';
tocTitleH1 = document.createElement('h1');
tocTitleH1.id = 'pagination-toc-title';
tocDiv.appendChild(tocTitleH1);
}
for (i = 0; i < bodyObjects.length; i++) {
bodyObjects[i].findTitle();
bodyObjects[i].findStartpageNumber();
if (bodyObjects[i].type === 'chapter') {
currentChapterTitle = bodyObjects[i].title;
} else if (bodyObjects[i].type === 'section') {
currentSectionTitle = bodyObjects[i].title;
}
pages = bodyObjects[i].div.childNodes;
for (j = 0; j < pages.length; j++) {
chapterHeader = pages[j].querySelector(
'.pagination-header .pagination-header-chapter');
chapterHeader.innerHTML = currentChapterTitle;
sectionHeader = pages[j].querySelector(
'.pagination-header .pagination-header-section');
sectionHeader.innerHTML = currentSectionTitle;
}
if (bodyObjects[i].type && pagination.config('numberPages')) {
tocItemDiv = document.createElement('div');
tocItemDiv.classList.add('pagination-toc-entry');
tocItemDiv.classList.add(bodyObjects[i].type);
tocItemTextSpan = document.createElement('span');
tocItemTextSpan.classList.add('pagination-toc-text');
tocItemTextSpan.innerHTML = bodyObjects[i].title;
tocItemDiv.appendChild(tocItemTextSpan);
tocItemPnSpan = document.createElement('span');
tocItemPnSpan.classList.add('pagination-toc-pagenumber');
tocItemPnText = document.createTextNode(
bodyObjects[i].startpageNumber);
tocItemPnSpan.appendChild(tocItemPnText);
tocItemDiv.appendChild(tocItemPnSpan);
tocDiv.appendChild(tocItemDiv);
}
}
return tocDiv;
};
pagination.createBodyObjects = function () {
/* Go through the entire body contents and look for chapterStartMarker and
* sectionStartMarker to divide it up. We will then float these elements
* individually, as CSS Regions has problems flowing material that requires
* 100+ regions.
*/
var bodyObjects = [], chapterCounter = 0, bodyContainer, bodyContents, i;
bodyObjects.push(
new pagination.flowObject(
'pagination-body-pre',
pagination.pageCounters.arab));
bodyContainer = eval(pagination.config('flowElement'));
bodyContents = bodyContainer.childNodes;
for (i = bodyContents.length; i > 0; i--) {
if (bodyContents[0].nodeType === 1) {
if (
bodyContents[0].webkitMatchesSelector(
pagination.config('chapterStartMarker'))) {
bodyObjects.push(
new pagination.flowObject(
'pagination-body-' + chapterCounter++,
pagination.pageCounters.arab));
bodyObjects[chapterCounter].setType('chapter');
} else if (
bodyContents[0].webkitMatchesSelector(
pagination.config('sectionStartMarker'))) {
bodyObjects.push(
new pagination.flowObject(
'pagination-body-' + chapterCounter++,
pagination.pageCounters.arab));
bodyObjects[chapterCounter].setType('section');
}
}
bodyObjects[chapterCounter].rawdiv.appendChild(bodyContents[0]);
}
return bodyObjects;
};
pagination.applyBookLayoutNonDestructive = function () {
// Apply layout without changing the original DOM.
var rawdiv, bodyObject, layoutDiv;
if (eval(pagination.config('flowElement')) === document.body) {
/* We are reflowing the body itself, yet the layout will be added to
* the body. This will make the broser crash. So we need to move the
* original contents inside a Div of its own first.
*/
rawdiv = document.createElement('div');
rawdiv.id = 'pagination-contents';
rawdiv.innerHTML = document.body.innerHTML;
document.body.innerHTML = '';
document.body.appendChild(rawdiv);
} else {
rawdiv = eval(pagination.config('flowElement'));
}
bodyObject = new pagination.flowObject(
'body',
pagination.pageCounters.arab,
rawdiv);
// Create div for layout
layoutDiv = document.createElement('div');
layoutDiv.id = 'pagination-layout';
layoutDiv.appendChild(bodyObject.div);
document.body.appendChild(layoutDiv);
bodyObject.initiate();
document.dispatchEvent(pagination.events.layoutFlowFinished);
};
pagination.applyBookLayout = function () {
/* Apply this layout if CSS Regions are present.
* Will first divide the original DOM up into individual chapters and
* sections.
*/
var bodyObjects, layoutDiv, contentsDiv, toc, redoToc, fmObject, i;
bodyObjects = pagination.createBodyObjects();
// Create div for layout
layoutDiv = document.createElement('div');
layoutDiv.id = 'pagination-layout';
document.body.appendChild(layoutDiv);
// Create div for contents
contentsDiv = document.createElement('div');
contentsDiv.id = 'pagination-contents';
document.body.appendChild(contentsDiv);
// counter = 0;
for (i = 0; i < bodyObjects.length; i++) {
layoutDiv.appendChild(bodyObjects[i].div);
contentsDiv.appendChild(bodyObjects[i].rawdiv);
bodyObjects[i].initiate();
}
pagination.pageCounters.arab.numberPages();
if (pagination.config('enableFrontmatter')) {
//Create and flow frontmatter
fmObject = new pagination.flowObject(
'pagination-frontmatter',
pagination.pageCounters.roman,
false);
fmObject.columns = 1;
contentsDiv.insertBefore(fmObject.rawdiv, contentsDiv.firstChild);
fmObject.rawdiv.innerHTML = pagination.config('frontmatterContents');
toc = pagination.headersAndToc(bodyObjects);
if (pagination.config('numberPages')) {
fmObject.rawdiv.appendChild(toc);
}
layoutDiv.insertBefore(fmObject.div, bodyObjects[0].div);
fmObject.initiate();
redoToc = function () {
var oldToc = toc;
toc = pagination.headersAndToc(bodyObjects);
fmObject.rawdiv.replaceChild(toc, oldToc);
};
document.body.addEventListener('bodyLayoutUpdated', redoToc);
}
document.dispatchEvent(pagination.events.layoutFlowFinished);
};
pagination.applySimpleBookLayout = function () {
// Apply this alternative layout in case CSS Regions are not present
var contentsDiv, simplePage;
if (eval(pagination.config('flowElement')) === document.body) {
/* We are reflowing the body itself, yet the layout will be added to
* the body. This will make the broser crash. So we need to move the
* original contents inside a Div of its own first.
*/
contentsDiv = document.createElement('div');
contentsDiv.id = 'pagination-contents';
contentsDiv.innerHTML = document.body.innerHTML;
document.body.innerHTML = '';
document.body.appendChild(contentsDiv);
if (!window.hasOwnProperty('paginationConfig')) {
window.paginationConfig = {};
}
paginationConfig.flowElement =
"document.getElementById('pagination-contents')";
}
simplePage = eval(pagination.config('flowElement'));
//var simplePage = document.createElement('div');
simplePage.classList.add('pagination-page');
simplePage.classList.add('pagination-simple');
//simplePage.innerHTML = bodyContainer.innerHTML;
//simplePage.id = bodyContainer.id;
//bodyContainer.innerHTML = '';
//document.body.appendChild(simplePage);
document.dispatchEvent(pagination.events.layoutFlowFinished);
};
pagination._cssRegionsCheck = function () {
// Check whether CSS Regions are present in Chrome 23+ version
var returnValue;
if (
(
document.webkitGetNamedFlows) && (
document.webkitGetNamedFlows() !== null)) {
returnValue = true;
} else {
returnValue = false;
}
return returnValue;
};
pagination.autoStartInitiator = function () {
// To be executed upon document loading.
var cssRegionsPresent = pagination._cssRegionsCheck();
if (document.readyState === 'interactive' && !cssRegionsPresent) {
pagination.applySimpleBookLayout();
} else if (document.readyState === 'complete' && cssRegionsPresent) {
if (pagination.config('divideContents')) {
pagination.applyBookLayout();
} else {
pagination.applyBookLayoutNonDestructive();
}
}
};
if (pagination.config('autoStart') === true) {
/* Hook pagination.autoStartInitiator to document loading stage if
* autoStart is set to true.
*/
document.addEventListener(
"readystatechange",
pagination.autoStartInitiator);
}
exports.pagination = pagination;
}).call(this);
(function () {
var exports = this,
flowObject;
flowObject = function (name, pageCounter, rawdiv) {
/* A flowObject is either a chapter, a section start, the frontmatter or
* the contents of the body of the text that come before the first
* chapter/section title.
*/
this.name = name;
this.pageCounter = pageCounter;
if (rawdiv) {
this.rawdiv = rawdiv;
} else {
this.rawdiv = document.createElement('div');
}
this.rawdiv.classList.add(name + '-contents');
this.rawdiv.classList.add('pagination-contents-item');
this.div = document.createElement('div');
this.div.classList.add(name + '-layout');
this.bulkPagesToAdd = pagination.config('bulkPagesToAdd');
this.columns = pagination.config('columns');
this.escapes = {};
this.escapes.footnote = [];
this.escapes.topfloat = [];
this.escapes.marginnote = [];
this.escapeStylesheets = {};
this.escapeStylesheets.footnote = document.createElement('style');
this.escapeStylesheets.topfloat = document.createElement('style');
this.escapeStylesheets.marginnote = document.createElement('style');
};
flowObject.prototype.redoPages = false;
// redoPages is set if page numbering needs to be updated.
flowObject.prototype.overset = false;
/* We record the current state of the overset of the region flow so that we
* only have to find out if pages need to be added or removed when it
* changes, rather than every time the contents of the region flow changes.
*/
flowObject.prototype.firstEmptyRegionIndex = -1;
/* In addition to overset, we also need to monitor changes to the
* firstEmptyRegionIndex property of the flow, because in the case of multi
* column pages, there may be empty regions (unfilled columns) that we do not
* want to remove.
*/
flowObject.prototype.initiate = function () {
/* To be run upon the initiation of any flowObject after rawdiv and div
* have been set and rawdiv has been filled with initial contents.
*/
this.setStyle();
this.namedFlow = document.webkitGetNamedFlows()[this.name];
this.addOrRemovePages();
this.setupReflow();
this.findAllTopfloats();
this.findAllFootnotes();
this.findAllMarginnotes();
// Layout magrin notes once before everything else, so that they don't fill up text
//this.layoutMarginnotes();
this.placeAllEscapes();
this.setupEscapeReflow();
if (pagination.config('numberPages')) {
this.pageCounter.numberPages();
}
};
flowObject.prototype.setStyle = function () {
/* Create a style element for this flowObject and add it to the header in
* the DOM. That way it will not be mixing with the DOM of the
* contents.
*/
var stylesheet = document.createElement('style');
stylesheet.innerHTML = "." + this.name + "-layout" +
" .pagination-contents-column {-webkit-flow-from: " + this.name +
";}" + "\n." + this.name + "-contents " + "{-webkit-flow-into: " +
this.name + ";}";
document.head.appendChild(stylesheet);
};
flowObject.prototype.setType = function (type) {
// Set the type of this flowObject (chapter or section start).
this.type = type;
this.div.classList.add('pagination-' + type);
};
flowObject.prototype.findTitle = function () {
// Find the title of section or chapter that this flowObject is covering.
var titleField;
if (this.type === 'chapter') {
titleField = this.rawdiv.querySelector(
pagination.config('chapterTitleMarker'));
if (titleField) {
this.title = titleField.innerHTML;
} else {
this.title = '';
}
} else if (this.type === 'section') {
titleField = this.rawdiv.querySelector(
pagination.config('sectionTitleMarker'));
if (titleField) {
this.title = titleField.innerHTML;
} else {
this.title = '';
}
}
};
flowObject.prototype.findStartpageNumber = function () {
// Find the first page number used in this flowObject.
var startpageNumberField;
if (this.rawdiv.innerText.length > 0 && pagination.config('numberPages')) {
startpageNumberField =
this.div.querySelector('.pagination-pagenumber');
this.startpageNumber = startpageNumberField.innerText;
}
};
// Footnote and top float handling
flowObject.prototype.findEscapeReferencePage = function (
escapeReference) {
/* Find the page where the the escape would be placed in the body text.
*/
var escapeReferenceNode;
if (!escapeReference) {
return false;
}
escapeReferenceNode = this.namedFlow.getRegionsByContent(