-
Notifications
You must be signed in to change notification settings - Fork 105
/
Annotator.js
778 lines (693 loc) · 23.7 KB
/
Annotator.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
import EventEmitter from 'events';
import autobind from 'autobind-decorator';
import AnnotationService from './AnnotationService';
import * as annotatorUtil from './annotatorUtil';
import { ICON_CLOSE } from '../icons/icons';
import './Annotator.scss';
import {
CLASS_ACTIVE,
CLASS_HIDDEN,
DATA_TYPE_ANNOTATION_DIALOG,
CLASS_MOBILE_ANNOTATION_DIALOG,
CLASS_ANNOTATION_DIALOG,
CLASS_ANNOTATION_DRAW_MODE,
CLASS_ANNOTATION_POINT_MODE,
CLASS_MOBILE_DIALOG_HEADER,
CLASS_DIALOG_CLOSE,
SELECTOR_ANNOTATION_BUTTON_DRAW_CANCEL,
SELECTOR_ANNOTATION_BUTTON_DRAW_ENTER,
SELECTOR_ANNOTATION_BUTTON_DRAW_POST,
TYPES
} from './annotationConstants';
@autobind
class Annotator extends EventEmitter {
//--------------------------------------------------------------------------
// Typedef
//--------------------------------------------------------------------------
/**
* The data object for constructing an Annotator.
* @typedef {Object} AnnotatorData
* @property {HTMLElement} annotatedElement HTML element to annotate on
* @property {AnnotationService} [annotationService] Annotations CRUD service
* @property {string} fileVersionId File version ID
*/
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
/**
* [constructor]
*
* @param {AnnotatorData} data - Data for constructing an Annotator
* @return {Annotator} Annotator instance
*/
constructor(data) {
super();
this.canAnnotate = data.canAnnotate;
this.container = data.container;
this.options = data.options;
this.fileVersionId = data.fileVersionId;
this.locale = data.locale;
this.validationErrorEmitted = false;
this.isMobile = data.isMobile;
this.previewUI = data.previewUI;
this.modeButtons = data.modeButtons;
this.annotationModeHandlers = [];
}
/**
* [destructor]
*
* @return {void}
*/
destroy() {
this.unbindModeListeners();
if (this.threads) {
Object.keys(this.threads).forEach((page) => {
this.threads[page].forEach((thread) => {
this.unbindCustomListenersOnThread(thread);
});
});
}
this.unbindDOMListeners();
this.unbindCustomListenersOnService();
}
/**
* Initializes annotator.
*
* @param {number} [initialScale] - The initial scale factor to render the annotations
* @return {void}
*/
init(initialScale = 1) {
this.annotatedElement = this.getAnnotatedEl(this.container);
const { apiHost, fileId, token } = this.options;
this.annotationService = new AnnotationService({
apiHost,
fileId,
token,
canAnnotate: this.canAnnotate
});
// Set up mobile annotations dialog
if (this.isMobile) {
this.setupMobileDialog();
}
const scale = initialScale;
this.setScale(scale);
this.setupAnnotations();
this.showAnnotations();
}
/**
* Sets up the shared mobile dialog element.
*
* @return {void}
*/
setupMobileDialog() {
// Generate HTML of dialog
const mobileDialogEl = document.createElement('div');
mobileDialogEl.setAttribute('data-type', DATA_TYPE_ANNOTATION_DIALOG);
mobileDialogEl.classList.add(CLASS_MOBILE_ANNOTATION_DIALOG);
mobileDialogEl.classList.add(CLASS_ANNOTATION_DIALOG);
mobileDialogEl.classList.add(CLASS_HIDDEN);
mobileDialogEl.innerHTML = `
<div class="${CLASS_MOBILE_DIALOG_HEADER}">
<button class="${CLASS_DIALOG_CLOSE}">${ICON_CLOSE}</button>
</div>`.trim();
this.container.appendChild(mobileDialogEl);
}
/**
* Fetches and shows saved annotations.
*
* @return {void}
*/
showAnnotations() {
// Show annotations after we've generated an in-memory map
this.fetchAnnotations().then(this.renderAnnotations);
}
/**
* Hides annotations.
*
* @return {void}
*/
hideAnnotations() {
Object.keys(this.threads).forEach((page) => {
this.threads[page].forEach((thread) => {
thread.hide();
});
});
}
/**
* Hides annotations on a specified page.
*
* @param {number} pageNum - Page number
* @return {void}
*/
hideAnnotationsOnPage(pageNum) {
if (this.threads[pageNum]) {
this.threads[pageNum].forEach((thread) => {
thread.hide();
});
}
}
/**
* Renders annotations from memory.
*
* @private
* @return {void}
*/
renderAnnotations() {
Object.keys(this.threads).forEach((page) => {
this.threads[page].forEach((thread) => {
thread.show();
});
});
}
/**
* Renders annotations from memory for a specified page.
*
* @private
* @param {number} pageNum - Page number
* @return {void}
*/
renderAnnotationsOnPage(pageNum) {
if (this.threads && this.threads[pageNum]) {
this.threads[pageNum].forEach((thread) => {
thread.show();
});
}
}
/**
* Rotates annotations. Hides point annotation mode button if rotated
*
* @override
* @param {number} [rotationAngle] - current angle image is rotated
* @param {number} [pageNum] - Page number
* @return {void}
* @private
*/
rotateAnnotations(rotationAngle = 0, pageNum = 0) {
// Only render a specific page's annotations unless no page number
// is specified
if (pageNum) {
this.renderAnnotationsOnPage(pageNum);
} else {
this.renderAnnotations();
}
// Only show/hide point annotation button if user has the
// appropriate permissions
if (!this.annotationService.canAnnotate) {
return;
}
// Hide create annotations button if image is rotated
const pointButtonSelector = this.modeButtons[TYPES.point].selector;
const pointAnnotateButton = this.previewUI.getAnnotateButton(pointButtonSelector);
if (rotationAngle !== 0) {
annotatorUtil.hideElement(pointAnnotateButton);
} else {
annotatorUtil.showElement(pointAnnotateButton);
}
}
/**
* Sets the zoom scale.
*
* @param {number} scale - current zoom scale
* @return {void}
*/
setScale(scale) {
this.annotatedElement.setAttribute('data-scale', scale);
}
/**
* Toggles point annotation mode on and off. When point annotation mode is
* on, clicking an area will create a point annotation at that location.
*
* @param {HTMLEvent} event - DOM event
* @return {void}
*/
togglePointAnnotationHandler(event = {}) {
this.destroyPendingThreads();
const pointButtonSelector = this.modeButtons[TYPES.point].selector;
const buttonEl = event.target || this.previewUI.getAnnotateButton(pointButtonSelector);
if (this.isInDrawMode()) {
this.toggleDrawAnnotationHandler();
}
// If in annotation mode, turn it off
if (this.isInPointMode()) {
this.emit('annotationmodeexit');
this.annotatedElement.classList.remove(CLASS_ANNOTATION_POINT_MODE);
if (buttonEl) {
buttonEl.classList.remove(CLASS_ACTIVE);
}
this.unbindModeListeners(); // Disable point mode
this.bindDOMListeners(); // Re-enable other annotations
// Otherwise, enable annotation mode
} else {
this.emit('annotationmodeenter', TYPES.point);
this.annotatedElement.classList.add(CLASS_ANNOTATION_POINT_MODE);
if (buttonEl) {
buttonEl.classList.add(CLASS_ACTIVE);
}
this.unbindDOMListeners(); // Disable other annotations
this.bindPointModeListeners(); // Enable point mode
}
}
/**
* Toggles draw annotation mode on and off. When draw annotation mode is
* on, a click and draw
*
* @param {HTMLEvent} event - DOM event
* @return {void}
*/
toggleDrawAnnotationHandler(event = {}) {
this.destroyPendingThreads();
if (this.isInPointMode()) {
this.togglePointAnnotationHandler();
}
const drawButtonSelector = this.modeButtons[TYPES.draw].selector;
const buttonEl = event.target || this.previewUI.getAnnotateButton(drawButtonSelector);
const postButtonEl = this.previewUI.getAnnotateButton(SELECTOR_ANNOTATION_BUTTON_DRAW_POST);
// Exit if in draw mode
if (this.isInDrawMode()) {
this.emit('annotationmodeexit');
this.annotatedElement.classList.remove(CLASS_ANNOTATION_DRAW_MODE);
if (buttonEl) {
buttonEl.classList.remove(CLASS_ACTIVE);
buttonEl.querySelector(SELECTOR_ANNOTATION_BUTTON_DRAW_ENTER).classList.remove(CLASS_HIDDEN);
buttonEl.querySelector(SELECTOR_ANNOTATION_BUTTON_DRAW_CANCEL).classList.add(CLASS_HIDDEN);
postButtonEl.classList.add(CLASS_HIDDEN);
}
this.unbindModeListeners(); // Disable draw mode
this.bindDOMListeners(); // Re-enable other annotations
// Otherwise enter draw mode
} else {
this.emit('annotationmodeenter', TYPES.draw);
this.annotatedElement.classList.add(CLASS_ANNOTATION_DRAW_MODE);
if (buttonEl) {
buttonEl.classList.add(CLASS_ACTIVE);
buttonEl.querySelector(SELECTOR_ANNOTATION_BUTTON_DRAW_ENTER).classList.add(CLASS_HIDDEN);
buttonEl.querySelector(SELECTOR_ANNOTATION_BUTTON_DRAW_CANCEL).classList.remove(CLASS_HIDDEN);
postButtonEl.classList.remove(CLASS_HIDDEN);
}
const thread = this.createAnnotationThread([], {}, TYPES.draw);
this.unbindDOMListeners();
this.bindDrawModeListeners(thread, postButtonEl);
}
}
//--------------------------------------------------------------------------
// Abstract
//--------------------------------------------------------------------------
/**
* Must be implemented to return an annotation location object from the DOM
* event.
*
* @param {Event} event - DOM event
* @param {string} annotationType - Type of annotation
* @return {Object} Location object
*/
/* eslint-disable no-unused-vars */
getLocationFromEvent(event, annotationType) {}
/* eslint-enable no-unused-vars */
/**
* Must be implemented to create the appropriate new thread, add it to the
* in-memory map, and return the thread.
*
* @param {Annotation[]} annotations - Annotations in thread
* @param {Object} location - Location object
* @param {string} type - Annotation type
* @return {AnnotationThread} Created annotation thread
*/
/* eslint-disable no-unused-vars */
createAnnotationThread(annotations, location, type) {}
/* eslint-enable no-unused-vars */
/**
* Must be implemented to determine the annotated element in the viewer.
*
* @param {HTMLElement} containerEl - Container element for the viewer
* @return {HTMLElement} Annotated element in the viewer
*/
/* eslint-disable no-unused-vars */
getAnnotatedEl(containerEl) {}
/* eslint-enable no-unused-vars */
//--------------------------------------------------------------------------
// Protected
//--------------------------------------------------------------------------
/**
* Annotations setup.
*
* @protected
* @return {void}
*/
setupAnnotations() {
// Map of page => [threads on page]
this.threads = {};
this.bindDOMListeners();
this.bindCustomListenersOnService(this.annotationService);
}
/**
* Fetches persisted annotations, creates threads as needed, and generates
* an in-memory map of page to threads.
*
* @protected
* @return {Promise} Promise for fetching saved annotations
*/
fetchAnnotations() {
this.threads = {};
return this.annotationService.getThreadMap(this.fileVersionId).then((threadMap) => {
// Generate map of page to threads
Object.keys(threadMap).forEach((threadID) => {
const annotations = threadMap[threadID];
const firstAnnotation = annotations[0];
// Bind events on valid annotation thread
const thread = this.createAnnotationThread(annotations, firstAnnotation.location, firstAnnotation.type);
if (thread) {
this.bindCustomListenersOnThread(thread);
}
});
this.emit('annotationsfetched');
});
}
/**
* Binds DOM event listeners. Can be overridden by any annotator that
* needs to bind event listeners to the DOM in the normal state (ie not
* in any annotation mode).
*
* @return {void}
*/
bindDOMListeners() {
this.addListener('scaleAnnotations', this.scaleAnnotations);
}
/**
* Unbinds DOM event listeners. Can be overridden by any annotator that
* needs to bind event listeners to the DOM in the normal state (ie not
* in any annotation mode).
*
* @protected
* @return {void}
*/
unbindDOMListeners() {
this.removeListener('scaleAnnotations', this.scaleAnnotations);
}
/**
* Binds custom event listeners for the Annotation Service.
*
* @protected
* @return {void}
*/
bindCustomListenersOnService() {
const service = this.annotationService;
if (!service || !(service instanceof AnnotationService)) {
return;
}
/* istanbul ignore next */
service.addListener('annotatorerror', this.handleServiceEvents);
}
/**
* Handle events emitted by the annotaiton service
*
* @private
* @param {Object} [data] - Annotation service event data
* @param {string} [data.event] - Annotation service event
* @param {string} [data.data] -
* @return {void}
*/
handleServiceEvents(data) {
let errorMessage = '';
switch (data.reason) {
case 'read':
errorMessage = __('annotations_load_error');
break;
case 'create':
errorMessage = __('annotations_create_error');
this.showAnnotations();
break;
case 'delete':
errorMessage = __('annotations_delete_error');
this.showAnnotations();
break;
case 'authorization':
errorMessage = __('annotations_authorization_error');
break;
default:
}
if (errorMessage) {
this.emit('annotatorerror', errorMessage);
}
}
/**
* Unbinds custom event listeners for the Annotation Service.
*
* @protected
* @return {void}
*/
unbindCustomListenersOnService() {
const service = this.annotationService;
if (!service || !(service instanceof AnnotationService)) {
return;
}
service.removeAllListeners('annotatorerror');
}
/**
* Binds custom event listeners for a thread.
*
* @protected
* @param {AnnotationThread} thread - Thread to bind events to
* @return {void}
*/
bindCustomListenersOnThread(thread) {
// Thread was deleted, remove from thread map
thread.addListener('threaddeleted', () => {
const page = thread.location.page || 1;
// Remove from map
if (this.threads[page] instanceof Array) {
this.threads[page] = this.threads[page].filter(
(searchThread) => searchThread.threadID !== thread.threadID
);
}
});
// Thread should be cleaned up, unbind listeners - we don't do this
// in threaddeleted listener since thread may still need to respond
// to error messages
thread.addListener('threadcleanup', () => {
this.unbindCustomListenersOnThread(thread);
});
}
/**
* Unbinds custom event listeners for the thread.
*
* @protected
* @param {AnnotationThread} thread - Thread to bind events to
* @return {void}
*/
unbindCustomListenersOnThread(thread) {
thread.removeAllListeners('threaddeleted');
thread.removeAllListeners('threadcleanup');
}
/**
* Binds event listeners for point annotation mode.
*
* @protected
* @return {void}
*/
bindPointModeListeners() {
const handlers = [
{
type: 'mousedown',
func: this.pointClickHandler,
eventObj: this.annotatedElement
},
{
type: 'touchstart',
func: this.pointClickHandler,
eventObj: this.annotatedElement
}
];
handlers.forEach((handler) => {
handler.eventObj.addEventListener(handler.type, handler.func);
this.annotationModeHandlers.push(handler);
});
}
/**
* Event handler for adding a point annotation. Creates a point annotation
* thread at the clicked location.
*
* @protected
* @param {Event} event - DOM event
* @return {void}
*/
pointClickHandler(event) {
event.stopPropagation();
event.preventDefault();
// Determine if a point annotation dialog is already open and close the
// current open dialog
const hasPendingThreads = this.destroyPendingThreads();
if (hasPendingThreads) {
return;
}
// Exits point annotation mode on first click
this.togglePointAnnotationHandler();
// Get annotation location from click event, ignore click if location is invalid
const location = this.getLocationFromEvent(event, TYPES.point);
if (!location) {
return;
}
// Create new thread with no annotations, show indicator, and show dialog
const thread = this.createAnnotationThread([], location, TYPES.point);
if (thread) {
thread.show();
// Bind events on thread
this.bindCustomListenersOnThread(thread);
}
}
/**
* Binds event listeners for draw annotation mode.
*
* @param {DrawingThread} drawingThread - The drawing thread to bind event listeners to.
* @param {HTMLElement} postButtonEl - The HTML element that will save the DrawingThread on click.
* @return {void}
*/
bindDrawModeListeners(drawingThread, postButtonEl) {
if (!drawingThread || !postButtonEl) {
return;
}
/* eslint-disable require-jsdoc */
const locationFunction = (event) => this.getLocationFromEvent(event, TYPES.point);
/* eslint-enable require-jsdoc */
const handlers = [
{
type: 'mousemove',
func: annotatorUtil.eventToLocationHandler(locationFunction, drawingThread.handleMove),
eventObj: this.annotatedElement
},
{
type: 'mousedown',
func: annotatorUtil.eventToLocationHandler(locationFunction, drawingThread.handleStart),
eventObj: this.annotatedElement
},
{
type: 'mouseup',
func: annotatorUtil.eventToLocationHandler(locationFunction, drawingThread.handleStop),
eventObj: this.annotatedElement
}
];
if (postButtonEl) {
handlers.push({
type: 'click',
func: () => {
drawingThread.saveAnnotation(TYPES.draw);
this.toggleDrawAnnotationHandler();
},
eventObj: postButtonEl
});
}
handlers.forEach((handler) => {
handler.eventObj.addEventListener(handler.type, handler.func);
this.annotationModeHandlers.push(handler);
});
}
/**
* Unbinds event listeners for annotation modes.
*
* @protected
* @return {void}
*/
unbindModeListeners() {
while (this.annotationModeHandlers.length > 0) {
const handler = this.annotationModeHandlers.pop();
handler.eventObj.removeEventListener(handler.type, handler.func);
}
}
/**
* Adds thread to in-memory map.
*
* @protected
* @param {AnnotationThread} thread - Thread to add
* @return {void}
*/
addThreadToMap(thread) {
// Add thread to in-memory map
const page = thread.location.page || 1; // Defaults to page 1 if thread has no page
this.threads[page] = this.threads[page] || [];
this.threads[page].push(thread);
}
/**
* Returns whether or not annotator is in point mode.
*
* @protected
* @return {boolean} Whether or not in point mode
*/
isInPointMode() {
return this.annotatedElement.classList.contains(CLASS_ANNOTATION_POINT_MODE);
}
/**
* Returns whether or not annotator is in drawing mode.
*
* @protected
* @return {boolean} True if drawing mode is on, otherwise returns false.
*/
isInDrawMode() {
return this.annotatedElement.classList.contains(CLASS_ANNOTATION_DRAW_MODE);
}
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* Orient annotations to the correct scale and orientation of the annotated document.
*
* @protected
* @param {Object} data - Scale and orientation values needed to orient annotations.
* @return {void}
*/
scaleAnnotations(data) {
this.setScale(data.scale);
this.rotateAnnotations(data.rotationAngle, data.pageNum);
}
/**
* Destroys pending threads.
*
* @private
* @return {boolean} Whether or not any pending threads existed on the
* current file
*/
destroyPendingThreads() {
let hasPendingThreads = false;
Object.keys(this.threads).forEach((page) => {
this.threads[page].forEach((pendingThread) => {
if (annotatorUtil.isPending(pendingThread.state)) {
hasPendingThreads = true;
pendingThread.destroy();
}
});
});
return hasPendingThreads;
}
/**
* Displays annotation validation error notification once on load. Does
* nothing if notification was already displayed once.
*
* @private
* @return {void}
*/
handleValidationError() {
if (this.validationErrorEmitted) {
return;
}
this.emit('annotatorerror', __('annotations_load_error'));
this.validationErrorEmitted = true;
}
/**
* Emits a generic viewer event
*
* @private
* @emits viewerevent
* @param {string} event - Event name
* @param {Object} data - Event data
* @return {void}
*/
emit(event, data) {
const { annotator, fileId } = this.options;
super.emit(event, data);
super.emit('annotatorevent', {
event,
data,
annotatorName: annotator ? annotator.NAME : '',
fileId
});
}
}
export default Annotator;