-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathviewer.js
More file actions
1776 lines (1443 loc) · 60.4 KB
/
viewer.js
File metadata and controls
1776 lines (1443 loc) · 60.4 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
/* eslint-disable import/no-cycle */
import scribe from './scribe.js/scribe.js';
import Konva from './js/konva/index.js';
import { search } from './js/viewerSearch.js';
import {
KonvaDataColumn, KonvaLayout, KonvaRegion, layout,
} from './js/viewerLayout.js';
import { clearObjectProperties } from './scribe.js/js/utils/miscUtils.js';
import { KonvaIText, KonvaOcrWord } from './js/viewerWordObjects.js';
import { ViewerImageCache } from './js/viewerImageCache.js';
import { handleKeyboardEvent } from './js/viewerShortcuts.js';
import { contextMenuFunc, mouseupFunc2 } from './js/viewerCanvasInteraction.js';
import {
deleteSelectedWord, modifySelectedWordBbox, modifySelectedWordStyle,
} from './js/viewerModifySelectedWords.js';
import { getAllFileEntries } from './js/dragAndDrop.js';
import { deleteSelectedLayoutDataTable, deleteSelectedLayoutRegion } from './js/viewerModifySelectedLayout.js';
import { applyHighlight, removeHighlight, modifyHighlightComment, updateHighlightGroupOutline } from './js/viewerHighlights.js';
Konva.autoDrawEnabled = false;
Konva.dragButtons = [0];
class stateViewer {
static recognizeAllPromise = Promise.resolve();
static layoutMode = false;
static searchMode = false;
/** @type {'color'|'gray'|'binary'} */
static colorMode = 'color';
static cp = {
n: 0,
};
}
/**
* This object contains the values of options for the GUI that do not directly map to options in the `scribe` module.
* This includes both GUI-specific options and options that are implemented through arguments rather than the `opts` object.
*/
class optViewer {
static enableRecognition = true;
static enableXlsxExport = false;
static downloadFormat = 'pdf';
static vanillaMode = false;
static langs = ['eng'];
/** @type {'conf'|'data'} */
static combineMode = 'data';
/**
* Whether to show the intermediate, internal versions of OCR.
* This is useful for debugging and testing, but should not be enabled by default.
*/
static showInternalOCRVersions = false;
static outlineWords = false;
static outlineLines = false;
static outlinePars = false;
}
let evalStatsConfig = {
/** @type {string|undefined} */
ocrActive: undefined,
ignorePunct: scribe.opt.ignorePunct,
ignoreCap: scribe.opt.ignoreCap,
ignoreExtra: scribe.opt.ignoreExtra,
};
/** @type {Array<EvalMetrics>} */
const evalStats = [];
/**
* Class for managing the selection of words, layout boxes, and data columns on the canvas.
* This is a class due to JSDoc type considerations. All methods and properties are static.
*/
class CanvasSelection {
/** @type {Array<KonvaOcrWord>} */
static _selectedWordArr = [];
/** @type {?KonvaOcrWord} */
static selectedWordFirst = null;
/** @type {Array<import('./js/viewerLayout.js').KonvaRegion>} */
static _selectedRegionArr = [];
/** @type {Array<KonvaDataColumn>} */
static _selectedDataColumnArr = [];
static getKonvaWords = () => CanvasSelection._selectedWordArr;
static getKonvaRegions = () => CanvasSelection._selectedRegionArr;
static getKonvaDataColumns = () => CanvasSelection._selectedDataColumnArr;
static getKonvaWordsCopy = () => CanvasSelection._selectedWordArr.slice();
static getKonvaRegionsCopy = () => CanvasSelection._selectedRegionArr.slice();
static getKonvaDataColumnsCopy = () => CanvasSelection._selectedDataColumnArr.slice();
static getKonvaLayoutBoxes = () => [...CanvasSelection._selectedRegionArr, ...CanvasSelection._selectedDataColumnArr];
static getDataTables = () => ([...new Set(CanvasSelection._selectedDataColumnArr.map((x) => x.layoutBox.table))]);
static getKonvaDataTables = () => ([...new Set(CanvasSelection._selectedDataColumnArr.map((x) => x.konvaTable))]);
/**
* Add word or array of words to the current selection.
* Ignores words that are already selected.
* @param {KonvaOcrWord|Array<KonvaOcrWord>} words
*/
static addWords = (words) => {
if (!Array.isArray(words)) words = [words];
for (let i = 0; i < words.length; i++) {
const wordI = words[i];
if (i === 0 && CanvasSelection._selectedWordArr.length === 0) CanvasSelection.selectedWordFirst = wordI;
if (!CanvasSelection._selectedWordArr.map((x) => x.word.id).includes(wordI.word.id)) {
CanvasSelection._selectedWordArr.push(wordI);
}
}
};
/**
* Add layout boxes, including both regions and data columns, to the current selection.
* Ignores boxes that are already selected.
* @param {Array<import('./js/viewerLayout.js').KonvaRegion|import('./js/viewerLayout.js').KonvaDataColumn>|
* import('./js/viewerLayout.js').KonvaRegion|import('./js/viewerLayout.js').KonvaDataColumn} konvaLayoutBoxes
*/
static addKonvaLayoutBoxes = (konvaLayoutBoxes) => {
let konvaLayoutBoxesArr;
if (konvaLayoutBoxes instanceof KonvaRegion || konvaLayoutBoxes instanceof KonvaDataColumn) {
konvaLayoutBoxesArr = [konvaLayoutBoxes];
} else {
konvaLayoutBoxesArr = konvaLayoutBoxes;
}
konvaLayoutBoxesArr.forEach((konvaLayoutBox) => {
if (konvaLayoutBox instanceof KonvaDataColumn) {
if (!CanvasSelection._selectedDataColumnArr.map((x) => x.layoutBox.id).includes(konvaLayoutBox.layoutBox.id)) {
CanvasSelection._selectedDataColumnArr.push(konvaLayoutBox);
}
} else if (!CanvasSelection._selectedRegionArr.map((x) => x.layoutBox.id).includes(konvaLayoutBox.layoutBox.id)) {
CanvasSelection._selectedRegionArr.push(konvaLayoutBox);
}
});
// Other code assumes that these arrays are sorted left to right.
CanvasSelection._selectedDataColumnArr.sort((a, b) => a.layoutBox.coords.left - b.layoutBox.coords.left);
CanvasSelection._selectedRegionArr.sort((a, b) => a.layoutBox.coords.left - b.layoutBox.coords.left);
};
/**
*
* @param {Array<string>} layoutBoxIdArr
*/
static selectLayoutBoxesById = (layoutBoxIdArr) => {
// eslint-disable-next-line no-use-before-define
const konvaLayoutBoxes = ScribeViewer.getKonvaRegions().filter((x) => layoutBoxIdArr.includes(x.layoutBox.id));
// eslint-disable-next-line no-use-before-define
const konvaDataColumns = ScribeViewer.getKonvaDataColumns().filter((x) => layoutBoxIdArr.includes(x.layoutBox.id));
CanvasSelection.selectLayoutBoxes([...konvaLayoutBoxes, ...konvaDataColumns]);
};
/**
*
* @param {Array<KonvaRegion|KonvaDataColumn>} konvaLayoutBoxes
*/
static selectLayoutBoxes = (konvaLayoutBoxes) => {
// eslint-disable-next-line no-use-before-define
const selectedLayoutBoxes = ScribeViewer.CanvasSelection.getKonvaRegions();
// eslint-disable-next-line no-use-before-define
const selectedDataColumns = ScribeViewer.CanvasSelection.getKonvaDataColumns();
// eslint-disable-next-line no-use-before-define
ScribeViewer.CanvasSelection.addKonvaLayoutBoxes(konvaLayoutBoxes);
selectedDataColumns.forEach((shape) => (shape.select()));
selectedLayoutBoxes.forEach((shape) => (shape.select()));
};
/**
* Get arrays of distinct font families and font sizes from the selected words.
*/
static getWordProperties = () => {
const fontFamilyArr = Array.from(new Set(CanvasSelection._selectedWordArr.map((x) => (x.fontFamilyLookup))));
const fontSizeArr = Array.from(new Set(CanvasSelection._selectedWordArr.map((x) => (x.fontSize))));
return { fontFamilyArr, fontSizeArr };
};
/**
* Get arrays of distinct layout box properties from the selected layout boxes.
* Includes both layout boxes and data columns.
*/
static getLayoutBoxProperties = () => {
const selectedWordsAll = CanvasSelection.getKonvaLayoutBoxes();
const inclusionRuleArr = Array.from(new Set(selectedWordsAll.map((x) => (x.layoutBox.inclusionRule))));
const inclusionLevelArr = Array.from(new Set(selectedWordsAll.map((x) => (x.layoutBox.inclusionLevel))));
return { inclusionRuleArr, inclusionLevelArr };
};
/**
*
* @param {number} [n]
*/
static deselectAllWords = (n) => {
for (let i = CanvasSelection._selectedWordArr.length - 1; i >= 0; i--) {
if (n === null || n === undefined || CanvasSelection._selectedWordArr[i].word.line.page.n === n) {
CanvasSelection._selectedWordArr[i].deselect();
CanvasSelection._selectedWordArr.splice(i, 1);
}
}
if (CanvasSelection.selectedWordFirst && (n === null || n === undefined)) {
CanvasSelection.selectedWordFirst = null;
} else if (CanvasSelection.selectedWordFirst && CanvasSelection.selectedWordFirst.word.line.page.n === n) {
CanvasSelection.selectedWordFirst = CanvasSelection._selectedWordArr[0] || null;
}
};
static deselectAllRegions = () => {
CanvasSelection._selectedRegionArr.forEach((shape) => (shape.deselect()));
CanvasSelection._selectedRegionArr.length = 0;
};
static deselectAllDataColumns = () => {
CanvasSelection._selectedDataColumnArr.forEach((shape) => (shape.deselect()));
CanvasSelection._selectedDataColumnArr.length = 0;
};
static deselectAll = () => {
CanvasSelection.deselectAllWords();
CanvasSelection.deselectAllRegions();
CanvasSelection.deselectAllDataColumns();
};
/**
*
* @param {string|Array<string>} ids
*/
static deselectDataColumnsByIds = (ids) => {
if (!Array.isArray(ids)) ids = [ids];
for (let j = 0; j < CanvasSelection._selectedDataColumnArr.length; j++) {
if (ids.includes(CanvasSelection._selectedDataColumnArr[j].layoutBox.id)) {
CanvasSelection._selectedDataColumnArr.splice(j, 1);
j--;
}
}
};
static deleteSelectedWord = deleteSelectedWord;
static modifySelectedWordBbox = modifySelectedWordBbox;
static modifySelectedWordStyle = modifySelectedWordStyle;
static deleteSelectedLayoutDataTable = deleteSelectedLayoutDataTable;
static deleteSelectedLayoutRegion = deleteSelectedLayoutRegion;
static applyHighlight = applyHighlight;
static removeHighlight = removeHighlight;
static modifyHighlightComment = modifyHighlightComment;
static updateHighlightGroupOutline = updateHighlightGroupOutline;
}
function getCenter(p1, p2) {
return {
x: (p1.x + p2.x) / 2,
y: (p1.y + p2.y) / 2,
};
}
function getDistance(p1, p2) {
return Math.sqrt((p2.x - p1.x) ** 2 + (p2.y - p1.y) ** 2);
}
let mouseDownTarget;
/**
* @typedef {import('./js/konva/Node.js').KonvaEventObject<MouseEvent>} KonvaMouseEvent
* @typedef {import('./js/konva/Node.js').KonvaEventObject<TouchEvent>} KonvaTouchEvent
* @typedef {import('./js/konva/Node.js').KonvaEventObject<WheelEvent>} KonvaWheelEvent
*/
/**
* Class for managing the selection of words, layout boxes, and data columns on the canvas.
* Only one canvas should be used at a time, as most properties are static.
*/
export class ScribeViewer {
/** @type {HTMLElement} */
static elem;
/** @type {HTMLDivElement} */
static HTMLOverlayBackstopElem;
static textOverlayHidden = false;
/** @type {Array<number>} */
static #pageStopsStart = [];
/** @type {Array<number>} */
static #pageStopsEnd = [];
/**
*
* @param {number} n
* @param {boolean} start
* @returns {number}
*/
static getPageStop = (n, start = true) => {
// This needs to be here to prevent `ScribeCanvas.calcPageStops` from being called before the final page dimensions are known.
// This is an issue when a PDF is being uploaded alongside existing OCR data, as the correct dimensions are not known until the OCR data is parsed.
if (start && n === 0) return 30;
if (start && ScribeViewer.#pageStopsStart[n]) return ScribeViewer.#pageStopsStart[n];
if (!start && ScribeViewer.#pageStopsEnd[n]) return ScribeViewer.#pageStopsEnd[n];
ScribeViewer.calcPageStops();
if (start && ScribeViewer.#pageStopsStart[n]) return ScribeViewer.#pageStopsStart[n];
if (!start && ScribeViewer.#pageStopsEnd[n]) return ScribeViewer.#pageStopsEnd[n];
// The `null` condition is only true briefly during initialization, and is not worth checking for every time throughout the program.
// @ts-ignore
return null;
};
/** @type {?Function} */
static displayPageCallback = null;
/** @type {Array<InstanceType<typeof Konva.Rect>>} */
static placeholderRectArr = [];
static calcPageStops = () => {
const margin = 30;
let y = margin;
for (let i = 0; i < scribe.data.pageMetrics.length; i++) {
ScribeViewer.#pageStopsStart[i] = y;
const dims = scribe.data.pageMetrics[i]?.dims;
if (!dims) return;
// TODO: This does not work because angle is not populated at this point.
// This is true even when uploading a PDF with existing OCR data, as dims are defined before parsing the OCR data.
const rotation = (scribe.data.pageMetrics[i].angle || 0) * -1;
y += dims.height + margin;
ScribeViewer.#pageStopsEnd[i] = y;
if (!ScribeViewer.placeholderRectArr[i]) {
ScribeViewer.placeholderRectArr[i] = new Konva.Rect({
x: 0,
y: ScribeViewer.getPageStop(i),
width: dims.width,
height: dims.height,
stroke: 'black',
strokeWidth: 2,
strokeScaleEnabled: false,
listening: false,
rotation,
});
ScribeViewer.layerBackground.add(ScribeViewer.placeholderRectArr[i]);
}
}
};
/**
*
* @returns {{x: number, y: number}}
*/
static getStageCenter = () => {
const layerWidth = ScribeViewer.stage.width();
const layerHeight = ScribeViewer.stage.height();
// Calculate the center point of the layer before any transformations
const centerPoint = {
x: layerWidth / 2,
y: layerHeight / 2,
};
return centerPoint;
};
/**
*
* @param {InstanceType<typeof Konva.Layer>|InstanceType<typeof Konva.Stage>} layer
* @param {number} scaleBy
* @param {{x: number, y: number}} center - The center point to zoom in/out from.
*/
static _zoomStageImp = (layer, scaleBy, center) => {
const oldScale = layer.scaleX();
const mousePointTo = {
x: (center.x - layer.x()) / oldScale,
y: (center.y - layer.y()) / oldScale,
};
const newScale = oldScale * scaleBy;
layer.scaleX(newScale);
layer.scaleY(newScale);
const newPos = {
x: center.x - mousePointTo.x * newScale,
y: center.y - mousePointTo.y * newScale,
};
layer.position(newPos);
};
/**
*
* @param {number} scaleBy
* @param {?{x: number, y: number}} [center=null] - The center point to zoom in/out from.
* If `null` (default), the center of the layer is used.
*/
static _zoomStage = (scaleBy, center = null) => {
if (!center) {
const selectedWords = ScribeViewer.CanvasSelection.getKonvaWords();
// If words are selected, zoom in on the selection.
if (selectedWords.length > 0) {
const selectionLeft = Math.min(...selectedWords.map((x) => x.x()));
const selectionRight = Math.max(...selectedWords.map((x) => x.x() + x.width()));
const selectionTop = Math.min(...selectedWords.map((x) => x.y()));
const selectionBottom = Math.max(...selectedWords.map((x) => x.y() + x.height()));
const center0 = { x: (selectionLeft + selectionRight) / 2, y: (selectionTop + selectionBottom) / 2 };
const transform = ScribeViewer.layerText.getAbsoluteTransform();
// Apply the transformation to the center point
center = transform.point(center0);
// Otherwise, zoom in on the center of the text layer.
} else {
center = ScribeViewer.getStageCenter();
}
}
ScribeViewer._zoomStageImp(ScribeViewer.stage, scaleBy, center);
if (!ScribeViewer.updateCurrentPage()) {
ScribeViewer.stage.batchDraw();
}
};
static updateCurrentPage = () => {
const y = (ScribeViewer.stage.y() - ScribeViewer.stage.height() / 2) / ScribeViewer.stage.getAbsoluteScale().y * -1;
const pageNew = ScribeViewer.calcPage(y);
if (stateViewer.cp.n !== pageNew && pageNew >= 0) {
ScribeViewer.displayPage(pageNew, false, false);
return true;
}
return false;
};
/**
*
* @param {Object} coords
* @param {number} [coords.deltaX=0]
* @param {number} [coords.deltaY=0]
*/
static panStage = ({ deltaX = 0, deltaY = 0 }) => {
const x = ScribeViewer.stage.x();
const y = ScribeViewer.stage.y();
// Clip the inputs to prevent the user from panning the entire document outside of the viewport.
if (stateViewer.cp.n === 0) {
const maxY = (ScribeViewer.getPageStop(0) - 100) * ScribeViewer.stage.getAbsoluteScale().y * -1 + ScribeViewer.stage.height() / 2;
const maxYDelta = Math.max(0, maxY - y);
deltaY = Math.min(deltaY, maxYDelta);
}
if (stateViewer.cp.n === scribe.data.pageMetrics.length - 1) {
const minY = ScribeViewer.getPageStop(stateViewer.cp.n, false) * ScribeViewer.stage.getAbsoluteScale().y * -1
+ ScribeViewer.stage.height() / 2;
const minYDelta = Math.max(0, y - minY);
deltaY = Math.max(deltaY, -minYDelta);
}
// Prevent panning the document outside of the viewport.
// These limits impose the less restrictive of:
// (1) half of the document must be within the viewport, or
// (2) half of the viewport must contain the document.
const minX1 = (scribe.data.pageMetrics[stateViewer.cp.n].dims.width / 2) * ScribeViewer.stage.getAbsoluteScale().y * -1;
const minX2 = scribe.data.pageMetrics[stateViewer.cp.n].dims.width * ScribeViewer.stage.getAbsoluteScale().y * -1 + ScribeViewer.stage.width() / 2;
const minX = Math.min(minX1, minX2);
const minXDelta = Math.max(0, x - minX);
deltaX = Math.max(deltaX, -minXDelta);
const maxX1 = (scribe.data.pageMetrics[stateViewer.cp.n].dims.width / 2) * ScribeViewer.stage.getAbsoluteScale().y * -1
+ ScribeViewer.stage.width();
const maxX2 = ScribeViewer.stage.width() / 2;
const maxX = Math.max(maxX1, maxX2);
const maxXDelta = Math.max(0, maxX - x);
deltaX = Math.min(deltaX, maxXDelta);
ScribeViewer.stage.x(x + deltaX);
ScribeViewer.stage.y(y + deltaY);
if (!ScribeViewer.updateCurrentPage()) {
ScribeViewer.stage.batchDraw();
}
};
/**
* Zoom in or out on the canvas.
* This function should be used for mapping buttons or other controls to zooming,
* as it handles redrawing the text overlay in addition to zooming the canvas.
* @param {number} scaleBy
* @param {?{x: number, y: number}} [center=null] - The center point to zoom in/out from.
* If `null` (default), the center of the layer is used.
*/
static zoom = (scaleBy, center = null) => {
ScribeViewer.deleteHTMLOverlay();
ScribeViewer._zoomStage(scaleBy, center);
if (ScribeViewer.enableHTMLOverlay) ScribeViewer.renderHTMLOverlayAfterDelay();
};
/**
* Initiates dragging if the middle mouse button is pressed.
* @param {MouseEvent} event
*/
static startDrag = (event) => {
ScribeViewer.deleteHTMLOverlay();
ScribeViewer.drag.isDragging = true;
ScribeViewer.drag.lastX = event.x;
ScribeViewer.drag.lastY = event.y;
event.preventDefault();
};
/**
* Initiates dragging if the middle mouse button is pressed.
* @param {KonvaTouchEvent} event
*/
static startDragTouch = (event) => {
ScribeViewer.deleteHTMLOverlay();
ScribeViewer.drag.isDragging = true;
ScribeViewer.drag.lastX = event.evt.touches[0].clientX;
ScribeViewer.drag.lastY = event.evt.touches[0].clientY;
event.evt.preventDefault();
};
/**
* Updates the layer's position based on mouse movement.
* @param {KonvaMouseEvent} event
*/
static executeDrag = (event) => {
if (ScribeViewer.drag.isDragging) {
const deltaX = event.evt.x - ScribeViewer.drag.lastX;
const deltaY = event.evt.y - ScribeViewer.drag.lastY;
if (Math.round(deltaX) === 0 && Math.round(deltaY) === 0) return;
// This is an imprecise heuristic, so not bothering to calculate distance properly.
ScribeViewer.drag.dragDeltaTotal += Math.abs(deltaX);
ScribeViewer.drag.dragDeltaTotal += Math.abs(deltaY);
ScribeViewer.drag.lastX = event.evt.x;
ScribeViewer.drag.lastY = event.evt.y;
ScribeViewer.panStage({ deltaX, deltaY });
}
};
/**
* @param {KonvaTouchEvent} event
*/
static executeDragTouch = (event) => {
if (ScribeViewer.drag.isDragging) {
const deltaX = event.evt.touches[0].clientX - ScribeViewer.drag.lastX;
const deltaY = event.evt.touches[0].clientY - ScribeViewer.drag.lastY;
ScribeViewer.drag.lastX = event.evt.touches[0].clientX;
ScribeViewer.drag.lastY = event.evt.touches[0].clientY;
ScribeViewer.panStage({ deltaX, deltaY });
}
};
/**
* Stops dragging when the mouse button is released.
* @param {KonvaMouseEvent|KonvaTouchEvent} event
*/
static stopDragPinch = (event) => {
ScribeViewer.drag.isDragging = false;
ScribeViewer.drag.isPinching = false;
ScribeViewer.drag.dragDeltaTotal = 0;
ScribeViewer.drag.lastCenter = null;
ScribeViewer.drag.lastDist = null;
if (ScribeViewer.enableHTMLOverlay && ScribeViewer._wordHTMLArr.length === 0) {
ScribeViewer.renderHTMLOverlay();
}
};
/**
* @param {KonvaTouchEvent} event
*/
static executePinchTouch = (event) => {
ScribeViewer.deleteHTMLOverlay();
const touch1 = event.evt.touches[0];
const touch2 = event.evt.touches[1];
if (!touch1 || !touch2) return;
ScribeViewer.drag.isPinching = true;
const p1 = {
x: touch1.clientX,
y: touch1.clientY,
};
const p2 = {
x: touch2.clientX,
y: touch2.clientY,
};
const center = getCenter(p1, p2);
const dist = getDistance(p1, p2);
if (!ScribeViewer.drag.lastDist || !ScribeViewer.drag.lastCenter) {
ScribeViewer.drag.lastCenter = center;
ScribeViewer.drag.lastDist = dist;
return;
}
ScribeViewer._zoomStage(dist / ScribeViewer.drag.lastDist, center);
ScribeViewer.drag.lastDist = dist;
if (ScribeViewer.enableHTMLOverlay) ScribeViewer.renderHTMLOverlayAfterDelay();
};
/**
* Function called after the canvas is interacted with, whether by a click or a keyboard event.
* @param {*} event
*/
static interactionCallback = (event) => {};
/**
* Function called after controls are destroyed.
* @param {boolean} deselect
*/
static destroyControlsCallback = (deselect) => {};
/**
*
* @param {HTMLDivElement} elem
* @param {number} width
* @param {number} height
*/
static init(elem, width, height) {
this.elem = elem;
ScribeViewer.stage = new Konva.Stage({
container: elem,
// width: document.documentElement.clientWidth,
// height: document.documentElement.clientHeight,
// width: this.elem.scrollWidth,
// height: this.elem.scrollHeight,
width,
height,
});
ScribeViewer.stage.on('contextmenu', contextMenuFunc);
ScribeViewer.HTMLOverlayBackstopElem = document.createElement('div');
ScribeViewer.HTMLOverlayBackstopElem.className = 'endOfContent';
ScribeViewer.HTMLOverlayBackstopElem.style.position = 'absolute';
ScribeViewer.HTMLOverlayBackstopElem.style.top = '0';
ScribeViewer.HTMLOverlayBackstopElem.style.left = '0';
ScribeViewer.HTMLOverlayBackstopElem.style.width = `${width}px`;
ScribeViewer.HTMLOverlayBackstopElem.style.height = `${height}px`;
ScribeViewer.HTMLOverlayBackstopElem.style.display = 'none';
ScribeViewer.layerBackground = new Konva.Layer();
ScribeViewer.layerText = new Konva.Layer();
ScribeViewer.layerOverlay = new Konva.Layer();
ScribeViewer.stage.add(ScribeViewer.layerBackground);
ScribeViewer.stage.add(ScribeViewer.layerText);
ScribeViewer.stage.add(ScribeViewer.layerOverlay);
ScribeViewer.selectingRectangle = new Konva.Rect({
fill: 'rgba(40,123,181,0.5)',
visible: true,
// disable events to not interrupt with events
listening: false,
});
ScribeViewer.layerText.add(ScribeViewer.selectingRectangle);
ScribeViewer.stage.on('mousemove', ScribeViewer.executeDrag);
ScribeViewer.stage.on('touchstart', (event) => {
if (ScribeViewer.mode === 'select') {
if (event.evt.touches[1]) {
ScribeViewer.executePinchTouch(event);
} else {
ScribeViewer.startDragTouch(event);
}
}
});
ScribeViewer.stage.on('touchmove', (event) => {
if (event.evt.touches[1]) {
ScribeViewer.executePinchTouch(event);
} else if (ScribeViewer.drag.isDragging) {
ScribeViewer.executeDragTouch(event);
}
});
ScribeViewer.stage.on('mousedown touchstart', (event) => {
if (scribe.data.pageMetrics.length === 0) return;
// Left click only
if (event.type === 'mousedown' && event.evt.button !== 0) return;
if (!ScribeViewer.enableCanvasSelection) return;
mouseDownTarget = event.target;
if (ScribeViewer.isTouchScreen && ScribeViewer.mode === 'select') return;
// Move selection rectangle to top.
ScribeViewer.selectingRectangle.zIndex(ScribeViewer.layerText.children.length - 1);
event.evt.preventDefault();
const startCoords = ScribeViewer.layerText.getRelativePointerPosition() || { x: 0, y: 0 };
ScribeViewer.bbox.left = startCoords.x;
ScribeViewer.bbox.top = startCoords.y;
ScribeViewer.bbox.right = startCoords.x;
ScribeViewer.bbox.bottom = startCoords.y;
ScribeViewer.selectingRectangle.width(0);
ScribeViewer.selectingRectangle.height(0);
ScribeViewer.selecting = true;
});
ScribeViewer.stage.on('mousemove touchmove', (e) => {
e.evt.preventDefault();
// do nothing if we didn't start selection
if (!ScribeViewer.selecting) {
return;
}
e.evt.preventDefault();
const endCoords = ScribeViewer.layerText.getRelativePointerPosition();
if (!endCoords) return;
ScribeViewer.bbox.right = endCoords.x;
ScribeViewer.bbox.bottom = endCoords.y;
ScribeViewer.selectingRectangle.setAttrs({
visible: true,
x: Math.min(ScribeViewer.bbox.left, ScribeViewer.bbox.right),
y: Math.min(ScribeViewer.bbox.top, ScribeViewer.bbox.bottom),
width: Math.abs(ScribeViewer.bbox.right - ScribeViewer.bbox.left),
height: Math.abs(ScribeViewer.bbox.bottom - ScribeViewer.bbox.top),
});
ScribeViewer.layerText.batchDraw();
});
ScribeViewer.stage.on('mouseup touchend', (event) => {
// const navBarElem = /** @type {HTMLDivElement} */(document.getElementById('navBar'));
// const activeElem = document.activeElement instanceof HTMLElement ? document.activeElement : null;
// if (activeElem && navBarElem.contains(activeElem)) activeElem.blur();
// For dragging layout boxes, other events are needed to stop the drag.
if (!stateViewer.layoutMode) {
event.evt.preventDefault();
event.evt.stopPropagation();
}
const mouseUpTarget = event.target;
const editingWord = !!ScribeViewer.KonvaIText.input;
// If a word is being edited, the only action allowed is clicking outside the word to deselect it.
if (editingWord) {
if (mouseDownTarget === ScribeViewer.KonvaIText.inputWord || mouseUpTarget === ScribeViewer.KonvaIText.inputWord) {
ScribeViewer.selecting = false;
return;
}
ScribeViewer.destroyControls();
ScribeViewer.layerText.batchDraw();
// Delete any current selections if either (1) this is a new selection or (2) nothing is being clicked.
// Clicks must pass this check on both start and end.
// This prevents accidentally clearing a selection when the user is trying to highlight specific letters, but the mouse up happens over another word.
} else if (event.evt.button === 0 && (mouseUpTarget instanceof Konva.Stage || mouseUpTarget instanceof Konva.Image)
&& (ScribeViewer.selecting || event.target instanceof Konva.Stage || event.target instanceof Konva.Image)) {
ScribeViewer.destroyControls();
}
ScribeViewer.selecting = false;
// Return early if this was a drag or pinch rather than a selection.
// `isDragging` will be true even for a touch event, so a minimum distance moved is required to differentiate between a click and a drag.
if (event.evt.button === 1 || (ScribeViewer.drag.isDragging && ScribeViewer.drag.dragDeltaTotal > 10) || ScribeViewer.drag.isPinching || ScribeViewer.drag.isResizingColumns) {
ScribeViewer.stopDragPinch(event);
return;
}
mouseupFunc2(event);
ScribeViewer.mode = 'select';
ScribeViewer.layerText.batchDraw();
});
}
static renderHTMLOverlay = () => {
const words = ScribeViewer.getKonvaWords();
words.forEach((word) => {
const elem = KonvaIText.itextToElem(word);
ScribeViewer._wordHTMLArr.push(elem);
ScribeViewer.elem.appendChild(elem);
});
};
static _renderHTMLOverlayEvents = 0;
/**
* Render the HTML overlay after 150ms, if no other events have been triggered in the meantime.
* This function should be called whenever a frequently-triggered event needs to render the HTML overlay,
* such as scrolling or zooming, which can result in performance issues if the overlay is rendered too frequently.
*/
static renderHTMLOverlayAfterDelay = () => {
ScribeViewer._renderHTMLOverlayEvents++;
const eventN = ScribeViewer._renderHTMLOverlayEvents;
setTimeout(() => {
if (eventN === ScribeViewer._renderHTMLOverlayEvents && ScribeViewer._wordHTMLArr.length === 0) {
ScribeViewer.renderHTMLOverlay();
}
}, 200);
};
static deleteHTMLOverlay = () => {
ScribeViewer._wordHTMLArr.forEach((elem) => {
if (elem.parentNode) {
elem.parentNode.removeChild(elem);
}
});
ScribeViewer._wordHTMLArr.length = 0;
};
static runSetInitial = true;
/**
* Set the initial position and zoom of the canvas to reasonable defaults.
* @param {dims} imgDims - Dimensions of image
*/
static setInitialPositionZoom = (imgDims) => {
ScribeViewer.runSetInitial = false;
const totalHeight = document.documentElement.clientHeight;
const interfaceHeight = 100;
const bottomMarginHeight = 50;
const targetHeight = totalHeight - interfaceHeight - bottomMarginHeight;
const zoom = targetHeight / imgDims.height;
ScribeViewer.stage.scaleX(zoom);
ScribeViewer.stage.scaleY(zoom);
ScribeViewer.stage.x(((ScribeViewer.stage.width() - (imgDims.width * zoom)) / 2));
ScribeViewer.stage.y(interfaceHeight);
};
// Function that handles page-level info for rendering to canvas
static renderWords = async (n) => {
let ocrData = scribe.data.ocr.active?.[n];
// Return early if there is not enough data to render a page yet
// (0) Necessary info is not defined yet
const noInfo = scribe.inputData.xmlMode[n] === undefined;
// (1) No data has been imported
const noInput = !scribe.inputData.xmlMode[n] && !(scribe.inputData.imageMode || scribe.inputData.pdfMode);
// (2) XML data should exist but does not (yet)
const xmlMissing = scribe.inputData.xmlMode[n]
&& (ocrData === undefined || ocrData === null || scribe.data.pageMetrics[n].dims === undefined);
const pageStopsMissing = ScribeViewer.getPageStop(n) === null;
const imageMissing = false;
const pdfMissing = false;
if (ScribeViewer.#textGroups[n]) {
for (const group of Object.values(ScribeViewer.#textGroups[n])) {
group.destroyChildren();
}
}
if (ScribeViewer.KonvaIText.inputWord && ScribeViewer.KonvaIText.inputWord.word.line.page.n === n
&& ScribeViewer.KonvaIText.inputRemove
) {
ScribeViewer.KonvaIText.inputRemove();
}
ScribeViewer.CanvasSelection.deselectAllWords(n);
if (noInfo || noInput || xmlMissing || imageMissing || pdfMissing || pageStopsMissing) {
return;
}
if (scribe.inputData.evalMode) {
await compareGroundTruth();
// ocrData must be re-assigned after comparing to ground truth or it will not update.
ocrData = scribe.data.ocr.active?.[n];
}
if (scribe.inputData.xmlMode[n]) {
renderCanvasWords(ocrData);
}
};
/**
* Render page `n` in the UI.
* @param {number} n
* @param {boolean} [scroll=false] - Scroll to the top of the page being rendered.
* @param {boolean} [refresh=true] - Refresh the page even if it is already displayed.
* @returns
*/
static async displayPage(n, scroll = false, refresh = true) {
// Return early if (1) page does not exist or (2) another page is actively being rendered.
if (Number.isNaN(n) || n < 0 || n > (scribe.inputData.pageCount - 1)) {
// Reset the value of pageNumElem (number in UI) to match the internal value of the page
// elem.nav.pageNum.value = (stateGUI.cp.n + 1).toString();
if (ScribeViewer.displayPageCallback) ScribeViewer.displayPageCallback();
return;
}
if (ScribeViewer.runSetInitial) {
ScribeViewer.setInitialPositionZoom(scribe.data.pageMetrics[n].dims);
}
ScribeViewer.deleteHTMLOverlay();
if (scribe.inputData.xmlMode[stateViewer.cp.n]) {
// TODO: This is currently run whenever the page is changed.
// If this adds any meaningful overhead, we should only have stats updated when edits are actually made.
search.updateFindStats();
}
if (scribe.opt.displayMode === 'ebook') {
ScribeViewer.layerBackground.hide();
ScribeViewer.layerBackground.batchDraw();
} else {
ScribeViewer.layerBackground.show();
ScribeViewer.layerBackground.batchDraw();
}
ScribeViewer.textOverlayHidden = false;
if (refresh || !ScribeViewer.textGroupsRenderIndices.includes(n)) {
await ScribeViewer.renderWords(n);
}
if (n - 1 >= 0 && (refresh || !ScribeViewer.textGroupsRenderIndices.includes(n - 1))) {
await ScribeViewer.renderWords(n - 1);
}
if (n + 1 < scribe.data.ocr.active.length && (refresh || !ScribeViewer.textGroupsRenderIndices.includes(n + 1))) {
await ScribeViewer.renderWords(n + 1);
}
if (scroll) {
ScribeViewer.stage.y((ScribeViewer.getPageStop(n) - 100) * ScribeViewer.stage.getAbsoluteScale().y * -1);
}
ScribeViewer.layerText.batchDraw();
stateViewer.cp.n = n;
ScribeViewer.destroyText();
ScribeViewer.destroyOverlay();
if (ScribeViewer.enableHTMLOverlay && !ScribeViewer.drag.isDragging && !ScribeViewer.drag.isPinching) {
ScribeViewer.renderHTMLOverlayAfterDelay();
}
if (ScribeViewer.displayPageCallback) ScribeViewer.displayPageCallback();
if (stateViewer.layoutMode) {
if (refresh || !ScribeViewer.overlayGroupsRenderIndices.includes(n)) {
await layout.renderLayoutBoxes(n);
}
if (n - 1 >= 0 && (refresh || !ScribeViewer.overlayGroupsRenderIndices.includes(n - 1))) {
await layout.renderLayoutBoxes(n - 1);
}
if (n + 1 < scribe.data.ocr.active.length && (refresh || !ScribeViewer.overlayGroupsRenderIndices.includes(n + 1))) {
await layout.renderLayoutBoxes(n + 1);
}
}
// Render background images ahead and behind current page to reduce delay when switching pages
if ((scribe.inputData.pdfMode || scribe.inputData.imageMode)) {