-
Notifications
You must be signed in to change notification settings - Fork 485
Expand file tree
/
Copy pathBookReader.js
More file actions
1989 lines (1725 loc) · 59.8 KB
/
BookReader.js
File metadata and controls
1989 lines (1725 loc) · 59.8 KB
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
/*
Copyright(c)2008-2019 Internet Archive. Software license AGPL version 3.
This file is part of BookReader.
BookReader is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
BookReader is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with BookReader. If not, see <http://www.gnu.org/licenses/>.
The BookReader source is hosted at http://github.com/internetarchive/bookreader/
*/
// Needed by touch-punch
import 'jquery-ui/ui/widget.js';
import 'jquery-ui/ui/widgets/mouse.js';
import 'jquery-ui-touch-punch';
import PACKAGE_JSON from '../package.json';
import * as utils from './BookReader/utils.js';
import { exposeOverrideable } from './BookReader/utils/classes.js';
import { Navbar } from './BookReader/Navbar/Navbar.js';
import { DEFAULT_OPTIONS, OptionsParseError } from './BookReader/options.js';
/** @typedef {import('./BookReader/options.js').BookReaderOptions} BookReaderOptions */
/** @typedef {import('./BookReader/options.js').ReductionFactor} ReductionFactor */
/** @typedef {import('./BookReader/BookModel.js').PageIndex} PageIndex */
import { EVENTS } from './BookReader/events.js';
import { Toolbar } from './BookReader/Toolbar/Toolbar.js';
import { BookModel } from './BookReader/BookModel.js';
import { Mode1Up } from './BookReader/Mode1Up.js';
import { Mode2Up } from './BookReader/Mode2Up.js';
import { ModeThumb } from './BookReader/ModeThumb.js';
import { ImageCache } from './BookReader/ImageCache.js';
import { PageContainer } from './BookReader/PageContainer.js';
import { NAMED_REDUCE_SETS } from './BookReader/ReduceSet.js';
import '@internetarchive/elements/ia-status-indicator/ia-status-indicator';
import '@internetarchive/elements/ia-combo-box/ia-combo-box';
/**
* BookReader
* @param {Partial<BookReaderOptions>} overrides
* TODO document all options properties
* @constructor
*/
export default function BookReader(overrides = {}) {
const options = BookReader.extendOptions({}, BookReader.defaultOptions, overrides, BookReader.optionOverrides);
this.setup(options);
}
/**
* Extend the default options for BookReader
* Accepts any number of option objects and merges them in order.
*
* Does a shallow merge of everything except plugin options. These are individually merged.
* @param {...Partial<BookReaderOptions>} newOptions
*/
BookReader.extendOptions = function(...newOptions) {
if (newOptions.length <= 1) {
return newOptions[0];
}
/** @type {Array<keyof BookReaderOptions>} */
const shallowOverrides = ['onePage', 'twoPage', 'vars'];
/** @type {Array<keyof BookReaderOptions>} */
const mapOverrides = ['plugins', 'controls'];
const result = newOptions.shift();
for (const opts of newOptions) {
for (const [key, value] of Object.entries(opts)) {
if (shallowOverrides.includes(key)) {
result[key] ||= {};
result[key] = Object.assign(result[key], value);
} else if (mapOverrides.includes(key)) {
result[key] ||= {};
for (const [name, mapValue] of Object.entries(value)) {
result[key][name] ||= {};
Object.assign(result[key][name], mapValue);
}
} else {
result[key] = value;
}
}
}
return result;
};
BookReader.version = PACKAGE_JSON.version;
// Mode constants
/** 1 page view */
BookReader.constMode1up = 1;
/** 2 pages view */
BookReader.constMode2up = 2;
/** thumbnails view */
BookReader.constModeThumb = 3;
// Although this can actualy have any BookReaderPlugin subclass as value, we
// hardcode the known plugins here for type checking
BookReader.PLUGINS = {
/** @type {typeof import('./plugins/plugin.archive_analytics.js').ArchiveAnalyticsPlugin | null}*/
archiveAnalytics: null,
/** @type {typeof import('./plugins/plugin.autoplay.js').AutoplayPlugin | null}*/
autoplay: null,
/** @type {typeof import('./plugins/plugin.chapters.js').ChaptersPlugin | null}*/
chapters: null,
/** @type {typeof import('./plugins/plugin.experiments.js').ExperimentsPlugin | null}*/
experiments: null,
/** @type {typeof import('./plugins/plugin.resume.js').ResumePlugin | null}*/
resume: null,
/** @type {typeof import('./plugins/search/plugin.search.js').SearchPlugin | null}*/
search: null,
/** @type {typeof import('./plugins/plugin.text_selection.js').TextSelectionPlugin | null}*/
textSelection: null,
/** @type {typeof import('./plugins/translate/plugin.translate.js').TranslatePlugin | null}*/
translate: null,
/** @type {typeof import('./plugins/tts/plugin.tts.js').TtsPlugin | null}*/
tts: null,
};
/**
* @param {string} pluginName
* @param {new (...args: any[]) => import('./BookReaderPlugin.js').BookReaderPlugin} plugin
*/
BookReader.registerPlugin = function(pluginName, plugin) {
if (BookReader.PLUGINS[pluginName]) {
console.warn(`Plugin ${pluginName} already registered. Overwriting.`);
}
BookReader.PLUGINS[pluginName] = plugin;
};
/** image cache */
BookReader.imageCache = null;
// Animation constants
BookReader.constNavAnimationDuration = 300;
BookReader.constResizeAnimationDuration = 100;
// Names of events that can be triggered via BookReader.prototype.trigger()
BookReader.eventNames = EVENTS;
BookReader.defaultOptions = DEFAULT_OPTIONS;
/**
* @type {BookReaderOptions}
* This is here, just in case you need to absolutely override an option.
*/
BookReader.optionOverrides = {};
/**
* Setup
* It is separate from the constructor, so plugins can extend.
* @param {BookReaderOptions} options
*/
BookReader.prototype.setup = function(options) {
// Store the options used to setup bookreader
this.options = options;
/** @type {import('@/src/ia-bookreader/ia-bookreader.js').IaBookReader} */
this.shell;
// Base server used by some api calls
/** @deprecated */
this.bookId = options.bookId;
/** @deprecated */
this.server = options.server;
/** @deprecated */
this.subPrefix = options.subPrefix;
/** @deprecated */
this.bookPath = options.bookPath;
// Construct the usual plugins first to get type hints
this.plugins = {
archiveAnalytics: BookReader.PLUGINS.archiveAnalytics ? new BookReader.PLUGINS.archiveAnalytics(this) : null,
autoplay: BookReader.PLUGINS.autoplay ? new BookReader.PLUGINS.autoplay(this) : null,
chapters: BookReader.PLUGINS.chapters ? new BookReader.PLUGINS.chapters(this) : null,
experiments: BookReader.PLUGINS.experiments ? new BookReader.PLUGINS.experiments(this) : null,
search: BookReader.PLUGINS.search ? new BookReader.PLUGINS.search(this) : null,
resume: BookReader.PLUGINS.resume ? new BookReader.PLUGINS.resume(this) : null,
textSelection: BookReader.PLUGINS.textSelection ? new BookReader.PLUGINS.textSelection(this) : null,
translate: BookReader.PLUGINS.translate ? new BookReader.PLUGINS.translate(this) : null,
tts: BookReader.PLUGINS.tts ? new BookReader.PLUGINS.tts(this) : null,
};
// Delete anything that's null
for (const [pluginName, plugin] of Object.entries(this.plugins)) {
if (!plugin) delete this.plugins[pluginName];
}
// Now construct the rest of the plugins
for (const [pluginName, PluginClass] of Object.entries(BookReader.PLUGINS)) {
if (this.plugins[pluginName] || !PluginClass) continue;
this.plugins[pluginName] = new PluginClass(this);
}
// And call setup on them
for (const [pluginName, plugin] of Object.entries(this.plugins)) {
try {
plugin.setup(this.options.plugins?.[pluginName] ?? {});
// Write the options back; this way the plugin is the source of truth,
// and BR just contains a reference to it.
this.options.plugins[pluginName] = plugin.options;
} catch (e) {
console.error(`Error setting up plugin ${pluginName}`, e);
}
}
if (this.plugins.search?.options.enabled) {
// Expose the search method for convenience / backward compat
this.search = this.plugins.search.search.bind(this.plugins.search);
}
/** @type {number} @deprecated some past iterations set this */
this.numLeafs = undefined;
/**
* Store viewModeOrder states
* @var {boolean}
*/
this.viewModeOrder = [];
/**
* Used to suppress fragment change for init with canonical URLs
* @var {boolean}
*/
this.suppressFragmentChange = false;
/** @type {function(): void} */
this.animationFinishedCallback = null;
// @deprecated: Instance constants. Use Class constants instead
/** 1 page view */
this.constMode1up = BookReader.constMode1up;
/** 2 pages view */
this.constMode2up = BookReader.constMode2up;
/** thumbnails view */
this.constModeThumb = BookReader.constModeThumb;
// Private properties below. Configuration should be done with options.
/** @type {number} TODO: Make private */
this.reduce = 8; /* start very small */
this.defaults = options.defaults;
this.padding = options.padding;
this.reduceSet = NAMED_REDUCE_SETS[options.reduceSet];
if (!this.reduceSet) {
console.warn(`Invalid reduceSet ${options.reduceSet}. Ignoring.`);
this.reduceSet = NAMED_REDUCE_SETS[DEFAULT_OPTIONS.reduceSet];
}
/** @type {number}
* can be 1 or 2 or 3 based on the display mode const value
*/
this.mode = null;
this.prevReadMode = null;
this.ui = options.ui;
this.uiAutoHide = options.uiAutoHide;
this.thumbWidth = 100; // will be overridden during this._modes.modeThumb.prepare();
this.thumbRowBuffer = options.thumbRowBuffer;
this.thumbColumns = options.thumbColumns;
this.thumbMaxLoading = options.thumbMaxLoading;
this.thumbPadding = options.thumbPadding;
this.displayedRows = [];
this.displayedIndices = [];
this.animating = false;
this.flipSpeed = utils.parseAnimationSpeed(options.flipSpeed) || 400;
/**
* Represents the first displayed index
* In 2up mode it will be the left page
* In 1 up mode it is the highest page
* @property {number|null} firstIndex
*/
this.firstIndex = null;
this.isFullscreenActive = options.startFullscreen || false;
this.lastScroll = null;
this.showLogo = options.showLogo;
this.logoURL = options.logoURL;
this.imagesBaseURL = options.imagesBaseURL;
this.reductionFactors = options.reductionFactors;
this.onePage = options.onePage;
/** @type {import('./BookReader/Mode2Up').TwoPageState} */
this.twoPage = options.twoPage;
this.onePageMinBreakpoint = options.onePageMinBreakpoint;
this.bookTitle = options.bookTitle;
this.bookUrl = options.bookUrl;
this.bookUrlText = options.bookUrlText;
this.bookUrlTitle = options.bookUrlTitle;
this.titleLeaf = options.titleLeaf;
this.metadata = options.metadata;
this.thumbnail = options.thumbnail;
this.bookUrlMoreInfo = options.bookUrlMoreInfo;
this.enableExperimentalControls = options.enableExperimentalControls;
this.el = options.el;
this.pageProgression = options.pageProgression;
this.protected = options.protected;
this.getEmbedCode = options.getEmbedCode;
this.popup = null;
// Assign the data methods
this.data = options.data;
/** @type {{[name: string]: JQuery}} */
this.refs = {};
/** The book being displayed in BookReader*/
this.book = new BookModel(this);
if (options.getNumLeafs) this.book.getNumLeafs = options.getNumLeafs.bind(this);
if (options.getPageWidth) this.book.getPageWidth = options.getPageWidth.bind(this);
if (options.getPageHeight) this.book.getPageHeight = options.getPageHeight.bind(this);
if (options.getPageURI) this.book.getPageURI = options.getPageURI.bind(this);
if (options.getPageSide) this.book.getPageSide = options.getPageSide.bind(this);
if (options.getPageNum) this.book.getPageNum = options.getPageNum.bind(this);
if (options.getPageProp) this.book.getPageProp = options.getPageProp.bind(this);
if (options.getSpreadIndices) this.book.getSpreadIndices = options.getSpreadIndices.bind(this);
if (options.leafNumToIndex) this.book.leafNumToIndex = options.leafNumToIndex.bind(this);
/**
* @private Components are 'subchunks' of bookreader functionality, usually UI related
* They should be relatively decoupled from each other/bookreader.
* Note there are no hooks right now; components just provide methods that bookreader
* calls at the correct moments.
**/
this._components = {
navbar: new Navbar(this),
toolbar: new Toolbar(this),
};
this._modes = {
mode1Up: new Mode1Up(this, this.book),
mode2Up: new Mode2Up(this, this.book),
modeThumb: new ModeThumb(this, this.book),
};
/** Stores classes which we want to expose (selectively) some methods as overridable */
this._overrideable = {
'book': this.book,
'_components.navbar': this._components.navbar,
'_components.toolbar': this._components.toolbar,
'_modes.mode1Up': this._modes.mode1Up,
'_modes.mode2Up': this._modes.mode2Up,
'_modes.modeThumb': this._modes.modeThumb,
};
/** Image cache for general image fetching */
this.imageCache = new ImageCache(this.book, {
useSrcSet: this.options.useSrcSet,
reduceSet: this.reduceSet,
renderPageURI: options.renderPageURI.bind(this),
});
/**
* Flag if BookReader has "focus" for keyboard shortcuts
* Initially true, set to false when:
* - BookReader scrolled out of view
* Set to true when:
* - BookReader scrolled into view
*/
this.hasKeyFocus = true;
};
BookReader.prototype.initializePlugin = function(pluginName) {
const plugin = new BookReader.PLUGINS[pluginName](this);
this.plugins[pluginName] = plugin;
try {
plugin.setup(this.options.plugins?.[pluginName] ?? {});
this.options.plugins[pluginName] = plugin.options;
} catch (e) {
console.error(`Error setting up plugin ${pluginName} outside of regular cycle`, e);
throw e;
}
try {
plugin.init();
} catch (e) {
console.error(`Error initializing plugin ${pluginName} outside of regular cycle`, e);
throw e;
}
};
/**
* Get all the HTML Elements that are being/can be rendered.
* Includes cached elements which might be rendered again.
*/
BookReader.prototype.getActivePageContainerElements = function() {
let containerEls = Object.values(this._modes.mode2Up.mode2UpLit.pageContainerCache).map(pc => pc.$container[0])
.concat(Object.values(this._modes.mode1Up.mode1UpLit.pageContainerCache).map(pc => pc.$container[0]));
if (this.mode == this.constModeThumb) {
containerEls = containerEls.concat(this.$('.BRpagecontainer').toArray());
}
return containerEls;
};
/**
* Get the HTML Elements for the rendered page. Note there can be more than one, since
* (at least as of writing) different modes can maintain different caches.
* @param {PageIndex} pageIndex
* @returns {HTMLElement[]}
*/
BookReader.prototype.getActivePageContainerElementsForIndex = function(pageIndex) {
return [
this._modes.mode2Up.mode2UpLit.pageContainerCache[pageIndex]?.$container?.[0],
this._modes.mode1Up.mode1UpLit.pageContainerCache[pageIndex]?.$container?.[0],
...(this.mode == this.constModeThumb ? this.$(`.pagediv${pageIndex}`).toArray() : []),
].filter(x => x);
};
Object.defineProperty(BookReader.prototype, 'activeMode', {
/** @return {Mode1Up | Mode2Up | ModeThumb} */
get() { return {
1: this._modes.mode1Up,
2: this._modes.mode2Up,
3: this._modes.modeThumb,
}[this.mode]; },
});
/**
* BookReader.util are static library functions
* At top of file so they can be used below
*/
BookReader.util = utils;
/**
* Helper to merge in params in to a params object.
* It normalizes "page" into the "index" field to disambiguate and prevent concflicts
* @private
*/
BookReader.prototype.extendParams = function(params, newParams) {
const modifiedNewParams = $.extend({}, newParams);
if ('undefined' != typeof(modifiedNewParams.page)) {
const pageIndex = this.book.parsePageString(modifiedNewParams.page);
if (!isNaN(pageIndex))
modifiedNewParams.index = pageIndex;
delete modifiedNewParams.page;
}
$.extend(params, modifiedNewParams);
};
/**
* Parses params from from various initialization contexts (url, cookie, options)
* @private
* @return {object} the parsed params
*/
BookReader.prototype.initParams = function() {
const params = {};
// Flag initializing for updateFromParams()
params.init = true;
// Flag if page given in defaults or URL (not cookie)
// Used for overriding goToFirstResult in plugin.search.js
// Note: extendParams() converts params.page to index and gets rid of page
// so check and set before extendParams()
params.pageFound = false;
// True if changing the URL
params.fragmentChange = false;
// This is ordered from lowest to highest priority
// If we have a title leaf, use that as the default instead of index 0,
// but only use as default if book has a few pages
if ('undefined' != typeof(this.titleLeaf) && this.book.getNumLeafs() > 2) {
params.index = this.book.leafNumToIndex(this.titleLeaf);
} else {
params.index = 0;
}
// this.defaults is a string passed in the url format. eg "page/1/mode/1up"
if (this.defaults) {
const defaultParams = this.paramsFromFragment(this.defaults);
if ('undefined' != typeof(defaultParams.page)) {
params.pageFound = true;
}
this.extendParams(params, defaultParams);
}
// Check for Resume plugin
if (this.plugins.resume?.options.enabled) {
// Check cookies
const val = this.plugins.resume.getResumeValue();
if (val !== null) {
// If page index different from default
if (params.index !== val) {
// Show in URL
params.fragmentChange = true;
}
params.index = val;
}
}
// Check for URL plugin
if (this.options.enableUrlPlugin) {
// Params explicitly set in URL take precedence over all other methods
let urlParams = this.paramsFromFragment(this.urlReadFragment());
// Get params if hash fragment available with 'history' urlMode
const hasHashURL = !Object.keys(urlParams).length && this.urlReadHashFragment();
if (hasHashURL && (this.options.urlMode === 'history')) {
urlParams = this.paramsFromFragment(this.urlReadHashFragment());
}
// If there were any parameters
if (Object.keys(urlParams).length) {
if ('undefined' != typeof(urlParams.page)) {
params.pageFound = true;
}
this.extendParams(params, urlParams);
// Show in URL
params.fragmentChange = true;
}
}
// Check for Search plugin
if (this.plugins.search?.options.enabled) {
const sp = this.plugins.search;
// Go to first result only if no default or URL page
sp.options.goToFirstResult = !params.pageFound;
// If initialSearchTerm not set
if (!sp.initialSearchTerm) {
// Look for any term in URL
if (params.search) {
// Old style: /search/[term]
sp.options.initialSearchTerm = params.search;
sp.searchTerm = params.search;
} else {
// If we have a query string: q=[term]
const searchParams = new URLSearchParams(this.readQueryString());
const searchTerm = searchParams.get('q');
if (searchTerm) {
sp.options.initialSearchTerm = utils.decodeURIComponentPlus(searchTerm);
}
}
}
}
// Set for init process, return to false at end of init()
this.suppressFragmentChange = !params.fragmentChange;
return params;
};
/**
* Allow mocking of window.location.search
*/
BookReader.prototype.getLocationSearch = function () {
return window.location.search;
};
/**
* Allow mocking of window.location.hash
*/
BookReader.prototype.getLocationHash = function () {
return window.location.hash;
};
/**
* Return URL or fragment querystring
*/
BookReader.prototype.readQueryString = function() {
const queryString = this.getLocationSearch();
if (queryString) {
return queryString;
}
const hash = this.getLocationHash();
const found = hash.search(/\?\w+=/);
return found > -1 ? hash.slice(found) : '';
};
/**
* Determines the initial mode for starting if a mode is not already
* present in the params argument
* @param {object} params
* @return {1 | 2 | 3} the initial mode
*/
BookReader.prototype.getInitialMode = function(params) {
// if mobile breakpoint, we always show this.constMode1up mode
const windowWidth = $(window).width();
const isMobile = windowWidth && windowWidth <= this.onePageMinBreakpoint;
let initialMode;
if (params.mode) {
initialMode = params.mode;
} else if (isMobile) {
initialMode = this.constMode1up;
} else {
initialMode = this.constMode2up;
}
if (!this.canSwitchToMode(initialMode)) {
initialMode = this.constMode1up;
}
// override defaults mode via `options.defaults` metadata
if (this.options.defaults) {
try {
initialMode = _modeStringToNumber(this.options.defaults);
} catch (e) {
// Can ignore this error
}
}
return initialMode;
};
/**
* Converts a mode string to a the mode numeric constant
* @param {'mode/1up'|'mode/2up'|'mode/thumb'} modeString
* @return {1 | 2 | 3}
*/
export function _modeStringToNumber(modeString) {
const MAPPING = {
'mode/1up': 1,
'mode/2up': 2,
'mode/thumb': 3,
};
if (!(modeString in MAPPING)) {
throw new OptionsParseError(`Invalid mode string: ${modeString}`);
}
return MAPPING[modeString];
}
/**
* This is called by the client to initialize BookReader.
* It renders onto the DOM. It should only be called once.
*/
BookReader.prototype.init = function() {
this.init.initComplete = false;
this.pageScale = this.reduce; // preserve current reduce
const params = this.initParams();
this.firstIndex = params.index ? params.index : 0;
// Setup Navbars and other UI
this.isTouchDevice = !!('ontouchstart' in window) || !!('msmaxtouchpoints' in window.navigator);
this.refs.$br = $(this.el)
.empty()
.removeClass()
.addClass("ui-" + this.ui)
.addClass("br-ui-" + this.ui)
.addClass('BookReader');
// Add a class if this is a touch enabled device
if (this.isTouchDevice) {
this.refs.$br.addClass("touch");
} else {
this.refs.$br.addClass("no-touch");
}
this.refs.$brContainer = $("<div class='BRcontainer' dir='ltr'></div>");
this.refs.$br.append(this.refs.$brContainer);
// Explicitly ensure params.mode exists for updateFromParams() below
params.mode = this.getInitialMode(params);
// Explicitly ensure this.mode exists for initNavbar() below
this.mode = params.mode;
// Display Navigation
if (this.options.showToolbar) {
this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
}
if (this.options.showNavbar) { // default navigation
const $navBar = this.initNavbar();
// extend navbar with plugins
for (const plugin of Object.values(this.plugins)) {
plugin.extendNavBar($navBar);
}
}
// Switch navbar controls on mobile/desktop
this._components.navbar.switchNavbarControls();
this.resizeBRcontainer();
this.updateFromParams(params);
this.initUIStrings();
// Bind to events
this._components.navbar.bindControlClickHandlers();
for (const plugin of Object.values(this.plugins)) {
plugin._bindNavigationHandlers();
}
this.setupKeyListeners();
this.lastScroll = (new Date().getTime());
this.refs.$brContainer.on('scroll', this, function(e) {
// Note, this scroll event fires for both user, and js generated calls
// It is functioning in some cases as the primary triggerer for rendering
e.data.lastScroll = (new Date().getTime());
if (e.data.constModeThumb == e.data.mode) {
e.data.drawLeafsThrottled();
}
});
if (this.options.autoResize) {
$(window).on('resize', this, function(e) {
e.data.resize();
});
$(window).on("orientationchange", this, function(e) {
e.data.resize();
}.bind(this));
}
if (this.protected) {
this.$('.BRicon.share').hide();
}
// If not searching, set to allow on-going fragment changes
if (!this.plugins.search?.options.initialSearchTerm) {
this.suppressFragmentChange = false;
}
if (this.options.startFullscreen) {
this.enterFullscreen(true);
}
// Init plugins
for (const [pluginName, plugin] of Object.entries(this.plugins)) {
try {
plugin.init();
}
catch (e) {
console.error(`Error initializing plugin ${pluginName}`, e);
}
}
this.init.initComplete = true;
this.trigger(BookReader.eventNames.PostInit);
// Must be called after this.init.initComplete set to true to allow
// BookReader.prototype.resize to run.
};
/**
* @param {EVENTS} name
* @param {array | object} [props]
*/
BookReader.prototype.trigger = function(name, props = this) {
const eventName = 'BookReader:' + name;
utils.polyfillCustomEvent(window);
window.dispatchEvent(new CustomEvent(eventName, {
bubbles: true,
composed: true,
detail: { props },
}));
$(document).trigger(eventName, props);
};
BookReader.prototype.on = function(name, callback) {
$(document).on('BookReader:' + name, callback);
};
BookReader.prototype.off = function(name, callback) {
$(document).off('BookReader:' + name, callback);
};
/**
* @deprecated Use .on and .off instead
*/
BookReader.prototype.bind = function(name, callback) {
return this.on(name, callback);
};
/**
* @deprecated Use .on and .off instead
*/
BookReader.prototype.unbind = function(name, callback) {
return this.off(name, callback);
};
/**
* Resizes based on the container width and height
*/
BookReader.prototype.resize = function() {
if (!this.init.initComplete) return;
this.resizeBRcontainer();
// Switch navbar controls on mobile/desktop
this._components.navbar.switchNavbarControls();
if (this.constMode1up == this.mode) {
if (this.onePage.autofit != 'none') {
this._modes.mode1Up.resizePageView();
this.centerPageView();
} else {
this.centerPageView();
this.displayedIndices = [];
this.drawLeafsThrottled();
}
} else if (this.constModeThumb == this.mode) {
this._modes.modeThumb.prepare();
} else {
this._modes.mode2Up.resizePageView();
}
this.trigger(BookReader.eventNames.resize);
};
/**
* Binds keyboard and keyboard focus event listeners
*/
BookReader.prototype.setupKeyListeners = function () {
// Keyboard focus by BookReader in viewport
//
// Intersection observer and callback sets BookReader keyboard
// "focus" flag off when the BookReader is not in the viewport.
if (window.IntersectionObserver) {
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.intersectionRatio === 0) {
this.hasKeyFocus = false;
} else {
this.hasKeyFocus = true;
}
});
}, {
root: null,
rootMargin: '0px',
threshold: [0, 0.05, 1],
});
observer.observe(this.refs.$br[0]);
}
// Keyboard listeners
document.addEventListener('keydown', (e) => {
// Ignore if BookReader "focus" flag not set
if (!this.hasKeyFocus) {
return;
}
// Ignore if modifiers are active.
if (e.getModifierState('Control') ||
e.getModifierState('Alt') ||
e.getModifierState('Meta') ||
e.getModifierState('Win') /* hack for IE */) {
return;
}
// Ignore in input elements
if (utils.isInputActive()) {
return;
}
// KeyboardEvent code values:
// https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code/code_values
switch (e.key) {
// Page navigation
case "Home":
e.preventDefault();
this.first();
break;
case "End":
e.preventDefault();
this.last();
break;
case "PageDown":
// In 1up and thumb mode page scrolling handled by browser
if (this.constMode2up === this.mode) {
e.preventDefault();
this.next();
}
break;
case "PageUp":
// In 1up and thumb mode page scrolling handled by browser
if (this.constMode2up === this.mode) {
e.preventDefault();
this.prev();
}
break;
case "ArrowLeft":
case "Left": // hack for IE and old Gecko
// No y-scrolling in thumb mode
if (this.constModeThumb != this.mode) {
e.preventDefault();
this.left();
}
break;
case "ArrowRight":
case "Right": // hack for IE and old Gecko
// No y-scrolling in thumb mode
if (this.constModeThumb != this.mode) {
e.preventDefault();
this.right();
}
break;
// Zoom
case '-':
case 'Subtract':
e.preventDefault();
this.zoom(-1);
break;
case '+':
case '=':
case 'Add':
e.preventDefault();
this.zoom(1);
break;
// Fullscreen
case 'F':
case 'f':
e.preventDefault();
this.toggleFullscreen();
break;
}
});
};
BookReader.prototype.drawLeafs = function() {
if (this.constMode1up == this.mode) {
// Not needed for Mode1Up anymore
return;
} else {
this.activeMode.drawLeafs();
}
};
/**
* @protected
* @param {PageIndex} index
*/
BookReader.prototype._createPageContainer = function(index) {
const pageContainer = new PageContainer(this.book.getPage(index, false), {
isProtected: this.protected,
imageCache: this.imageCache,
});
// Call plugin handlers
for (const plugin of Object.values(this.plugins)) {
plugin._configurePageContainer(pageContainer);
}
return pageContainer;
};
BookReader.prototype.bindGestures = function(jElement) {
// TODO support gesture change is only iOS. Support android.
// HACK(2017-01-20) - Momentum scrolling is causing the scroll position
// to jump after zooming in on mobile device. I am able to reproduce
// when you move the book with one finger and then add another
// finger to pinch. Gestures are aware of scroll state.
const self = this;
let numTouches = 1;
jElement.unbind('touchmove').bind('touchmove', function(e) {
if (e.originalEvent.cancelable) numTouches = e.originalEvent.touches.length;
e.stopPropagation();
});
jElement.unbind('gesturechange').bind('gesturechange', function(e) {
e.preventDefault();
// These are two very important fixes to adjust for the scroll position
// issues described below
if (!(numTouches !== 2 || (new Date().getTime()) - self.lastScroll < 500)) {
if (e.originalEvent.scale > 1.5) {
self.zoom(1);
} else if (e.originalEvent.scale < 0.6) {
self.zoom(-1);
}
}
});
};
/**
* A throttled version of drawLeafs
*/
BookReader.prototype.drawLeafsThrottled = utils.throttle(
BookReader.prototype.drawLeafs,
250, // 250 ms gives quick feedback, but doesn't eat cpu
);
/**
* @param {number} direction Pass 1 to zoom in, anything else to zoom out
*/