-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathannotations_report.js
487 lines (433 loc) · 18.7 KB
/
annotations_report.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
// fill the html skeleton with hthe annotations report once DOM has fully loaded
// `DOMContentLoaded` event on the document
document.addEventListener('DOMContentLoaded', function () {
// Before starting getting data from sciwheel we need to know which reference
// to query and the authorization token
// TODO: consider improvements such as:
// - Pass refId differently (get request params, session, local storage, etc.)
// since we do not really need to use storage.sync for that (yes for token)
// currently here just for convenience to keep the code short
// - improvements to async behaviour and callback handling
// - module pattern to avoid global vars
chrome.storage.sync.get(['sciwheelAuthToken', 'sciwheelRefId'], function(result) {
var sciwheelRefId = result.sciwheelRefId;
var sciwheelAuthToken = result.sciwheelAuthToken;
// Error handling, notifying user and return to terminate here
if (!sciwheelAuthToken) return errorToken();
if (!sciwheelRefId) return errorRefId();
if (chrome.runtime.lastError) return errorGeneric();
// once refId and AuthToken are ready
buildAnnotationReports(sciwheelRefId, sciwheelAuthToken);
});
});
function errorToken() {
notifyError(
`It seems you have not provided the Sciwheel authorization token yet.
Please go to the extension options and follow the instructions to obtain
and provide the authorization token to enable this extension to access
the data from your Sciwheel account.`
);
}
function errorRefId() {
notifyError(
`Something went wrong getting the reference id!
Please try refreshing this page`
);
}
function errorGeneric(errMsg) {
notifyError(`Something went wrong! Please try refreshing this page`);
if (errMsg) notifyError(errMsg);
}
function notifyError(errMsg) {
document.getElementById("tab_a").innerHTML = errMsg;
}
// https://www.tjvantoll.com/2015/09/13/fetch-and-errors/
// https://stackoverflow.com/questions/54163952/async-await-in-fetch-how-to-handle-errors
// https://itnext.io/error-handling-with-async-await-in-js-26c3f20bc06a
// http://thecodebarbarian.com/async-await-error-handling-in-javascript
// https://stackoverflow.com/questions/58815415/how-to-handle-multiple-awaits-in-async-function
// https://stackoverflow.com/questions/46889290/waiting-for-more-than-one-concurrent-await-operation
// https://javascript.info/promise-error-handling
async function buildAnnotationReports(sciwheelRefId, sciwheelAuthToken) {
// TODO: consider using Promise.parallel, maybe a bit faster and fail earlier
refJsonData = await getRefData(sciwheelRefId, sciwheelAuthToken);
notesJsonData = await getNotesData(sciwheelRefId, sciwheelAuthToken);
if (!refJsonData || !notesJsonData) return; // terminate if error above
// Build reports
includeVisReport(refJsonData, notesJsonData);
includeJsonTreeViewer(refJsonData, notesJsonData);
// We can add here other output formats
}
function includeJsonTreeViewer(refData, notesData) {
var container = document.getElementById('tab_b');
var tree = jsonTree.create(notesData, container);
}
async function getRefData(sciwheelRefId, sciwheelAuthToken) {
var urlApiReq = "/references/" + sciwheelRefId;
return sciwheelApiCall(urlApiReq, sciwheelAuthToken);
}
async function getNotesData(sciwheelRefId, sciwheelAuthToken) {
var urlApiReq = "/references/" + sciwheelRefId + "/notes";
return sciwheelApiCall(urlApiReq, sciwheelAuthToken);
}
// using async/await for the fetch calls, cleaner code (avoids callbac-hell)
async function sciwheelApiCall(urlApiReq, sciwheelAuthToken) {
var baseUrl = "https://sciwheel.com/extapi/work";
var apiCallUrl = baseUrl + "/" + urlApiReq;
return fetch(apiCallUrl, {
method: 'get',
headers: {
"Authorization": "Bearer " + sciwheelAuthToken,
"Content-type": "application/json;charset=UTF-8"
}
})
.then(handleApiErrors) // fetch doesn't catch response codes like 401, 500
.then(response => response.ok ? response.json(): null)
.catch(err => errorGeneric(err.message));
}
function handleApiErrors(response) {
switch (response.status) {
case 200: // Successful request
break;
case 401: // Unauthorized: User authorization error (e.g., invalid authorization token), or client has broken the rate limit
notifyError(`
We got User authorization error from Sciwheel. Either you have provided
an invalid authorization token or you have used too much and too quickly
this extension or other tools that call the Sciwheel API with your
token. The later seems unlikely. So go ahead and check the
authorization token is up to date.
`);
break;
case 403: // Insufficient privileges for the request
notifyError(`
We got Insufficient privileges for the request error from Sciwheel.
Check your authorization token and try again. If the error persists
please contact us.
`);
break;
case 500: // Server-related issue. Please contact us if the error persists
notifyError(`
We got a Server-related issue from Sciwheel.
Please try again. If the error persists please contact us.
`);
break;
default: // TODO: if (!response.ok)
notifyError(`
We got an undefined error from Sciwheel.
Please try again. If the error persists please contact us.
`);
}
return response;
}
function includeVisReport(refData, notesData) {
// refData is an object with reference metadata, incuding 27 fields
// relevant fields are:
// title, abstractText, publishedYear, authorsText, fullTextLink, pdfUrl
// notesData is an array of comments where each comment has:
// id, user, comment, highlightText, replies, created, updated, url
// Ffor now, we are interested in:
// comment (put it as node text, if available, otherwise use highlightText)
// highlightText (to put it as tooltip)
// TODO: perhaps later include replies
// TODO: sort the report based on created or updated
// https://stackoverflow.com/questions/1078118/how-do-i-iterate-over-a-json-structure
// https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript
visData = buildVisData(refData, notesData);
visOptions = getVisOptions();
var container = document.getElementById('tab_a');
var network = new vis.Network(container, visData, visOptions);
}
// This is a monster fn that could be better implemented / modularized
function buildVisData(refData, notesData) {
// We start with the mind map skeleton and we will add comments as nodes
// skeleton already have nodes for title, objectives, methods, etc.
// with short ids such as #t, #o, #m
var visData = getMindMapSkeleton();
// We want to start by adding the reference data to the title (main) node
refData['authorsText'] = refData['authorsText'] || '';
refData['publishedYear'] = refData['publishedYear'] || '';
refData['title'] = refData['title'] || '';
refData['abstractText'] = refData['abstractText'] || '';
nodeTxt = refData['authorsText'].substring(0, 20) + ' (' +
refData['publishedYear'] + ')\n\n' +
wordWrap(refData['title'], 35, '\n');
// We do want a full-text tooltip, but we want it word-wrapped, otherwise it
// could be a very long line that overflows horizontally
tooltip = wordWrap(refData['abstractText'], 50, '<br/>');
visData.nodes.update([{
id: '#t', label: nodeTxt, title: tooltip, level: 1
}]);
for (var val of notesData) {
// If there is no comment (either empty string, null or undefined) put it
// in highlights using the highlightText as node text
if((val['comment'] === null && typeof val['comment'] === "object") ||
(val['comment'] === undefined && typeof val['comment'] === "undefined")||
(val['comment'] === "" && typeof val['comment'] === "string")) {
newId = Math.random();
// We do not want too long labels, so truncate and word-wrap as necessary
nodeTxt = wordWrap(val['highlightText'], 30, '\n', 80);
tooltip = wordWrap(val['highlightText'], 50, '<br/>');
// Finally add the node and edge
visData.nodes.add([{
id: newId, label: nodeTxt, title: tooltip, level: 3
}]);
visData.edges.add([{from: '#h', to: newId}]);
} else {
if(!val['comment'].includes("#")) { // this means there are no delimiters,
// only unstructured comment => add it as highlight
newId = Math.random();
nodeTxt = wordWrap(val['comment'], 30, '\n');
tooltip = wordWrap(val['highlightText'], 50, '<br/>');
// Finally add the node and edge
visData.nodes.add([{
id: newId, label: nodeTxt, title: tooltip, level: 3
}]);
visData.edges.add([{from: '#h', to: newId}]);
} else {
// Then let's tokenize the comment that has structure
// We separate the comments using hashtags (#)
// and filter with arrow function to remove empty tokens
// So we end up with a flattened array (one element per token,
// regardless of the structure indicated by the number of #)
tokenText = val['comment'].
split('#').
map(function(itm){return itm.trim();}).
filter(item => item);
// And to determine the level of each token from the comment, we count
// the number of #s that precede it
tokenLevel = val['comment'].match(/(#)\1*/g) || [];//match sequences of #
tokenLevel = tokenLevel.map(function(itm){return itm.length;});
var parentId = ['#t'];
let i = 0;
for (token_i of tokenText) {
// We want to generate a hierarchical structure across annotations.
// That means we want to match tokens to their respective parents,
// either in:
// 1. the skeleton,
// 2. within the annotation (e.g. #dad ##son1)
// 3. across annotations (e.g. if annotation A has #dad ##son1 and
// annotation B has #dad ##son2, the vis should show son1 and son2
// both under dad, not each of them in a different branch)
// Thus, we want to check if every token matches existing nodes
// in the visData, either by ID (e.g. to match those in the skeleton),
// or by label (e.g. to be able to match across annotations)
// TODO: check the levels to assign color. Currently there is
// inconsistent behaviour if you match either by id or label
// using a different level than the level it aready has
// e.g. #hey ##t
// #sub ##subsub ; #subsub ##wow
var nodeIds = visData.nodes.map(function(itm){return itm.id;});
var nodeLabels = visData.nodes.map(function(itm){
return itm.label.trim().replace(/\n/g, ' ');
});
var nodeLevels = visData.nodes.map(function(itm){
return itm.level;
});
// watchout, it may not work because indexof internally uses strict
// comparison ===
var nodeIdIndex = nodeIds.indexOf('#' + token_i);
var nodeLabelIndex = nodeLabels.indexOf(token_i);
var nodeIndex = (nodeIdIndex != -1) ? nodeIdIndex : nodeLabelIndex
// We will need the id of the existing token, matching the current one
// If it was a match by id, easy, that is the id
// But if it matched by label, we need to get the id of that label
existingNodeId = nodeIds[nodeIndex];
existingNodeLevel = nodeLevels[nodeIndex];
var alreadyExists = nodeIdIndex != -1 || nodeLabelIndex != -1;
var isLeaf = tokenText.indexOf(token_i) === tokenText.length - 1;
var hasDirectChild = tokenLevel[i] < tokenLevel[i + 1];
var hasNoChildNoSibling = tokenLevel[i] > tokenLevel[i + 1];
var hasSibling = tokenLevel[i] == tokenLevel[i + 1];
// This defines children as those that have exactly one more level
if (alreadyExists) {
if (hasDirectChild) {
parentId.push(existingNodeId);
} else if (hasNoChildNoSibling) {
parentId.pop();
}
// If current token has no children, add a child to the existing one
// (e.g. the comment is just #m, then matches the methods node in
// the skeleton but has no further comments -no children-.
// this would be useful to quickly add the highlight under the
// methods node)
if (isLeaf || hasNoChildNoSibling || hasSibling) {
nodeTxt = wordWrap(val['highlightText'], 30, '\n', 80);
tooltip = wordWrap(val['highlightText'], 50, '<br/>');
newId = Math.random();
// level 3 'cause it should match most of the time existing
// level2 nodes, that is, those in the skeleton and under the #t
visData.nodes.add([{
id: newId, label: nodeTxt, title: tooltip,
level: existingNodeLevel + 1
}]);
visData.edges.add([{from: existingNodeId, to: newId}]);
}
} else {
// If does not exists simply add it
nodeTxt = wordWrap(token_i, 30, '\n');
tooltip = wordWrap(val['highlightText'], 50, '<br/>');
newId = Math.random();
// parent is the last one in the parentId
// Note that this effectively sets the corresponding parent
// even if the level does not match. So the levels are used to
// determine whether to add (push) or drop (pop) elements from the
// parentsId array
dadId = parentId[parentId.length - 1];
visData.nodes.add([{
id: newId, label: nodeTxt, title: tooltip,
level: tokenLevel[i] + 1
}]);
visData.edges.add([{from: dadId, to: newId}]);
if (hasDirectChild) {
parentId.push(newId);
} else if (hasNoChildNoSibling) {
parentId.pop();
}
}
i++;
}
}
}
}
// Set node colors according to the level
visData.nodes.forEach(function(node_i){
switch (node_i.level) {
case 0:
visData.nodes.update([{id: node_i.id, color:'#7BE141'}]);
break;
case 1:
visData.nodes.update([{id: node_i.id, color:'#7BE141'}]);
break;
case 2:
visData.nodes.update([{id: node_i.id, color:'#FFA807'}]);
break;
case 3:
visData.nodes.update([{id: node_i.id, color:'#97C2FC'}]);
break;
case 4:
visData.nodes.update([{id: node_i.id, color:'#FFFF00'}]);
break;
case 5:
visData.nodes.update([{id: node_i.id, color:'#FB7E81'}]);
break;
case 6:
visData.nodes.update([{id: node_i.id, color:'violet'}]);
break;
case 7:
visData.nodes.update([{id: node_i.id, color:'#C2FABC'}]);
break;
}
});
// Remove level 1 empty nodes, before creating the network. So remove nodes
// in the skeleton that after filling the data, have no children
var edgesFroms = visData.edges.map(function(itm){return itm.from;});
if(edgesFroms.indexOf('#b') === -1) visData.nodes.remove({id: '#b'});
if(edgesFroms.indexOf('#o') === -1) visData.nodes.remove({id: '#o'});
if(edgesFroms.indexOf('#m') === -1) visData.nodes.remove({id: '#m'});
if(edgesFroms.indexOf('#r') === -1) visData.nodes.remove({id: '#r'});
if(edgesFroms.indexOf('#c') === -1) visData.nodes.remove({id: '#c'});
if(edgesFroms.indexOf('#q') === -1) visData.nodes.remove({id: '#q'});
if(edgesFroms.indexOf('#h') === -1) visData.nodes.remove({id: '#h'});
if(edgesFroms.indexOf('#k') === -1) visData.nodes.remove({id: '#k'});
if(edgesFroms.indexOf('#crossref') === -1) visData.nodes.remove({id: '#crossref'});
if(edgesFroms.indexOf('#todo') === -1) visData.nodes.remove({id: '#todo'});
return visData;
}
function getVisOptions() {
var options = {
autoResize: true,
//width: (window.innerWidth - 125) + "px",
height: (window.innerHeight - 75) + "px",
nodes:{
shape: 'box'
},
edges: {
smooth: {
//forceDirection: 'vertical',
roundness: 1
}
},
/*layout: {
randomSeed: 777
},
physics: {
barnesHut: {
gravitationalConstant: -1500,
centralGravity: 0.0,
springLength: 2,
avoidOverlap: 0.3
}
},
physics:{
enabled: true,
hierarchicalRepulsion: {
centralGravity: 0.0,
springLength: 5,
springConstant: 0.01,
nodeDistance: 5,
damping: 0.9
}
},*/
/*layout:{
randomSeed: undefined,
improvedLayout:true,
hierarchical: {
enabled:true,
levelSeparation: 15,
nodeSpacing: 10,
treeSpacing: 20,
blockShifting: true,
edgeMinimization: true,
parentCentralization: true,
direction: 'LR', // UD, DU, LR, RL
sortMethod: 'hubsize' // hubsize, directed
}
}/**/
};
return options;
}
function getMindMapSkeleton() {
// create an array with predefined nodes
var nodes = new vis.DataSet([
{id: '#t', label: 'Title \n subtitle', level: 1, color: '#7BE141'},
{id: '#b', label: 'Background', level: 2, color: '#FFA807'},
{id: '#o', label: 'Objectives', level: 2, color: '#FFA807'},
{id: '#m', label: 'Methods', level: 2, color: '#FFA807'},
{id: '#r', label: 'Results', level: 2, color: '#FFA807'},
{id: '#c', label: 'Conclusions', level: 2, color: '#FFA807'},
{id: '#q', label: 'Questions / Comments', level: 2, color: '#FFA807'},
{id: '#h', label: 'Highlights', level: 2, color: '#FFA807'},
{id: '#k', label: 'Key Messages', level: 2, color: '#FFA807'},
{id: '#crossref', label: 'Cross-References', level: 2, color: '#FFA807'},
{id: '#todo', label: 'To Do', level: 2, color: '#FFA807'}
]);
// create an array with predefined edges
var edges = new vis.DataSet([
{from: '#t', to: '#b'},
{from: '#t', to: '#o'},
{from: '#t', to: '#m'},
{from: '#t', to: '#r'},
{from: '#t', to: '#c'},
{from: '#t', to: '#q'},
{from: '#t', to: '#h'},
{from: '#t', to: '#k'},
{from: '#t', to: '#crossref'},
{from: '#t', to: '#todo'}
]);
var visData = {
nodes: nodes,
edges: edges
};
return visData;
}
function wordWrap(rawText, wrapWidth = 50, wrapSeparator = '\n', trunc = -1) {
var wrapped = rawText || ''; // idiom to prevent errors if it is null
wrapped = trunc != -1 ? wrapped.substring(0, trunc) + '...' : wrapped;
var wrapRegexp = new RegExp(
'(?![^\\n]{1,' + wrapWidth + '}$)([^\\n]{1,' + wrapWidth + '})\\s', 'g'
);
wrapped = wrapped.replace(wrapRegexp, '$1' + wrapSeparator);
return wrapped;
}
// https://visjs.github.io/vis-network/docs/network/
// https://visjs.github.io/vis-network/examples/