-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclustergraph.js
585 lines (525 loc) · 13 KB
/
clustergraph.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
// by Charles Lehner
var node,
link,
courses,
clusters,
all,
focusNode,
degree;
var force = d3.layout.force()
.on("tick", tick);
var vis = d3.select("#chart").append("svg:svg")
.classed("vis", true);
d3.json("courses-clusters.json", function(data) {
courses = data.courses;
clusters = data.clusters;
all = courses.concat(clusters);
onHashChange();
if (!focusNode) {
// Start with a random course or cluster
var n = Math.floor(Math.random() * (courses.length + clusters.length));
var node = (n >= courses.length) ?
clusters[n - courses.length] : courses[n];
click(node);
}
});
// Set up degree slider
var deg = d3.select("#degrees_value");
var degSlider = d3.select("#degrees_slider")
.on("change", function () {
degree = +this.value;
deg.html(degree);
sessionStorage.clusterexplorerdegree = degree;
update();
});
degree = sessionStorage.clusterexplorerdegree;
if (degree == null) {
degree = +degSlider.attr("value");
} else {
degree = +degree || 0;
degSlider.attr("value", degree);
}
deg.html(degree);
function isCourse(node) {
return !!node.clusters;
}
function isCluster(node) {
return !!node.courses;
}
function isCollapsed(node) {
return node.isCollapsed;
}
function isFocus(node) {
return node == focusNode;
}
function listingToString(listing) {
return listing.dept + " " + listing.cn;
}
// Capitalize course titles
var capRegex = /(^|\s)(iv|iii|ii|[a-z])/g;
function capResult(m, p1, p2) {
return p1 + p2.toUpperCase();
}
function shortTitle(node) {
return node.clusters ? "" : node.title;
}
function longTitle(node) {
// Cluster names are fine
if (node.courses) return node.title;
// Cache
if (!node._longtitle) {
var listings = node.listings.map(listingToString).join("/");
var title = node.title.toLowerCase().replace(capRegex, capResult);
node._longtitle = listings + ": " + title;
}
return node._longtitle;
}
function radius(node) {
return node.clusters ? 4.5 : 7;
}
var allLinks = {};
function getLink(course, cluster) {
var id = nodeId(course) + "|" + cluster.id;
return allLinks[id] || (allLinks[id] = {
id: id,
source: course,
target: cluster
});
}
var nodeIds = 1;
function nodeId(node) {
return node._id || (node._id = nodeIds++);
}
// remove duplicates from an array
function uniq(arr) {
return arr.filter(function (el, i) {
return arr.indexOf(el, i + 1) == -1;
});
}
function getDups(arr) {
var n = 0;
arr.forEach(function (el, i) {
n += (arr.indexOf(el, i + 1) != -1);
});
return n;
}
function traverse(focus, degree, alreadySeen) {
if (degree == null) {
degree = 1;
}
var focusId = nodeId(focus);
var previousDegree = -1; // degree last time this node was hit
if (!alreadySeen) {
alreadySeen = {};
} else if (focusId in alreadySeen) {
previousDegree = alreadySeen[focusId];
//return null;
if (previousDegree > degree) {
// already traversed past this node
return null;
}
}
alreadySeen[focusId] = degree;
var nodes = [],
links = [];
if (previousDegree == -1) {
nodes.push(focus);
}
if (degree > 0) {
focus.isCollapsed = false;
if (focus.clusters) {
// node is a course
focus.clusters.forEach(function (clusterId) {
var cluster = clusters[clusterId];
var more = traverse(cluster, degree - 1, alreadySeen);
if (more) {
nodes.push.apply(nodes, more.nodes);
links.push.apply(links, more.links);
if (previousDegree < 1) {
// problem.
//console.log(nodes.indexOf(cluster) != -1);
var link = getLink(focus, cluster);
//if (links.indexOf(link) != -1) debugger;
//console.log(clusterVisited, links.indexOf(link) != -1);
if (links.indexOf(link) == -1) {
links.push(link);
}
}
}
});
} else if (focus.courses) {
// node is a cluster
focus.courses.forEach(function (courseId) {
var course = courses[courseId];
var more = traverse(course, degree - 1, alreadySeen);
if (more) {
nodes.push.apply(nodes, more.nodes);
links.push.apply(links, more.links);
if (previousDegree < 1) {
var link = getLink(course, focus);
//if (links.indexOf(link) != -1) debugger;
//console.log(courseVisited, links.indexOf(link) != -1);
if (links.indexOf(link) == -1) {
links.push(link);
}
}
}
});
}
} else {
focus.isCollapsed = true;
}
return {
nodes: nodes,
links: links
};
}
function showAll() {
var links = [];
// todo
}
function resize(resume) {
var svg = vis.node();
force.size([
window.innerWidth, //svg.offsetWidth,
window.innerHeight //svg.offsetHeight
]);
if (resume !== false)
force.resume();
}
window.addEventListener("resize", resize, false);
function update() {
var info = traverse(focusNode, degree);
var nodes = info.nodes;
var links = info.links;
// Remove duplicates. :( Todo: Fix this!
links = uniq(links);
// Restart the force layout.
resize(false);
force
.nodes(nodes)
.links(links)
.distance(50)
.charge(-180)
.gravity(0.35)
.start();
// Update the links…
link = vis.selectAll("line.link")
.data(links, function(d) { return d.id; });
// Enter any new links.
link.enter().insert("svg:line", ".node")
.attr("class", "link")
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; })
.style("opacity", 0)
.transition()
.duration(1000)
.style("opacity", 1);
// Exit any old links.
link.exit().remove();
// Update the nodes…
node = vis.selectAll("g.node")
.data(nodes, nodeId)
.classed("focus", isFocus)
.classed("collapsed", isCollapsed);
// Enter any new nodes.
var newG = node.enter().insert("svg:g")
.attr("class", "node")
.classed("course", isCourse)
.classed("cluster", isCluster)
.classed("collapsed", isCollapsed)
.classed("focus", isFocus)
.call(force.drag);
newG.style("opacity", 0)
.transition()
.duration(1000)
.style("opacity", 1);
newG.append("svg:circle")
.attr("r", radius)
.on("click", click)
.on("mouseover", mouseOver)
.on("mouseout", mouseOut);
newG.append("svg:text")
.attr("class", "nodetext")
.attr("dx", 9)
.attr("dy", ".35em")
.text(shortTitle);
// Exit any old nodes.
node.exit().remove();
}
function tick() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("transform", function(d) {
return "translate(" + (d.x || 0) + "," + (d.y || 0) + ")";
});
}
// Change focus on click.
function click(node) {
focusNode = node;
updateNodeInfo();
updateHash();
// redraw graph
update();
}
function updateNodeInfo() {
var d = focusNode;
var url, info, type;
if (d.clusters) {
// Course
url = "https://cdcs.ur.rochester.edu/Query.aspx?id=DARS&dept=" +
d.listings[0].dept + "&cn=" + d.listings[0].cn;
info = type = "";
} else {
// Cluster
url = "https://secure1.rochester.edu/registrar/CSE/searchResults.php#" +
d.id;
type = d.dept + " (" + d.division + ")";
info = d.description;
}
d3.select("#node_title a")
.text(longTitle(d))
.attr("href", url);
d3.select("#node_type")
.text(type);
d3.select("#node_info")
.html(info);
}
// Encode focus node (state) in location hash.
function hashNode(node) {
return (node.clusters ?
"#course:" + node.listings[0].dept + node.listings[0].cn :
"#cluster:" + node.id
).toLowerCase();
}
function nodeByHash(hash) {
var i;
if (hash.indexOf("#course:") === 0) {
for (i = 0; i < courses.length; i++) {
if (hash == hashNode(courses[i])) {
return courses[i];
}
}
} else if (hash.indexOf("#cluster:") === 0) {
for (i = 0; i < clusters.length; i++) {
if (hash == hashNode(clusters[i])) {
return clusters[i];
}
}
}
return null;
}
function updateHash() {
location.hash = hashNode(focusNode);
}
function onHashChange() {
var hash = location.hash;
if (!hash) return;
var node = nodeByHash(hash);
if (node) click(node);
else alert(hash + " could not be found.");
}
window.addEventListener("hashchange", onHashChange, false);
var hoveredNode, hoveredEl;
function mouseOver(node) {
if (hoveredNode) {
mouseOut(hoveredNode);
}
hoveredNode = node;
hoveredEl = d3.select(this.parentNode)
.classed("hover", true);
var text = hoveredEl.select("text")
.text(longTitle);
hoveredEl.insert("svg:rect", "text")
.attr("class", "label")
.attr("x", 8)
.attr("y", "-.5em")
.attr("height", "1em")
.attr("width", (text.node().offsetWidth || 0) + 2);
// bring to front
vis.node().appendChild(hoveredEl.node());
}
function mouseOut(node) {
if (hoveredNode == node) {
hoveredEl.classed("hover", false)
.select("text")
.text(shortTitle);
hoveredEl.select("rect")
.remove();
hoveredNode = hoveredEl = null;
}
}
// debounce, by John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
// discard close invokations for the last one.
Function.prototype.debounce = function (threshold, execAsap) {
var func = this, timeout;
return function debounced() {
var obj = this, args = arguments;
function delayed() {
if (!execAsap)
func.apply(obj, args);
timeout = null;
}
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
};
var f;
function getFuse() {
if (f) return f;
all.forEach(longTitle);
f = new Fuse(all, {
keys: ["id", "title", "_longtitle"]
});
return f;
}
var windowFocused = true,
resultsFocused,
searchFocused;
// Search functionality
var searchResults = d3.select("#search_results");
var results = [];
var activeResult; // highlighted result
function search() {
var f = getFuse();
// Get search results
var query = this.value;
results = f.search(query).filter(function (node) {
// remove nodes without title
// todo: remove them in scrape.js instead
return node.title;
});
// Update search results list
var result = searchResults.selectAll("li")
.data(results, nodeId);
result.enter().append("li")
.on("mouseover", maybeHighlightResult)
.on("mousemove", maybeHighlightResult)
.append("a")
.attr("href", hashNode)
.text(longTitle);
result.exit().remove();
result.order();
}
var prevMouse = {};
function maybeHighlightResult() {
var x = d3.event.pageX;
var y = d3.event.pageY;
var mouseActuallyMoved = (prevMouse.x != x || prevMouse.y != y);
if (mouseActuallyMoved) {
highlightResult(this);
}
prevMouse = {x: x, y: y};
}
// make a result active
function highlightResult(li) {
if (activeResult && activeResult != li) {
activeResult.className = "";
}
activeResult = li;
li.className = "highlight";
// Scroll the highlighted result into view
var container = li.parentNode;
var scroll;
var down = li.offsetTop + li.offsetHeight - container.clientHeight;
if (down > container.scrollTop) {
scroll = down;
} else {
var up = li.offsetTop;
if (up < container.scrollTop) {
scroll = up;
}
}
if (!isNaN(scroll)) {
container.scrollTop = scroll;
}
}
var searchField = d3.select("#search");
var supportsInputSearch = "onsearch" in document.createElement("input");
if (supportsInputSearch) {
searchField.on("search", search);
} else {
searchField.on("keyup", search.debounce());
}
searchField
.on("keydown", function () {
if (!results.length) return;
var e = d3.event;
switch(e.which || e.keyCode) {
case 38: // up
if (activeResult && activeResult.parentNode) {
if (activeResult.previousSibling) {
highlightResult(activeResult.previousSibling);
} else {
return;
}
} else {
highlightResult(searchResults.node().lastChild);
}
break;
case 40: // down
if (activeResult && activeResult.parentNode) {
if (activeResult.nextSibling) {
highlightResult(activeResult.nextSibling);
} else {
return;
}
} else {
highlightResult(searchResults.node().firstChild);
}
break;
case 13: // enter
location.href = activeResult.firstChild.href;
this.blur();
}
})
.on("focus", function () {
searchFocused = true;
updateResultsFocus();
})
.on("blur", function () {
searchFocused = false;
// delay because on window blur, input blur fires first
setTimeout(updateResultsFocus, 10);
});
function updateResultsFocus() {
// Don't close the results list on blur if:
// 1. focus has left the window, or
// 2. focus has gone to a list item.
var visible = (searchFocused || !windowFocused || resultsFocused);
searchResults.style("display", visible ? "block" : "none");
}
d3.select(window)
.on("blur", function () {
windowFocused = false;
})
.on("focus", function () {
windowFocused = true;
updateResultsFocus();
});
searchResults
.on("mouseup", function () {
resultsFocused = false;
updateResultsFocus();
})
.on("mousedown", function () {
resultsFocused = true;
updateResultsFocus();
});
// About screen
var about = d3.select("#about");
d3.select("#about_link").on("click", function() {
about.style("display", "block");
d3.event.preventDefault();
});
d3.select("#close_about").on("click", function () {
about.style("display", "none");
});