-
Notifications
You must be signed in to change notification settings - Fork 105
/
annotatorUtil.js
358 lines (314 loc) · 11.7 KB
/
annotatorUtil.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
import { CLASS_ACTIVE, CLASS_HIDDEN, CLASS_INVISIBLE } from '../constants';
import * as constants from './annotationConstants';
const AVATAR_COLOR_COUNT = 9; // 9 colors defined in Box React UI avatar code
const THREAD_PARAMS = [
'annotatedElement',
'annotations',
'annotationService',
'fileVersionId',
'locale',
'location',
'type'
];
//------------------------------------------------------------------------------
// DOM Utils
//------------------------------------------------------------------------------
/**
* Finds the closest ancestor DOM element with the specified class.
*
* @param {HTMLElement} element - Element to search ancestors of
* @param {string} className - Class name to query
* @return {HTMLElement|null} Closest ancestor with given class or null
*/
export function findClosestElWithClass(element, className) {
for (let el = element; el && el !== document; el = el.parentNode) {
if (el.classList && el.classList.contains(className)) {
return el;
}
}
return null;
}
/**
* Returns the page element and page number that the element is on.
*
* @param {HTMLElement} element - Element to find page and page number for
* @return {Object} Page element/page number if found or null/-1 if not
*/
export function getPageInfo(element) {
const pageEl = findClosestElWithClass(element, 'page') || null;
let page = -1;
if (pageEl) {
page = parseInt(pageEl.getAttribute('data-page-number'), 10);
}
return { pageEl, page };
}
/**
* Finds the closest element with a data type and returns that data type. If
* an attributeName is provided, search for that data atttribute instead of
* data type.
*
* @param {HTMLElement} element - Element to find closest data type for
* @param {string} [attributeName] - Optional different data attribute to search
* for
* @return {string} Closest data type or empty string
*/
export function findClosestDataType(element, attributeName) {
const attributeToFind = attributeName || 'data-type';
for (let el = element; el && el !== document; el = el.parentNode) {
if (el && el.getAttribute(attributeToFind)) {
return el.getAttribute(attributeToFind);
}
}
return '';
}
/**
* Shows the specified element or element with specified selector.
*
* @param {HTMLElement|string} elementOrSelector - Element or CSS selector
* @return {void}
*/
export function showElement(elementOrSelector) {
let element = elementOrSelector;
if (typeof elementOrSelector === 'string' || elementOrSelector instanceof String) {
element = document.querySelector(elementOrSelector);
}
if (element) {
element.classList.remove(CLASS_HIDDEN);
}
}
/**
* Hides the specified element or element with specified selector.
*
* @param {HTMLElement|string} elementOrSelector - Element or CSS selector
* @return {void}
*/
export function hideElement(elementOrSelector) {
let element = elementOrSelector;
if (typeof elementOrSelector === 'string' || elementOrSelector instanceof String) {
element = document.querySelector(elementOrSelector);
}
if (element) {
element.classList.add(CLASS_HIDDEN);
}
}
/**
* Shows the specified element or element with specified selector.
*
* @param {HTMLElement|string} elementOrSelector - Element or CSS selector
* @return {void}
*/
export function showInvisibleElement(elementOrSelector) {
let element = elementOrSelector;
if (typeof elementOrSelector === 'string' || elementOrSelector instanceof String) {
element = document.querySelector(elementOrSelector);
}
if (element) {
element.classList.remove(CLASS_INVISIBLE);
}
}
/**
* Hides the specified element or element with specified selector. The element
* will still take up DOM space but not be visible in the UI
*
* @param {HTMLElement|string} elementOrSelector - Element or CSS selector
* @return {void}
*/
export function hideElementVisibility(elementOrSelector) {
let element = elementOrSelector;
if (typeof elementOrSelector === 'string' || elementOrSelector instanceof String) {
element = document.querySelector(elementOrSelector);
}
if (element) {
element.classList.add(CLASS_INVISIBLE);
}
}
/**
* Reset textarea element - clears value, resets styles, and remove active
* state.
*
* @param {HTMLElement} element - Textarea to reset
* @param {boolean} clearText - Whether or not text in text area should be cleared
* @return {void}
*/
export function resetTextarea(element, clearText) {
const textareaEl = element;
textareaEl.style.width = '';
textareaEl.style.height = '';
textareaEl.classList.remove(CLASS_ACTIVE);
if (clearText) {
textareaEl.value = '';
}
}
//------------------------------------------------------------------------------
// Point Utils
//------------------------------------------------------------------------------
/**
* Checks whether element is fully in viewport.
*
* @param {HTMLElement} element - Element to check
* @return {boolean} Whether element is fully in viewport
*/
export function isElementInViewport(element) {
const dimensions = element.getBoundingClientRect();
return (
dimensions.top >= 0 &&
dimensions.left >= 0 &&
dimensions.bottom <= window.innerHeight &&
dimensions.right <= window.innerWidth
);
}
/**
* Returns avatar image HTML for annotation dialog. This will be either an
* image with the supplied avatar URL as a source if there is a URL passed in
* or one generated using the initials of the annotator.
*
* @param {string} avatarUrl - URL of avatar photo
* @param {string} userId - User ID of annotator
* @param {string} userName - Username of annotator
* @return {string} HTML for profile image
*/
export function getAvatarHtml(avatarUrl, userId, userName) {
if (avatarUrl !== '') {
return `<img src="${avatarUrl}" alt="${__('annotation_profile_alt')}">`.trim();
}
let initials = '';
if (userId !== '0') {
// http://stackoverflow.com/questions/8133630/spliting-the-first-character-of-the-words
initials = userName.replace(/\W*(\w)\w*/g, '$1').toUpperCase().substring(0, 3);
}
const index = parseInt(userId, 10) || 0;
return `<div class="bp-annotation-profile avatar-color-${index % AVATAR_COLOR_COUNT}">${initials}</div>`.trim();
}
/**
* Returns zoom scale of annotated element.
*
* @param {HTMLElement} annotatedElement - HTML element being annotated on
* @return {number} Zoom scale
*/
export function getScale(annotatedElement) {
return parseFloat(annotatedElement.getAttribute('data-scale')) || 1;
}
//------------------------------------------------------------------------------
// Highlight Utils
//------------------------------------------------------------------------------
/**
* Whether or not a highlight annotation has comments or is a plain highlight
*
* @param {Annotation[]} annotations - Annotations in highlight thread
* @return {boolean} Whether annotation is a plain highlight annotation
*/
export function isPlainHighlight(annotations) {
return annotations.length === 1 && annotations[0].text === '';
}
/**
* Returns whether or not the annotation type is 'highlight' or
* 'highlight-comment'
*
* @param {string} type - Annotatation type
* @return {boolean} Whether or not annotation is a highlight
*/
export function isHighlightAnnotation(type) {
return type === constants.ANNOTATION_TYPE_HIGHLIGHT || type === constants.ANNOTATION_TYPE_HIGHLIGHT_COMMENT;
}
//------------------------------------------------------------------------------
// General Utils
//------------------------------------------------------------------------------
/**
* Returns dimension scale multiplier for x and y axes calculated from comparing
* the current annotated element dimensions scaled to 100% with annotated
* element dimensions when annotations were created.
*
* @param {Object} dimensions - Dimensions saved in annotation
* @param {Object} fileDimensions - Current annotated element dimensions
* @param {number} zoomScale - Zoom scale
* @param {number} heightPadding - Top & bottom padding for annotated element
* @return {Object|null} {x, y} dimension scale if needed, null otherwise
*/
export function getDimensionScale(dimensions, fileDimensions, zoomScale, heightPadding) {
let dimensionScale = null;
// Scale comparing current dimensions with saved dimensions if needed
if (dimensions && dimensions.x !== undefined && dimensions.y !== undefined) {
const width = fileDimensions.width / zoomScale;
const height = (fileDimensions.height - heightPadding) / zoomScale;
// Ignore sub-pixel variations that could result from float math
if (Math.abs(width - dimensions.x) > 1 || Math.abs(height !== dimensions.y) > 1) {
dimensionScale = {
x: width / dimensions.x,
y: height / dimensions.y
};
}
}
return dimensionScale;
}
/**
* Escapes HTML.
*
* @param {string} str - Input string
* @return {string} HTML escaped string
*/
export function htmlEscape(str) {
return `${str}`
.replace(/&/g, '&') // first!
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/`/g, '`');
}
/**
* Repositions caret if annotations dialog will run off the right or left
* side of the page. Otherwise positions caret at the center of the
* annotations dialog and the updated left corner x coordinate.
*
* @param {HTMLElement} dialogEl Annotations dialog element
* @param {number} dialogX Left corner x coordinate of the annotations dialog
* @param {number} highlightDialogWidth Width of the annotations dialog
* @param {number} browserX X coordinate of the mouse position
* @param {number} pageWidth Width of document page
* @return {number} Adjusted left corner x coordinate of the annotations dialog
*/
export function repositionCaret(dialogEl, dialogX, highlightDialogWidth, browserX, pageWidth) {
// Reposition to avoid sides - left side of page is 0px, right side is
// ${pageWidth}px
const dialogPastLeft = dialogX < 0;
const dialogPastRight = dialogX + highlightDialogWidth > pageWidth;
const annotationCaretEl = dialogEl.querySelector('.bp-annotation-caret');
if (dialogPastLeft && !dialogPastRight) {
// Leave a minimum of 10 pixels so caret doesn't go off edge
const caretLeftX = Math.max(10, browserX);
annotationCaretEl.style.left = `${caretLeftX}px`;
return 0;
} else if (dialogPastRight && !dialogPastLeft) {
// Leave a minimum of 10 pixels so caret doesn't go off edge
const caretRightX = Math.max(10, pageWidth - browserX);
// We set the 'left' property even when we have caretRightX for
// IE10/11
annotationCaretEl.style.left = `${highlightDialogWidth - caretRightX}px`;
return pageWidth - highlightDialogWidth;
}
// Reset caret to center
annotationCaretEl.style.left = '50%';
return dialogX;
}
/**
* Checks thread is in a pending or pending-active state
*
* @param {string} threadState - State of thread
* @return {boolean} Whether annotation thread is in a pending state
*/
export function isPending(threadState) {
return constants.PENDING_STATES.indexOf(threadState) > -1;
}
/**
* Checks whether annotation thread is valid by checking whether each property
* in THREAD_PARAMS on the specified file object is defined.
*
* @param {Object} thread - Annotation thread params to check
* @return {boolean} Whether or not annotation thread has all the required params
*/
export function validateThreadParams(thread) {
if (thread) {
return THREAD_PARAMS.every((param) => typeof thread[param] !== 'undefined');
}
return false;
}