-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInteractiveUndergradProgramCourse_v8.html
More file actions
837 lines (763 loc) · 36.6 KB
/
InteractiveUndergradProgramCourse_v8.html
File metadata and controls
837 lines (763 loc) · 36.6 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
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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>iSchool Program–Course Network (Standalone)</title>
<!-- Tailwind via CDN for styling -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- React 18 UMD builds + Babel for in-browser JSX -->
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<!-- D3 and PapaParse UMD -->
<script src="https://unpkg.com/d3@7/dist/d3.min.js"></script>
<script src="https://unpkg.com/papaparse@5.4.1/papaparse.min.js"></script>
<style>
html, body, #root { height: 100%; }
body { margin: 0; background: white; }
svg text { font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, "Apple Color Emoji", "Segoe UI Emoji"; }
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const { useEffect, useMemo, useRef, useState } = React;
// Strong, contrasting palette for program colors
const PROGRAM_PALETTE = [
"#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd",
"#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf",
"#4e79a7", "#f28e2c", "#e15759", "#76b7b2", "#59a14f",
"#edc948", "#b07aa1", "#ff9da7", "#9c755f", "#bab0ac"
];
// Build nodes (programs, courses) and edges from CSV rows {Program, Course}
function buildGraph(rows) {
// Properly normalize keys and values
const normalized = rows.map((r) => {
const obj = {};
for (const k in r) {
const nk = (k || "").trim();
obj[nk] = String(r[k] ?? "").trim();
}
return obj;
});
const sample = normalized[0] || {};
const programKey = Object.keys(sample).find((k) => /program/i.test(k)) || "Program";
const courseKey = Object.keys(sample).find((k) => /course/i.test(k)) || "Course";
const nodesMap = new Map();
const edges = [];
let colorIdx = 0;
function ensureNode(id, type) {
if (!nodesMap.has(id)) {
nodesMap.set(id, { id, type });
if (type === "program") {
const c = PROGRAM_PALETTE[colorIdx % PROGRAM_PALETTE.length];
nodesMap.get(id).color = c;
colorIdx += 1;
} else {
nodesMap.get(id).color = "#444"; // neutral for courses
}
}
}
normalized.forEach((row, i) => {
const program = String(row[programKey] ?? "").trim();
const course = String(row[courseKey] ?? "").trim();
if (!program || !course) return;
ensureNode(program, "program");
ensureNode(course, "course");
edges.push({ id: `e${i}`, source: program, target: course, program });
});
// Degree counts
const degree = new Map();
edges.forEach((e) => {
degree.set(e.source, (degree.get(e.source) || 0) + 1);
degree.set(e.target, (degree.get(e.target) || 0) + 1);
});
nodesMap.forEach((n) => n.degree = degree.get(n.id) || 0);
return { nodes: Array.from(nodesMap.values()), edges };
}
// Graph helpers
function buildAdjacency(nodes, edges) {
const idToIndex = new Map();
nodes.forEach((n, i) => idToIndex.set(n.id, i));
const adj = Array.from({ length: nodes.length }, () => []);
edges.forEach((e) => {
const u = idToIndex.get(e.source), v = idToIndex.get(e.target);
adj[u].push(v); adj[v].push(u);
});
return { idToIndex, adj };
}
function connectedComponents(nodes, adj) {
const n = nodes.length; const seen = new Array(n).fill(false); const comps = [];
for (let i = 0; i < n; i++) {
if (seen[i]) continue; const stack = [i]; seen[i] = true; const comp = [];
while (stack.length) {
const u = stack.pop(); comp.push(u);
for (const v of adj[u]) if (!seen[v]) { seen[v] = true; stack.push(v); }
}
comps.push(comp);
}
return comps;
}
function allPairsShortestPaths(adj) {
const n = adj.length; const dist = Array.from({ length: n }, () => new Array(n).fill(Infinity));
for (let s = 0; s < n; s++) {
const q = [s]; dist[s][s] = 0; let qi = 0;
while (qi < q.length) {
const u = q[qi++];
for (const v of adj[u]) if (dist[s][v] === Infinity) {
dist[s][v] = dist[s][u] + 1;
q.push(v);
}
}
}
return dist;
}
// Kamada–Kawai on a component, then components are packed in a grid
function kamadaKawaiLayout(nodes, edges, comp) {
const { adj } = buildAdjacency(nodes, edges);
const distAll = allPairsShortestPaths(adj);
const idxArr = comp; const m = idxArr.length;
const pairs = []; let sumL = 0, cntL = 0;
for (let a = 0; a < m; a++) for (let b = a + 1; b < m; b++) {
const i = idxArr[a], j = idxArr[b];
const d = distAll[i][j];
if (!isFinite(d) || d === 0) continue;
sumL += d; cntL += 1;
}
const L0 = cntL ? 1 / (sumL / cntL) : 1;
for (let a = 0; a < m; a++) for (let b = a + 1; b < m; b++) {
const i = idxArr[a], j = idxArr[b];
const d = distAll[i][j];
if (!isFinite(d) || d === 0) continue;
const lij = L0 * d; const wij = 1 / (d * d);
pairs.push([a, b, lij, wij]);
}
const pos = Array.from({ length: m }, (_, k) => ({
x: 0.5 + 0.4 * Math.cos((2 * Math.PI * k) / m),
y: 0.5 + 0.4 * Math.sin((2 * Math.PI * k) / m)
}));
const T = Math.min(600, 100 + 20 * m); let step = 0.02;
for (let t = 0; t < T; t++) {
const grad = Array.from({ length: m }, () => ({ x: 0, y: 0 }));
for (const [a, b, lij, wij] of pairs) {
const dx = pos[a].x - pos[b].x, dy = pos[a].y - pos[b].y;
const d = Math.hypot(dx, dy) || 1e-6;
const coeff = 2 * wij * (1 - lij / d);
const gx = coeff * dx, gy = coeff * dy;
grad[a].x += gx; grad[a].y += gy;
grad[b].x -= gx; grad[b].y -= gy;
}
for (let a = 0; a < m; a++) {
pos[a].x -= step * grad[a].x;
pos[a].y -= step * grad[a].y;
}
if ((t + 1) % 50 === 0) step *= 0.7;
}
let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
for (let a = 0; a < m; a++) {
minX = Math.min(minX, pos[a].x); maxX = Math.max(maxX, pos[a].x);
minY = Math.min(minY, pos[a].y); maxY = Math.max(maxY, pos[a].y);
}
const scaleX = maxX - minX || 1, scaleY = maxY - minY || 1;
const out = {};
for (let a = 0; a < m; a++) {
const id = nodes[idxArr[a]].id;
out[id] = { x: (pos[a].x - minX) / scaleX, y: (pos[a].y - minY) / scaleY };
}
return out;
}
function forceDirectedLayout(nodes, edges) {
const idToNode = new Map(nodes.map((n) => [n.id, { x: Math.random(), y: Math.random() }]));
const sim = d3.forceSimulation(
nodes.map((n) => ({ id: n.id, x: idToNode.get(n.id).x * 500, y: idToNode.get(n.id).y * 500 }))
)
.force("link", d3.forceLink(edges.map((e) => ({ source: e.source, target: e.target })))
.id((d) => d.id).distance(50).strength(0.8))
.force("charge", d3.forceManyBody().strength(-200))
.force("center", d3.forceCenter(250, 250))
.stop();
sim.tick(200);
const out = {};
(sim.nodes()).forEach((n) => {
out[n.id] = { x: (n.x || 0) / 500, y: (n.y || 0) / 500 };
});
return out;
}
function circularLayout(nodes) {
const n = nodes.length; const out = {};
nodes.forEach((node, i) => {
out[node.id] = {
x: 0.5 + 0.45 * Math.cos((2 * Math.PI * i) / n),
y: 0.5 + 0.45 * Math.sin((2 * Math.PI * i) / n)
};
});
return out;
}
function bipartiteLayout(nodes) {
const programs = nodes.filter((n) => n.type === "program");
const courses = nodes.filter((n) => n.type === "course");
const out = {};
programs.forEach((n, i) => {
out[n.id] = { x: 0.2, y: 0.1 + (0.8 * i) / Math.max(1, programs.length - 1) };
});
courses.forEach((n, i) => {
out[n.id] = { x: 0.8, y: 0.1 + (0.8 * i) / Math.max(1, courses.length - 1) };
});
return out;
}
// Extra layouts
function randomLayout(nodes) {
const out = {};
nodes.forEach((n) => { out[n.id] = { x: Math.random(), y: Math.random() }; });
return out;
}
function spiralLayout(nodes) {
const out = {};
const n = nodes.length || 1;
const turns = 3;
nodes.forEach((node, i) => {
const t = i / Math.max(1, n - 1);
const angle = 2 * Math.PI * turns * t;
const r = 0.1 + 0.35 * t;
out[node.id] = { x: 0.5 + r * Math.cos(angle), y: 0.5 + r * Math.sin(angle) };
});
return out;
}
function gridLayout(nodes) {
const out = {};
const n = nodes.length || 1;
const cols = Math.ceil(Math.sqrt(n));
const rows = Math.ceil(n / cols);
nodes.forEach((node, i) => {
const r = Math.floor(i / cols);
const c = i % cols;
const x = (c + 0.5) / cols;
const y = (r + 0.5) / rows;
out[node.id] = { x, y };
});
return out;
}
function twoRingLayout(nodes) {
const programs = nodes.filter((n) => n.type === "program");
const courses = nodes.filter((n) => n.type === "course");
const out = {};
const rp = 0.25, rc = 0.45;
programs.forEach((n, i) => {
const angle = (2 * Math.PI * i) / Math.max(1, programs.length);
out[n.id] = { x: 0.5 + rp * Math.cos(angle), y: 0.5 + rp * Math.sin(angle) };
});
courses.forEach((n, i) => {
const angle = (2 * Math.PI * i) / Math.max(1, courses.length);
out[n.id] = { x: 0.5 + rc * Math.cos(angle), y: 0.5 + rc * Math.sin(angle) };
});
return out;
}
// Order programs around the ring by shared-course overlap
function programOverlapOrdering(nodes, edges) {
const programs = nodes.filter(n => n.type === "program").map(p => p.id);
const courseSetByProgram = new Map(programs.map(pid => [pid, new Set()]));
edges.forEach(e => {
if (courseSetByProgram.has(e.source)) courseSetByProgram.get(e.source).add(e.target);
});
function overlap(a, b) {
const A = courseSetByProgram.get(a) || new Set();
const B = courseSetByProgram.get(b) || new Set();
let cnt = 0; for (const c of A) if (B.has(c)) cnt += 1;
return cnt;
}
const remaining = new Set(programs);
const order = [];
while (remaining.size) {
let pick = null;
if (order.length === 0) {
// Seed with the program that has the most courses, tie-break alphabetically
pick = Array.from(remaining).sort((a, b) => {
const da = (courseSetByProgram.get(a) || new Set()).size;
const db = (courseSetByProgram.get(b) || new Set()).size;
if (db !== da) return db - da;
return a.localeCompare(b);
})[0];
} else {
const last = order[order.length - 1];
let best = null, bestScore = -1, bestDeg = -1;
for (const p of remaining) {
const s = overlap(last, p);
const deg = (courseSetByProgram.get(p) || new Set()).size;
if (s > bestScore || (s === bestScore && deg > bestDeg) || (s === bestScore && deg === bestDeg && p.localeCompare(best || "") < 0)) {
best = p; bestScore = s; bestDeg = deg;
}
}
// If there is no overlap with the current chain, start a new chain with the highest-degree remaining program
if (bestScore === 0) {
best = Array.from(remaining).sort((a, b) => {
const da = (courseSetByProgram.get(a) || new Set()).size;
const db = (courseSetByProgram.get(b) || new Set()).size;
if (db !== da) return db - da;
return a.localeCompare(b);
})[0];
}
pick = best;
}
order.push(pick);
remaining.delete(pick);
}
return order;
}
// Programs on outer ring, courses inside with force-directed placement
function ringInnerForceLayout(nodes, edges) {
const width = 500, height = 500;
const cx = width / 2, cy = height / 2;
const R = Math.min(width, height) * 0.42;
const innerR = R - 40;
const programs = nodes.filter((n) => n.type === "program");
const courses = nodes.filter((n) => n.type === "course");
// determine ring order by shared-course overlap
const orderedProgramIds = programOverlapOrdering(nodes, edges);
const progOrder = new Map(orderedProgramIds.map((pid, i) => [pid, i]));
const progCount = Math.max(1, programs.length);
const simNodes = nodes.map((n) => {
if (n.type === "program") {
const idx = progOrder.get(n.id) ?? 0;
const angle = (2 * Math.PI * idx) / progCount;
const x = cx + R * Math.cos(angle);
const y = cy + R * Math.sin(angle);
return { id: n.id, x, y, fx: x, fy: y };
} else {
return {
id: n.id,
x: cx + (Math.random() * 2 - 1) * innerR * 0.6,
y: cy + (Math.random() * 2 - 1) * innerR * 0.6
};
}
});
const links = edges.map((e) => ({ source: e.source, target: e.target }));
const sim = d3.forceSimulation(simNodes)
.force("link", d3.forceLink(links).id((d) => d.id).distance(40).strength(0.7))
.force("charge", d3.forceManyBody().strength(-70))
.force("center", d3.forceCenter(cx, cy))
.force("collision", d3.forceCollide().radius((d) => 10))
.stop();
sim.tick(320);
// Keep courses inside inner circle
simNodes.forEach((n) => {
if (n.fx != null && n.fy != null) return;
const dx = n.x - cx, dy = n.y - cy;
const dist = Math.hypot(dx, dy) || 1e-6;
if (dist > innerR) {
const s = innerR / dist;
n.x = cx + dx * s;
n.y = cy + dy * s;
}
});
const out = {};
simNodes.forEach((n) => { out[n.id] = { x: n.x / width, y: n.y / height }; });
return out;
}
function computePositions(nodes, edges, layout) {
if (layout === "Circular") return circularLayout(nodes);
if (layout === "Force-Directed") return forceDirectedLayout(nodes, edges);
if (layout === "Bipartite") return bipartiteLayout(nodes, edges);
if (layout === "Random") return randomLayout(nodes);
if (layout === "Spiral") return spiralLayout(nodes);
if (layout === "Grid") return gridLayout(nodes);
if (layout === "Two-Ring") return twoRingLayout(nodes);
if (layout === "Ring + Inner Force") return ringInnerForceLayout(nodes, edges);
// Default, Kamada–Kawai with component packing
const { adj } = buildAdjacency(nodes, edges); const comps = connectedComponents(nodes, adj);
const perComp = []; const positions = {};
for (const comp of comps) {
const kk = kamadaKawaiLayout(nodes, edges, comp);
const pts = comp.map((idx) => ({ id: nodes[idx].id, x: kk[nodes[idx].id].x, y: kk[nodes[idx].id].y }));
perComp.push(pts);
}
const cols = Math.ceil(Math.sqrt(perComp.length));
perComp.forEach((pts, i) => {
const gx = i % cols, gy = Math.floor(i / cols);
const offsetX = (gx + 0.5) / cols, offsetY = (gy + 0.5) / cols;
const scale = 0.8 / cols;
pts.forEach((p) => {
positions[p.id] = { x: offsetX + scale * (p.x - 0.5), y: offsetY + scale * (p.y - 0.5) };
});
});
return positions;
}
// Steeper node size scaling with adjustable maximum
function radiusForNode(n, maxDegree, maxNodeSize) {
const minR = 6;
const deg = n.degree || 0;
const t = Math.pow(deg / Math.max(1, maxDegree), 1.5);
return minR + (maxNodeSize - minR) * t;
}
function download(filename, href) {
const a = document.createElement("a"); a.href = href; a.download = filename;
document.body.appendChild(a); a.click(); document.body.removeChild(a);
}
// allow export background to match current theme
function exportSVG(svgRef, backgroundColor = "white") {
const svg = svgRef.current; if (!svg) return;
const serializer = new XMLSerializer();
const copy = svg.cloneNode(true);
const bg = document.createElementNS("http://www.w3.org/2000/svg", "rect");
bg.setAttribute("x", "0"); bg.setAttribute("y", "0");
bg.setAttribute("width", String(svg.clientWidth));
bg.setAttribute("height", String(svg.clientHeight));
bg.setAttribute("fill", backgroundColor);
copy.insertBefore(bg, copy.firstChild);
const str = serializer.serializeToString(copy);
const blob = new Blob([str], { type: "image/svg+xml;charset=utf-8" });
const url = URL.createObjectURL(blob);
download("network.svg", url); URL.revokeObjectURL(url);
}
async function exportPNG(svgRef, backgroundColor = "white") {
const svg = svgRef.current; if (!svg) return;
const serializer = new XMLSerializer();
const copy = svg.cloneNode(true);
const bg = document.createElementNS("http://www.w3.org/2000/svg", "rect");
bg.setAttribute("x", "0"); bg.setAttribute("y", "0");
bg.setAttribute("width", String(svg.clientWidth));
bg.setAttribute("height", String(svg.clientHeight));
bg.setAttribute("fill", backgroundColor);
copy.insertBefore(bg, copy.firstChild);
const str = serializer.serializeToString(copy);
const svgBlob = new Blob([str], { type: "image/svg+xml;charset=utf-8" });
const url = URL.createObjectURL(svgBlob);
const img = new Image();
const canvas = document.createElement("canvas");
canvas.width = svg.clientWidth; canvas.height = svg.clientHeight;
const ctx = canvas.getContext("2d");
await new Promise((resolve) => { img.onload = () => resolve(); img.src = url; });
ctx.fillStyle = backgroundColor; ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
URL.revokeObjectURL(url);
download("network.png", canvas.toDataURL("image/png"));
}
function App() {
const [rows, setRows] = useState([]);
const [nodes, setNodes] = useState([]);
const [edges, setEdges] = useState([]);
const [layoutName, setLayoutName] = useState("Ring + Inner Force"); // default
const [positions, setPositions] = useState({});
const [showLabels, setShowLabels] = useState(true);
const [labelPrograms, setLabelPrograms] = useState(new Set());
const [selectedNode, setSelectedNode] = useState(null);
const [search, setSearch] = useState("");
const [fixed, setFixed] = useState(new Set());
const [maxNodeSize, setMaxNodeSize] = useState(36);
const [darkBg, setDarkBg] = useState(false); // background toggle
const svgRef = useRef(null); const zoomRef = useRef(null); const gRef = useRef(null);
const containerRef = useRef(null); const [size, setSize] = useState({ width: 800, height: 600 });
// rAF throttle lock for drag updates
const dragRafLocked = useRef(false);
useEffect(() => {
if (!rows.length) return;
const { nodes, edges } = buildGraph(rows);
setNodes(nodes); setEdges(edges);
}, [rows]);
useEffect(() => {
if (!nodes.length) return;
const base = computePositions(nodes, edges, layoutName);
const merged = { ...base };
for (const id of fixed) if (positions[id]) merged[id] = positions[id];
setPositions(merged);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [nodes, edges, layoutName]);
useEffect(() => {
const el = containerRef.current; if (!el) return;
const ro = new ResizeObserver(() => {
setSize({ width: el.clientWidth, height: el.clientHeight });
});
ro.observe(el); return () => ro.disconnect();
}, []);
useEffect(() => {
const svg = svgRef.current; const g = gRef.current; if (!svg || !g) return;
const zoomed = (event) => {
const { transform } = event; g.setAttribute("transform", transform.toString());
};
const zoom = d3.zoom().scaleExtent([0.2, 10]).on("zoom", zoomed);
d3.select(svg).call(zoom); zoomRef.current = zoom;
}, []);
const idToNode = useMemo(() => new Map(nodes.map((n) => [n.id, n])), [nodes]);
const programList = useMemo(
() => nodes.filter((n) => n.type === "program").map((n) => n.id).sort(),
[nodes]
);
const margin = 24;
const toScreen = (p) => ({
x: margin + (p.x || 0.5) * (size.width - 2 * margin),
y: margin + (p.y || 0.5) * (size.height - 2 * margin)
});
const neighbors = useMemo(() => {
const map = new Map(); nodes.forEach((n) => map.set(n.id, new Set()));
edges.forEach((e) => { map.get(e.source).add(e.target); map.get(e.target).add(e.source); });
return map;
}, [nodes, edges]);
const isEdgeActive = (e) => !selectedNode || e.source === selectedNode || e.target === selectedNode;
const isNodeDimmed = (id) => selectedNode && !(id === selectedNode || neighbors.get(selectedNode).has(id));
const handleBackgroundClick = () => setSelectedNode(null);
// Drag behavior, bounded re-attachment and rAF throttled updates
useEffect(() => {
const svg = svgRef.current; if (!svg) return;
const selection = d3.select(svg).selectAll("g.node-group");
const drag = d3.drag()
.on("start", function(event) {
event.sourceEvent?.stopPropagation?.();
const group = event.sourceEvent?.target?.closest?.("g.node-group");
const id = group?.getAttribute ? group.getAttribute("data-id") : null;
if (!id) return;
setSelectedNode(id);
setFixed((prev) => new Set([...prev, id]));
})
.on("drag", function(event) {
const svg = svgRef.current; if (!svg) return;
const group = event.sourceEvent?.target?.closest?.("g.node-group");
const id = group?.getAttribute ? group.getAttribute("data-id") : null;
if (!id) return;
if (dragRafLocked.current) return;
dragRafLocked.current = true;
requestAnimationFrame(() => {
const z = d3.zoomTransform(svg);
const pt = z.invert([event.x, event.y]);
const ux = pt[0], uy = pt[1];
const px = (ux - margin) / Math.max(1, size.width - 2 * margin);
const py = (uy - margin) / Math.max(1, size.height - 2 * margin);
setPositions((prev) => ({
...prev,
[id]: {
x: Math.max(0, Math.min(1, px)),
y: Math.max(0, Math.min(1, py))
}
}));
dragRafLocked.current = false;
});
})
.on("end", function(event) {
const group = event.sourceEvent?.target?.closest?.("g.node-group");
const id = group?.getAttribute ? group.getAttribute("data-id") : null;
if (!id) return;
setFixed((prev) => new Set([...prev, id]));
});
// Attach once per node-count change to avoid re-attaching every render
selection.call(drag);
}, [nodes.length, size.width, size.height]); // re-bind if node count or canvas size changes
function runSearch() {
const q = search.trim().toLowerCase(); if (!q) return;
const match = nodes.find((n) => n.id.toLowerCase().includes(q)); if (!match) return;
setSelectedNode(match.id);
const svg = svgRef.current;
const p = toScreen(positions[match.id] || { x: 0.5, y: 0.5 });
const current = d3.zoomTransform(svg); const k = current.k || 1;
const tx = size.width / 2 - k * p.x; const ty = size.height / 2 - k * p.y;
d3.select(svg).transition().duration(500)
.call(zoomRef.current.transform, d3.zoomIdentity.translate(tx, ty).scale(k));
}
function onFileSelected(file) {
Papa.parse(file, {
header: true, skipEmptyLines: true,
complete: (res) => { const data = (res.data || []).filter(Boolean); setRows(data); }
});
}
function resetView() {
const svg = svgRef.current; if (!svg) return;
d3.select(svg).transition().duration(400).call(zoomRef.current.transform, d3.zoomIdentity);
setSelectedNode(null);
}
function resetPositions() {
setFixed(new Set());
setPositions(computePositions(nodes, edges, layoutName));
}
function edgePath(e) {
const a = toScreen(positions[e.source] || { x: 0.5, y: 0.5 });
const b = toScreen(positions[e.target] || { x: 0.5, y: 0.5 });
return `M${a.x},${a.y} L${b.x},${b.y}`;
}
function showLabelFor(id) {
if (!showLabels) return false;
if (labelPrograms.size === 0) return true;
const n = idToNode.get(id);
if (n.type === "program") return labelPrograms.has(n.id);
const inc = edges.filter((e) => e.target === id || e.source === id).map((e) => e.program);
return inc.some((p) => labelPrograms.has(p));
}
const maxDegree = useMemo(
() => (nodes.length ? Math.max(...nodes.map(n => n.degree || 0)) : 1),
[nodes]
);
const drawableEdges = edges; const drawableNodes = nodes;
const isISTCourse = (id) => /^IST/i.test(id);
return (
<div className={`w-full h-screen ${darkBg ? 'bg-black text-gray-100' : 'bg-white text-gray-900'} flex`}>
{/* Sidebar Controls */}
<div className={`w-80 flex-shrink-0 ${darkBg ? 'border-gray-800' : 'border-gray-200'} border-r p-4 space-y-4 overflow-y-auto`}>
<h1 className="text-xl font-semibold">iSchool Program–Course Network</h1>
<p className={`text-sm ${darkBg ? 'text-gray-400' : 'text-gray-600'}`}>Upload a CSV with columns <span className="font-mono">Program</span> and <span className="font-mono">Course</span>.</p>
<div>
<label className="block text-sm font-medium mb-1">Load data (CSV)</label>
<input type="file" accept=".csv" onChange={(e) => e.target.files && onFileSelected(e.target.files[0])} className="block w-full text-sm" />
<div className={`mt-2 text-xs ${darkBg ? 'text-gray-400' : 'text-gray-500'}`}>{rows.length ? `${rows.length} rows loaded` : `No data loaded yet`}</div>
</div>
<div className="space-y-1">
<label className="block text-sm font-medium">Layout</label>
<select value={layoutName} onChange={(e) => setLayoutName(e.target.value)} className="w-full border rounded-md px-2 py-1">
{/* Ring layout first in the list */}
<option>Ring + Inner Force</option>
<option>Kamada–Kawai</option>
<option>Force-Directed</option>
<option>Circular</option>
<option>Bipartite</option>
<option>Two-Ring</option>
<option>Grid</option>
<option>Spiral</option>
<option>Random</option>
</select>
<div className="flex gap-2 pt-2">
<button className="px-3 py-1.5 bg-gray-900 text-white rounded-md" onClick={resetPositions}>Reset positions</button>
<button className={`px-3 py-1.5 rounded-md ${darkBg ? 'bg-gray-800 text-white' : 'bg-gray-100'}`} onClick={resetView}>Reset view</button>
</div>
</div>
{/* Background theme toggle */}
<div className="space-y-2">
<label className="inline-flex items-center gap-2 text-sm">
<input type="checkbox" checked={darkBg} onChange={(e) => setDarkBg(e.target.checked)} />
Black background (labels white, orange for non-IST)
</label>
</div>
<div className="space-y-1">
<label className="block text-sm font-medium">Max node size</label>
<input
type="number"
min={12}
max={72}
step={1}
value={maxNodeSize}
onChange={(e) => setMaxNodeSize(Number(e.target.value) || 36)}
className="w-full border rounded-md px-2 py-1"
/>
<p className={`text-xs ${darkBg ? 'text-gray-400' : 'text-gray-500'}`}>Sets radius cap for highest degree node, default 36.</p>
</div>
<div className="space-y-2">
<label className="inline-flex items-center gap-2 text-sm">
<input type="checkbox" checked={showLabels} onChange={(e) => setShowLabels(e.target.checked)} />
Show labels
</label>
<div>
<div className="text-sm font-medium mb-1">Filter labels by program</div>
<div className={`h-32 overflow-y-auto border rounded-md p-2 space-y-1 ${darkBg ? 'border-gray-700' : ''}`}>
{programList.map((p) => (
<label key={p} className="flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={labelPrograms.has(p)}
onChange={(e) => {
setLabelPrograms((prev) => {
const n = new Set(prev);
if (e.target.checked) n.add(p); else n.delete(p);
return n;
});
}}
/>
<span className="inline-flex items-center gap-2">
<span className="w-3 h-3 inline-block rounded-sm" style={{ background: idToNode.get(p)?.color || "#000" }} /> {p}
</span>
</label>
))}
</div>
<div className="mt-1">
<button className={`text-xs underline mr-3 ${darkBg ? 'text-gray-300' : 'text-gray-600'}`} onClick={() => setLabelPrograms(new Set())}>Clear</button>
<button className={`text-xs underline ${darkBg ? 'text-gray-300' : 'text-gray-600'}`} onClick={() => setLabelPrograms(new Set(programList))}>All</button>
</div>
</div>
</div>
<div className="space-y-2">
<label className="block text-sm font-medium">Search node</label>
<div className="flex gap-2">
<input
value={search}
onChange={(e) => setSearch(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && runSearch()}
placeholder="Type a course or program"
className="border rounded-md px-2 py-1 flex-1"
/>
<button onClick={runSearch} className="px-3 py-1.5 bg-blue-600 text-white rounded-md">Go</button>
</div>
<p className={`text-xs ${darkBg ? 'text-gray-400' : 'text-gray-600'}`}>When a node is selected, only its incident edges keep their color, others turn gray. Click empty space to clear.</p>
</div>
<div className="space-y-2">
<div className="text-sm font-medium">Export view</div>
<div className="flex gap-2">
<button onClick={() => exportPNG(svgRef, darkBg ? "black" : "white")} className="px-3 py-1.5 bg-green-600 text-white rounded-md">PNG</button>
<button onClick={() => exportSVG(svgRef, darkBg ? "black" : "white")} className="px-3 py-1.5 bg-gray-900 text-white rounded-md">SVG</button>
</div>
</div>
<div className={`pt-2 text-xs ${darkBg ? 'text-gray-400' : 'text-gray-500'}`}>
<p>Drag nodes to reposition, they will stick until you reset positions. Scroll or pinch to zoom, drag to pan.</p>
</div>
</div>
{/* Graph Canvas */}
<div className="flex-1" ref={containerRef}>
<svg
ref={svgRef}
width={size.width}
height={size.height}
className={darkBg ? 'bg-black' : 'bg-white'}
onClick={(e) => { if (e.target === e.currentTarget) handleBackgroundClick(); }}
>
<g ref={gRef}>
{/* Edges */}
{drawableEdges.map((e) => {
const programColor = idToNode.get(e.program)?.color || (darkBg ? "#888" : "#999");
const stroke = isEdgeActive(e) ? programColor : (darkBg ? "#555" : "#ccc");
const sw = isEdgeActive(e) ? 1.8 : 1.4;
const op = isEdgeActive(e) ? (darkBg ? 0.95 : 0.9) : (darkBg ? 0.55 : 0.6);
return (<path key={e.id} d={edgePath(e)} stroke={stroke} strokeWidth={sw} fill="none" opacity={op} />);
})}
{/* Nodes */}
{drawableNodes.map((n) => {
const p = toScreen(positions[n.id] || { x: 0.5, y: 0.5 });
const r = radiusForNode(n, maxDegree, maxNodeSize);
const fill = n.type === "program" ? (n.color || (darkBg ? "#ddd" : "#000")) : (darkBg ? "#bbbbbb" : "#666666");
const stroke = selectedNode === n.id ? (darkBg ? "#ffffff" : "#111111") : (darkBg ? "#222222" : "#ffffff");
const opacity = isNodeDimmed(n.id) ? 0.25 : 1;
const labelFill = darkBg
? (n.type === "program" ? "#ffffff" : (isISTCourse(n.id) ? "#ffffff" : "#f59e0b")) // white; orange for non-IST
: (n.type === "program"
? "#111111"
: (isISTCourse(n.id) ? "#000000" : "#ef4444"));
return (
<g
className="node-group"
data-id={n.id}
key={n.id}
transform={`translate(${p.x},${p.y})`}
style={{ cursor: "pointer" }}
onClick={(ev) => { ev.stopPropagation(); setSelectedNode(n.id); }}
>
<circle className="node" data-id={n.id} r={r} fill={fill} stroke={stroke} strokeWidth={1.5} opacity={opacity} />
{showLabelFor(n.id) && (
<text
x={0}
y={-(r + 6)}
textAnchor="middle"
fontSize={n.type === "program" ? 14 : 12}
fontWeight={n.type === "program" ? 700 : 400}
fill={labelFill}
className="select-none"
style={{ pointerEvents: "none" }}
>
{n.id}
</text>
)}
</g>
);
})}
</g>
</svg>
</div>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
</script>
</body>
</html>