-
Notifications
You must be signed in to change notification settings - Fork 2
/
book.js
621 lines (491 loc) · 22.7 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
/*!
* BookJS v.0.23.1-dev
* Copyright 2012 Aleksandar Erkalovic, Marita Fraser, Steven Levithan,
* Philip Schatz 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 the corresponding file as well as this
* javascript file within your html code. If you need to set custom options,
* set them before including this file by defining an object named
* paginationConfig and setting the customization options as keys within this
* object. Like this:
*
* <link href="book.css" rel="stylesheet" type="text/css" />
* <script type="text/javascript">
* paginationConfig = {
* 'sectionStartMarker': 'h3',
* 'columns': 3,
* 'autoStart': false,
* }
* </script>
* <script src="book.js" type="text/javascript"></script>
*
* 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.
*
* 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 deletin 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 by calling Pagination.applyBookLayout() or
* Pagination.applySimpleBookLayout() in case CSS Regions are not present.
* Check Pagination._cssRegionCheck() to see if CSS Regions are present.
*/
/*
* The Pagination object represents all the pagination functionality which is
* added to its namespace.
*/
var Pagination = new Object;
Pagination.config = {
'sectionStartMarker': 'h1',
'sectionTitleMarker': 'h1',
'chapterStartMarker': 'h2',
'chapterTitleMarker': 'h2',
'flowElement': 'document.body',
'alwaysEven': false,
'columns': 1,
'enableFrontmatter': true,
'bulkPagesToAdd': 50,
'pagesToAddIncreementRatio': 1.4,
'frontmatterContents': '',
'autoStart': true
};
Pagination.initiate = function() {
this.userConfigImport();
this.setStyle();
}
Pagination.userConfigImport = function() {
if (window.paginationConfig) {
for (var key in paginationConfig) {
Pagination.config[key] = paginationConfig[key];
}
}
}
Pagination.setStyle = function() {
var stylesheet = document.createElement('style');
stylesheet.innerHTML = ".contentsContainer {display: -webkit-box; -webkit-box-orient: vertical;}"
+ " .contents {display: -webkit-box; -webkit-box-flex: 1}"
+ " .contents-column {-webkit-box-flex: 1}"
+ " .footnotes .invisible {visibility: hidden}"
+ " #contents .footnote {display: none}";
document.head.appendChild(stylesheet);
}
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 Array(+digits.join("") + 1).join("M") + roman;
};
Pagination.pageCounterCreator = function (selector, show) {
this.selector = selector;
if (show !== undefined) {
this.show = show;
}
};
Pagination.pageCounterCreator.prototype.value = 0;
Pagination.pageCounterCreator.prototype.needsUpdate = false;
Pagination.pageCounterCreator.prototype.show = function(){
return this.value;
};
Pagination.pageCounterCreator.prototype.incrementAndShow = function () {
this.value++;
return this.show();
};
Pagination.pageCounterCreator.prototype.numberPages = function () {
if (this.needsUpdate) {
this.value = 0;
this.needsUpdate = false;
var pagenumbersToNumber = document.querySelectorAll('.page .pagenumber.' + this.selector);
for (var i = 0; i < pagenumbersToNumber.length; i++) {
pagenumbersToNumber[i].innerHTML = this.incrementAndShow();
}
}
};
Pagination.pageCounters = {};
Pagination.pageCounters.arab = new Pagination.pageCounterCreator('arabic');
Pagination.pageCounters.roman = new Pagination.pageCounterCreator('roman', Pagination.romanize);
Pagination.createPages = function (num, flowName, pageCounterSelector, columns) {
// Create the DOM structure of each page.
var page, contents, footnotes, contentsContainer, column, topFloats;
var tempRoot = document.createDocumentFragment();
for (var i = 0; i < num; i++) {
page = document.createElement('div');
page.classList.add('page');
header = document.createElement('div');
header.classList.add('header');
chapterheader = document.createElement('span');
chapterheader.classList.add('chapter');
header.appendChild(chapterheader);
sectionheader = document.createElement('span');
sectionheader.classList.add('section');
header.appendChild(sectionheader);
page.appendChild(header);
pagenumberfield = document.createElement('div');
pagenumberfield.classList.add('pagenumber');
pagenumberfield.classList.add(pageCounterSelector);
page.appendChild(pagenumberfield);
// If flowName is given, create a page with content flow.
if (flowName) {
contentsContainer = document.createElement('div');
contentsContainer.classList.add('contentsContainer');
topFloats = document.createElement('div');
topFloats.classList.add('topFloats');
contents = document.createElement('div');
contents.classList.add('contents');
for (var j = 0; j < columns; j++) {
column = document.createElement('div');
column.classList.add('contents-column');
contents.appendChild(column);
}
footnotes = document.createElement('div');
footnotes.classList.add('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('empty');
}
tempRoot.appendChild(page);
}
return tempRoot;
};
Pagination.bodyLayoutUpdatedEvent = document.createEvent('Event');
Pagination.bodyLayoutUpdatedEvent.initEvent('bodyLayoutUpdated', true, true);
Pagination.layoutFlowFinishedEvent = document.createEvent('Event');
Pagination.layoutFlowFinishedEvent.initEvent('layoutFlowFinished', true, true);
Pagination.pageLayoutUpdateEvent = document.createEvent('Event');
Pagination.pageLayoutUpdateEvent.initEvent('pageLayoutUpdated', true, true);
Pagination.headersAndToc = function (bodyObjects) {
var currentChapterTitle = '';
var currentSectionTitle = '';
var tocDiv = document.createElement('div');
tocDiv.id = 'toc';
tocTitleDiv = document.createElement('div');
tocTitleDiv.id = 'toc-title';
tocDiv.appendChild(tocTitleDiv);
for (var 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;
}
var pages = bodyObjects[i].div.childNodes;
for (var j = 0; j < pages.length; j++) {
var chapterHeader = pages[j].querySelector('.header .chapter');
chapterHeader.innerHTML = currentChapterTitle;
var sectionHeader = pages[j].querySelector('.header .section');
sectionHeader.innerHTML = currentSectionTitle;
}
if (bodyObjects[i].type) {
var tocItemDiv = document.createElement('div');
tocItemDiv.classList.add('toc-entry');
tocItemDiv.classList.add(bodyObjects[i].type);
var tocItemTextSpan = document.createElement('span');
tocItemTextSpan.classList.add('toc-text');
tocItemTextSpan.innerHTML = bodyObjects[i].title;
tocItemDiv.appendChild(tocItemTextSpan);
var tocItemPnSpan = document.createElement('span');
tocItemPnSpan.classList.add('toc-pagenumber');
if(typeof bodyObjects[i].startpageNumber !== 'undefined') {
var tocItemPnText = document.createTextNode(bodyObjects[i].startpageNumber);
tocItemPnSpan.appendChild(tocItemPnText);
}
tocItemDiv.appendChild(tocItemPnSpan);
tocDiv.appendChild(tocItemDiv);
}
}
return tocDiv;
};
/**
* Creates objects for each item in the body (section start, chapter)
*/
Pagination.createBodyObjects = function () {
//
var bodyObjects = [];
var chapterCounter = 0;
bodyObjects.push(new Pagination.flowObject('bodypre', Pagination.pageCounters.arab));
var bodyContainer = eval(Pagination.config.flowElement);
var bodyContents = bodyContainer.childNodes;
for (var i = bodyContents.length; i > 0; i--) {
if (bodyContents[0].nodeType == 1) {
if (bodyContents[0].webkitMatchesSelector(Pagination.config.chapterStartMarker)) {
bodyObjects.push(new Pagination.flowObject('body' + chapterCounter++, Pagination.pageCounters.arab));
bodyObjects[chapterCounter].setType('chapter');
} else if (bodyContents[0].webkitMatchesSelector(Pagination.config.sectionStartMarker)) {
bodyObjects.push(new Pagination.flowObject('body' + chapterCounter++, Pagination.pageCounters.arab));
bodyObjects[chapterCounter].setType('section');
}
}
bodyObjects[chapterCounter].rawdiv.appendChild(bodyContents[0]);
}
return bodyObjects;
};
Pagination.applyBookLayout = function () {
var bodyObjects = Pagination.createBodyObjects();
//Create div for layout
var layoutDiv = document.createElement('div');
layoutDiv.id = 'layout';
document.body.appendChild(layoutDiv);
//Create div for contents
var contentsDiv = document.createElement('div');
contentsDiv.id = 'contents';
document.body.appendChild(contentsDiv);
counter = 0;
for (var 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('frontmatter', Pagination.pageCounters.roman, 1);
fmObject.columns = 1;
contentsDiv.insertBefore(fmObject.rawdiv,contentsDiv.firstChild);
fmObject.rawdiv.innerHTML = Pagination.config.frontmatterContents;
var toc = Pagination.headersAndToc(bodyObjects);
fmObject.rawdiv.appendChild(toc);
layoutDiv.insertBefore(fmObject.div, bodyObjects[0].div);
fmObject.initiate();
var redoToc = function() {
var oldToc = toc;
toc = Pagination.headersAndToc(bodyObjects);
fmObject.rawdiv.replaceChild(toc, oldToc);
};
document.body.addEventListener('bodyLayoutUpdated',redoToc);
}
document.dispatchEvent(Pagination.layoutFlowFinishedEvent);
};
Pagination.applySimpleBookLayout = function () {
// Apply this alternative layout in case CSS Regions are not present
bodyContainer = eval(Pagination.config.flowElement);
simplePage = document.createElement('div');
simplePage.classList.add('page');
simplePage.classList.add('simple');
simplePage.innerHTML = bodyContainer.innerHTML;
simplePage.id = bodyContainer.id;
bodyContainer.innerHTML = '';
document.body.appendChild(simplePage);
};
Pagination._cssRegionsCheck = function() {
// Check whether CSS Regions are present in Chrome 23+ version
if ((document.webkitGetNamedFlows) && (document.webkitGetNamedFlows() !== null)) {
return true;
}
return false;
};
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)) {
Pagination.applyBookLayout();
}
}
Pagination.flowObject = function (name, pageCounter) {
this.name = name;
this.pageCounter = pageCounter;
this.rawdiv = document.createElement('div');
this.rawdiv.id = name + 'raw';
this.div = document.createElement('div');
this.div.id = name;
this.bulkPagesToAdd = Pagination.config.bulkPagesToAdd;
this.columns = Pagination.config.columns;
};
Pagination.flowObject.prototype.totalPages = 0;
Pagination.flowObject.prototype.redoPages = false;
Pagination.flowObject.prototype.overset = false;
Pagination.flowObject.prototype.firstEmptyRegionIndex = -1;
Pagination.flowObject.prototype.initiate = function () {
this.setStyle();
this.namedFlow = document.webkitGetNamedFlows()[this.name];
this.addOrRemovePages();
this.setupReflow();
this.layoutFootnotes();
this.pageCounter.numberPages();
}
Pagination.flowObject.prototype.setStyle = function() {
var stylesheet = document.createElement('style');
stylesheet.innerHTML = "#"+this.name+" .contents-column {-webkit-flow-from:"+this.name+";}"
+ " #"+this.name+"raw {-webkit-flow-into:"+this.name+";}";
document.head.appendChild(stylesheet);
}
Pagination.flowObject.prototype.setType = function (type) {
this.type = type;
this.div.classList.add(type);
};
Pagination.flowObject.prototype.findTitle = function () {
var titleField;
if (this.type == 'chapter') {
titleField = this.rawdiv.querySelector(Pagination.config.chapterTitleMarker);
this.title = titleField.innerHTML;
} else if (this.type == 'section') {
titleField = this.rawdiv.querySelector(Pagination.config.sectionTitleMarker);
this.title = titleField.innerHTML;
}
};
Pagination.flowObject.prototype.findStartpageNumber = function () {
if (this.rawdiv.innerText.length > 0) {
var startpageNumberField = this.div.querySelector('.pagenumber');
this.startpageNumber = startpageNumberField.innerText;
}
};
Pagination.flowObject.prototype.layoutFootnotes = function () {
var numFootnote, footnote, footnoteReferencePageBeforeInsertion, footnoteReferencePageAfterInsertion, currentFootnoteContainer, nextpageFootnote;
var allFootnotes = this.rawdiv.getElementsByClassName('footnote'); // Look for all the items that have "footnote" in their class list. These will be treated as footnote texts.
for (var i = 0; i < allFootnotes.length; i++) {
numFootnote = document.createElement('sup'); // Create a sup-element with the class "footnote-reference" that holds the current footnote number. This will be used both in the body text and in the footnote itself.
numFootnote.classList.add('footnote-reference');
numFootnoteContents = document.createTextNode(i+1);
numFootnote.appendChild(numFootnoteContents);
footnote = document.createElement('div'); // Put the footnote number and footnote text together in a div-element with the class footnote-item
footnote.classList.add('footnote-item');
footnote.classList.add('visible');
footnote.appendChild(numFootnote);
footnoteText = allFootnotes[i].cloneNode(true);
footnote.appendChild(footnoteText);
numFootnoteReference = numFootnote.cloneNode(true)
allFootnotes[i].parentNode.insertBefore(numFootnoteReference, allFootnotes[i]); // Insert the footnote number in the body text just before the original footnote text appeared in the body (the text that is now hidden).
footnoteReferencePageBeforeInsertion = this.namedFlow.getRegionsByContent(numFootnoteReference)[0].parentNode.parentNode.parentNode; // We find the page where the footnote is referenced from before the insertion procedure begins.
currentFootnoteContainer = footnoteReferencePageBeforeInsertion.querySelector('.footnotes');
currentFootnoteContainer.appendChild(footnote); // We insert the footnote in the footnote contianer of that page.
footnoteReferencePageAfterInsertion = this.namedFlow.getRegionsByContent(numFootnoteReference)[0].parentNode.parentNode.parentNode; // We find the page where the footnote is referenced from after the insertion procedure has taken place.
if (footnoteReferencePageBeforeInsertion !== footnoteReferencePageAfterInsertion) { //If the footnote reference has been moved from oen page to another through the insertion procedure, we set the visibility of the footnote to "hidden" so that it continues to take up the same space and then insert it one more time on the page from where it now is referenced.
nextpageFootnote = footnote.cloneNode(true);
footnote.classList.remove('visible');
footnote.classList.add('invisible');
currentFootnoteContainer = footnoteReferencePageAfterInsertion.querySelector('.footnotes');
currentFootnoteContainer.appendChild(nextpageFootnote);
}
}
};
Pagination.flowObject.prototype.makeEvenPages = function () {
var emptyPage = this.div.querySelector('.page.empty');
if (emptyPage) {
this.div.removeChild(emptyPage);
}
var allPages = this.div.querySelectorAll('.page');
if (allPages.length % 2 == 1) {
this.div.appendChild(Pagination.createPages(1, false, this.pageCounter.selector, this.columns));
}
};
Pagination.flowObject.prototype.addPagesLoop = function (pages) {
if ('undefined' === typeof (pages)) {
this.totalPages += this.bulkPagesToAdd;
this.div.appendChild(Pagination.createPages(this.bulkPagesToAdd, this.name, this.pageCounter.selector, this.columns));
this.bulkPagesToAdd = Math.floor(this.bulkPagesToAdd * Pagination.config.pagesToAddIncrementRatio);
} else {
this.totalPages += pages;
this.div.appendChild(Pagination.createPages(pages, this.name, this.pageCounter.selector, this.columns));
}
this.addOrRemovePages(pages);
};
Pagination.flowObject.prototype.addOrRemovePages = function (pages) {
if ((this.namedFlow.overset) && (this.rawdiv.innerText.length > 0)) {
this.pageCounter.needsUpdate = true;
this.redoPages = true;
this.addPagesLoop(pages);
} else if ((this.namedFlow.firstEmptyRegionIndex!=-1) && ((this.totalPages * this.columns - this.namedFlow.firstEmptyRegionIndex) > this.columns )) {
this.redoPages = true;
this.removeExcessPages(pages);
} else if (this.redoPages) {
this.redoPages = false;
if (Pagination.config.alwaysEven) {
this.makeEvenPages();
}
if (this.name!='frontmatter') {
document.body.dispatchEvent(Pagination.bodyLayoutUpdatedEvent);
}
}
};
Pagination.flowObject.prototype.removeExcessPages = function (pages) {
var allPages = this.div.querySelectorAll('.page');
for (var i = (Math.ceil(this.namedFlow.firstEmptyRegionIndex/this.columns)); i < allPages.length; i++) {
this.div.removeChild(allPages[i]);
this.totalPages--;
}
this.addOrRemovePages(pages);
};
Pagination.flowObject.prototype.setupReflow = function () {
var flowObject = this;
var checkOverset = function () {
// Something has changed in the contents of this flow. Check if the overset has changed, and if it has, emit a pageLayoutUpdateEvent.
if ((flowObject.namedFlow.overset !== flowObject.overset) || (flowObject.namedFlow.firstEmptyRegionIndex !== flowObject.firstEmptyRegionIndex)){
flowObject.overset = flowObject.namedFlow.overset;
flowObject.firstEmptyRegionIndex = flowObject.namedFlow.firstEmptyRegionIndex;
flowObject.namedFlow.dispatchEvent(Pagination.pageLayoutUpdateEvent);
}
}
this.namedFlow.addEventListener('webkitRegionLayoutUpdate',checkOverset);
var reFlow = function () {
// The page layout has changed. Reflow by adding pages one by one.
flowObject.addOrRemovePages(1);
flowObject.pageCounter.numberPages();
};
this.namedFlow.addEventListener('pageLayoutUpdated',reFlow);
};
Pagination.initiate();
if (Pagination.config.autoStart === true) {
// Hook Pagination.autoStartInitiator to document loading stage if
document.addEventListener("readystatechange", Pagination.autoStartInitiator);
}