forked from box/box-annotations
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AnnotationModeController.js
754 lines (652 loc) · 23.1 KB
/
AnnotationModeController.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
// @flow
import rbush from 'rbush';
import EventEmitter from 'events';
import noop from 'lodash/noop';
import { insertTemplate, replaceHeader, hasValidBoundaryCoordinates, shouldDisplayMobileUI } from '../util';
import {
CLASS_HIDDEN,
CLASS_ACTIVE,
CLASS_ANNOTATION_MODE,
CLASS_ANNNOTATION_MODE_BACKGROUND,
SELECTOR_BOX_PREVIEW_BASE_HEADER,
THREAD_EVENT,
CONTROLLER_EVENT,
BORDER_OFFSET,
STATES
} from '../constants';
import AnnotationAPI from '../api/AnnotationAPI';
class AnnotationModeController extends EventEmitter {
/** @property {Object} - Object containing annotation threads */
annotations: Object = {};
/** @property {Array} - The array of annotation handlers */
handlers: Array<any> = [];
/** @property {string} - File version ID */
fileVersionId: string;
/** @property {HTMLElement} - Container of the annotatedElement */
container: HTMLElement;
/** @property {HTMLElement} - Annotated HTML DOM element */
annotatedElement: HTMLElement;
/** @property {HTMLElement} - Header HTML DOM element */
headerElement: HTMLElement;
/** @property {HTMLElement} - Annotation mode button HTML DOM element */
buttonEl: HTMLElement;
/** @property {Object} - Annotation mode button selector and title */
modeButton: Object;
/** @property {AnnotationType} - Mode for annotation controller */
mode: AnnotationType;
/** @property {string} - Mode for annotation controller */
annotatorType: string;
/** @property {Object} */
permissions: BoxItemPermissions;
/** @property {Object} - Localized strings */
localized: Object;
/** @property {boolean} */
hasTouch: boolean = false;
/** @property {boolean} */
isMobile: boolean = false;
/** @property {string} */
locale: string = 'en-US';
/** @property {AnnotationAPI} */
api: AnnotationAPI;
/** @property {Function} */
getLocation: Function = noop;
/** @property {AnnotationType} */
annotationType: AnnotationType;
/** @property {boolean} */
hadPendingThreads: boolean;
/** @property {string} */
visibleThreadID: ?string;
/** @property {string} */
pendingThreadID: ?string;
/** @property {HTMLElement} */
headerElement: HTMLElement;
/** @property {AnnotationThread} */
currentThread: ?AnnotationThread;
constructor(annotatorType: string): void {
super();
this.annotatorType = annotatorType;
}
/**
* Initializes mode controller.
*
* @param {Object} data - Options for constructing a controller
* @return {void}
*/
init(data: Object): void {
this.container = data.container;
this.headerElement = data.headerElement;
this.annotatedElement = data.annotatedElement;
this.mode = data.mode;
this.fileVersionId = data.fileVersionId;
this.permissions = data.permissions;
this.localized = data.localized || {};
this.hasTouch = data.options ? data.options.hasTouch : false;
this.locale = data.options ? data.options.locale : 'en-US';
this.getLocation = data.getLocation;
this.api = new AnnotationAPI({
apiHost: data.apiHost,
fileId: data.fileId,
token: data.token,
anonymousUserName: data.localized.anonymousUserName,
permissions: this.permissions
});
this.api.addListener(CONTROLLER_EVENT.error, this.handleAPIErrors);
if (data.modeButton && this.permissions.can_annotate) {
this.modeButton = data.modeButton;
this.showButton();
}
}
/**
* [destructor]
*
* @return {void}
*/
destroy(): void {
Object.keys(this.annotations).forEach((pageNum) => {
const pageThreads = this.annotations[pageNum].all() || [];
pageThreads.forEach((thread) => thread.removeListener('threadevent', this.handleThreadEvents));
this.annotations[pageNum].clear();
});
if (this.buttonEl) {
this.buttonEl.removeEventListener('click', this.toggleMode);
}
this.api.removeListener(CONTROLLER_EVENT.error, this.handleAPIErrors);
}
/**
* Gets the annotation button element.
*
* @param {string} annotatorSelector - Class selector for a custom annotation button.
* @return {HTMLElement|null} Annotate button element or null if the selector did not find an element.
*/
getButton(annotatorSelector: string): HTMLElement {
// $FlowFixMe
return this.container.querySelector(annotatorSelector);
}
/**
* Shows the annotate button for the specified mode
*
* @return {void}
*/
showButton(): void {
if (!this.permissions.can_annotate) {
return;
}
this.buttonEl = this.getButton(this.modeButton.selector);
// $FlowFixMe
if (this.buttonEl) {
this.buttonEl.title = this.modeButton.title;
this.buttonEl.classList.remove(CLASS_HIDDEN);
// $FlowFixMe
this.toggleMode = this.toggleMode.bind(this);
// $FlowFixMe
this.buttonEl.addEventListener('click', this.toggleMode);
}
}
/**
* Hides the annotate button for the specified mode
*
* @return {void}
*/
hideButton() {
if (!this.permissions.can_annotate || !this.modeButton) {
return;
}
this.buttonEl = this.getButton(this.modeButton.selector);
if (this.buttonEl) {
this.buttonEl.classList.add(CLASS_HIDDEN);
}
}
/**
* Toggles annotation modes on and off. When an annotation mode is
* on, annotation threads will be created at that location.
*
* @return {void}
*/
toggleMode(): void {
this.destroyPendingThreads();
// No specific mode available for annotation type
if (!this.modeButton) {
return;
}
// Exit any other annotation mode
this.emit(CONTROLLER_EVENT.toggleMode);
}
/**
* @return {void}
*/
resetMode() {}
/**
* Disables the specified annotation mode
*
* @return {void}
*/
exit(): void {
this.resetMode();
if (this.currentThread) {
this.currentThread.unmountPopover();
}
this.emit(CONTROLLER_EVENT.exit, { mode: this.mode });
replaceHeader(this.headerElement, SELECTOR_BOX_PREVIEW_BASE_HEADER);
this.destroyPendingThreads();
this.annotatedElement.classList.remove(CLASS_ANNOTATION_MODE);
this.annotatedElement.classList.remove(CLASS_ANNNOTATION_MODE_BACKGROUND);
this.buttonEl.classList.remove(CLASS_ACTIVE);
this.unbindListeners(); // Disable mode
this.emit(CONTROLLER_EVENT.bindDOMListeners);
this.hadPendingThreads = false;
this.currentThread = undefined;
}
/**
* Enables the specified annotation mode
*
* @return {void}
*/
enter(): void {
this.annotatedElement.classList.add(CLASS_ANNOTATION_MODE);
this.annotatedElement.classList.add(CLASS_ANNNOTATION_MODE_BACKGROUND);
this.buttonEl.classList.add(CLASS_ACTIVE);
this.emit(CONTROLLER_EVENT.enter, { mode: this.mode });
this.emit(CONTROLLER_EVENT.unbindDOMListeners); // Disable other annotations
this.bindListeners(); // Enable mode
}
/**
* Returns whether or not the current annotation mode is enabled
*
* @return {boolean} Whether or not the annotation mode is enabled
*/
isEnabled(): boolean {
return this.buttonEl ? this.buttonEl.classList.contains(CLASS_ACTIVE) : false;
}
/**
* Bind the mode listeners and store each handler for future unbinding
*
* @return {void}
*/
bindListeners(): void {
const currentHandlerIndex = this.handlers.length;
this.setupHandlers();
for (let index = currentHandlerIndex; index < this.handlers.length; index++) {
const handler = this.handlers[index];
const types = handler.type instanceof Array ? handler.type : [handler.type];
types.forEach((eventName) =>
handler.eventObj.addEventListener(eventName, handler.func, handler.useCapture)
);
}
}
/**
* Unbind the previously bound mode listeners
*
* @return {void}
*/
unbindListeners(): void {
while (this.handlers.length > 0) {
const handler = this.handlers.pop();
const types = handler.type instanceof Array ? handler.type : [handler.type];
types.forEach((eventName) => {
handler.eventObj.removeEventListener(eventName, handler.func, handler.useCapture);
});
}
}
/**
* Gets thread params for the new annotation thread
*
* @param {Annotation} annotation - Annotation
* @return {Object} Params to create annotation thread
*/
getThreadParams(annotation: Annotation): ?Object {
return {
annotatedElement: this.annotatedElement,
api: this.api,
container: this.container,
fileVersionId: this.fileVersionId,
isMobile: shouldDisplayMobileUI(this.container),
hasTouch: this.hasTouch,
headerHeight: this.headerElement.clientHeight,
...annotation
};
}
/**
* Instantiates the appropriate annotation thread for the current viewer
*
* @param {Object} params - Annotation thread params
* @return {AnnotationThread|null} Annotation thread instance or null
*/
/* eslint-disable no-unused-vars */
instantiateThread(params: Object): AnnotationThread {
/* eslint-enable no-unused-vars */
throw new Error('Implement me!');
}
/**
* Register a thread with the controller so that the controller can keep track of relevant threads
*
* @param {Annotation} annotation - Annotation
* @return {AnnotationThread} registered thread
*/
registerThread(annotation: Annotation): AnnotationThread {
let thread;
const threadParams = this.getThreadParams(annotation);
if (!threadParams) {
return thread;
}
thread = this.instantiateThread(threadParams);
if (!thread || !hasValidBoundaryCoordinates(thread)) {
return thread;
}
const page = thread.location.page || 1; // Defaults to page 1 if thread has no page'
if (!(page in this.annotations)) {
/* eslint-disable new-cap */
this.annotations[page] = new rbush();
/* eslint-enable new-cap */
}
this.annotations[page].insert(thread);
let threadEventHandler = (data) => this.handleThreadEvents(thread, data);
threadEventHandler = threadEventHandler.bind(this);
thread.addListener('threadevent', threadEventHandler);
this.emit(CONTROLLER_EVENT.register, thread);
return thread;
}
/**
* Custom comparator function to remove annotations from the rbush
*
* @param {DrawingThread} currentAnnotation current annotation in rbush
* @param {DrawingThread} annotationToRemove annotation which is being unregistered
* @return {boolean} Whether or not the
*/
deleteAnnotation(currentAnnotation: DrawingThread, annotationToRemove: DrawingThread): boolean {
return currentAnnotation.id === annotationToRemove.id;
}
/**
* Unregister a previously registered thread
*
*
* @param {AnnotationThread} thread - The thread to unregister with the controller
* @param {Object} annotation - The annotation with comments to register with the controller
* @return {void}
*/
unregisterThread(thread: AnnotationThread): void {
if (!thread || !thread.location || !thread.location.page || !this.annotations[thread.location.page]) {
return;
}
this.annotations[thread.location.page].remove(thread);
if (this.annotations[thread.location.page].data.children.length === 0) {
delete this.annotations[thread.location.page];
}
this.emit(CONTROLLER_EVENT.unregister, thread);
thread.removeListener('threadevent', this.handleThreadEvents);
}
/**
* Apply predicate method to every thread on the specified page
*
* @param {Function} func Predicate method to apply on threads
* @param {string} pageNum Page number
* @return {void}
*/
applyActionToPageThreads(func: Function, pageNum: string): void {
if (!this.annotations[pageNum]) {
return;
}
const pageThreads = this.annotations[pageNum].all() || [];
pageThreads.forEach(func);
}
/**
* Apply predicate method to every thread on the entire file
*
* @param {Function} func Predicate method to apply on threads
* @return {void}
*/
applyActionToThreads(func: Function): void {
Object.keys(this.annotations).forEach((page) => this.applyActionToPageThreads(func, page));
}
/**
* Gets thread specified by threadID
*
* @param {string} [threadID] - Thread ID
* @param {string} [pageNum] - Optional page number
* @return {AnnotationThread} Annotation thread specified by threadID
*/
getThreadByID(threadID: ?string, pageNum?: string): ?AnnotationThread {
let thread = null;
if (!threadID) {
return thread;
}
if (pageNum) {
thread = this.doesThreadMatch(threadID, pageNum);
} else {
Object.keys(this.annotations).some((page) => {
// $FlowFixMe
const matchingThread = this.doesThreadMatch(threadID, page);
if (matchingThread) {
thread = matchingThread;
}
return !!matchingThread;
});
}
return thread;
}
/**
* Determines whether a thread matches the specified threadID
*
* @param {string} [threadID] - Thread ID
* @param {string} [pageNum] - Page number
* @return {AnnotationThread|null} Matching annotation thread or null
*/
doesThreadMatch(threadID: ?string, pageNum: ?string): ?AnnotationThread {
let thread = null;
const pageThreads = this.annotations[pageNum];
if (!pageThreads) {
return thread;
}
thread = pageThreads.all().filter((t) => {
return t.threadID === threadID;
})[0];
return thread;
}
/**
* Clean up any selected annotations
*
* @return {void}
*/
removeSelection(): void {}
/**
* Set up and return the necessary handlers for the annotation mode
*
* @return {Array} An array where each element is an object containing the object that will emit the event,
* the type of events to listen for, and the callback
*/
setupHandlers(): void {}
/**
* Handles annotation thread events and emits them to the viewer
*
* @param {AnnotationThread} thread - The thread that emitted the event
* @param {Object} [data] - Annotation thread event data
* @param {string} [data.event] - Annotation thread event
* @param {Object} [data.data] - Annotation thread event data
* @return {void}
*/
handleThreadEvents(thread: AnnotationThread, data: Object): void {
const { event, data: threadData, eventData } = data;
switch (event) {
case THREAD_EVENT.save:
case THREAD_EVENT.cancel:
this.hadPendingThreads = false;
this.pendingThreadID = null;
this.emit(event, threadData);
break;
case THREAD_EVENT.show:
this.visibleThreadID = threadData.threadID;
break;
case THREAD_EVENT.hide:
this.visibleThreadID = null;
break;
case THREAD_EVENT.render:
if (eventData && eventData.page) {
this.renderPage(eventData.page);
} else {
this.render();
}
break;
case THREAD_EVENT.delete:
// Thread should be cleaned up, unbind listeners - we
// don't do this in annotationdelete listener since thread
// may still need to respond to error messages
this.unregisterThread(thread);
this.emit(event, threadData);
break;
case THREAD_EVENT.deleteError:
this.emit(CONTROLLER_EVENT.error, this.localized.deleteError);
this.emit(event, threadData);
break;
case THREAD_EVENT.createError:
this.emit(CONTROLLER_EVENT.error, this.localized.createError);
this.emit(event, threadData);
break;
default:
this.emit(event, threadData);
}
}
/**
* Creates a handler description object and adds its to the internal handler container.
* Useful for setupAndGetHandlers.
*
* @param {HTMLElement} element - The element to bind the listener to
* @param {Array|string} type - An array of event types to listen for or the event name to listen for
* @param {Function} handlerFn - The callback to be invoked when the element emits a specified eventname
* @param {boolean} [useCapture] - Whether or not to prioritize handler call
* @return {void}
*/
pushElementHandler(
element: HTMLElement,
type: Array<any> | string,
handlerFn: Function,
useCapture: boolean = false
): void {
if (!element) {
return;
}
this.handlers.push({
eventObj: element,
func: handlerFn,
type,
useCapture
});
}
/**
* Setups the header for the annotation mode
*
* @param {HTMLElement} container - Container element
* @param {HTMLElement} header - Header to add to DOM
* @return {void}
*/
setupHeader(container: HTMLElement, header: HTMLElement): void {
const baseHeaderEl = container.firstElementChild;
insertTemplate(container, header, baseHeaderEl);
}
/**
* Renders annotations from memory.
*
* @return {void}
*/
render(): void {
if (!this.annotations) {
return;
}
Object.keys(this.annotations).forEach((pageNum) => this.renderPage(pageNum));
}
/**
* Unregisters and destroys the specified thread
*
* @param {AnnotationThread} thread thread to destroy
* @return {void}
*/
destroyThread(thread: AnnotationThread) {
this.unregisterThread(thread);
thread.destroy();
}
/**
* Renders annotations from memory for a specified page.
*
* @param {string} pageNum - Page number
* @return {void}
*/
renderPage(pageNum: string) {
if (!this.annotations || !this.annotations[pageNum]) {
return;
}
const pageThreads = this.annotations[pageNum].all() || [];
pageThreads.forEach((thread, index) => {
// Destroy any pending threads that may exist on re-render
if (thread.state === STATES.pending || thread.id === this.pendingThreadID) {
this.destroyThread(thread);
return;
}
thread.reset();
thread.unmountPopover();
// Sets the annotatedElement if the thread was fetched before the
// dependent document/viewer finished loading
if (!thread.annotatedElement) {
pageThreads[index].annotatedElement = this.annotatedElement;
}
thread.show();
});
}
/**
* Destroys pending threads.
*
* @return {boolean} Whether or not any pending threads existed on the
* current file
*/
destroyPendingThreads(): boolean {
let hadPendingThreads = false;
Object.keys(this.annotations).forEach((pageNum) => {
const pageThreads = this.annotations[pageNum].all() || [];
pageThreads.forEach((thread) => {
if (thread.state === STATES.pending || thread.id === this.pendingThreadID) {
this.destroyThread(thread);
hadPendingThreads = true;
this.pendingThreadID = null;
}
});
});
return hadPendingThreads;
}
/**
* Find the intersecting threads given a pointer event
*
* @param {Event} event The event object containing the pointer information
* @param {PointLocationInfo} location Annotation location object
* @return {Array<AnnotationThread>} Array of intersecting annotation threads
*/
getIntersectingThreads(event: Event, location: PointLocationInfo): Array<AnnotationThread> {
if (
!event ||
!this.annotations ||
!location ||
Object.keys(this.annotations).length === 0 ||
!this.annotations[location.page]
) {
return [];
}
const eventBoundary = {
// $FlowFixMe
minX: +location.x - BORDER_OFFSET,
// $FlowFixMe
minY: +location.y - BORDER_OFFSET,
// $FlowFixMe
maxX: +location.x + BORDER_OFFSET,
// $FlowFixMe
maxY: +location.y + BORDER_OFFSET
};
// Get the threads that correspond to the point that was clicked on
return this.annotations[location.page].search(eventBoundary);
}
/**
* Handle events emitted by the annotation service
*
* @param {Object} [data] - Annotation service event data
* @param {Event} [data.event] - Annotation service event
* @param {Object} [data.data] -
* @return {void}
*/
handleAPIErrors(data: Object): void {
let errorMessage = '';
switch (data.reason) {
case 'create':
errorMessage = this.localized.createError;
this.emit(CONTROLLER_EVENT.load);
break;
case 'delete':
errorMessage = this.localized.deleteError;
this.emit(CONTROLLER_EVENT.load);
break;
case 'authorization':
errorMessage = this.localized.authError;
break;
default:
}
if (data.error) {
/* eslint-disable no-console */
console.error(CONTROLLER_EVENT.error, data.error);
/* eslint-enable no-console */
}
if (errorMessage) {
this.emit(CONTROLLER_EVENT.error, errorMessage);
}
}
/**
* Emits a generic annotator event
*
* @emits annotatorevent
* @param {string} event - Event name
* @param {Object} [data] - Event data
* @return {void}
*/
emit(event: string, data?: Object): boolean {
super.emit('annotationcontrollerevent', {
event,
data,
mode: this.mode
});
return super.emit(event, data);
}
}
export default AnnotationModeController;