Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
2481 lines (2314 loc) · 102 KB
/
Copy pathapp.js
File metadata and controls
2481 lines (2314 loc) · 102 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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* CodeBread interactive graph UI — vanilla JS + SVG, no dependencies. */
(function () {
"use strict";
// CSS custom properties so light/dark themes recolor the graph for free.
// SVG presentation attributes can't take var(), so marks set these via .style.
const LAYER_COLOR = {
frontend: "var(--frontend)", backend: "var(--backend)", database: "var(--database)",
config: "var(--config)", unknown: "var(--unknown)",
};
const LAYER_LABEL = {
frontend: "Frontend", backend: "Backend", database: "Database",
config: "Config", unknown: "Unclassified",
};
const SVGNS = "http://www.w3.org/2000/svg";
/* ---------------- state ---------------- */
const S = {
data: null,
nodesById: new Map(),
outEdges: new Map(), // id -> [edge]
inEdges: new Map(), // id -> [edge]
fileFns: new Map(), // file path -> [fn node ids]
visible: new Set(), // node ids currently on canvas
expanded: new Set(), // file ids whose functions are shown
pos: new Map(), // id -> {x,y,vx,vy,fx,fy}
selected: null,
litNodes: new Set(),
litEdges: new Set(),
filter: "all",
mode: "orbit", // "orbit" (files float, functions ring around them) |
// "free" (plain force layout)
view: "chart", // "chart" (graph) | "ide" (full code editor)
ideFile: null, // file currently open in IDE mode
tf: { x: 0, y: 0, k: 1 },
alpha: 0,
elNodes: new Map(), // id -> <g>
elEdges: new Map(), // edge key -> {vis, hit}
drawnEdges: [], // [{edge, key}] currently in DOM
drag: null,
searchSel: -1,
crumbs: [], // navigation history (node ids)
crumbIdx: -1,
navList: [], // neighbor cycle list for ArrowLeft/ArrowRight
navIdx: -1,
mmT: null, // minimap world->minimap transform
mmDots: new Map(),
mmViewportEl: null,
focusMode: false, // when on, picking a file in the Explorer
// spotlights just that file instead of adding to the view
obfByFile: new Map(), // file id -> Map(line -> [obfuscation finding, ...])
};
const $ = (id) => document.getElementById(id);
const svg = $("graph"), viewport = $("viewport");
const edgesG = $("edges-g"), nodesG = $("nodes-g");
/* getBoundingClientRect() forces a synchronous layout — cheap in
isolation, but called on every mousemove (tooltip positioning, drag)
while the simulation is *also* mutating the SVG every animation frame,
the two interleave into "layout thrashing" that alone can tank FPS
independent of how many nodes/edges exist. The rect only actually
changes on resize or a view-mode switch, so cache it and invalidate on
just those. */
let _svgRectCache = null, _canvasRectCache = null;
function getSvgRect() { return _svgRectCache || (_svgRectCache = svg.getBoundingClientRect()); }
function getCanvasRect() { return _canvasRectCache || (_canvasRectCache = $("canvas-wrap").getBoundingClientRect()); }
function invalidateRectCache() { _svgRectCache = null; _canvasRectCache = null; }
window.addEventListener("resize", invalidateRectCache);
/* ---------------- boot ---------------- */
function boot(data) {
S.data = data;
bindAccent(); // first, so a saved accent applies before anything animates in
indexData();
renderHeader();
renderLanguages();
renderLegend();
renderTree();
initialVisible();
layoutInitial();
rebuild();
runTicks(260);
fitView(0.82);
startLoop();
bindUI();
bindGraphDelegatedEvents();
bindMinimap();
bindOverview();
setView("overview");
}
// (started at the bottom of this file — see "start")
/* ---------------- indexing ---------------- */
function indexData() {
for (const n of S.data.nodes) {
S.nodesById.set(n.id, n);
if ((n.kind === "function" || n.kind === "method") && n.file) {
if (!S.fileFns.has(n.file)) S.fileFns.set(n.file, []);
S.fileFns.get(n.file).push(n.id);
}
if (n.kind === "file" && n.obfuscation && n.obfuscation.length) {
const byLine = new Map();
for (const f of n.obfuscation) {
if (!byLine.has(f.line)) byLine.set(f.line, []);
byLine.get(f.line).push(f);
}
S.obfByFile.set(n.id, byLine);
}
}
for (const e of S.data.edges) {
if (!S.nodesById.has(e.source) || !S.nodesById.has(e.target)) continue;
if (!S.outEdges.has(e.source)) S.outEdges.set(e.source, []);
if (!S.inEdges.has(e.target)) S.inEdges.set(e.target, []);
S.outEdges.get(e.source).push(e);
S.inEdges.get(e.target).push(e);
}
}
const edgeKey = (e) => e.source + "→" + e.target + "·" + e.kind;
function nodeLayer(n) {
return n.kind === "table" ? "database" : (n.layer || "unknown");
}
function passesFilter(n) {
return S.filter === "all" || nodeLayer(n) === S.filter;
}
/* ---------------- header / legend / warnings ---------------- */
/* ---------------- language breakdown ----------------
Lines of code per language: one stacked bar + a legend. The bar wipes in
once, legend percentages count up; hover links a segment to its entry. */
const LANG_NAME = {
javascript: "JavaScript", typescript: "TypeScript", python: "Python", php: "PHP",
csharp: "C#", cpp: "C++", go: "Go", java: "Java", ruby: "Ruby", sql: "SQL", vue: "Vue",
html: "HTML", css: "CSS", scss: "SCSS", markdown: "Markdown", config: "Config",
kotlin: "Kotlin", swift: "Swift", rust: "Rust", dart: "Dart", shell: "Shell", unknown: "Other",
};
const LANG_SLOTS = 7; // ponytail: top 7 get their own color; the rest fold into "Other"
function renderLanguages() {
const by = new Map();
for (const n of S.data.nodes) {
if (n.kind !== "file") continue;
const k = n.language || "unknown";
const v = by.get(k) || { lines: 0, files: 0 };
v.lines += n.loc || 0; v.files += 1;
by.set(k, v);
}
let langs = [...by].map(([k, v]) => ({ k, ...v })).filter(l => l.lines > 0)
.sort((a, b) => b.lines - a.lines);
const total = langs.reduce((s, l) => s + l.lines, 0);
if (!total) return;
// undetected files and the long tail share one "Other" bucket, always last
let known = langs.filter(l => l.k !== "unknown"), rest = langs.filter(l => l.k === "unknown");
if (known.length > LANG_SLOTS) { rest = [...known.slice(LANG_SLOTS), ...rest]; known = known.slice(0, LANG_SLOTS); }
langs = rest.length ? [...known, { k: "other", lines: rest.reduce((s, l) => s + l.lines, 0),
files: rest.reduce((s, l) => s + l.files, 0),
names: rest.map(l => l.k === "unknown" ? "undetected" : (LANG_NAME[l.k] || l.k)) }] : known;
const fmt = (n) => n.toLocaleString();
const name = (l) => l.k === "other" ? "Other" : (LANG_NAME[l.k] || l.k.charAt(0).toUpperCase() + l.k.slice(1));
const color = (l, i) => l.k === "other" || l.k === "unknown" ? "var(--l-other)" : `var(--l${i + 1})`;
const pct = (l) => l.lines / total * 100;
const files = langs.reduce((s, l) => s + l.files, 0);
$("lang-total").textContent = `${fmt(total)} lines · ${fmt(files)} files`;
$("lang-bar").setAttribute("aria-label", langs.map(l => `${name(l)} ${pct(l).toFixed(1)}%`).join(", "));
$("lang-bar").innerHTML = langs.map((l, i) =>
`<span data-i="${i}" style="flex-grow:${l.lines};background:${color(l, i)}" ` +
`title="${esc(name(l))} · ${pct(l).toFixed(1)}%"></span>`).join("");
$("lang-list").innerHTML = langs.map((l, i) =>
`<li data-i="${i}" style="--i:${i}"${l.names ? ` title="${esc(l.names.join(", "))}"` : ""}>` +
`<span class="lg-dot" style="background:${color(l, i)}"></span>` +
`<span class="lang-name">${esc(name(l))}</span>` +
`<b data-pct="${pct(l).toFixed(1)}">${pct(l).toFixed(1)}%</b>` +
`<small>${fmt(l.lines)} lines · ${fmt(l.files)} file${l.files === 1 ? "" : "s"}</small></li>`).join("");
$("langs").classList.remove("hidden");
// percentages count up alongside the bar wipe (skipped for reduced motion)
if (!matchMedia("(prefers-reduced-motion: reduce)").matches) {
const els = [...$("lang-list").querySelectorAll("b[data-pct]")];
const t0 = performance.now() + 250, dur = 1100;
const tick = (now) => {
const t = Math.min(1, Math.max(0, (now - t0) / dur)), e = 1 - Math.pow(1 - t, 3);
els.forEach(b => { b.textContent = (b.dataset.pct * e).toFixed(1) + "%"; });
if (t < 1) requestAnimationFrame(tick);
};
requestAnimationFrame(tick);
}
// hovering either side highlights the same language in both
const box = $("langs");
const focus = (i) => {
box.classList.toggle("focus", i != null);
box.querySelectorAll("[data-i]").forEach(el => el.classList.toggle("on", el.dataset.i === i));
};
box.addEventListener("mouseover", (ev) => focus(ev.target.closest("[data-i]")?.dataset.i ?? null));
box.addEventListener("mouseleave", () => focus(null));
}
function renderHeader() {
const name = S.data.meta?.name || "";
$("project-name").textContent = name;
$("ov-title").textContent = name || "Your codebase";
document.title = "CodeBread — " + (name || "codebase map");
const st = S.data.stats || {};
const stat = (label, v) => `<div class="stat"><b>${v ?? 0}</b><span>${label}</span></div>`;
let html = stat("files", st.files) + stat("functions", st.functions) +
stat("tables", st.tables) + stat("connections", st.connections);
$("stats").innerHTML = html;
if (st.warnings) {
const b = document.createElement("button");
b.className = "stat warn-btn";
b.innerHTML = `<b>${st.warnings}</b><span>warnings — view</span>`;
b.onclick = toggleWarnings;
$("stats").appendChild(b);
}
if (st.orphans || st.cycles) {
const bits = [];
if (st.orphans) bits.push(`${st.orphans} orphan${st.orphans === 1 ? "" : "s"}`);
if (st.cycles) bits.push(`${st.cycles} cycle${st.cycles === 1 ? "" : "s"}`);
const b = document.createElement("button");
b.className = "stat warn-btn insight-btn";
b.innerHTML = `<b>${(st.orphans || 0) + (st.cycles || 0)}</b><span>${bits.join(" · ")} — view</span>`;
b.onclick = toggleInsights;
$("stats").appendChild(b);
}
}
function toggleInsights() {
const p = $("insights-panel");
if (!p.classList.contains("hidden")) { p.classList.add("hidden"); return; }
const st = S.data.stats || {};
$("ip-orphan-count").textContent = `(${st.orphans || 0})`;
$("ip-cycle-count").textContent = `(${st.cycles || 0})`;
const orphanList = $("ip-orphans-list");
orphanList.innerHTML = "";
const orphans = S.data.nodes.filter(n => n.orphan);
if (!orphans.length) orphanList.innerHTML = "<div class='wp-item'>None detected.</div>";
for (const n of orphans.slice(0, 300)) {
const d = document.createElement("div");
d.className = "wp-item ip-clickable";
d.innerHTML = `<div class="wp-path">${esc(n.file || "")}</div>` +
`<div class="wp-msg">${esc(n.label)}() — no detected callers</div>`;
d.onclick = () => { p.classList.add("hidden"); jumpTo(n.id); };
orphanList.appendChild(d);
}
const cycleList = $("ip-cycles-list");
cycleList.innerHTML = "";
const cycles = S.data.cycles || [];
if (!cycles.length) cycleList.innerHTML = "<div class='wp-item'>None detected.</div>";
for (const c of cycles.slice(0, 100)) {
const d = document.createElement("div");
d.className = "wp-item ip-clickable";
const chain = [...c.labels, c.labels[0]].map(esc).join(" → ");
d.innerHTML = `<div class="wp-msg">${chain}</div>`;
d.onclick = () => { p.classList.add("hidden"); jumpTo(c.nodes[0]); };
cycleList.appendChild(d);
}
p.classList.remove("hidden");
}
function toggleWarnings() {
const p = $("warnings-panel");
if (!p.classList.contains("hidden")) { p.classList.add("hidden"); return; }
const list = $("warnings-list");
list.innerHTML = "";
const all = [...(S.data.warnings || [])];
for (const n of S.data.nodes) {
if (n.kind === "file" && n.warnings)
for (const w of n.warnings) all.push({ path: n.file, message: w });
}
if (!all.length) list.innerHTML = "<div class='wp-item'>No warnings.</div>";
for (const w of all.slice(0, 400)) {
const d = document.createElement("div");
d.className = "wp-item";
d.innerHTML = `<div class="wp-path">${esc(w.path)}</div>` +
`<div class="wp-msg">${esc(w.message)}</div>`;
list.appendChild(d);
}
p.classList.remove("hidden");
}
function renderLegend() {
const layers = Object.entries(LAYER_LABEL).map(([k, label]) =>
`<div class="lg-row"><span class="lg-dot" style="background:${LAYER_COLOR[k]}"></span>${label}</div>`);
const lines = [["call", "calls a function"], ["api", "API request"], ["db", "reads / writes a table"],
["include", "imports a file"], ["link", "links to a page"]].map(([k, label]) =>
`<div class="lg-row"><svg class="lg-line" viewBox="0 0 24 6"><line class="edge k-${k}" x1="0" y1="3" x2="24" y2="3"/></svg>${label}</div>`);
$("legend").innerHTML =
`<div class="lg-col"><div class="lg-h">Color = layer</div>${layers.join("")}</div>` +
`<div class="lg-col"><div class="lg-h">Line = relationship</div>${lines.join("")}</div>`;
}
/* ---------------- sidebar tree ---------------- */
function renderTree() {
const root = S.data.tree;
const el = buildTreeNode(root, 0);
el.classList.add("open");
$("tree").innerHTML = "";
$("tree").appendChild(el);
}
function buildTreeNode(node, depth) {
const isDir = node.type === "dir";
const wrap = document.createElement("div");
wrap.className = "tnode " + (isDir ? "dir" : "file");
const row = document.createElement("div");
row.className = "trow";
row.dataset.path = node.path || "";
const caret = document.createElement("span");
caret.className = "tcaret";
caret.textContent = isDir ? "▶" : "";
row.appendChild(caret);
const dot = document.createElement("span");
dot.className = "tdot";
dot.style.background = LAYER_COLOR[node.layer] || "var(--line2)";
row.appendChild(dot);
const name = document.createElement("span");
name.className = "tname";
name.textContent = node.name;
row.appendChild(name);
if (node.warning) {
const w = document.createElement("span");
w.className = "twarn";
w.title = "This entry has a warning — see Warnings on the Overview.";
w.textContent = "⚠";
row.appendChild(w);
}
if (node.obfuscated) {
const o = document.createElement("span");
o.className = "tobf";
o.title = "Obfuscated code detected — decoded inline in the code viewer.";
const icon = document.createElementNS(SVGNS, "svg");
icon.setAttribute("viewBox", "0 0 24 24");
icon.setAttribute("width", "12");
icon.setAttribute("height", "12");
const use = document.createElementNS(SVGNS, "use");
use.setAttribute("href", "#icon-unlock");
icon.appendChild(use);
o.appendChild(icon);
row.appendChild(o);
}
if (!isDir && node.nFunctions) {
const c = document.createElement("span");
c.className = "tcount";
c.textContent = node.nFunctions;
row.appendChild(c);
}
wrap.appendChild(row);
if (isDir) {
const kids = document.createElement("div");
kids.className = "tchildren";
for (const ch of node.children || []) kids.appendChild(buildTreeNode(ch, depth + 1));
wrap.appendChild(kids);
row.onclick = () => wrap.classList.toggle("open");
if (depth < 1) wrap.classList.add("open");
} else {
row.onclick = () => {
document.querySelectorAll(".trow.selected").forEach(x => x.classList.remove("selected"));
row.classList.add("selected");
if (!S.nodesById.has(node.path)) return;
if (S.view === "ide" && S.nodesById.get(node.path)?.source) {
openIde(node.path); // IDE mode: open the file like an editor
} else if (S.focusMode) {
spotlightFile(node.path); // focus mode: show just this file
} else {
jumpTo(node.path); // overview mode: add to what's shown
}
};
}
return wrap;
}
/* ---------------- initial visibility & layout ---------------- */
function initialVisible() {
const files = S.data.nodes.filter(n => n.kind === "file");
const tables = S.data.nodes.filter(n => n.kind === "table");
// dense codebases: start with files that actually contain code
const interesting = files.filter(f =>
(f.nFunctions || 0) > 0 || S.outEdges.has(f.id) || S.inEdges.has(f.id) ||
(f.dbConfig || []).length);
const show = (interesting.length ? interesting : files).slice(0, 400);
for (const f of show) S.visible.add(f.id);
for (const t of tables) S.visible.add(t.id);
}
const BAND = { frontend: 0.16, unknown: 0.38, backend: 0.55, config: 0.5, database: 0.84 };
function layoutInitial() {
const W = 1600, H = 1100;
let i = 0;
for (const id of S.visible) {
const n = S.nodesById.get(id);
const bx = BAND[nodeLayer(n)] ?? 0.5;
const by = nodeLayer(n) === "config" ? 0.88 : 0.18 + 0.64 * hash01(id);
S.pos.set(id, {
x: bx * W + (hash01(id + "x") - 0.5) * 260,
y: by * H + (hash01(id + "y") - 0.5) * 120,
vx: 0, vy: 0,
});
i++;
}
}
function hash01(s) {
let h = 2166136261;
for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }
return ((h >>> 0) % 10000) / 10000;
}
function ensurePos(id, nearId) {
if (S.pos.has(id)) return;
const near = nearId && S.pos.get(nearId);
const n = S.nodesById.get(id);
const bx = BAND[nodeLayer(n)] ?? 0.5;
const base = near || { x: bx * 1600, y: 550 };
const a = hash01(id) * Math.PI * 2;
S.pos.set(id, {
x: base.x + Math.cos(a) * (60 + hash01(id + "r") * 70),
y: base.y + Math.sin(a) * (60 + hash01(id + "r") * 70),
vx: 0, vy: 0,
});
}
/* ---------------- visible edge computation ---------------- */
function visibleEdges() {
const out = [];
for (const e of S.data.edges) {
if (S.visible.has(e.source) && S.visible.has(e.target)) {
const sn = S.nodesById.get(e.source), tn = S.nodesById.get(e.target);
if (passesFilter(sn) && passesFilter(tn)) out.push(e);
}
}
// synthetic containment edges: file -> its expanded functions
for (const fid of S.expanded) {
if (!S.visible.has(fid)) continue;
const fnode = S.nodesById.get(fid);
if (!passesFilter(fnode)) continue;
for (const fnId of S.fileFns.get(fid) || []) {
if (S.visible.has(fnId) && passesFilter(S.nodesById.get(fnId)))
out.push({ source: fid, target: fnId, kind: "contains", label: "" });
}
}
return out;
}
/* ---------------- DOM (re)build ---------------- */
/* Incremental: only the nodes/edges that actually entered or left the
visible set touch the DOM. A full teardown+rebuild here would mean every
single click in a large, densely-linked graph re-creates *everything*
already on screen (elements + listeners) just to add one more node —
that's the "too many links = lag" complaint this replaced. */
function rebuild() {
const newEdges = visibleEdges();
const newEdgeKeys = new Set(newEdges.map(edgeKey));
for (const { key } of S.drawnEdges) {
if (newEdgeKeys.has(key)) continue;
const els = S.elEdges.get(key);
if (!els) continue;
els.vis.remove(); els.hit.remove();
S.elEdges.delete(key);
}
// Batch every newly-created element into a fragment and append it once —
// appendChild() one at a time on a live, rendered SVG can force a
// reflow *per call*; a big reveal (hundreds of new nodes/edges at once)
// turns that into a single multi-hundred-millisecond blocking frame.
const edgeFrag = document.createDocumentFragment();
const drawnEdges = [];
for (const e of newEdges) {
const key = edgeKey(e);
let els = S.elEdges.get(key);
if (!els) {
const vis = document.createElementNS(SVGNS, "path");
vis.setAttribute("class", "edge k-" + e.kind + (e.cycle ? " cycle" : ""));
const hit = document.createElementNS(SVGNS, "path");
hit.setAttribute("class", "edge-hit");
hit.__edge = e; // delegated handlers on edgesG read this back — see bindGraphDelegatedEvents()
edgeFrag.appendChild(vis); edgeFrag.appendChild(hit);
els = { vis, hit };
S.elEdges.set(key, els);
}
drawnEdges.push({ edge: e, key });
}
edgesG.appendChild(edgeFrag);
S.drawnEdges = drawnEdges;
updateEdgeAnimationMode();
for (const [id, g] of S.elNodes) {
const n = S.nodesById.get(id);
if (S.visible.has(id) && n && passesFilter(n)) continue;
g.remove();
S.elNodes.delete(id);
}
const nodeFrag = document.createDocumentFragment();
let enterIdx = 0;
for (const id of S.visible) {
const n = S.nodesById.get(id);
if (!n || !passesFilter(n) || S.elNodes.has(id)) continue;
ensurePos(id);
const g = makeNodeEl(n);
g.style.setProperty("--i", Math.min(enterIdx++, 24)); // stagger cap: big reveals don't drag on
nodeFrag.appendChild(g);
S.elNodes.set(id, g);
}
nodesG.appendChild(nodeFrag);
applyHighlight();
updatePositions();
renderMinimap();
updateEmptyState();
}
/* Same dashed line design either way — above this many edges on screen,
the per-edge "flowing" CSS animation (continuous repaint, forever, on
every one of them) gets frozen to a static dashed line instead. Below
the threshold it flows normally. Recomputed on every rebuild() so it
tracks what's actually revealed, in either direction. */
const DENSE_EDGE_THRESHOLD = 120;
function updateEdgeAnimationMode() {
svg.classList.toggle("static-edges", S.drawnEdges.length > DENSE_EDGE_THRESHOLD);
}
function updateEmptyState() {
const empty = $("empty-state");
if (S.elNodes.size > 0) { empty.classList.add("hidden"); return; }
const totalFiles = S.data.nodes.filter(n => n.kind === "file").length;
if (totalFiles === 0) {
$("empty-title").textContent = "Nothing to show";
$("empty-msg").textContent = "CodeBread didn't find any scannable files in this folder.";
} else if (S.visible.size === 0) {
$("empty-title").textContent = "Pick a file to begin";
$("empty-msg").textContent = "Pick a file in the list on the left to see its " +
"functions and how it connects to the rest of the codebase.";
} else {
$("empty-title").textContent = "Nothing to show";
$("empty-msg").textContent = "No nodes match the current layer filter — try “All”.";
}
empty.classList.remove("hidden");
}
function nodeSize(n) {
const label = n.label || "?";
if (n.kind === "file") {
return { w: Math.max(74, label.length * 7.4 + 34), h: 30, r: 9 };
}
if (n.kind === "table") {
return { w: Math.max(66, label.length * 7.2 + 30), h: 30, r: 15 };
}
return { w: Math.max(56, label.length * 6.6 + 26), h: 22, r: 11 };
}
function makeNodeEl(n) {
const g = document.createElementNS(SVGNS, "g");
g.setAttribute("class", "node k-" + n.kind);
g.dataset.id = n.id;
const { w, h, r } = nodeSize(n);
const color = LAYER_COLOR[nodeLayer(n)];
const rect = document.createElementNS(SVGNS, "rect");
rect.setAttribute("class", "shape");
rect.setAttribute("x", -w / 2); rect.setAttribute("y", -h / 2);
rect.setAttribute("width", w); rect.setAttribute("height", h);
rect.setAttribute("rx", r);
rect.style.stroke = color;
g.appendChild(rect);
const dot = document.createElementNS(SVGNS, "circle");
dot.setAttribute("class", "ldot");
dot.setAttribute("cx", -w / 2 + 12); dot.setAttribute("cy", 0);
dot.setAttribute("r", n.kind === "file" ? 4 : 3);
dot.style.fill = color;
g.appendChild(dot);
const label = document.createElementNS(SVGNS, "text");
label.setAttribute("x", -w / 2 + 21);
label.setAttribute("font-size", n.kind === "file" ? "11.5" : "10.5");
label.textContent = n.label;
g.appendChild(label);
if (n.kind === "file" && n.nFunctions) {
const c = document.createElementNS(SVGNS, "text");
c.setAttribute("class", "badge");
c.setAttribute("x", w / 2 - 8); c.setAttribute("text-anchor", "end");
c.setAttribute("y", 0.5);
c.textContent = n.nFunctions;
g.appendChild(c);
}
if (n.routes && n.routes.length) {
const rb = document.createElementNS(SVGNS, "text");
rb.setAttribute("class", "routeb");
rb.setAttribute("x", -w / 2 + 2); rb.setAttribute("y", -h / 2 - 6);
rb.textContent = n.routes[0].method + " " + n.routes[0].path;
g.appendChild(rb);
}
if (n.kind === "file" && n.warnings && n.warnings.length) {
const wb = document.createElementNS(SVGNS, "text");
wb.setAttribute("class", "warnb");
wb.setAttribute("x", w / 2 - 2); wb.setAttribute("y", -h / 2 - 5);
wb.setAttribute("text-anchor", "end");
wb.textContent = "⚠";
g.appendChild(wb);
}
if (n.kind === "file" && n.obfuscation && n.obfuscation.length) {
const ob = document.createElementNS(SVGNS, "use");
ob.setAttribute("class", "obfb");
ob.setAttribute("href", "#icon-unlock");
const hasWarn = n.warnings && n.warnings.length;
const isz = 10.5;
ob.setAttribute("x", w / 2 - (hasWarn ? 18 : 2) - isz);
ob.setAttribute("y", -h / 2 - 5 - isz + 1.5);
ob.setAttribute("width", isz);
ob.setAttribute("height", isz);
g.appendChild(ob);
}
if ((n.kind === "function" || n.kind === "method") && n.cycle) {
const cb = document.createElementNS(SVGNS, "text");
cb.setAttribute("class", "cycleb");
cb.setAttribute("x", w / 2 - 2); cb.setAttribute("y", -h / 2 - 5);
cb.setAttribute("text-anchor", "end");
cb.textContent = "↻";
g.appendChild(cb);
}
// No per-node listeners here on purpose — a graph with hundreds of
// nodes would mean hundreds of addEventListener calls (x6 each) as
// part of the same synchronous burst that creates the elements. All
// interaction is handled by fixed, one-time delegated listeners on
// nodesG/edgesG/svg — see bindGraphDelegatedEvents().
return g;
}
/* ---------------- interaction: reveal / select ---------------- */
function onNodeClick(id) {
if (S.drag && S.drag.moved) return;
const n = S.nodesById.get(id);
if (n.kind === "file") expandFile(id);
else revealNeighbors(id);
select(id);
}
function expandFile(fileId) {
const fns = S.fileFns.get(fileId) || [];
const wasExpanded = S.expanded.has(fileId);
if (!wasExpanded && fns.length) {
S.expanded.add(fileId);
for (const fnId of fns) { S.visible.add(fnId); ensurePos(fnId, fileId); }
}
revealNeighbors(fileId);
rebuild(); reheat();
if (S.mode === "orbit" && !wasExpanded && fns.length) {
// orbit rings can be large — reframe once the ring has been laid out
// (deterministic, so one simulation frame is enough to know its size)
requestAnimationFrame(() => requestAnimationFrame(() => fitView(0.82)));
}
}
function collapseFile(fileId) {
const n = S.nodesById.get(fileId);
if (!n || n.kind !== "file" || !S.expanded.has(fileId)) return;
S.expanded.delete(fileId);
for (const fnId of S.fileFns.get(fileId) || []) S.visible.delete(fnId);
if (S.selected && !S.visible.has(S.selected)) select(null);
rebuild(); reheat();
}
/* ---------------- spotlight: pick one file, see just its world --------- */
/* Clears the canvas down to a single file — its functions plus everything
one hop away — so picking a file from the Explorer answers "does this
thing connect to anything else, or not" without other clutter. */
function spotlightFile(fid) {
const n = S.nodesById.get(fid);
if (!n) return;
S.visible = new Set();
S.expanded = new Set();
S.visible.add(fid); ensurePos(fid);
const fns = S.fileFns.get(fid) || [];
for (const fnId of fns) { S.visible.add(fnId); ensurePos(fnId, fid); }
if (fns.length) S.expanded.add(fid);
const revealFor = (id) => {
for (const e of S.outEdges.get(id) || [])
if (!S.visible.has(e.target)) { S.visible.add(e.target); ensurePos(e.target, id); }
for (const e of S.inEdges.get(id) || [])
if (!S.visible.has(e.source)) { S.visible.add(e.source); ensurePos(e.source, id); }
};
revealFor(fid);
for (const fnId of fns) revealFor(fnId);
if (!passesFilter(n)) setFilter("all");
rebuild(); reheat();
select(fid);
fitView(0.82);
}
/* ---------------- focus mode toggle ------------------------------------ */
/* Off (default): the full "interesting files" overview, click-to-explore
cumulatively. On: canvas clears and picking a file in the Explorer
spotlights just that file instead of adding to what's already shown. */
function toggleFocusMode() {
S.focusMode = !S.focusMode;
$("focus-toggle").classList.toggle("active", S.focusMode);
if (S.focusMode) {
S.visible = new Set(); S.expanded = new Set();
select(null);
rebuild(); reheat();
} else {
S.visible = new Set(); S.expanded = new Set();
initialVisible(); layoutInitial();
select(null);
rebuild(); reheat();
fitView(0.82);
}
}
function revealNeighbors(id) {
let added = false;
for (const e of S.outEdges.get(id) || []) {
if (!S.visible.has(e.target)) { S.visible.add(e.target); ensurePos(e.target, id); added = true; }
}
for (const e of S.inEdges.get(id) || []) {
if (!S.visible.has(e.source)) { S.visible.add(e.source); ensurePos(e.source, id); added = true; }
}
if (added) { rebuild(); reheat(); }
}
function select(id, opts) {
opts = opts || {};
S.selected = id;
computeChain();
applyHighlight();
renderDetail();
if (!opts.fromNav) computeNavList(id);
if (!opts.fromHistory) pushHistory(id);
renderBreadcrumb();
}
/* ---------------- navigation: neighbor cycling + history --------------- */
function computeNavList(id) {
if (id == null) { S.navList = []; S.navIdx = -1; return; }
const outs = (S.outEdges.get(id) || []).filter(e => e.kind !== "contains").map(e => e.target);
const ins = (S.inEdges.get(id) || []).filter(e => e.kind !== "contains").map(e => e.source);
const seen = new Set([id]);
S.navList = [...outs, ...ins].filter(nid => {
if (seen.has(nid)) return false;
seen.add(nid); return true;
});
S.navIdx = -1;
}
function pushHistory(id) {
if (id == null) return;
if (S.crumbs[S.crumbIdx] === id) return;
S.crumbs = S.crumbs.slice(0, S.crumbIdx + 1);
S.crumbs.push(id);
if (S.crumbs.length > 40) S.crumbs.shift();
S.crumbIdx = S.crumbs.length - 1;
}
function historyBack() {
if (S.crumbIdx <= 0) return;
S.crumbIdx--;
jumpTo(S.crumbs[S.crumbIdx], { fromHistory: true });
}
function historyForward() {
if (S.crumbIdx >= S.crumbs.length - 1) return;
S.crumbIdx++;
jumpTo(S.crumbs[S.crumbIdx], { fromHistory: true });
}
function navStep(dir) {
if (!S.navList.length) return;
S.navIdx = ((S.navIdx + dir) % S.navList.length + S.navList.length) % S.navList.length;
jumpTo(S.navList[S.navIdx], { fromNav: true });
}
/* shows WHERE the current selection lives — folder / file / function —
not a history of past clicks (arrow-key history still works via
historyBack/historyForward, it's just not what's drawn here) */
function renderBreadcrumb() {
const el = $("breadcrumb");
const n = S.selected && S.nodesById.get(S.selected);
if (!n) { el.classList.add("hidden"); el.innerHTML = ""; return; }
const segs = [];
if (n.kind === "table") {
segs.push({ label: "Database", id: null });
segs.push({ label: n.label, id: n.id });
} else {
const parts = (n.file || "").split("/").filter(Boolean);
parts.forEach((part, i) => {
const isFileSeg = i === parts.length - 1;
segs.push({ label: part, id: isFileSeg ? n.file : null });
});
if (n.kind === "function" || n.kind === "method") {
segs.push({ label: n.label + "()", id: n.id });
}
}
el.innerHTML = segs.map((s, i) => {
const isLast = i === segs.length - 1;
const cls = "bc-item" + (isLast ? " current" : "") + (s.id ? "" : " bc-dir");
return `<span class="${cls}"${s.id ? ` data-id="${esc(s.id)}"` : ""}>${esc(s.label)}</span>`;
}).join('<span class="bc-sep">›</span>');
el.classList.remove("hidden");
el.querySelectorAll(".bc-item[data-id]").forEach(elm => elm.addEventListener("click", () => {
jumpTo(elm.dataset.id, { fromHistory: true });
}));
}
/* full call chain: everything reachable upstream + downstream */
function computeChain() {
S.litNodes.clear(); S.litEdges.clear();
if (!S.selected) return;
S.litNodes.add(S.selected);
const walk = (start, dir) => {
const stack = [start], seen = new Set([start]);
while (stack.length) {
const cur = stack.pop();
const edges = (dir === "out" ? S.outEdges : S.inEdges).get(cur) || [];
for (const e of edges) {
if (e.kind === "contains") continue;
const next = dir === "out" ? e.target : e.source;
if (!S.visible.has(next)) continue;
S.litEdges.add(edgeKey(e));
if (!seen.has(next)) {
seen.add(next); S.litNodes.add(next); stack.push(next);
}
}
}
};
walk(S.selected, "out");
walk(S.selected, "in");
}
function applyHighlight() {
const hasSel = !!S.selected;
for (const [id, el] of S.elNodes) {
el.classList.toggle("selected", id === S.selected);
el.classList.toggle("lit", hasSel && S.litNodes.has(id));
el.classList.toggle("dim", hasSel && !S.litNodes.has(id));
}
for (const { edge, key } of S.drawnEdges) {
const els = S.elEdges.get(key);
const lit = hasSel && (S.litEdges.has(key) ||
(edge.kind === "contains" && S.litNodes.has(edge.target)));
els.vis.classList.toggle("lit", lit);
els.vis.classList.toggle("dim", hasSel && !lit);
els.hit.classList.toggle("dim", hasSel && !lit);
}
}
/* ---------------- detail panel ---------------- */
function renderDetail() {
const panel = $("detail"), body = $("detail-body");
if (!S.selected) { panel.classList.add("hidden"); return; }
const n = S.nodesById.get(S.selected);
const color = LAYER_COLOR[nodeLayer(n)];
let html = `<span class="d-kind" style="color:${color};border-color:color-mix(in srgb, ${color} 40%, transparent)">` +
`${esc(n.kind)} · ${esc(LAYER_LABEL[nodeLayer(n)])}</span>`;
html += `<div class="d-name">${esc(n.label)}${n.kind === "function" || n.kind === "method" ? "()" : ""}</div>`;
const subBits = [];
if (n.kind === "function" || n.kind === "method") {
subBits.push(`Function ${n.index}`);
if (n.parentClass) subBits.push("in class " + n.parentClass);
}
if (n.file) subBits.push(`<span class="d-file" data-file="${esc(n.file)}">${esc(n.file)}</span>` +
(n.line ? `:${n.line}` : ""));
if (n.kind === "file") subBits.push(`${n.language} · ${n.loc} lines`);
html += `<div class="d-sub">${subBits.join(" · ")}</div>`;
if (n.description) html += `<div class="d-desc">${esc(n.description)}</div>`;
if (n.orphan) html += `<div class="d-warn">⚠ Orphaned — no detected callers.</div>`;
if (n.cycle) html += `<div class="d-warn d-cycle">↻ Part of a circular call chain.</div>`;
if (n.params && n.params.length)
html += section("Parameters", n.params.map(p => `<span class="d-chip">${esc(p)}</span>`).join(""));
if (n.returns) html += section("Returns", `<span class="d-chip">${esc(n.returns)}</span>`);
if (n.routes && n.routes.length)
html += section("Handles routes", n.routes.map(r =>
`<div class="d-route">⇢ ${esc(r.method)} ${esc(r.path)}</div>`).join(""));
{
const srcFileId = n.kind === "file" ? n.id : n.file;
const srcFile = srcFileId && S.nodesById.get(srcFileId);
let src = "";
if (n.code) {
const lineInfo = n.line ? ` (lines ${n.line}–${n.endLine || n.line})` : "";
src += `<button class="d-code-toggle" data-lines="${esc(lineInfo)}">▸ View code${esc(lineInfo)}</button>` +
`<pre class="d-code hidden"><code>${highlightCode(n.code, n.line || 1, S.obfByFile.get(n.file))}</code></pre>`;
}
if (srcFile && srcFile.source) {
src += `<button class="d-code-toggle d-ide-open" data-idefile="${esc(srcFileId)}"` +
` data-idefocus="${n.kind === "file" ? "" : esc(n.id)}"` +
` style="margin-top:6px">Open in Code view →</button>`;
}
if (src) html += section("Source", src);
}
if (n.kind === "table") {
if (n.model) html += section("ORM model", `<span class="d-chip">${esc(n.model)}</span>`);
if (n.fields && n.fields.length)
html += section("Fields / columns", `<div class="d-fields">${n.fields.map(esc).join("<br>")}</div>`);
}
if (n.dbConfig && n.dbConfig.length)
html += section("DB config (masked)", `<div class="d-fields">${n.dbConfig.map(esc).join("<br>")}</div>`);
const outs = (S.outEdges.get(n.id) || []);
const ins = (S.inEdges.get(n.id) || []);
if (outs.length) html += section(`Calls into (${outs.length})`,
outs.slice(0, 40).map(e => linkRow(e.target, e)).join(""));
if (ins.length) html += section(`Called from (${ins.length})`,
ins.slice(0, 40).map(e => linkRow(e.source, e)).join(""));
if (!outs.length && !ins.length) {
const msg = n.kind === "file"
? "No detected connections — this file doesn't appear to link to anything else in the scan."
: "No detected connections — possibly unused (orphaned).";
html += section("Connections", `<div class="d-empty">${msg}</div>`);
}
if (n.kind === "file" && n.nFunctions)
html += section(`Functions (${n.nFunctions})`,
(S.fileFns.get(n.id) || []).map(fid => {
const f = S.nodesById.get(fid);
return `<div class="d-link" data-jump="${esc(fid)}">` +
`<span class="dl-kind">${f.index}.</span>` +
`<span class="dl-label">${esc(f.label)}()</span></div>`;
}).join(""));
if (n.warnings && n.warnings.length)
html += section("Warnings", n.warnings.map(w => `<div class="d-warn">⚠ ${esc(w)}</div>`).join(""));
body.innerHTML = html;
body.querySelectorAll("[data-jump]").forEach(el =>
el.addEventListener("click", () => jumpTo(el.dataset.jump)));
body.querySelectorAll(".d-file").forEach(el =>
el.addEventListener("click", () => jumpTo(el.dataset.file)));
body.querySelectorAll(".d-code-toggle:not(.d-ide-open)").forEach(el =>
el.addEventListener("click", () => {
const pre = el.nextElementSibling;
const hidden = pre.classList.toggle("hidden");
el.textContent = (hidden ? "▸ View code" : "▾ Hide code") + el.dataset.lines;
}));
body.querySelectorAll(".d-ide-open").forEach(el =>
el.addEventListener("click", () =>
openIde(el.dataset.idefile, el.dataset.idefocus || null)));
if (S.view !== "ide") panel.classList.remove("hidden");
}
function section(title, inner) {
return `<div class="d-section"><h4>${esc(title)}</h4>${inner}</div>`;
}
function linkRow(id, e) {
const t = S.nodesById.get(id);
if (!t) return "";
const kindTag = { call: "call", api: "API", db: "DB", include: "incl",
link: "page", contains: "" }[e.kind] || e.kind;
return `<div class="d-link" data-jump="${esc(id)}" title="${esc(e.label || "")}">` +
`<span class="dl-kind">${kindTag}</span>` +
`<span class="dl-label">${esc(t.label)}</span></div>`;
}
/* ---------------- jump / center ---------------- */
function jumpTo(id, opts) {
const n = S.nodesById.get(id);
if (!n) return;
if (S.view === "connect") { cxGo(rowIdOf(id)); return; } // stay in the explorer
if (S.view === "overview") setView("chart");
if (S.view === "ide") {
const fileId = n.kind === "file" ? n.id : n.file;
if (fileId && S.nodesById.get(fileId)?.source) {
openIde(fileId, n.kind === "file" ? null : id);
return;
}
setView("chart"); // no source to show (e.g. a table) — use the chart
}
if ((n.kind === "function" || n.kind === "method") && !S.visible.has(id)) {
if (n.file && S.nodesById.has(n.file)) {
S.visible.add(n.file); ensurePos(n.file);
S.expanded.add(n.file);
for (const fid of S.fileFns.get(n.file) || []) {
S.visible.add(fid); ensurePos(fid, n.file);
}
} else { S.visible.add(id); ensurePos(id); }
} else if (!S.visible.has(id)) {
S.visible.add(id); ensurePos(id);
}
if (!passesFilter(n)) setFilter("all");
rebuild(); reheat();
select(id, opts);
centerOn(id);
}