-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathhelpers.js
More file actions
535 lines (463 loc) · 17.2 KB
/
helpers.js
File metadata and controls
535 lines (463 loc) · 17.2 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
const SVG = {
text: {
label: "label",
functionLogo: "label",
},
path: {
hollow: "timeline_mut",
staticref: "static_ref_line",
mutref: "mut_ref_line",
},
polyline: "arrow",
circle: "event",
line: "timeline_mut",
use: "function_event",
rect: "structBox",
};
/* --------------------- SIMPLE DRIVER --------------------- */
function helpers(classname) {
// console.log("class name is :", classname)
// create tooltip element before #page-wrapper
let page = document.querySelector("#page-wrapper");
let tooltip = document.getElementById("svg_tooltip");
if (!tooltip) {
tooltip = document.createElement("p");
tooltip.id = "svg_tooltip";
tooltip.style.cssText =
"position: absolute; padding: 0.5em; font-size: 0.75em; border-radius: 8px;" +
"font-family: 'Trebuchet MS', Helvetica, sans-serif;" +
"background: rgb(70, 70, 70, 0.6); color: white; z-index: 100; display: none;";
page.parentNode.insertBefore(tooltip, page);
}
displayFn(classname);
displayTooltip(tooltip, classname);
}
/* --------------------- FUNCTION HIGHLIGHT --------------------- */
// change function name color on hover
function displayFn(classname) {
// get svg elements
let vis_num = document.getElementsByClassName(classname);
let code_obj = vis_num[0];
let tl_obj = vis_num[1];
let c_svg = code_obj.contentDocument.firstChild;
let tl_svg = tl_obj.contentDocument.firstChild;
// get elements that will trigger function
let triggers = tl_svg.getElementsByClassName("fn-trigger");
var functions = c_svg.getElementsByClassName("fn");
for (let i = 0; i < triggers.length; i++) {
triggers[i].addEventListener("mouseover", showFn);
triggers[i].addEventListener("mouseout", hideFn);
}
function showFn(evt) {
// console.log("showFn")
// get target attributes
let evt_hash = evt.target.dataset.hash;
for (let i = 0; i < functions.length; i++) {
// if hashes match, temporarily change color
if (functions[i].getAttribute("hash") == evt_hash) {
functions[i].dataset.hash = evt_hash;
}
}
}
function hideFn() {
// console.log("hideFn");
// // send hover msg to API
// var xhr = new XMLHttpRequest();
// xhr.open("POST", "/action/hover", true); // could add authentification info
// xhr.setRequestHeader("Content-Type", "application/json");
// xhr.send(
// JSON.stringify({
// action_type: "hideFn",
// })
// );
// reset to hash 0, styling to black on mouseout
for (let i = 0; i < functions.length; i++) {
functions[i].dataset.hash = 0;
}
}
}
/* --------------------- SVG CODE-RELATED FUNCTIONS --------------------- */
// resize code block to fit comments
function sizeToFit(object) {
// Case for Chrome loading
if (navigator.userAgent.indexOf("Chrome") !== -1) {
object.addEventListener(
"load",
function () {
let svg_doc = object.contentDocument;
let code_width = svg_doc.getElementById("code").getBBox().width;
let new_width = Math.max(code_width + 30, 400);
svg_doc.firstChild.setAttribute("width", new_width + "px");
},
{ once: true }
);
} else {
if (object.contentDocument.readyState === "complete") {
let svg_doc = object.contentDocument;
let code_width = svg_doc.getElementById("code").getBBox().width;
let new_width = Math.max(code_width + 30, 400);
svg_doc.firstChild.setAttribute("width", new_width + "px");
}
}
}
/* --------------------- TOOLTIP-RELATED FUNCTIONS --------------------- */
// change tooltip text on hover
function displayTooltip(tooltip, classname) {
// get svg elements
let tl_obj = document.getElementsByClassName(classname)[1];
let tl_svg = tl_obj.contentDocument.firstChild;
// get elements that will trigger function
let triggers = tl_svg.getElementsByClassName("tooltip-trigger");
let start_line = 0;
let end_line = 0;
// track time
var time_start = null;
for (let i = 0; i < triggers.length; i++) {
// prevent adding duplicate listeners
if (triggers[i].classList.contains("listener")) break;
else triggers[i].classList.add("listener");
triggers[i].addEventListener("mousemove", showTooltip);
triggers[i].addEventListener("mouseleave", hideTooltip);
triggers[i].addEventListener("mouseenter", insertUnderline);
}
function showTooltip(e) {
// console.log("showTooltip")
// only set time once, prevent from changing every time mouse moves
if (!time_start) time_start = Date.now();
let mouse = mousePos(e, tl_obj);
tooltip.style.transform = "translate(" + mouse.x + "px, " + mouse.y + "px)";
tooltip.style.display = "block";
let text = e.currentTarget.getAttributeNS(null, "data-tooltip-text");
tooltip.innerHTML = text;
// if out of bounds, break text into two lines
if (tooltip.getBoundingClientRect().right >= document.body.clientWidth)
breakText(text, tooltip);
}
// function parseText(text) {
// let split_text = text.split(" ");
// let words = [];
// for (const elt of split_text) {
// if (elt.startsWith("<")) {
// parse1 = elt.substr(elt.indexOf(">") + 1);
// parse2 = parse1.substr(0, parse1.indexOf("<"));
// words.push(parse2);
// }
// else {
// words.push(elt);
// }
// }
// result = "";
// for (let elt of words) {
// result += elt;
// result += " ";
// }
// return result;
// }
function parseText(text) {
result = text;
while (result.indexOf("<") !== -1) {
left = result.substr(0, result.indexOf("<"));
right = result.substr(result.indexOf(">") + 1);
result = left + " " + right;
}
return result;
}
function hideTooltip(e) {
// console.log("hideTooltip");
// console.log(e);
// console.log(e.data-tooltip-text);
// console.log(e.currentTarget.ownerSVGElement.id);
let tgt = e.currentTarget;
// console.log(tgt.data-tooltip-text);
let text = e.currentTarget.getAttributeNS(null, "data-tooltip-text");
text = parseText(text);
let e_label =
tgt.tagName === "text"
? SVG["text"][tgt.classList[0]]
: tgt.tagName === "path"
? SVG["path"][tgt.classList[0]]
: SVG[tgt.tagName];
// console.log(e_label);
let now = Date.now();
let hover_time = now - time_start; // time in ms
var xhr = new XMLHttpRequest();
xhr.open("POST", "/action/hover", true); // could add authentification info
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(
JSON.stringify({
svg_name: e.currentTarget.ownerSVGElement.id,
hover_item: e_label,
hover_time: hover_time,
start: time_start,
end: now,
hover_message: text,
start_line: parseInt(start_line),
end_line: parseInt(end_line),
})
);
// console.log(xhr);
tooltip.style.display = "none";
tooltip.innerHTML = "";
start_line = 0;
end_line = 0;
// only track hovering after mouse leaves element
gtag("event", "tooltip_hover", {
event_label: e_label,
});
gtag("event", e_label, {
hover_time: Date.now() - time_start, // time in ms
});
time_start = null; // reset
removeUnderline(e, classname);
}
/* ---- SHOW RELEVANT LINES ---- */
function insertUnderline(e) {
// console.log("insertUnderline");
let doc = document.getElementsByClassName(classname + " code_panel")[0]
.contentDocument; //code_panel
let begin = 0,
end = 0;
if (e.currentTarget.tagName === "path") {
let arr = e.currentTarget.getAttribute("d").split(" ");
if (e.currentTarget.parentNode.id === "ref_line") {
begin = parseInt(arr[2]);
end = parseInt(begin) + 2 * parseInt(arr[5]) + parseInt(arr[7]) + 5; // + 5 to include last line
} else {
begin = parseInt(arr[7]);
end = parseInt(arr[3]);
}
} else if (e.currentTarget.tagName === "line") {
begin = e.currentTarget.getAttribute("y1");
end = e.currentTarget.getAttribute("y2");
} else {
let pos;
if (e.currentTarget.tagName === "circle") {
begin = end = parseInt(e.currentTarget.getAttribute("cy")) + 5;
} else if (e.currentTarget.tagName === "use") {
begin = end = parseInt(e.currentTarget.getAttribute("y")) + 5;
} else if (e.currentTarget.tagName === "polyline") {
let arr = e.currentTarget.getAttribute("points").split(" ");
begin = end = parseInt(arr[1]) + 5;
} else {
// e.currentTarget.tagName === 'text'
begin = end = parseInt(e.currentTarget.getAttribute("y"));
}
}
// add underlining to every relevant line
let lines = doc.getElementById("code").children;
let len = lines.length; // prevent len from changing
// start_line and end_line are computed from variables begin and end.
// begin and end are y-cordinates of the html elements on the website.
// They might have a remainder of 25 or 0 when divided by 30
// depending on the graphs generated by the code.
// Hence, we handle these situations differently
if (parseInt(begin) % 30 !== 0) {
start_line = (parseInt(begin) + 5 - 60) / 30;
}
else {
start_line = (parseInt(begin) - 60) / 30;
}
if (parseInt(end) % 30 !== 0) {
end_line = (parseInt(end) + 5 - 60) / 30;
}
else {
end_line = (parseInt(end) - 60) / 30;
}
for (let i = 0; i < len; ++i) {
let ly = parseInt(lines[i].getAttribute("y"));
if (ly >= begin && ly <= end) {
// only underline relevant code
let emph = doc.createElementNS("http://www.w3.org/2000/svg", "text");
emph.setAttribute("class", "code emph");
emph.setAttribute("x", "25");
emph.setAttribute("y", ly + 3); // +3 to hang just under text
emph.innerHTML = new Array(
Math.floor(lines[i].getBBox().width / 8) // size of '_' = 8
).join("_"); // string with all underscores
doc.getElementById("code").appendChild(emph);
}
}
}
}
// track mouse movement
function mousePos(evt, obj) {
let x_pos = evt.clientX + obj.getBoundingClientRect().x + 15; // offset from svg start + svg offset
let y_pos = evt.clientY + obj.getBoundingClientRect().y + window.scrollY + 45; // baseline hanging
return {
//object
x: Math.round(x_pos),
y: Math.round(y_pos),
};
}
function removeUnderline(e, classname) {
let doc = document.getElementsByClassName(classname + " code_panel")[0]
.contentDocument; //code_panel
let arr = doc.getElementsByClassName("emph");
for (let i = arr.length - 1; i >= 0; --i) {
arr[i].remove();
}
}
// adjust text box
function breakText(text, tooltip) {
// combine span into one element
let split_text = text.split(" ");
let words = [];
let last = 0,
span = false;
for (const elt of split_text) {
if (elt.startsWith("<")) {
span = true;
words.push(elt);
last = words.length - 1;
} else if (elt.startsWith("!important")) {
span = false;
words[last] += elt;
} else {
if (span) {
words[last] = words[last] + " " + elt;
} else {
words.push(elt);
}
}
}
// adjust size and split text based on page boundary
tooltip.innerHTML = "";
// console.log('enter?');
let left = tooltip.getBoundingClientRect().left;
for (const word of words) {
// console.log('yes?');
// console.log(word);
tooltip.innerHTML += word + " ";
if (left + tooltip.clientWidth > document.body.clientWidth - 20) {
// reset tooltip text and break into new lines
let idx = tooltip.innerHTML.lastIndexOf(
" ",
tooltip.innerHTML.length - 2
);
let temp = tooltip.innerHTML.substr(0, idx);
let other = tooltip.innerHTML.substr(idx + 1);
tooltip.innerHTML = "";
tooltip.innerHTML += temp;
tooltip.innerHTML += "<br />" + other;
}
}
}
/* --------------- TOGGLE ALL SVGS --------------- */
function toggleAll(turn_on) {
let evt = new MouseEvent("click", {
bubbles: true,
cancelable: true,
view: window,
});
let arr = document.getElementsByClassName("toggle-button");
for (const obj of arr) {
if (turn_on && obj.classList.contains("fa-toggle-off")) {
obj.dispatchEvent(evt);
} else if (!turn_on && obj.classList.contains("fa-toggle-on")) {
obj.dispatchEvent(evt);
}
}
}
/* --------------- TOGGLE ALL STRUCTS --------------- */
function toggleStruct(turn_on) {
var evt = new MouseEvent("click", {
bubbles: true,
cancelable: true,
view: window,
});
var arr = document.getElementsByClassName("non-struct");
for (const obj of arr) {
if (turn_on && obj.classList.contains("fa-toggle-off")) {
obj.dispatchEvent(evt);
} else if (!turn_on && obj.classList.contains("fa-toggle-on")) {
obj.dispatchEvent(evt);
}
}
}
/* --------------- DETECT TAB CLOSE --------------- */
// window.addEventListener("beforeunload", (event) => {
// chapter_list = document.getElementsByClassName("expanded");
// start = new Date();
// for (chapter of chapter_list) {
// // console.log(chapter.textContent);
// chapter.firstChild.addEventListener("click", function(e) {
// e.preventDefault();
// OnOneClick(window.location.pathname, start);
// window.location = this.href;
// // if(e.target && e.target.nodeName == "A") {
// // OnOneClick(window.location.pathname, start);
// // }
// }, false);
// }
// var xhr = new XMLHttpRequest();
// xhr.open("POST", "/action/close", true); // could add authentification info
// xhr.setRequestHeader("Content-Type", "application/json");
// xhr.send(
// JSON.stringify({
// action_type: "closed",
// })
// );
// delete event["returnValue"];
// });
/* --------------- DETECT PAGE LOAD --------------- */
window.addEventListener("load", function () {
chapter_list = document.getElementsByClassName("expanded");
start = new Date();
// the following handler will send a POST request when a tab is closed or switched
window.addEventListener("beforeunload", (event) => {
OnOneClick(window.location.pathname, start);
})
});
function callback(e) {
var e = window.e || e;
alert('The link is: ' + e.target.href);
}
function resume(s) {
return true;
}
var OnOneClick = function (chapter, start) {
// Your click handler
time_onpage = new Date() - start;
end_time = new Date();
var xhr = new XMLHttpRequest();
xhr.open("POST", "/action/switch", true); // could add authentification info
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(
JSON.stringify({
directory: chapter,
time_elpse: time_onpage,
start_time: start.getTime(),
end_time: end_time.getTime(),
})
);
console.log(xhr)
};
/*window.onload = function () {
var correct_doc = (document.getElementsByClassName('active')[0].attributes.href.value === 'ch04-01-what-is-ownership.html'
|| document.getElementsByClassName('active')[0].attributes.href.value === 'ch04-02-references-and-borrowing.html');
if (correct_doc) {
let top_btns = document.getElementsByClassName('left-buttons');
var eye = document.getElementById('viz-toggle');
var struct_eye = document.getElementById('viz-struct-toggle')
if (!eye) {
eye = document.createElement('button');
eye.id = 'viz-toggle';
eye.className = 'icon-button fa fa-eye';
eye.title = 'Toggle all visualizations';
top_btns[0].insertBefore(eye, top_btns[0].lastElementChild);
}
eye.addEventListener('click', function (e) {
if (e.currentTarget.classList.contains('fa-eye')) {
// on button click, show all visualizations
e.currentTarget.classList.remove('fa-eye');
e.currentTarget.classList.add('fa-eye-slash');
toggleAll(true);
} else if (e.currentTarget.classList.contains('fa-eye-slash')) {
// on button click, hide all visualizations
e.currentTarget.classList.remove('fa-eye-slash');
e.currentTarget.classList.add('fa-eye');
toggleAll(false);
}
});
}
};*/