-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgraph.js
More file actions
3847 lines (3315 loc) · 121 KB
/
Copy pathgraph.js
File metadata and controls
3847 lines (3315 loc) · 121 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
/**
* bv Force-Graph Visualization Component
*
* Production-quality, high-performance graph visualization for dependency analysis.
* Features: WASM-powered metrics, multiple view modes, rich interactions, accessibility.
*
* @module bv-graph
* @version 1.0.0
*/
// ============================================================================
// THEME & CONSTANTS
// ============================================================================
const THEME = {
// Dracula-inspired palette
bg: '#282a36',
bgSecondary: '#44475a',
bgTertiary: '#21222c',
fg: '#f8f8f2',
fgMuted: '#6272a4',
// Status colors
status: {
open: '#50FA7B',
in_progress: '#FFB86C',
blocked: '#FF5555',
closed: '#6272A4'
},
// Priority heat (flame intensity)
priority: {
0: '#FF0000', // Critical
1: '#FF5555', // High
2: '#FFB86C', // Medium
3: '#F1FA8C', // Low
4: '#6272A4' // Backlog
},
// Accent colors
accent: {
purple: '#BD93F9',
pink: '#FF79C6',
cyan: '#8BE9FD',
green: '#50FA7B',
orange: '#FFB86C',
red: '#FF5555',
yellow: '#F1FA8C',
gold: '#fbbf24'
},
// Link colors
link: {
default: '#44475a',
highlighted: '#BD93F9',
gold: '#fbbf24',
goldGlow: 'rgba(251, 191, 36, 0.6)',
critical: '#FF5555',
cycle: '#FF79C6'
}
};
const TYPE_ICONS = {
bug: '\uD83D\uDC1B', // 🐛
feature: '\u2728', // ✨
task: '\uD83D\uDCDD', // 📝
epic: '\uD83C\uDFAF', // 🎯
chore: '\uD83D\uDD27', // 🔧
default: '\uD83D\uDCCB' // 📋
};
const VIEW_MODES = {
FORCE: 'force', // Standard force-directed
HIERARCHY: 'hierarchy', // Top-down tree layout
RADIAL: 'radial', // Radial tree from selected node
CLUSTER: 'cluster', // Clustered by status
LABEL_GALAXY: 'label_galaxy' // Clustered by label ("galaxy" view)
};
// Label color palette (10 distinct colors, colorblind-friendly)
const LABEL_COLORS = [
'#8BE9FD', // Cyan
'#50FA7B', // Green
'#FFB86C', // Orange
'#FF79C6', // Pink
'#BD93F9', // Purple
'#F1FA8C', // Yellow
'#FF5555', // Red
'#6272A4', // Comment (muted)
'#44475A', // Selection
'#F8F8F2' // Foreground
];
// ============================================================================
// LAYOUT PRESETS (bv-97)
// ============================================================================
/**
* Layout presets for different visualization needs.
* Each preset configures force simulation parameters optimized for specific use cases.
*/
const LAYOUT_PRESETS = {
// Default force-directed layout - balanced readability
force: {
name: 'Force-Directed',
description: 'Standard physics-based layout with balanced spacing',
icon: '🔄',
config: {
linkDistance: 100,
chargeStrength: -150,
centerStrength: 0.05,
warmupTicks: 100,
cooldownTicks: 300
},
viewMode: VIEW_MODES.FORCE
},
// Compact layout for large graphs - tighter spacing, faster settling
compact: {
name: 'Compact DAG',
description: 'Tight layout for large graphs, emphasizes structure',
icon: '📦',
config: {
linkDistance: 50,
chargeStrength: -80,
centerStrength: 0.15,
warmupTicks: 50,
cooldownTicks: 150
},
viewMode: VIEW_MODES.HIERARCHY,
customForces: {
// Stronger vertical alignment for DAG appearance
yStrength: 0.4,
depthSpacing: 80
}
},
// Spread layout for clarity - more spacing, slower but cleaner
spread: {
name: 'Spread',
description: 'Maximum spacing for readability, ideal for exports',
icon: '🌟',
config: {
linkDistance: 180,
chargeStrength: -300,
centerStrength: 0.02,
warmupTicks: 150,
cooldownTicks: 500
},
viewMode: VIEW_MODES.FORCE
},
// Orthogonal-ish layout - grid-aligned, clean edges
orthogonal: {
name: 'Orthogonal',
description: 'Grid-aligned layout with cleaner edge routing',
icon: '📐',
config: {
linkDistance: 120,
chargeStrength: -100,
centerStrength: 0.1,
warmupTicks: 200,
cooldownTicks: 400
},
viewMode: VIEW_MODES.FORCE,
customForces: {
// Snap to grid forces
gridSize: 60,
gridStrength: 0.3
}
},
// Radial layout - emanates from center/selection
radial: {
name: 'Radial',
description: 'Circular layout from center or selected node',
icon: '🎯',
config: {
linkDistance: 80,
chargeStrength: -100,
centerStrength: 0.01,
warmupTicks: 100,
cooldownTicks: 300
},
viewMode: VIEW_MODES.RADIAL
},
// Cluster layout - groups by status
cluster: {
name: 'Status Clusters',
description: 'Groups nodes by status (open, in_progress, blocked)',
icon: '🔲',
config: {
linkDistance: 70,
chargeStrength: -60,
centerStrength: 0.05,
warmupTicks: 100,
cooldownTicks: 250
},
viewMode: VIEW_MODES.CLUSTER
}
};
// Default preset for exports
const DEFAULT_EXPORT_PRESET = 'spread';
// ============================================================================
// STATE MANAGEMENT
// ============================================================================
class GraphStore {
constructor() {
this.graph = null;
this.wasmGraph = null;
this.wasmReady = false;
this.container = null;
// Data
this.issues = [];
this.dependencies = [];
this.nodeMap = new Map(); // id -> issue
this.nodeIndexMap = new Map(); // id -> index
// Computed metrics
this.metrics = {
pagerank: null,
betweenness: null,
criticalPath: null,
eigenvector: null,
kcore: null,
hits: null, // { hub: Float32Array, authority: Float32Array }
slack: null, // Float32Array of slack values
articulationPoints: null, // Set of node IDs (cut vertices)
cycles: null
};
// UI State
this.viewMode = VIEW_MODES.FORCE;
this.currentPreset = 'force'; // Layout preset (bv-97)
this.selectedNode = null;
this.hoveredNode = null;
this.highlightedNodes = new Set();
this.highlightedLinks = new Set();
this.connectedNodes = new Set(); // Gold glow connected subgraph
this.focusedPath = null;
// Heatmap & metrics mode
this.heatmapMode = false;
this.sizeMetric = 'pagerank'; // pagerank | betweenness | critical | indegree
this.maxMetrics = { pagerank: 1, betweenness: 1, critical: 1, indegree: 1 };
// Filters
this.filters = {
status: null,
priority: null,
labels: [],
search: '',
showClosed: true // Default to showing all issues in static export
};
// Config
this.config = {
nodeMinSize: 4,
nodeMaxSize: 24,
linkDistance: 100,
chargeStrength: -150,
centerStrength: 0.05,
warmupTicks: 100,
cooldownTicks: 300,
enableParticles: true,
particleSpeed: 0.005,
showLabels: true,
labelZoomThreshold: 0.6
};
// Animation state
this.animationFrame = null;
this.particlePositions = new Map();
}
reset() {
this.issues = [];
this.dependencies = [];
this.nodeMap.clear();
this.nodeIndexMap.clear();
this.selectedNode = null;
this.hoveredNode = null;
this.highlightedNodes.clear();
this.highlightedLinks.clear();
this.connectedNodes.clear();
this.focusedPath = null;
this.heatmapMode = false;
}
}
const store = new GraphStore();
/**
* Helper to force ForceGraph to redraw without disturbing the simulation.
* Uses a micro zoom adjustment trick - imperceptible to users but forces canvas redraw.
* This avoids the "wiggle" caused by graphData() potentially reheating the simulation.
*/
function refreshGraph() {
if (!store.graph) return;
// Get current zoom level
const currentZoom = store.graph.zoom();
// Guard against undefined/NaN zoom values
if (typeof currentZoom !== 'number' || isNaN(currentZoom)) return;
// Apply imperceptible zoom change (0.0001% = invisible) with 0ms duration (instant)
store.graph.zoom(currentZoom * 1.000001, 0);
// Immediately restore - this triggers a redraw without any visual change
requestAnimationFrame(() => {
if (store.graph) store.graph.zoom(currentZoom, 0);
});
}
// ============================================================================
// HEATMAP & GOLD GLOW HELPERS
// ============================================================================
/**
* Compute max metric values for normalization
* Note: Must be called AFTER prepareGraphData since metrics are on prepared nodes
*/
function computeMaxMetrics() {
// Get prepared nodes from graph data if available, otherwise use raw issues
const graphData = store.graph?.graphData();
const nodes = graphData?.nodes || store.issues;
if (!nodes.length) return;
store.maxMetrics.pagerank = Math.max(...nodes.map(n => n.pagerank || 0), 0.001);
store.maxMetrics.betweenness = Math.max(...nodes.map(n => n.betweenness || 0), 0.001);
store.maxMetrics.critical = Math.max(...nodes.map(n => n.criticalDepth || 0), 1);
store.maxMetrics.indegree = Math.max(...nodes.map(n => n.blockerCount || 0), 1);
}
/**
* Get heatmap color for a node based on current sizeMetric
* Uses HSL: 120 (green) to 0 (red) based on metric intensity
*/
function getHeatmapColor(node) {
let val = 0, max = 1;
switch (store.sizeMetric) {
case 'pagerank':
val = node.pagerank || 0;
max = store.maxMetrics.pagerank;
break;
case 'betweenness':
val = node.betweenness || 0;
max = store.maxMetrics.betweenness;
break;
case 'critical':
val = node.criticalDepth || 0;
max = store.maxMetrics.critical;
break;
case 'indegree':
val = node.blockerCount || 0;
max = store.maxMetrics.indegree;
break;
}
const ratio = Math.min(val / max, 1);
const hue = 120 - ratio * 120; // Green (120) to Red (0)
return `hsl(${hue}, 80%, 50%)`;
}
/**
* Get connected subgraph nodes via BFS (for gold glow highlight)
* @param {string} nodeId - Starting node ID
* @param {number} depth - Max depth to traverse (default 2)
* @returns {Set<string>} Set of connected node IDs
*/
function getConnectedNodes(nodeId, depth = 2) {
const connected = new Set([nodeId]);
const queue = [{ id: nodeId, d: 0 }];
const graphData = store.graph?.graphData();
if (!graphData) return connected;
while (queue.length > 0) {
const { id, d } = queue.shift();
if (d >= depth) continue;
graphData.links.forEach(l => {
const src = typeof l.source === 'object' ? l.source.id : l.source;
const tgt = typeof l.target === 'object' ? l.target.id : l.target;
if (src === id && !connected.has(tgt)) {
connected.add(tgt);
queue.push({ id: tgt, d: d + 1 });
}
if (tgt === id && !connected.has(src)) {
connected.add(src);
queue.push({ id: src, d: d + 1 });
}
});
}
return connected;
}
/**
* Update connected nodes for gold glow effect
*/
function updateConnectedNodes(node) {
if (node?.id) {
store.connectedNodes = getConnectedNodes(node.id, 2);
} else {
store.connectedNodes.clear();
}
}
/**
* Toggle heatmap mode
*/
export function toggleHeatmap() {
store.heatmapMode = !store.heatmapMode;
refreshGraph();
dispatchEvent('heatmapToggle', { active: store.heatmapMode, metric: store.sizeMetric });
return store.heatmapMode;
}
/**
* Set the size/heatmap metric
*/
export function setSizeMetric(metric) {
if (['pagerank', 'betweenness', 'critical', 'indegree'].includes(metric)) {
store.sizeMetric = metric;
refreshGraph();
dispatchEvent('metricChange', { metric: store.sizeMetric });
}
}
/**
* Get current heatmap state
*/
export function getHeatmapState() {
return {
active: store.heatmapMode,
metric: store.sizeMetric
};
}
// ============================================================================
// LABEL CLUSTERING STATE
// ============================================================================
const labelClusterState = {
active: false,
labels: [], // Unique labels in dataset
labelColorMap: new Map(), // label -> color
labelCenters: new Map(), // label -> {x, y} center position
clusterHulls: new Map(), // label -> hull points array
showHulls: true,
showLegend: true,
crossLabelEdges: new Set() // Set of edge IDs crossing label boundaries
};
/**
* Build label color map and compute cluster centers
*/
function buildLabelColorMap() {
labelClusterState.labelColorMap.clear();
labelClusterState.labelCenters.clear();
// Collect all unique labels
const labelSet = new Set();
store.issues.forEach(issue => {
(issue.labels || []).forEach(label => labelSet.add(label));
});
// Add "unlabeled" for issues without labels
labelSet.add('(unlabeled)');
labelClusterState.labels = [...labelSet].sort();
// Assign colors
labelClusterState.labels.forEach((label, i) => {
labelClusterState.labelColorMap.set(label, LABEL_COLORS[i % LABEL_COLORS.length]);
});
// Compute initial cluster centers in a circle
const numLabels = labelClusterState.labels.length;
const radius = Math.max(200, numLabels * 30);
labelClusterState.labels.forEach((label, i) => {
const angle = (2 * Math.PI * i) / numLabels - Math.PI / 2; // Start from top
labelClusterState.labelCenters.set(label, {
x: Math.cos(angle) * radius,
y: Math.sin(angle) * radius
});
});
return labelClusterState.labelColorMap;
}
/**
* Get the primary label for a node (first label or 'unlabeled')
*/
function getPrimaryLabel(node) {
return (node.labels && node.labels.length > 0) ? node.labels[0] : '(unlabeled)';
}
/**
* Get the color for a node based on its primary label
*/
function getLabelColor(node) {
const label = getPrimaryLabel(node);
return labelClusterState.labelColorMap.get(label) || LABEL_COLORS[0];
}
/**
* Check if an edge crosses label boundaries
*/
function isCrossLabelEdge(link) {
const sourceNode = typeof link.source === 'object' ? link.source : store.nodeMap.get(link.source);
const targetNode = typeof link.target === 'object' ? link.target : store.nodeMap.get(link.target);
if (!sourceNode || !targetNode) return false;
const sourceLabel = getPrimaryLabel(sourceNode);
const targetLabel = getPrimaryLabel(targetNode);
return sourceLabel !== targetLabel;
}
/**
* Compute convex hulls for each label cluster
*/
function computeClusterHulls() {
if (!store.graph) return;
labelClusterState.clusterHulls.clear();
const graphData = store.graph.graphData();
// Group nodes by primary label
const labelGroups = new Map();
graphData.nodes.forEach(node => {
const label = getPrimaryLabel(node);
if (!labelGroups.has(label)) {
labelGroups.set(label, []);
}
labelGroups.get(label).push([node.x, node.y]);
});
// Compute hull for each group with 3+ nodes
labelGroups.forEach((points, label) => {
if (points.length >= 3) {
// Use d3.polygonHull for convex hull computation
const hull = d3.polygonHull(points);
if (hull) {
labelClusterState.clusterHulls.set(label, hull);
}
} else if (points.length > 0) {
// For 1-2 nodes, just store the points
labelClusterState.clusterHulls.set(label, points);
}
});
return labelClusterState.clusterHulls;
}
/**
* Draw cluster hulls on the canvas (bv-qpt0)
* Called during onRenderFramePre to draw behind nodes
*/
function drawClusterHulls(ctx, globalScale) {
// Recompute hulls if needed (layout may have changed)
computeClusterHulls();
labelClusterState.clusterHulls.forEach((hull, label) => {
if (!hull || hull.length < 3) return;
const color = labelClusterState.labelColorMap.get(label) || LABEL_COLORS[0];
ctx.save();
// Draw semi-transparent filled hull
ctx.beginPath();
ctx.moveTo(hull[0][0], hull[0][1]);
for (let i = 1; i < hull.length; i++) {
ctx.lineTo(hull[i][0], hull[i][1]);
}
ctx.closePath();
// Fill with label color at low opacity
ctx.fillStyle = color + '15'; // ~8% opacity
ctx.fill();
// Draw hull border
ctx.strokeStyle = color + '40'; // ~25% opacity
ctx.lineWidth = Math.max(1, 2 / globalScale);
ctx.setLineDash([5 / globalScale, 5 / globalScale]);
ctx.stroke();
ctx.setLineDash([]);
// Draw label name at cluster center (when zoomed out enough)
if (globalScale < 0.8 && hull.length >= 3) {
// Compute centroid
let cx = 0, cy = 0;
hull.forEach(point => {
cx += point[0];
cy += point[1];
});
cx /= hull.length;
cy /= hull.length;
// Draw label text - keep ~14px on screen regardless of zoom
const fontSize = Math.min(14, Math.max(5, 14 / globalScale));
ctx.font = `600 ${fontSize}px 'Inter', sans-serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = color + '99'; // ~60% opacity
ctx.fillText(label, cx, cy);
}
ctx.restore();
});
}
// ============================================================================
// WASM INTEGRATION
// ============================================================================
async function initWasm() {
try {
if (typeof window.bvGraphWasm !== 'undefined') {
await window.bvGraphWasm.default();
store.wasmReady = true;
console.log('[bv-graph] WASM initialized, version:', window.bvGraphWasm.version());
return true;
}
} catch (e) {
console.warn('[bv-graph] WASM init failed:', e);
}
store.wasmReady = false;
return false;
}
function buildWasmGraph() {
if (!store.wasmReady) return;
try {
const { DiGraph } = window.bvGraphWasm;
if (store.wasmGraph) {
store.wasmGraph.free();
store.wasmGraph = null;
}
store.wasmGraph = DiGraph.withCapacity(store.issues.length, store.dependencies.length);
// Add all nodes
store.issues.forEach(issue => {
store.wasmGraph.addNode(issue.id);
});
// Add blocking edges
store.dependencies
.filter(d => d.type === 'blocks' || !d.type)
.forEach(d => {
const fromIdx = store.wasmGraph.nodeIdx(d.issue_id);
const toIdx = store.wasmGraph.nodeIdx(d.depends_on_id);
if (fromIdx !== undefined && toIdx !== undefined) {
store.wasmGraph.addEdge(fromIdx, toIdx);
}
});
console.log(`[bv-graph] WASM graph: ${store.wasmGraph.nodeCount()} nodes, ${store.wasmGraph.edgeCount()} edges`);
} catch (e) {
console.warn('[bv-graph] Failed to build WASM graph:', e);
store.wasmGraph = null;
}
}
function computeMetrics() {
if (!store.wasmReady || !store.wasmGraph) return;
const start = performance.now();
try {
// PageRank (importance)
store.metrics.pagerank = store.wasmGraph.pagerankDefault();
// Critical path heights (depth)
store.metrics.criticalPath = store.wasmGraph.criticalPathHeights();
// Eigenvector (influence)
store.metrics.eigenvector = store.wasmGraph.eigenvectorDefault();
// K-core (cohesion)
store.metrics.kcore = store.wasmGraph.kcore();
// Betweenness (bottleneck) - use approx for large graphs
const nodeCount = store.wasmGraph.nodeCount();
if (nodeCount > 500) {
store.metrics.betweenness = store.wasmGraph.betweennessApprox(Math.min(100, nodeCount));
} else if (nodeCount > 0) {
store.metrics.betweenness = store.wasmGraph.betweenness();
}
// HITS (hub and authority scores)
try {
const hitsResult = store.wasmGraph.hitsDefault();
if (hitsResult) {
store.metrics.hits = {
hub: hitsResult.hub,
authority: hitsResult.authority
};
}
} catch (e) {
console.warn('[bv-graph] HITS computation skipped:', e);
}
// Slack (schedule flexibility - 0 means on critical path)
try {
store.metrics.slack = store.wasmGraph.slack();
} catch (e) {
console.warn('[bv-graph] Slack computation skipped:', e);
}
// Articulation points (cut vertices - removing them disconnects the graph)
try {
const artPoints = store.wasmGraph.articulationPoints();
if (artPoints && artPoints.length > 0) {
// Convert indices to node IDs
store.metrics.articulationPoints = new Set(
Array.from(artPoints).map(idx => {
for (const [id, i] of store.nodeIndexMap.entries()) {
if (i === idx) return id;
}
return null;
}).filter(Boolean)
);
} else {
store.metrics.articulationPoints = new Set();
}
} catch (e) {
console.warn('[bv-graph] Articulation points computation skipped:', e);
}
// Cycles
const cycleResult = store.wasmGraph.enumerateCycles(100);
store.metrics.cycles = cycleResult;
const elapsed = performance.now() - start;
console.log(`[bv-graph] Metrics computed in ${elapsed.toFixed(1)}ms`);
} catch (e) {
console.warn('[bv-graph] Metric computation failed:', e);
}
}
// ============================================================================
// GRAPH INITIALIZATION
// ============================================================================
export async function initGraph(containerId, options = {}) {
store.container = document.getElementById(containerId);
if (!store.container) {
throw new Error(`Container '${containerId}' not found`);
}
// Merge config
Object.assign(store.config, options);
// Clear container
store.container.innerHTML = '';
// Initialize WASM
await initWasm();
// Create force-graph instance
store.graph = ForceGraph()(store.container)
// Data binding
.nodeId('id')
.linkSource('source')
.linkTarget('target')
// Node rendering
.nodeCanvasObject(drawNode)
.nodeCanvasObjectMode(() => 'replace')
.nodePointerAreaPaint(drawNodeHitArea)
// Link rendering
.linkCanvasObject(drawLink)
.linkCanvasObjectMode(() => 'replace')
.linkDirectionalParticles(node => store.config.enableParticles ? 2 : 0)
.linkDirectionalParticleSpeed(store.config.particleSpeed)
.linkDirectionalParticleColor(() => THEME.accent.cyan)
// Forces
.d3Force('charge', d3.forceManyBody()
.strength(store.config.chargeStrength)
.distanceMax(300))
.d3Force('link', d3.forceLink()
.distance(link => getLinkDistance(link))
.strength(0.7))
.d3Force('center', d3.forceCenter())
.d3Force('x', d3.forceX()
.strength(store.config.centerStrength))
.d3Force('y', d3.forceY()
.strength(store.config.centerStrength))
.d3Force('collision', d3.forceCollide()
.radius(node => getNodeSize(node) + 5))
// Warmup
.warmupTicks(store.config.warmupTicks)
.cooldownTicks(store.config.cooldownTicks)
// Interaction handlers
.onNodeClick(handleNodeClick)
.onNodeRightClick(handleNodeRightClick)
.onNodeHover(handleNodeHover)
.onNodeDrag(handleNodeDrag)
.onNodeDragEnd(handleNodeDragEnd)
.onLinkClick(handleLinkClick)
.onLinkHover(handleLinkHover)
.onBackgroundClick(handleBackgroundClick)
.onZoom(handleZoom)
// Simulation progress tracking with early "done" detection
// The simulation can run for a long time at very low alpha values,
// but the layout is visually stable much earlier. We consider it "done"
// when alpha drops below 0.05 (95% progress) for smoother UX.
.onEngineTick(() => {
// Get current simulation alpha (1 = start, 0 = done)
// Alpha decays from 1 towards alphaMin (0.001)
const alpha = store.graph.d3Alpha?.() ?? 0;
const progress = Math.round((1 - alpha) * 100);
// Consider layout stable when alpha < 0.05 (95% progress)
// This provides a much snappier feel without waiting for full convergence
const effectivelyDone = alpha < 0.05;
dispatchEvent('simulationProgress', {
alpha,
progress: effectivelyDone ? 100 : progress,
done: effectivelyDone
});
})
.onEngineStop(() => {
dispatchEvent('simulationProgress', { alpha: 0, progress: 100, done: true });
})
// Background
.backgroundColor(THEME.bg)
// Custom rendering for cluster hulls (bv-qpt0)
.onRenderFramePre((ctx, globalScale) => {
if (labelClusterState.active && labelClusterState.showHulls) {
drawClusterHulls(ctx, globalScale);
}
});
// Setup keyboard shortcuts
setupKeyboardShortcuts();
// Emit ready event
dispatchEvent('ready', { graph: store.graph, wasmReady: store.wasmReady });
return store.graph;
}
// ============================================================================
// DATA LOADING
// ============================================================================
// Pre-computed layout cache
let precomputedLayout = null;
/**
* Load pre-computed graph layout for instant rendering.
* This fetches the compact layout file (~30KB) which contains positions and metrics.
* @returns {Promise<object|null>} Layout data or null if not available
*/
export async function loadPrecomputedLayout() {
try {
const response = await fetch('data/graph_layout.json');
if (!response.ok) return null;
precomputedLayout = await response.json();
console.log(`[bv-graph] Pre-computed layout: ${precomputedLayout.node_count} nodes`);
return precomputedLayout;
} catch (e) {
console.log('[bv-graph] No pre-computed layout, will use dynamic simulation');
return null;
}
}
/**
* Load data with optional pre-computed layout for instant rendering.
* @param {Array} issues - Issue objects from SQLite
* @param {Array} dependencies - Dependency objects from SQLite
* @param {object} [layout] - Optional pre-computed layout
*/
export function loadData(issues, dependencies, layout = precomputedLayout) {
store.reset();
store.issues = issues;
store.dependencies = dependencies;
// Build lookup maps
issues.forEach((issue, idx) => {
store.nodeMap.set(issue.id, issue);
store.nodeIndexMap.set(issue.id, idx);
});
// Merge pre-computed metrics if available
if (layout?.metrics) {
issues.forEach(issue => {
const m = layout.metrics[issue.id];
if (m) {
issue._precomputed = {
pagerank: m[0],
betweenness: m[1],
inDegree: m[2],
outDegree: m[3],
inCycle: m[4] === 1
};
}
});
}
// Build WASM graph structure (always, for cycle navigator etc.)
// Only skip metric computation if we have pre-computed metrics
if (store.wasmReady) {
buildWasmGraph();
if (!layout?.metrics) {
computeMetrics();
} else {
console.log('[bv-graph] Using pre-computed metrics, skipping WASM computation');
// Convert pre-computed cycle IDs to WASM indices for cycle navigator compatibility
if (layout.cycles && store.wasmGraph) {
const cyclesAsIndices = layout.cycles.map(cycle =>
cycle.map(id => store.wasmGraph.nodeIdx(id)).filter(idx => idx !== undefined)
).filter(cycle => cycle.length > 0);
store.metrics.cycles = { cycles: cyclesAsIndices, count: cyclesAsIndices.length };
}
}
}
// Build label color map for galaxy view
buildLabelColorMap();
// Prepare graph data with optional pre-computed positions
const graphData = prepareGraphData(layout);
// Update graph
store.graph.graphData(graphData);
// Compute max metric values for heatmap normalization (after graph data is set)
computeMaxMetrics();
// Fit immediately if pre-computed, otherwise wait for simulation
if (layout?.positions) {
store.graph.zoomToFit(200, 50);
} else {
setTimeout(() => store.graph.zoomToFit(400, 50), 500);
}
// Emit event
dispatchEvent('dataLoaded', {
nodeCount: graphData.nodes.length,
linkCount: graphData.links.length,
metrics: store.metrics,
precomputed: !!layout
});
return graphData;
}
function prepareGraphData(layout = null) {
const { issues, dependencies, filters, metrics } = store;
// Filter nodes
let nodes = issues.filter(issue => {
// Status filter
if (filters.status && issue.status !== filters.status) return false;
if (!filters.showClosed && issue.status === 'closed') return false;
// Priority filter
if (filters.priority !== null && issue.priority !== filters.priority) return false;
// Label filter
if (filters.labels.length > 0) {
const issueLabels = issue.labels || [];
if (!filters.labels.some(l => issueLabels.includes(l))) return false;
}
// Search filter
if (filters.search) {
const term = filters.search.toLowerCase();
const searchable = `${issue.id} ${issue.title} ${issue.description || ''}`.toLowerCase();
if (!searchable.includes(term)) return false;
}
return true;
});
// Build node set for link filtering
const nodeIds = new Set(nodes.map(n => n.id));
// Filter links
let links = dependencies
.filter(d => (d.type === 'blocks' || !d.type))
.filter(d => nodeIds.has(d.issue_id) && nodeIds.has(d.depends_on_id))
.map(d => ({
source: d.issue_id,