barad-dur 0.18.0

The all-seeing repository analyzer
Documentation
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

  /* ---- Import dependency graph tab ---- */
  function buildGraphTab() {
    var wrapper = el('div');
    wrapper.append(buildTabInfo(
      'Import Dependency Graph',
      'Each node is a file; an arrow from A to B means A imports B. Node size grows with total coupling (Ca + Ce); colour follows instability. Click a node to focus its neighbourhood; click the background to reset. Use "Group by directory" for a module-level view.',
      [
        { color: 'var(--c-good)',   label: 'Instability ≤ 0.3 (stable)' },
        { color: 'var(--c-warn)',   label: '≤ 0.7' },
        { color: 'var(--c-danger)', label: '> 0.7 (unstable)' },
        { color: '#ef4444',         label: 'Circular dependency (dashed edge)' }
      ]
    ));

    var allEdges = R.import_edges || [];
    if (allEdges.length === 0) {
      var none = el('div', { className: 'no-data' });
      none.append(txt('No import graph data available.'));
      wrapper.append(none);
      return wrapper;
    }

    var metricsByPath = {};
    (R.per_file_coupling || []).forEach(function(m) { metricsByPath[m.path] = m; });

    /* Cycle membership: path -> Set of cycle indices. An edge is cyclic
       when both endpoints share at least one cycle. */
    var cycles = R.import_cycles || [];
    var cyclesByPath = {};
    cycles.forEach(function(members, idx) {
      members.forEach(function(p) {
        (cyclesByPath[p] = cyclesByPath[p] || []).push(idx);
      });
    });
    function sharesCycle(a, b) {
      var ca = cyclesByPath[a], cb = cyclesByPath[b];
      if (!ca || !cb) return false;
      return ca.some(function(i) { return cb.indexOf(i) !== -1; });
    }

    /* Directory key: directory part of the path, truncated to two segments. */
    function dirKey(path) {
      var idx = path.lastIndexOf('/');
      if (idx === -1) return '(root)';
      var segs = path.slice(0, idx).split('/');
      return segs.slice(0, 2).join('/');
    }

    var BAND_COLORS = {
      good: 'var(--c-good)', warn: 'var(--c-warn)', danger: 'var(--c-danger)', none: '#3b82f6'
    };
    function instBand(i) {
      return i == null ? 'none' : i <= 0.3 ? 'good' : i <= 0.7 ? 'warn' : 'danger';
    }

    /* ---- Controls ---- */
    var state = { focus: null };

    var controls = el('div', { style: {
      margin: '8px 0', display: 'flex', gap: '14px', alignItems: 'center', flexWrap: 'wrap'
    }});
    var search = el('input', {
      type: 'search',
      placeholder: 'Filter files…',
      className: 'graph-search',
      style: {
        background: 'var(--bg-panel, #0f172a)', color: 'inherit',
        border: '1px solid #334155', borderRadius: '6px',
        padding: '5px 10px', fontSize: '13px', width: '220px'
      }
    });

    var degreeWrap = el('label', { style: { display: 'flex', gap: '6px', alignItems: 'center', fontSize: '12px', color: '#94a3b8' } });
    var degreeLabel = el('span');
    degreeLabel.append(txt('Min degree: 0'));
    var degreeSlider = el('input', { type: 'range', min: '0', max: '10', value: '0', style: { width: '110px' } });
    degreeWrap.append(degreeLabel, degreeSlider);

    var groupWrap = el('label', { style: { display: 'flex', gap: '6px', alignItems: 'center', fontSize: '12px', color: '#94a3b8', cursor: 'pointer' } });
    var groupToggle = el('input', { type: 'checkbox' });
    groupWrap.append(groupToggle, txt('Group by directory'));

    var exportBtn = el('button', { className: 'chip', style: { cursor: 'pointer' } });
    exportBtn.append(txt('Export SVG'));

    controls.append(search, degreeWrap, groupWrap, exportBtn);
    wrapper.append(controls);

    var capNotice = el('div', { style: { color: '#94a3b8', fontSize: '12px', margin: '4px 0' } });
    wrapper.append(capNotice);

    var W = 1100, H = 640;
    var graphBox = el('div', { className: 'graph-box', style: {
      border: '1px solid #1e293b', borderRadius: '8px', overflow: 'hidden', position: 'relative'
    }});
    wrapper.append(graphBox);

    /* Live render state, replaced wholesale by renderGraph(). Document-level
       listeners are registered once and read through this object. */
    var live = {
      svg: null, nodes: [], nodeMap: {}, nodeEls: [], edgeEls: [], drawEdges: [],
      viewX: 0, viewY: 0, viewScale: 1,
      isPanning: false, panSX: 0, panSY: 0, panVX: 0, panVY: 0, panMoved: 0,
      dragging: null, dragMoved: 0
    };
    var generation = 0;

    function nodeRadius(n) { return 4 + Math.sqrt(n.degree) * 2.5; }

    function updateViewBox() {
      if (!live.svg) return;
      live.svg.setAttribute('viewBox',
        live.viewX + ' ' + live.viewY + ' ' + (W / live.viewScale) + ' ' + (H / live.viewScale));
    }

    function neighbourSet(path) {
      var set = {};
      set[path] = true;
      live.drawEdges.forEach(function(e) {
        if (e.from === path) set[e.to] = true;
        if (e.to === path) set[e.from] = true;
      });
      return set;
    }

    function updateVisibility() {
      var q = search.value.toLowerCase();
      var hood = state.focus ? neighbourSet(state.focus) : null;
      live.nodeEls.forEach(function(ne) {
        var on = hood ? !!hood[ne.data.path]
          : q === '' || ne.data.path.toLowerCase().indexOf(q) !== -1;
        ne.el.setAttribute('opacity', on ? '1' : '0.1');
      });
      live.edgeEls.forEach(function(ee) {
        var on = hood ? (ee.data.from === state.focus || ee.data.to === state.focus)
          : q === '' ||
            ee.data.from.toLowerCase().indexOf(q) !== -1 ||
            ee.data.to.toLowerCase().indexOf(q) !== -1;
        /* element-level opacity also dims the arrowhead marker;
           stroke-opacity would leave it at full strength */
        ee.el.setAttribute('opacity', on ? '1' : '0.08');
      });
    }

    function buildModel() {
      var mode = groupToggle.checked ? 'dirs' : 'files';
      var minDegree = +degreeSlider.value;
      var notice = [];

      var nodeMap = {}, edges = [];
      if (mode === 'files') {
        allEdges.forEach(function(e) {
          nodeMap[e.from] = nodeMap[e.from] || { path: e.from, degree: 0 };
          nodeMap[e.to] = nodeMap[e.to] || { path: e.to, degree: 0 };
          nodeMap[e.from].degree++;
          nodeMap[e.to].degree++;
        });
        edges = allEdges.map(function(e) {
          return { from: e.from, to: e.to, weight: 1, cyclic: sharesCycle(e.from, e.to) };
        });

        var all = Object.keys(nodeMap).map(function(k) { return nodeMap[k]; });
        var MAX_NODES = 150;
        if (all.length > MAX_NODES) {
          var sorted = all.slice().sort(function(a, b) {
            return b.degree - a.degree || (a.path < b.path ? -1 : 1);
          });
          var kept = {};
          sorted.slice(0, MAX_NODES).forEach(function(n) { kept[n.path] = true; });
          notice.push('Showing the ' + MAX_NODES + ' most-connected files ('
            + (all.length - MAX_NODES) + ' hidden — use "Group by directory" for the full picture)');
          Object.keys(nodeMap).forEach(function(k) { if (!kept[k]) delete nodeMap[k]; });
          edges = edges.filter(function(e) { return kept[e.from] && kept[e.to]; });
        }
      } else {
        var dirEdges = {};
        var fileCounts = {};
        allEdges.forEach(function(e) {
          var a = dirKey(e.from), b = dirKey(e.to);
          (fileCounts[a] = fileCounts[a] || {})[e.from] = true;
          (fileCounts[b] = fileCounts[b] || {})[e.to] = true;
          if (a === b) return;
          var key = a + '' + b;
          dirEdges[key] = dirEdges[key] || { from: a, to: b, weight: 0, cyclic: false };
          dirEdges[key].weight++;
          dirEdges[key].cyclic = dirEdges[key].cyclic || sharesCycle(e.from, e.to);
        });
        Object.keys(dirEdges).forEach(function(k) {
          var e = dirEdges[k];
          nodeMap[e.from] = nodeMap[e.from] || { path: e.from, degree: 0 };
          nodeMap[e.to] = nodeMap[e.to] || { path: e.to, degree: 0 };
          nodeMap[e.from].degree++;
          nodeMap[e.to].degree++;
          edges.push(e);
        });
        Object.keys(nodeMap).forEach(function(k) {
          nodeMap[k].fileCount = Object.keys(fileCounts[k] || {}).length;
        });
      }

      if (minDegree > 0) {
        var before = Object.keys(nodeMap).length;
        Object.keys(nodeMap).forEach(function(k) {
          if (nodeMap[k].degree < minDegree) delete nodeMap[k];
        });
        edges = edges.filter(function(e) { return nodeMap[e.from] && nodeMap[e.to]; });
        var dropped = before - Object.keys(nodeMap).length;
        if (dropped > 0) notice.push(dropped + ' nodes below min degree ' + minDegree);
      }

      return {
        mode: mode,
        nodes: Object.keys(nodeMap).map(function(k) { return nodeMap[k]; }),
        nodeMap: nodeMap,
        edges: edges,
        notice: notice.join(' · ')
      };
    }

    function nodeColor(model, n) {
      if (model.mode === 'files') {
        var m = metricsByPath[n.path];
        return BAND_COLORS[instBand(m ? m.instability : null)];
      }
      /* directory: mean instability of member files that have metrics */
      var sum = 0, count = 0;
      (R.per_file_coupling || []).forEach(function(m) {
        if (dirKey(m.path) === n.path) { sum += m.instability; count++; }
      });
      return BAND_COLORS[instBand(count ? sum / count : null)];
    }

    function renderGraph() {
      generation++;
      var gen = generation;
      var model = buildModel();
      capNotice.replaceChildren();
      if (model.notice) capNotice.append(txt(model.notice));

      graphBox.replaceChildren();
      live.viewX = 0; live.viewY = 0; live.viewScale = 1;
      live.dragging = null; live.isPanning = false;

      var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, width: '100%', height: String(H) });
      var defs = svgEl('defs');
      function marker(id, color) {
        /* userSpaceOnUse keeps arrowheads a constant size — the default
           strokeWidth units blow them up on weighted directory edges */
        var m = svgEl('marker', {
          id: id, viewBox: '0 0 10 10', refX: '9', refY: '5',
          markerWidth: '8', markerHeight: '8',
          markerUnits: 'userSpaceOnUse', orient: 'auto-start-reverse'
        });
        m.append(svgEl('path', { d: 'M 0 0 L 10 5 L 0 10 z', fill: color }));
        return m;
      }
      defs.append(marker('arrow-dim', '#475569'), marker('arrow-cyc', '#ef4444'));
      var graphGroup = svgEl('g');
      svg.append(defs, graphGroup);
      graphBox.append(svg);

      var tip = el('div', { className: 'cp-tooltip', style: { position: 'absolute' } });
      graphBox.append(tip);

      var cx = W / 2, cy = H / 2;
      model.nodes.forEach(function(n, i) {
        var angle = (2 * Math.PI * i) / Math.max(model.nodes.length, 1);
        var radius = Math.min(W, H) * 0.4;
        n.x = cx + radius * Math.cos(angle);
        n.y = cy + radius * Math.sin(angle);
        n.vx = 0; n.vy = 0;
      });

      var maxWeight = model.edges.reduce(function(m, e) { return Math.max(m, e.weight); }, 1);
      var edgeEls = model.edges.map(function(e) {
        var attrs = {
          stroke: e.cyclic ? '#ef4444' : '#475569',
          'stroke-width': String(1 + (e.weight / maxWeight) * (model.mode === 'dirs' ? 5 : 0)),
          'stroke-opacity': e.cyclic ? '0.85' : '0.5',
          'marker-end': e.cyclic ? 'url(#arrow-cyc)' : 'url(#arrow-dim)'
        };
        if (e.cyclic) attrs['stroke-dasharray'] = '6,4';
        var line = svgEl('line', attrs);
        graphGroup.append(line);
        return { el: line, data: e };
      });

      var nodeEls = model.nodes.map(function(n) {
        var g = svgEl('g', { cursor: 'grab' });
        var circle = svgEl('circle', {
          r: String(nodeRadius(n)),
          fill: nodeColor(model, n),
          stroke: '#0f172a', 'stroke-width': '1.5'
        });
        var label = svgEl('text', {
          'text-anchor': 'middle', dy: String(nodeRadius(n) + 12),
          fill: '#94a3b8', 'font-size': '9'
        });
        label.append(txt(model.mode === 'dirs' ? n.path : fileParts(n.path).name));
        g.append(circle, label);
        graphGroup.append(g);
        return { el: g, circle: circle, data: n };
      });

      live.svg = svg;
      live.nodes = model.nodes;
      live.nodeMap = model.nodeMap;
      live.nodeEls = nodeEls;
      live.edgeEls = edgeEls;
      live.drawEdges = model.edges;

      /* Tooltip + focus + drag start */
      nodeEls.forEach(function(ne) {
        ne.el.addEventListener('mouseover', function() {
          tip.replaceChildren();
          var name = el('div', { style: { fontWeight: '600', marginBottom: '2px' } });
          name.append(txt(ne.data.path));
          tip.append(name);
          var detail = el('div', { style: { color: '#94a3b8' } });
          if (model.mode === 'dirs') {
            detail.append(txt(ne.data.fileCount + ' files · linked to ' + ne.data.degree + ' directories'));
          } else {
            var m = metricsByPath[ne.data.path];
            detail.append(txt(m
              ? 'Ca ' + m.ca + ' · Ce ' + m.ce + ' · instability ' + fmt(m.instability, 2)
              : 'Degree ' + ne.data.degree));
          }
          tip.append(detail);
          tip.style.display = 'block';
        });
        ne.el.addEventListener('mousemove', function(ev) {
          var rect = graphBox.getBoundingClientRect();
          var x = ev.clientX - rect.left + 14;
          var y = ev.clientY - rect.top - 10;
          if (x + tip.offsetWidth > rect.width - 8) x = ev.clientX - rect.left - tip.offsetWidth - 14;
          tip.style.left = x + 'px';
          tip.style.top = y + 'px';
        });
        ne.el.addEventListener('mouseout', function() { tip.style.display = 'none'; });
        ne.el.addEventListener('mousedown', function(ev) {
          live.dragging = ne.data;
          live.dragMoved = 0;
          ev.stopPropagation();
          ev.preventDefault();
        });
        ne.el.addEventListener('click', function(ev) {
          ev.stopPropagation();
          if (live.dragMoved > 4) return; // drag, not a click
          state.focus = state.focus === ne.data.path ? null : ne.data.path;
          updateVisibility();
          setHashState('graph', state.focus);
        });
      });

      /* Pan + background click resets focus */
      svg.addEventListener('mousedown', function(ev) {
        if (live.dragging) return;
        live.isPanning = true;
        live.panMoved = 0;
        live.panSX = ev.clientX; live.panSY = ev.clientY;
        live.panVX = live.viewX; live.panVY = live.viewY;
        ev.preventDefault();
      });
      svg.addEventListener('click', function() {
        if (live.panMoved > 4) return;
        if (state.focus !== null) {
          state.focus = null;
          updateVisibility();
          setHashState('graph', null);
        }
      });
      graphBox.addEventListener('wheel', function(ev) {
        ev.preventDefault();
        var rect = svg.getBoundingClientRect();
        var mx = ev.clientX - rect.left, my = ev.clientY - rect.top;
        var sx = live.viewX + (mx / rect.width) * (W / live.viewScale);
        var sy = live.viewY + (my / rect.height) * (H / live.viewScale);
        var factor = ev.deltaY < 0 ? 1.15 : 1 / 1.15;
        var ns = Math.max(0.2, Math.min(6, live.viewScale * factor));
        live.viewX = sx - (mx / rect.width) * (W / ns);
        live.viewY = sy - (my / rect.height) * (H / ns);
        live.viewScale = ns;
        updateViewBox();
      }, { passive: false });

      /* Force simulation */
      var REPULSION = 3000, SPRING_K = 0.004, SPRING_REST = 90, DAMPING = 0.85, CENTER_PULL = 0.012;
      var nodes = model.nodes, nodeMap = model.nodeMap;
      function simulate() {
        for (var i = 0; i < nodes.length; i++) {
          for (var j = i + 1; j < nodes.length; j++) {
            var dx = nodes[j].x - nodes[i].x, dy = nodes[j].y - nodes[i].y;
            var dist = Math.sqrt(dx * dx + dy * dy) || 1;
            var f = REPULSION / (dist * dist);
            var fx = (dx / dist) * f, fy = (dy / dist) * f;
            nodes[i].vx -= fx; nodes[i].vy -= fy;
            nodes[j].vx += fx; nodes[j].vy += fy;
          }
        }
        model.edges.forEach(function(e) {
          var a = nodeMap[e.from], b = nodeMap[e.to];
          var dx = b.x - a.x, dy = b.y - a.y;
          var dist = Math.sqrt(dx * dx + dy * dy) || 1;
          var f = SPRING_K * (dist - SPRING_REST);
          var fx = (dx / dist) * f, fy = (dy / dist) * f;
          a.vx += fx; a.vy += fy;
          b.vx -= fx; b.vy -= fy;
        });
        nodes.forEach(function(n) {
          n.vx += (cx - n.x) * CENTER_PULL;
          n.vy += (cy - n.y) * CENTER_PULL;
          n.vx *= DAMPING; n.vy *= DAMPING;
          n.x += n.vx; n.y += n.vy;
        });
      }
      function renderFrame() {
        edgeEls.forEach(function(ee) {
          var a = nodeMap[ee.data.from], b = nodeMap[ee.data.to];
          var dx = b.x - a.x, dy = b.y - a.y;
          var dist = Math.sqrt(dx * dx + dy * dy) || 1;
          var trim = nodeRadius(b) + 2;
          ee.el.setAttribute('x1', a.x);
          ee.el.setAttribute('y1', a.y);
          ee.el.setAttribute('x2', b.x - (dx / dist) * trim);
          ee.el.setAttribute('y2', b.y - (dy / dist) * trim);
        });
        nodeEls.forEach(function(ne) {
          ne.el.setAttribute('transform', 'translate(' + ne.data.x + ',' + ne.data.y + ')');
        });
      }
      var iterations = 0;
      function tickFrame() {
        if (gen !== generation) return; // a newer render took over
        simulate();
        renderFrame();
        iterations++;
        if (iterations < 300) requestAnimationFrame(tickFrame);
      }
      tickFrame();

      updateVisibility();
    }

    /* Document-level pan/drag handlers (registered once per tab build) */
    document.addEventListener('mousemove', function(ev) {
      if (!live.svg) return;
      if (live.isPanning && !live.dragging) {
        var rect = live.svg.getBoundingClientRect();
        live.panMoved += Math.abs(ev.movementX) + Math.abs(ev.movementY);
        live.viewX = live.panVX - (ev.clientX - live.panSX) / rect.width * (W / live.viewScale);
        live.viewY = live.panVY - (ev.clientY - live.panSY) / rect.height * (H / live.viewScale);
        updateViewBox();
      }
      if (live.dragging) {
        var r = live.svg.getBoundingClientRect();
        live.dragMoved += Math.abs(ev.movementX) + Math.abs(ev.movementY);
        live.dragging.x = live.viewX + ((ev.clientX - r.left) / r.width) * (W / live.viewScale);
        live.dragging.y = live.viewY + ((ev.clientY - r.top) / r.height) * (H / live.viewScale);
        live.dragging.vx = 0;
        live.dragging.vy = 0;
      }
    });
    document.addEventListener('mouseup', function() {
      live.isPanning = false;
      live.dragging = null;
    });

    /* Controls wiring */
    search.addEventListener('input', function() {
      if (state.focus) state.focus = null;
      updateVisibility();
    });
    degreeSlider.addEventListener('input', function() {
      degreeLabel.replaceChildren();
      degreeLabel.append(txt('Min degree: ' + degreeSlider.value));
      state.focus = null;
      renderGraph();
    });
    groupToggle.addEventListener('change', function() {
      state.focus = null;
      renderGraph();
    });
    exportBtn.addEventListener('click', function() {
      if (!live.svg) return;
      var clone = live.svg.cloneNode(true);
      clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
      var src = new XMLSerializer().serializeToString(clone);
      /* Standalone SVG cannot resolve the page's CSS variables */
      var styles = getComputedStyle(document.body);
      ['--c-good', '--c-warn', '--c-danger'].forEach(function(v) {
        var resolved = styles.getPropertyValue(v).trim();
        if (resolved) src = src.split('var(' + v + ')').join(resolved);
      });
      var blob = new Blob([src], { type: 'image/svg+xml' });
      var url = URL.createObjectURL(blob);
      var a = el('a', { href: url, download: (R.repo_name || 'import') + '-graph.svg' });
      document.body.append(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
    });

    /* Drill-through entry point used by the Coupling tab */
    window.__focusGraphNode = function(path) {
      if (groupToggle.checked) {
        groupToggle.checked = false;
        renderGraph();
      }
      if (live.nodeMap[path]) {
        search.value = '';
        state.focus = path;
      } else {
        /* node hidden by cap or min-degree filter — fall back to text filter */
        state.focus = null;
        search.value = path;
      }
      updateVisibility();
    };
    registerFileFocus('graph', window.__focusGraphNode);

    renderGraph();
    return wrapper;
  }