-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathreader.js
1620 lines (1427 loc) · 50 KB
/
reader.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
import { createRoot } from 'react-dom/client';
import React, { createContext } from 'react';
import { IntlProvider } from 'react-intl';
import ReaderUI from './components/reader-ui';
import PDFView from '../pdf/pdf-view';
import EPUBView from '../dom/epub/epub-view';
import SnapshotView from '../dom/snapshot/snapshot-view';
import AnnotationManager from './annotation-manager';
import {
createAnnotationContextMenu,
createColorContextMenu,
createSelectorContextMenu, createThumbnailContextMenu,
createViewContextMenu
} from './context-menu';
import { initPDFPrintService } from '../pdf/pdf-print-service';
import { ANNOTATION_COLORS, DEBOUNCE_STATE_CHANGE, DEBOUNCE_STATS_CHANGE } from './defines';
import { FocusManager } from './focus-manager';
import { KeyboardManager } from './keyboard-manager';
import {
getImageDataURL, isMac,
setMultiDragPreview,
} from './lib/utilities';
import { debounce } from './lib/debounce';
// Compute style values for usage in views (CSS variables aren't sufficient for that)
// Font family is necessary for text annotations
window.computedFontFamily = window.getComputedStyle(document.body).getPropertyValue('font-family');
export const ReaderContext = createContext({});
class Reader {
constructor(options) {
window.rtl = options.rtl;
document.getElementsByTagName("html")[0].dir = options.rtl ? 'rtl' : 'ltr';
this._type = options.type;
this._platform = options.platform;
this._data = options.data;
this._password = options.password;
this._preview = options.preview;
this._readerContext = { type: this._type, platform: this._platform };
this._onSaveAnnotations = options.onSaveAnnotations;
this._onDeleteAnnotations = options.onDeleteAnnotations;
this._onOpenTagsPopup = options.onOpenTagsPopup;
this._onAddToNote = options.onAddToNote;
this._onOpenContextMenu = options.onOpenContextMenu;
this._onToggleSidebar = options.onToggleSidebar;
this._onChangeSidebarWidth = options.onChangeSidebarWidth;
this._onChangeViewState = options.onChangeViewState;
this._onOpenLink = options.onOpenLink;
this._onCopyImage = options.onCopyImage;
this._onSaveImageAs = options.onSaveImageAs;
this._onConfirm = options.onConfirm;
this._onRotatePages = options.onRotatePages;
this._onDeletePages = options.onDeletePages;
this._onToggleContextPane = options.onToggleContextPane;
this._onToolbarShiftTab = options.onToolbarShiftTab;
this._onIframeTab = options.onIframeTab;
this._onBringReaderToFront = options.onBringReaderToFront;
this._onTextSelectionAnnotationModeChange = options.onTextSelectionAnnotationModeChange;
// Only used on Zotero client, sets text/plain and text/html values from Note Markdown and Note HTML translators
this._onSetDataTransferAnnotations = options.onSetDataTransferAnnotations;
this._onSetZoom = options.onSetZoom;
this._localizedStrings = options.localizedStrings;
this._readerRef = React.createRef();
this._primaryView = null;
this._secondaryView = null;
this._lastViewPrimary = true;
this.initializedPromise = new Promise(resolve => this._resolveInitializedPromise = resolve);
this._splitViewContainer = document.getElementById('split-view');
this._primaryViewContainer = document.getElementById('primary-view');
this._secondaryViewContainer = document.getElementById('secondary-view');
this._enableAnnotationDeletionFromComment = false;
this._annotationSelectionTriggeredFromView = false;
this._tools = {
pointer: {
type: 'pointer'
},
hand: {
type: 'hand'
},
highlight: {
type: 'highlight',
color: ANNOTATION_COLORS[0][1],
},
underline: {
type: 'underline',
color: ANNOTATION_COLORS[0][1],
},
note: {
type: 'note',
color: ANNOTATION_COLORS[0][1],
},
image: {
type: 'image',
color: ANNOTATION_COLORS[0][1],
},
text: {
type: 'text',
color: ANNOTATION_COLORS[0][1],
},
ink: {
type: 'ink',
color: ANNOTATION_COLORS[3][1],
size: 2
},
eraser: {
type: 'eraser',
size: 16
}
};
this._state = {
splitType: null,
splitSize: '50%',
primary: true,
freeze: false,
errorMessage: '',
annotations: [],
selectedAnnotationIDs: [],
filter: {
query: '',
colors: [],
tags: [],
authors: []
},
readOnly: options.readOnly !== undefined ? options.readOnly : false,
authorName: typeof options.authorName === 'string' ? options.authorName : '',
fontSize: options.fontSize || 1,
fontFamily: options.fontFamily,
hyphenate: options.hyphenate,
showAnnotations: options.showAnnotations !== undefined ? options.showAnnotations : true, // show/hide annotations in views
useDarkModeForContent: options.useDarkModeForContent !== undefined ? options.useDarkModeForContent : true,
textSelectionAnnotationMode: options.textSelectionAnnotationMode || 'highlight',
colorScheme: options.colorScheme,
tool: this._tools['pointer'], // Must always be a reference to one of this._tools objects
thumbnails: [],
outline: null, // null — loading, [] — empty
pageLabels: [],
sidebarOpen: options.sidebarOpen !== undefined ? options.sidebarOpen : true,
sidebarWidth: options.sidebarWidth !== undefined ? options.sidebarWidth : 240,
sidebarView: 'annotations',
bottomPlaceholderHeight: options.bottomPlaceholderHeight || null,
toolbarPlaceholderWidth: options.toolbarPlaceholderWidth || 0,
showContextPaneToggle: options.showContextPaneToggle,
enableAddToNote: false,
labelPopup: null,
passwordPopup: null,
printPopup: null,
contextMenu: null,
primaryViewState: options.primaryViewState,
primaryViewStats: {},
primaryViewAnnotationPopup: null,
primaryViewSelectionPopup: null,
primaryViewOverlayPopup: null,
primaryViewEPUBAppearancePopup: null,
primaryViewFindState: {
popupOpen: false,
active: false,
query: '',
highlightAll: true,
caseSensitive: false,
entireWord: false,
result: null,
},
secondaryViewState: null,
secondaryViewStats: {},
secondaryViewAnnotationPopup: null,
secondaryViewSelectionPopup: null,
secondaryViewOverlayPopup: null,
secondaryViewEPUBAppearancePopup: null,
secondaryViewFindState: {
popupOpen: false,
active: false,
query: '',
highlightAll: true,
caseSensitive: false,
entireWord: false,
result: null
},
a11yVirtualCursorTarget: {
node: null,
ts: null
}
};
if (options.secondaryViewState) {
let state = { ...options.secondaryViewState };
this._state.splitType = state.splitType;
this._state.splitSize = state.splitSize;
delete state.splitType;
delete state.splitSize;
this._state.secondaryViewState = state;
}
this._focusManager = new FocusManager({
reader: this,
onDeselectAnnotations: () => {
this.setSelectedAnnotations([]);
},
onToolbarShiftTab: () => {
this._onToolbarShiftTab();
},
onIframeTab: () => {
this._onIframeTab();
}
});
this._keyboardManager = new KeyboardManager({
reader: this
});
this._annotationManager = new AnnotationManager({
readOnly: this._state.readOnly,
authorName: options.authorName,
annotations: options.annotations,
onSave: this._onSaveAnnotations,
onDelete: this._handleDeleteAnnotations,
onRender: (annotations) => {
this._updateState({ annotations });
},
onChangeFilter: (filter) => {
this._updateState({ filter });
}
});
this._primaryView = this._createView(true, options.location);
if (!this._preview) {
createRoot(document.getElementById('reader-ui')).render(
<IntlProvider
locale={window.navigator.language}
messages={this._localizedStrings}
onError={window.development && (() => {
})}
>
<ReaderContext.Provider value={this._readerContext}>
<ReaderUI
type={this._type}
state={this._state}
onSelectAnnotations={this.setSelectedAnnotations.bind(this)}
onZoomIn={this.zoomIn.bind(this)}
onZoomOut={this.zoomOut.bind(this)}
onZoomReset={this.zoomReset.bind(this)}
onNavigateBack={this.navigateBack.bind(this)}
onNavigateToPreviousPage={this.navigateToPreviousPage.bind(this)}
onNavigateToNextPage={this.navigateToNextPage.bind(this)}
onChangePageNumber={pageNumber => this.navigate({ pageNumber })}
onChangeTool={this.setTool.bind(this)}
onToggleEPUBAppearance={this.toggleEPUBAppearancePopup.bind(this)}
onToggleFind={this.toggleFindPopup.bind(this)}
onChangeFilter={this.setFilter.bind(this)}
onChangeSidebarView={this.setSidebarView.bind(this)}
onToggleSidebar={(open) => {
this.toggleSidebar(open);
this._onToggleSidebar(open);
}}
onResizeSidebar={(width) => {
this.setSidebarWidth(width);
this._onChangeSidebarWidth(width);
}}
onResizeSplitView={this.setSplitViewSize.bind(this)}
onAddAnnotation={(annotation) => {
this._annotationManager.addAnnotation(annotation);
this.setSelectedAnnotations([]);
}}
onUpdateAnnotations={(annotations) => {
this._annotationManager.updateAnnotations(annotations);
this._enableAnnotationDeletionFromComment = false;
}}
onDeleteAnnotations={this._annotationManager.deleteAnnotations.bind(this._annotationManager)}
onOpenTagsPopup={this._onOpenTagsPopup}
onOpenPageLabelPopup={this._handleOpenPageLabelPopup.bind(this)}
onOpenColorContextMenu={params => this._onOpenContextMenu(createColorContextMenu(this, params))}
onOpenAnnotationContextMenu={params => this._onOpenContextMenu(createAnnotationContextMenu(this, params))}
onOpenSelectorContextMenu={params => this._onOpenContextMenu(createSelectorContextMenu(this, params))}
onOpenThumbnailContextMenu={params => this._onOpenContextMenu(createThumbnailContextMenu(this, params))}
onCloseContextMenu={this.closeContextMenu.bind(this)}
onCloseLabelPopup={this._handleLabelPopupClose.bind(this)}
onEnterPassword={this.enterPassword.bind(this)}
onAddToNote={(annotations) => {
this._onAddToNote(annotations);
this.setSelectedAnnotations([]);
}}
onNavigate={this.navigate.bind(this)}
onUpdateOutline={outline => this._updateState({ outline })}
onRenderThumbnails={(pageIndexes) => this._primaryView._pdfThumbnails.render(pageIndexes)}
onSetDataTransferAnnotations={this._handleSetDataTransferAnnotations.bind(this)}
onOpenLink={this._onOpenLink}
onChangeEPUBAppearance={this._handleEPUBAppearanceChange.bind(this)}
onChangeFindState={this._handleFindStateChange.bind(this)}
onFindNext={this.findNext.bind(this)}
onFindPrevious={this.findPrevious.bind(this)}
onToggleContextPane={this._onToggleContextPane}
onChangeTextSelectionAnnotationMode={this.setTextSelectionAnnotationMode.bind(this)}
ref={this._readerRef}
/>
</ReaderContext.Provider>
</IntlProvider>
);
}
this._updateState(this._state, true);
// window.addEventListener("wheel", event => {
// const delta = Math.sign(event.deltaY);
// console.info(event.target, delta);
// event.preventDefault();
// }, { passive: false });
if (this._platform !== 'web') {
window.addEventListener('contextmenu', (event) => {
if (event.target.nodeName !== 'INPUT' && !event.target.hasAttribute('contenteditable')) {
event.preventDefault();
}
});
}
}
_ensureType() {
if (!Array.from(arguments).includes(this._type)) {
throw new Error(`The operation is not supported for '${this._type}'`);
}
}
get _lastView() {
return this._lastViewPrimary ? this._primaryView : this._secondaryView;
}
_updateState(state, init) {
let previousState = this._state;
this._state = { ...this._state, ...state };
this._readerRef.current?.setState(this._state);
if (this._state.annotations !== previousState.annotations) {
let annotations = this._state.annotations.filter(x => !x._hidden);
this._primaryView?.setAnnotations(annotations);
this._secondaryView?.setAnnotations(annotations);
}
if (this._state.selectedAnnotationIDs !== previousState.selectedAnnotationIDs) {
this._primaryView?.setSelectedAnnotationIDs(this._state.selectedAnnotationIDs);
this._secondaryView?.setSelectedAnnotationIDs(this._state.selectedAnnotationIDs);
}
if (this._state.tool !== previousState.tool) {
this._primaryView?.setTool(this._state.tool);
this._secondaryView?.setTool(this._state.tool);
}
if (this._state.showAnnotations !== previousState.showAnnotations) {
this._primaryView?.setShowAnnotations(this._state.showAnnotations);
this._secondaryView?.setShowAnnotations(this._state.showAnnotations);
}
if (init || this._state.useDarkModeForContent !== previousState.useDarkModeForContent) {
document.body.classList.toggle(
'use-dark-mode-for-content',
this._state.useDarkModeForContent
);
if (!init) {
this._primaryView?.setUseDarkMode(this._state.useDarkModeForContent);
this._secondaryView?.setUseDarkMode(this._state.useDarkModeForContent);
}
}
if (init || this._state.colorScheme !== previousState.colorScheme) {
if (this._state.colorScheme) {
document.documentElement.dataset.colorScheme = this._state.colorScheme;
}
else {
delete document.documentElement.dataset.colorScheme;
}
if (!init) {
this._primaryView?.setColorScheme(this._state.colorScheme);
this._secondaryView?.setColorScheme(this._state.colorScheme);
// also update useDarkModeForContent as it depends on colorScheme
this._primaryView?.setUseDarkMode(this._state.useDarkModeForContent);
this._secondaryView?.setUseDarkMode(this._state.useDarkModeForContent);
}
}
if (this._state.readOnly !== previousState.readOnly) {
this._annotationManager.setReadOnly(this._state.readOnly);
this._primaryView?.setReadOnly?.(this._state.readOnly);
this._secondaryView?.setReadOnly?.(this._state.readOnly);
}
if (this._state.pageLabels !== previousState.pageLabels) {
this._primaryView?.setPageLabels(this._state.pageLabels);
this._secondaryView?.setPageLabels(this._state.pageLabels);
}
if (this._state.primaryViewAnnotationPopup !== previousState.primaryViewAnnotationPopup) {
this._primaryView?.setAnnotationPopup(this._state.primaryViewAnnotationPopup);
}
if (this._state.secondaryViewAnnotationPopup !== previousState.secondaryViewAnnotationPopup) {
this._secondaryView?.setAnnotationPopup(this._state.secondaryViewAnnotationPopup);
}
if (this._state.primaryViewSelectionPopup !== previousState.primaryViewSelectionPopup) {
this._primaryView?.setSelectionPopup(this._state.primaryViewSelectionPopup);
}
if (this._state.secondaryViewSelectionPopup !== previousState.secondaryViewSelectionPopup) {
this._secondaryView?.setSelectionPopup(this._state.secondaryViewSelectionPopup);
}
if (this._state.primaryViewOverlayPopup !== previousState.primaryViewOverlayPopup) {
this._primaryView?.setOverlayPopup(this._state.primaryViewOverlayPopup);
}
if (this._state.secondaryViewOverlayPopup !== previousState.secondaryViewOverlayPopup) {
this._secondaryView?.setOverlayPopup(this._state.secondaryViewOverlayPopup);
}
if (this._state.primaryViewFindState !== previousState.primaryViewFindState) {
this._primaryView?.setFindState(this._state.primaryViewFindState);
}
if (this._state.secondaryViewFindState !== previousState.secondaryViewFindState) {
this._secondaryView?.setFindState(this._state.secondaryViewFindState);
}
if (this._type === 'epub') {
if (this._state.fontFamily !== previousState.fontFamily) {
this._primaryView?.setFontFamily(this._state.fontFamily);
this._secondaryView?.setFontFamily(this._state.fontFamily);
}
if (this._state.hyphenate !== previousState.hyphenate) {
this._primaryView?.setHyphenate(this._state.hyphenate);
this._secondaryView?.setHyphenate(this._state.hyphenate);
}
}
if (init || this._state.sidebarView !== previousState.sidebarView) {
this._primaryView?.setSidebarView?.(this._state.sidebarView);
this._secondaryView?.setSidebarView?.(this._state.sidebarView);
}
if (init || this._state.sidebarOpen !== previousState.sidebarOpen) {
if (this._state.sidebarOpen) {
document.body.classList.add('sidebar-open');
}
else {
document.body.classList.remove('sidebar-open');
}
this._primaryView?.setSidebarOpen(this._state.sidebarOpen);
this._secondaryView?.setSidebarOpen(this._state.sidebarOpen);
}
if (init || this._state.splitType !== previousState.splitType) {
document.body.classList.remove('enable-horizontal-split-view');
document.body.classList.remove('enable-vertical-split-view');
// Split
if ((!previousState.splitType || init) && this._state.splitType) {
document.body.classList.add(
this._state.splitType === 'vertical'
? 'enable-vertical-split-view'
: 'enable-horizontal-split-view'
);
this._updateState({ secondaryViewState: { ...this._state.primaryViewState } });
this._secondaryView = this._createView(false);
}
// Unsplit
else if ((previousState.splitType || init) && !this._state.splitType) {
this._secondaryView?.destroy();
this._secondaryView = null;
this._secondaryViewContainer.replaceChildren();
this._lastViewPrimary = true;
this._onChangeViewState(null, false);
}
// Change existing split type
else {
document.body.classList.add(
this._state.splitType === 'vertical'
? 'enable-vertical-split-view'
: 'enable-horizontal-split-view'
);
}
}
if (init || this._state.splitSize !== previousState.splitSize) {
document.documentElement.style.setProperty('--split-view-size', this._state.splitSize);
}
if (init || this._state.sidebarWidth !== previousState.sidebarWidth) {
document.documentElement.style.setProperty('--sidebar-width', this._state.sidebarWidth + 'px');
}
if (init || this._state.bottomPlaceholderHeight !== previousState.bottomPlaceholderHeight) {
let root = document.documentElement;
root.style.setProperty('--bottom-placeholder-height', (this._state.bottomPlaceholderHeight || 0) + 'px');
}
if (init || this._state.toolbarPlaceholderWidth !== previousState.toolbarPlaceholderWidth) {
let root = document.documentElement;
root.style.setProperty('--toolbar-placeholder-width', this._state.toolbarPlaceholderWidth + 'px');
}
if (init || this._state.fontSize !== previousState.fontSize) {
let root = document.documentElement;
root.style.fontSize = this._state.fontSize + 'em';
}
if (init || this._state.freeze !== previousState.freeze) {
if (this._state.freeze) {
document.body.classList.add('freeze');
}
else {
document.body.classList.remove('freeze');
}
}
}
disableSplitView() {
this._updateState({ splitType: null });
}
toggleHorizontalSplit(enable) {
if (enable === undefined) {
enable = !this._state.splitType || this._state.splitType !== 'horizontal';
}
if (enable) {
this._updateState({ splitType: 'horizontal' });
}
else {
this.disableSplitView();
}
}
toggleVerticalSplit(enable) {
if (enable === undefined) {
enable = !this._state.splitType || this._state.splitType !== 'vertical';
}
if (enable) {
this._updateState({ splitType: 'vertical' });
}
else {
this.disableSplitView();
}
}
get splitType() {
return this._state.splitType;
}
setTool(params) {
if (this._state.readOnly && !['pointer', 'hand'].includes(params.type)) {
return;
}
let tool = this._state.tool;
if (params.type && tool.type !== params.type) {
tool = this._tools[params.type];
}
for (let key in params) {
tool[key] = params[key];
}
this._updateState({ tool });
if (!['pointer', 'hand'].includes(tool.type)) {
this.setSelectedAnnotations([]);
}
}
toggleTool(type) {
let tool = this._state.tool;
if (tool.type === type) {
this._updateState({ tool: this._tools.pointer });
}
else {
this._updateState({ tool: this._tools[type] });
}
this.setSelectedAnnotations([]);
}
setFilter(filter) {
this._annotationManager.setFilter(filter);
}
showAnnotations(enable) {
this._updateState({ showAnnotations: enable });
}
useDarkModeForContent(use) {
this._updateState({ useDarkModeForContent: use });
}
setColorScheme(colorScheme) {
this._updateState({ colorScheme });
}
setReadOnly(readOnly) {
// Also unset any active tool
this._updateState({ readOnly, tool: this._tools['pointer'] });
}
toggleHandTool(enable) {
if (enable === undefined) {
enable = this._state.tool.type !== 'hand';
}
if (enable) {
this.setTool({ type: 'hand' });
} else {
this.setTool({ type: 'pointer' });
}
}
enableAddToNote(enable) {
this._updateState({ enableAddToNote: enable });
}
setAnnotations(annotations) {
this._annotationManager.setAnnotations(annotations);
}
unsetAnnotations(ids) {
this._annotationManager.unsetAnnotations(ids);
}
openContextMenu(params) {
this._onBringReaderToFront?.(true);
this._updateState({ contextMenu: params });
setTimeout(() => {
window.focus();
document.activeElement.blur();
});
}
closeContextMenu() {
this._updateState({ contextMenu: null });
this._focusManager.restoreFocus();
this._onBringReaderToFront?.(false);
}
_handleEPUBAppearanceChange(params) {
this._ensureType('epub');
this._primaryView?.setAppearance(params);
this._secondaryView?.setAppearance(params);
}
_handleFindStateChange(primary, params) {
this._updateState({ [primary ? 'primaryViewFindState' : 'secondaryViewFindState']: params });
}
setTextSelectionAnnotationMode(mode) {
if (!['highlight', 'underline'].includes(mode)) {
throw new Error(`Invalid 'textSelectionAnnotationMode' value '${mode}'`);
}
this._updateState({ textSelectionAnnotationMode: mode });
this._onTextSelectionAnnotationModeChange(mode);
}
findNext(primary) {
if (primary === undefined) {
primary = this._lastViewPrimary;
}
(primary ? this._primaryView : this._secondaryView).findNext();
}
findPrevious(primary) {
if (primary === undefined) {
primary = this._lastViewPrimary;
}
(primary ? this._primaryView : this._secondaryView).findPrevious();
}
toggleEPUBAppearancePopup({ open }) {
let key = 'epubAppearancePopup';
if (open === undefined) {
open = !this._state[key];
}
if (open) {
this.toggleFindPopup({ primary: true, open: false });
this.toggleFindPopup({ primary: false, open: false });
}
this._updateState({ [key]: open });
if (open) {
setTimeout(() => {
let selector = '.epub-appearance-popup input';
document.querySelector(selector)?.focus();
}, 100);
}
else {
this._focusManager.restoreFocus();
}
}
toggleFindPopup({ primary, open } = {}) {
if (primary === undefined) {
primary = this._lastViewPrimary;
}
let key = primary ? 'primaryViewFindState' : 'secondaryViewFindState';
let findState = this._state[key];
if (open === undefined) {
open = !findState.popupOpen;
}
if (open) {
this.toggleEPUBAppearancePopup({ primary, open: false });
}
findState = { ...findState, popupOpen: open, active: false, result: null };
this._updateState({ [key]: findState });
if (open) {
setTimeout(() => {
let selector = (primary ? '.primary' : '.secondary') + ' .find-popup input';
document.querySelector(selector)?.select();
document.querySelector(selector)?.focus();
}, 100);
}
}
_sidebarScrollAnnotationIntoViev(id) {
this._readerRef.current.sidebarScrollAnnotationIntoView(id);
}
_sidebarEditAnnotationText(id) {
this._readerRef.current.sidebarEditAnnotationText(id);
}
_getString(name) {
return this._localizedStrings[name] || name;
}
_createView(primary, location) {
let view;
let container = primary ? this._primaryViewContainer : this._secondaryViewContainer;
let onSetThumbnails = (thumbnails) => {
this._updateState({ thumbnails });
};
let onSetOutline = (outline) => {
this._updateState({ outline });
};
let onSetPageLabels = (pageLabels) => {
this._updateState({ pageLabels });
};
let onChangeViewState = debounce((state) => {
this._updateState({ [primary ? 'primaryViewState' : 'secondaryViewState']: state });
if (!primary) {
let { splitType, splitSize } = this._state;
state = { ...state, splitType, splitSize };
}
this._onChangeViewState(state, primary);
}, DEBOUNCE_STATE_CHANGE);
let onChangeViewStats = debounce((state) => {
this._updateState({ [primary ? 'primaryViewStats' : 'secondaryViewStats']: state });
}, DEBOUNCE_STATS_CHANGE);
let onAddAnnotation = (annotation, select) => {
annotation = this._annotationManager.addAnnotation(annotation);
if (select) {
this.setSelectedAnnotations([annotation.id], true);
}
if (['note', 'text'].includes(annotation.type)) {
this.setTool({ type: 'pointer' });
}
return annotation;
};
let onUpdateAnnotations = (annotations) => {
this._annotationManager.updateAnnotations(annotations);
};
let onDeleteAnnotations = (ids) => {
this._annotationManager.deleteAnnotations(ids);
};
let onOpenLink = (url) => {
this._onOpenLink(url);
};
let onFocus = () => {
this.focusView(primary);
// A workaround for Firefox/Zotero because iframe focusing doesn't trigger 'focusin' event
this._focusManager._closeFindPopupIfEmpty();
this.placeA11yVirtualCursor();
};
let onRequestPassword = () => {
if (primary) {
this._updateState({ passwordPopup: {} });
}
};
let onOpenAnnotationContextMenu = (params) => {
this._onOpenContextMenu(createAnnotationContextMenu(this, params));
};
let onOpenViewContextMenu = (params) => {
// Trigger view context menu after focus even fires and focuses the current view
setTimeout(() => this._onOpenContextMenu(createViewContextMenu(this, params)));
};
let onSetSelectionPopup = (selectionPopup) => {
this._updateState({ [primary ? 'primaryViewSelectionPopup' : 'secondaryViewSelectionPopup']: selectionPopup });
};
let onSetAnnotationPopup = (annotationPopup) => {
this._updateState({ [primary ? 'primaryViewAnnotationPopup' : 'secondaryViewAnnotationPopup']: annotationPopup });
};
let onSetOverlayPopup = (overlayPopup) => {
this._updateState({ [primary ? 'primaryViewOverlayPopup' : 'secondaryViewOverlayPopup']: overlayPopup });
};
let onSetFindState = (params) => {
this._updateState({ [primary ? 'primaryViewFindState' : 'secondaryViewFindState']: params });
};
let onSelectAnnotations = (ids, triggeringEvent) => {
this.setSelectedAnnotations(ids, true, triggeringEvent);
};
let onTabOut = (reverse) => {
this._focusManager.tabToGroup(reverse);
};
let onKeyDown = (event) => {
this._keyboardManager.handleViewKeyDown(event);
};
let onKeyUp = (event) => {
this._keyboardManager.handleViewKeyUp(event);
};
let onSetZoom = this._onSetZoom && ((iframe, zoom) => {
this._onSetZoom(iframe, zoom);
});
let onEPUBEncrypted = () => {
this.setErrorMessage(this._getString('pdfReader.epubEncrypted'));
};
let onFocusAnnotation = (annotation) => {
if (!annotation) return;
// Announce the current annotation to screen readers
let annotationType = this._getString(`pdfReader.${annotation.type}Annotation`);
let annotationContent = `${annotationType}. ${annotation.text || annotation.comment}`;
this.setA11yMessage(annotationContent);
}
// Add page number as aria-label to provided node to improve screen reader navigation
let setA11yNavContent = (node, pageIndex) => {
node.setAttribute('aria-label', `${this._getString("pdfReader.page")}: ${pageIndex}`);
};
// Set which node should receive focus when the focus enters the reader to
// help screen readers place virtual cursor at the right location
let setA11yVirtualCursorTarget = (node) => {
if (node && node !== this._state.a11yVirtualCursorTarget.node) {
this._updateState({ a11yVirtualCursorTarget: { node, ts: Date.now() } });
}
// Clear the cursor only half a second after it was set. It ensures the
// target is not cleared by scrolling of the document during outline navigation.
// Particularly important for snapshots where a random scroll event would fire after
// debounceUntilScrollFinishes is done. In all other instances of scrolling,
// the virtual cursor target is cleared
if (node === null && Date.now() - this._state.a11yVirtualCursorTarget.ts > 500) {
this._updateState({ a11yVirtualCursorTarget: { node: null, ts: null } });
}
};
// Announce the search index, page and snippet of the search result
let a11yAnnounceSearchMessage = (index, total, pageLabel, snippet) => {
let searchIndex = `${this._getString("pdfReader.searchResultIndex")}: ${index + 1}.`;
let totalResults = `${this._getString("pdfReader.searchResultTotal")}: ${total}.`;
let page = pageLabel !== null ? `${this._getString("pdfReader.page")}: ${pageLabel}.` : "";
this.setA11yMessage(`${searchIndex} ${totalResults} ${snippet || ""} ${page}`);
};
let data;
if (this._type === 'pdf') {
data = this._data;
}
else if (this._primaryView) {
data = this._primaryView.getData();
}
else {
data = this._data;
delete this._data;
}
let common = {
primary,
container,
data,
platform: this._platform,
readOnly: this._state.readOnly,
preview: this._preview,
tool: this._state.tool,
selectedAnnotationIDs: this._state.selectedAnnotationIDs,
annotations: this._state.annotations.filter(x => !x._hidden),
showAnnotations: this._state.showAnnotations,
useDarkMode: this._state.useDarkModeForContent,
colorScheme: this._state.colorScheme,
findState: this._state[primary ? 'primaryViewFindState' : 'secondaryViewFindState'],
viewState: this._state[primary ? 'primaryViewState' : 'secondaryViewState'],
location,
onChangeViewState,
onChangeViewStats,
onSetDataTransferAnnotations: this._handleSetDataTransferAnnotations.bind(this),
onAddAnnotation,
onUpdateAnnotations,
onOpenLink,
onFocus,
onOpenAnnotationContextMenu,
onOpenViewContextMenu,
onSetSelectionPopup,
onSetAnnotationPopup,
onSetOverlayPopup,
onSetFindState,
onSetOutline,
onSelectAnnotations,
onTabOut,
onKeyDown,
onKeyUp,
onFocusAnnotation,
setA11yVirtualCursorTarget,
a11yAnnounceSearchMessage
};
if (this._type === 'pdf') {
view = new PDFView({
...common,
password: this._password,
pageLabels: this._state.pageLabels,
onRequestPassword,
onSetThumbnails,
onSetPageLabels,
onDeleteAnnotations // For complete ink erase
});
if (primary) {
initPDFPrintService({
onProgress: (percent) => {
this._handleSetPrintPopup({ percent });
},
onFinish: () => {
this._handleSetPrintPopup(null);
},
pdfView: view
});
}
} else if (this._type === 'epub') {
view = new EPUBView({
...common,
fontFamily: this._state.fontFamily,
hyphenate: this._state.hyphenate,
onEPUBEncrypted,
setA11yNavContent,
});
} else if (this._type === 'snapshot') {
view = new SnapshotView({
...common,
onSetZoom
});
}
if (primary) {
view.initializedPromise.then(() => view.focus());
}
return view;
}
setErrorMessage(errorMessage) {
this._updateState({ errorMessage });
}
// Set content of aria-live container that screen readers will announce
setA11yMessage(a11yMessage) {
// Voiceover won't announce messages inserted via <div id="a11yAnnouncement" aria-live="polite">{state.a11yMessage}</div>
// but setting .innerText does work. Likely due to either voiceover bug or not full aria-live support by firefox.
document.getElementById("a11yAnnouncement").innerText = a11yMessage;
}
// Make a11yVirtualCursorTarget node set previously focusable and
// focus it to help screen readers understand where the virtual cursor needs to
// be positioned. This is required because screen readers are not aware of
// scroll positioning, so without this, the virtual cursor will always land
// at the start of the document.
placeA11yVirtualCursor() {
let target = this._state.a11yVirtualCursorTarget.node;
let doc = this._lastView._iframe.contentDocument;
// If the target is a text node, use its parent (e.g. <p> or <h>)
if (target?.nodeType === Node.TEXT_NODE) {
target = target.parentNode;