-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathvisualization.js
More file actions
1939 lines (1657 loc) · 73.5 KB
/
visualization.js
File metadata and controls
1939 lines (1657 loc) · 73.5 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
// =============================================================================
// ATTRIBUTE MAPPING - Converts shortened names to original names for UX
// =============================================================================
/**
* Mapping from shortened attribute names (used in JSON) to original attribute names (used in UX)
* Based on test.md documentation
*/
const ATTRIBUTE_MAPPING = {
// Node attributes
node: {
'alias': 'alias', // unchanged
'c': 'cluster',
'br': 'is_bridge_node',
'ibr': 'is_important_bridge_node',
'bc': 'bridges_clusters',
'cc': 'cluster_connections',
'pk': 'pub_key',
'nt': 'node_type',
'tch': 'total_channels',
'tcap': 'total_capacity',
'fcap': 'formatted_total_capacity',
'cat': 'category_counts',
'pr': 'pleb_rank',
'cr': 'capacity_rank',
'chr': 'channels_rank',
'btx': 'birth_tx',
'clc': 'closed_channels_count'
},
// Edge attributes
edge: {
'br': 'is_bridge_channel',
'ibr': 'is_important_bridge_channel',
'cc': 'connects_clusters',
'cap': 'total_capacity',
'cnt': 'channel_count',
'chs': 'channels'
},
// Channel object attributes (inside channels array)
channel: {
't': 'tier',
'cap': 'capacity',
'btx': 'birth_tx'
}
};
/**
* Maps a node from the new shortened format to the original format expected by the visualization code
* @param {Object} node - Node object with shortened attribute names
* @returns {Object} Node object with original attribute names
*/
function mapNodeAttributes(node) {
const mapped = { id: node.id };
// Copy position if exists
if (node.x !== undefined) mapped.x = node.x;
if (node.y !== undefined) mapped.y = node.y;
// Map all attributes
for (const [shortName, longName] of Object.entries(ATTRIBUTE_MAPPING.node)) {
if (node[shortName] !== undefined) {
mapped[longName] = node[shortName];
}
}
return mapped;
}
/**
* Maps an edge from the new shortened format to the original format expected by the visualization code
* @param {Object} edge - Edge object with shortened attribute names
* @returns {Object} Edge object with original attribute names
*/
function mapEdgeAttributes(edge) {
const mapped = {
id: edge.id,
source: edge.source,
target: edge.target
};
// Copy type if exists
if (edge.type !== undefined) mapped.type = edge.type;
// Map all attributes
for (const [shortName, longName] of Object.entries(ATTRIBUTE_MAPPING.edge)) {
if (edge[shortName] !== undefined) {
// Special handling for channels array
if (shortName === 'chs' && Array.isArray(edge[shortName])) {
mapped[longName] = edge[shortName].map(mapChannelAttributes);
} else {
mapped[longName] = edge[shortName];
}
}
}
// For backward compatibility, if edge has 'cap' (total_capacity), also set it as 'capacity'
if (mapped.total_capacity !== undefined) {
mapped.capacity = mapped.total_capacity;
}
return mapped;
}
/**
* Maps a channel object from the new shortened format to the original format
* @param {Object} channel - Channel object with shortened attribute names
* @returns {Object} Channel object with original attribute names
*/
function mapChannelAttributes(channel) {
const mapped = {};
for (const [shortName, longName] of Object.entries(ATTRIBUTE_MAPPING.channel)) {
if (channel[shortName] !== undefined) {
mapped[longName] = channel[shortName];
}
}
return mapped;
}
// =============================================================================
// CONFIGURATION CONSTANTS
// =============================================================================
// Animation and timing settings for UI interactions
const TIMING = {
ZOOM_ANIMATION: 200, // Duration for zoom in/out animations (ms)
LAYOUT_AUTO_STOP: 5000, // Auto-stop layout after 5 seconds
TOOLTIP_OFFSET: 5, // Pixel offset from cursor for tooltips
SEARCH_MIN_LENGTH: 2 // Minimum characters to trigger search
};
// Bitcoin capacity conversion thresholds (satoshis to BTC/mBTC/μBTC)
const CAPACITY_THRESHOLDS = {
BTC: 100000000, // 1 BTC = 100M satoshis
MBTC: 100000, // 1 mBTC = 100K satoshis
UBTC: 1000 // 1 μBTC = 1K satoshis
};
// Cluster color palette for network communities
const CLUSTER_COLORS = {
0: '#60A5FA', // Warm blue (blue-400) - Distinct and vibrant
1: '#4ADE80', // Warm green (green-400) - High contrast with blue
2: '#C084FC', // Warm purple (purple-400) - Distinct from blue/green
3: '#FACC15', // Warm amber (amber-400) - Warm yellow tone
4: '#2DD4BF', // Warm teal (teal-400) - Green-blue blend
5: '#F87171', // Warm red (red-400) - Red for variety
6: '#FB923C', // Warm orange (orange-400) - Orange complement
7: '#EAB308', // Warm yellow (yellow-500) - Bright yellow
8: '#A3E635', // Warm lime (lime-400) - Light green
9: '#34D399', // Warm emerald (emerald-400) - Deeper green
10: '#22D3EE', // Warm cyan (cyan-400) - Blue-green
11: '#38BDF8', // Warm sky (sky-400) - Light blue
12: '#818CF8', // Warm indigo (indigo-400) - Blue-purple
13: '#A78BFA', // Warm violet (violet-400) - Purple-blue
14: '#F472B6', // Warm pink (pink-400) - Pink accent
DEFAULT: '#9CA3AF' // Soft gray (gray-400)
};
// Bridge node highlighting
const BRIDGE_NODE_CONFIG = {
IMPORTANT_BRIDGE: {
borderColor: '#EF4444',
borderWidth: 3
},
REGULAR_BRIDGE: {
borderColor: '#FB923C',
borderWidth: 2
}
};
// Edge coloring - using pre-calculated colors from data
const EDGE_HIGHLIGHT = {
IMPORTANT_BRIDGE: '#B0B0B0', // Darker gray for critical bridges
REGULAR_BRIDGE: '#C8C8C8', // Medium gray for regular bridges
DEFAULT: '#D8D8D8' // Light gray for normal edges
};
// =============================================================================
// GLOBAL STATE
// =============================================================================
// Global state for tracking selected node (used for gray-out effect on edges)
let selectedNode = null;
// Global reference to current renderer instance for proper cleanup
let currentRenderer = null;
let currentLayoutManager = null;
let currentGraph = null; // Track current graph for summary updates
// Store event listeners for proper cleanup
let controlButtonListeners = {
zoomIn: null,
zoomOut: null,
resetView: null,
toggleLayout: null
};
// Store the current search handler to remove it when needed
let currentSearchHandler = null;
// Track if a dataset is currently being loaded to prevent concurrent loads
let isLoadingDataset = false;
// Global filter state
let filterState = {
plebRankMax: null, // null = show all
minCapacity: 0, // Minimum capacity in BTC
minChannels: 0, // Minimum number of channels
isActive: false // Track if any filters are active
};
// Store total node count for filter results display
let totalNodeCount = 0;
// =============================================================================
// NETWORK SUMMARY FUNCTION
// =============================================================================
/**
* Updates the network summary box with current visible node and edge counts
* This shows the filtered/visible counts, not the total dataset
*/
function updateNetworkSummary() {
if (!currentGraph) {
console.warn('Graph not initialized yet');
return;
}
let visibleNodes = 0;
let visibleEdges = 0;
// Count visible nodes
currentGraph.forEachNode(nodeId => {
const isHidden = currentGraph.getNodeAttribute(nodeId, 'hidden');
if (!isHidden) {
visibleNodes++;
}
});
// Count visible edges
currentGraph.forEachEdge(edgeId => {
const isHidden = currentGraph.getEdgeAttribute(edgeId, 'hidden');
if (!isHidden) {
visibleEdges++;
}
});
// Update the summary display
const nodesElement = document.getElementById('summary-nodes-count');
const channelsElement = document.getElementById('summary-channels-count');
if (nodesElement) {
nodesElement.textContent = visibleNodes.toLocaleString();
}
if (channelsElement) {
channelsElement.textContent = visibleEdges.toLocaleString();
}
console.log(`📊 Network Summary: ${visibleNodes} nodes, ${visibleEdges} channels visible`);
}
// Make updateNetworkSummary available globally
window.updateNetworkSummary = updateNetworkSummary;
// =============================================================================
// URL STATE SYNC
// =============================================================================
/**
* Updates the browser URL to reflect the current state (selected node, search, filters)
* Allows for deep linking to specific graph views
*/
function syncURLState() {
try {
const urlParams = new URLSearchParams(window.location.search);
let hasChanges = false;
// Handle node selection
if (selectedNode) {
if (urlParams.get('node') !== selectedNode) {
urlParams.set('node', selectedNode);
hasChanges = true;
}
} else if (urlParams.has('node')) {
urlParams.delete('node');
hasChanges = true;
}
// Handle search
const searchInput = document.getElementById('search-input');
if (searchInput && searchInput.value.trim().length >= TIMING.SEARCH_MIN_LENGTH) {
if (urlParams.get('search') !== searchInput.value.trim()) {
urlParams.set('search', searchInput.value.trim());
hasChanges = true;
}
} else if (urlParams.has('search')) {
urlParams.delete('search');
hasChanges = true;
}
// Handle filters
if (filterState.plebRankMax) {
if (urlParams.get('plebRankMax') !== filterState.plebRankMax.toString()) {
urlParams.set('plebRankMax', filterState.plebRankMax);
hasChanges = true;
}
} else if (urlParams.has('plebRankMax')) {
urlParams.delete('plebRankMax');
hasChanges = true;
}
if (filterState.minCapacity > 0) {
if (urlParams.get('minCapacity') !== filterState.minCapacity.toString()) {
urlParams.set('minCapacity', filterState.minCapacity);
hasChanges = true;
}
} else if (urlParams.has('minCapacity')) {
urlParams.delete('minCapacity');
hasChanges = true;
}
if (filterState.minChannels > 0) {
if (urlParams.get('minChannels') !== filterState.minChannels.toString()) {
urlParams.set('minChannels', filterState.minChannels);
hasChanges = true;
}
} else if (urlParams.has('minChannels')) {
urlParams.delete('minChannels');
hasChanges = true;
}
// Update URL if changes occurred
if (hasChanges) {
const newUrl = window.location.pathname + '?' + urlParams.toString();
// Don't append empty '?' if no params
window.history.replaceState({}, '', urlParams.toString() ? newUrl : window.location.pathname);
}
} catch (error) {
console.warn('Error syncing URL state:', error);
}
}
/**
* Reads URL parameters and applies the corresponding state to the visualization
* Should be called after the graph is fully loaded and renderer initialized
*/
function applyUrlParams(graph, renderer, sidebarManager) {
try {
const urlParams = new URLSearchParams(window.location.search);
let shouldFilter = false;
// Apply filters first so they affect the graph before selecting/searching
if (urlParams.has('plebRankMax')) {
const val = parseInt(urlParams.get('plebRankMax'), 10);
if (!isNaN(val)) {
filterState.plebRankMax = val;
const radio = document.querySelector(`input[name="pleb-rank-filter"][value="${val}"]`);
if (radio) radio.checked = true;
shouldFilter = true;
}
}
if (urlParams.has('minCapacity')) {
const val = parseFloat(urlParams.get('minCapacity'));
if (!isNaN(val)) {
filterState.minCapacity = val;
const radio = document.querySelector(`input[name="min-capacity-filter"][value="${val}"]`);
if (radio) radio.checked = true;
shouldFilter = true;
}
}
if (urlParams.has('minChannels')) {
const val = parseInt(urlParams.get('minChannels'), 10);
if (!isNaN(val)) {
filterState.minChannels = val;
const radio = document.querySelector(`input[name="min-channels-filter"][value="${val}"]`);
if (radio) radio.checked = true;
shouldFilter = true;
}
}
// Execute filter logic if any filters were found
if (shouldFilter && typeof applyFilters === 'function') {
filterState.isActive = true;
applyFilters(graph, renderer);
}
// Apply search
if (urlParams.has('search')) {
const searchVal = urlParams.get('search');
const searchInput = document.getElementById('search-input');
if (searchInput) {
searchInput.value = searchVal;
// Dispatch input event to trigger search handler
searchInput.dispatchEvent(new Event('input', { bubbles: true }));
}
}
// Apply node selection
if (urlParams.has('node')) {
const nodeId = urlParams.get('node');
if (graph.hasNode(nodeId)) {
selectedNode = nodeId;
// Update sidebar
const nodeAttributes = graph.getNodeAttributes(nodeId);
sidebarManager.updateNodeInfo({ node: nodeId, attributes: nodeAttributes });
// Refresh renderer to apply visual reducers (graying out non-connected)
renderer.refresh();
// Animate camera to center on the selected node
const nodePosition = renderer.getNodeDisplayData(nodeId);
if (nodePosition) {
renderer.getCamera().animate(
{ x: nodePosition.x, y: nodePosition.y, ratio: 0.3 },
{ duration: TIMING.ZOOM_ANIMATION }
);
}
}
}
} catch (error) {
console.warn('Error applying URL parameters:', error);
}
}
// =============================================================================
// CLEANUP FUNCTION
// =============================================================================
/**
* Destroys the current visualization and cleans up all resources
* Call this before loading a new dataset to prevent memory leaks and conflicts
*/
async function destroyVisualization() {
console.log('🧹 Destroying current visualization...');
// Stop any running layout
if (currentLayoutManager && currentLayoutManager.isRunning) {
const toggleBtn = document.getElementById('toggle-layout');
if (toggleBtn) {
currentLayoutManager.stop(toggleBtn);
}
}
// Clear layout manager reference
currentLayoutManager = null;
// Destroy the Sigma renderer
if (currentRenderer) {
try {
currentRenderer.kill();
console.log('✅ Renderer destroyed');
} catch (e) {
console.warn('⚠️ Error killing renderer:', e);
}
currentRenderer = null;
}
// Remove the canvas element if it exists
const graphContainer = document.getElementById('graph-container');
const canvases = graphContainer.querySelectorAll('canvas');
canvases.forEach(canvas => {
canvas.remove();
console.log('✅ Canvas removed');
});
// Reset global state
selectedNode = null;
currentGraph = null; // Clear graph reference
// Reset summary display
const nodesCountEl = document.getElementById('summary-nodes-count');
const channelsCountEl = document.getElementById('summary-channels-count');
if (nodesCountEl) nodesCountEl.textContent = '0';
if (channelsCountEl) nodesCountEl.textContent = '0';
// Clear search input
const searchInput = document.getElementById('search-input');
if (searchInput) {
searchInput.value = '';
}
// Reset sidebar
const nodeInfo = document.getElementById('node-info');
const edgeInfo = document.getElementById('edge-info');
if (nodeInfo) {
nodeInfo.innerHTML = `
<div class="info-title">Node Information</div>
<div class="info-content">Select a node to see details</div>
`;
}
if (edgeInfo) {
edgeInfo.innerHTML = `
<div class="info-title">Channel Information</div>
<div class="info-content">Select a channel to see details</div>
`;
}
// Wait a moment for everything to clean up
await new Promise(resolve => setTimeout(resolve, 100));
console.log('✅ Cleanup complete');
}
// =============================================================================
// DATA PROCESSING UTILITIES
// =============================================================================
/**
* Calculates comprehensive statistics including percentiles for capacity and channels
* Works with the new enhanced data format (snake_case fields)
* @param {Array} nodes - Array of Lightning Network nodes
* @param {Array} edges - Array of Lightning Network channels
* @returns {Object} Enhanced statistics object with min/max values, percentiles, and total capacity
*/
function calculateDataStats(nodes, edges) {
/**
* Helper function to calculate percentiles from a sorted array
* @param {Array} sortedArray - Pre-sorted array of numbers
* @returns {Object} Statistics object with min, max, percentiles, and average
*/
function calculatePercentiles(sortedArray) {
const len = sortedArray.length;
if (len === 0) return { min: 0, q25: 0, median: 0, q75: 0, max: 0, avg: 0 };
const min = sortedArray[0];
const max = sortedArray[len - 1];
// Calculate percentile indices
const q25Index = Math.max(0, Math.floor((len - 1) * 0.25));
const medianIndex = Math.max(0, Math.floor((len - 1) * 0.50));
const q75Index = Math.max(0, Math.floor((len - 1) * 0.75));
const q25 = sortedArray[q25Index];
const median = sortedArray[medianIndex];
const q75 = sortedArray[q75Index];
// Calculate average
const sum = sortedArray.reduce((total, val) => total + val, 0);
const avg = sum / len;
return { min, q25, median, q75, max, avg };
}
// 1. Channel size distribution (from edges)
const channelSizes = edges
.map(edge => edge.capacity || 0)
.filter(capacity => capacity > 0)
.sort((a, b) => a - b);
const channelSizeStats = calculatePercentiles(channelSizes);
// 2. Node channel count distribution
const nodeChannels = nodes
.map(node => node.total_channels || 0)
.filter(channels => channels > 0)
.sort((a, b) => a - b);
const channelStats = calculatePercentiles(nodeChannels);
// 3. Node capacity distribution
const nodeCapacities = nodes
.map(node => node.total_capacity || 0)
.filter(capacity => capacity > 0)
.sort((a, b) => a - b);
const nodeCapacityStats = calculatePercentiles(nodeCapacities);
// 4. Node betweenness distribution
const nodeBetweenness = nodes
.map(node => node.node_betweenness || 0)
.filter(betweenness => betweenness > 0)
.sort((a, b) => a - b);
const betweennessStats = calculatePercentiles(nodeBetweenness);
// Calculate total capacity from node totals
const totalCapacity = nodeCapacities.reduce((sum, capacity) => sum + capacity, 0) / 2;
// Return enhanced statistics object
return {
nodes: {
min: channelStats.min || 1,
max: channelStats.max || 1
},
edges: {
min: channelSizeStats.min || 1,
max: channelSizeStats.max || 1
},
totalCapacity: totalCapacity,
channelSize: {
min: channelSizeStats.min,
q25: channelSizeStats.q25,
median: channelSizeStats.median,
q75: channelSizeStats.q75,
max: channelSizeStats.max,
avg: channelSizeStats.avg,
count: channelSizes.length
},
channels: {
min: channelStats.min,
q25: channelStats.q25,
median: channelStats.median,
q75: channelStats.q75,
max: channelStats.max,
avg: channelStats.avg,
count: nodeChannels.length
},
nodeCapacity: {
min: nodeCapacityStats.min,
q25: nodeCapacityStats.q25,
median: nodeCapacityStats.median,
q75: nodeCapacityStats.q75,
max: nodeCapacityStats.max,
avg: nodeCapacityStats.avg,
count: nodeCapacities.length
},
betweenness: {
min: betweennessStats.min,
q25: betweennessStats.q25,
median: betweennessStats.median,
q75: betweennessStats.q75,
max: betweennessStats.max,
avg: betweennessStats.avg,
count: nodeBetweenness.length
}
};
}
/**
* Creates reusable calculators for consistent node/edge sizing across the graph
* Node size based on channel count (more intuitive for Lightning Network)
* Edge width based on channel capacity
* Uses logarithmic scaling to handle wide range of values
* Optimized for large graphs (40k+ edges) following Sigma.js demo best practices
* @param {Object} dataStats - Pre-calculated statistics from calculateDataStats
* @returns {Object} Calculator functions for nodeSize and edgeWidth
*/
function createSizeCalculators(dataStats) {
const { nodes: nodeStats, edges: edgeStats } = dataStats;
// Sigma.js demo sizing for large graphs with 40k+ edges
const NODE_SIZE_RANGE = { min: 2, max: 20 }; // Nodes: 2-10px (smaller for dense graphs)
const EDGE_WIDTH_RANGE = { min: 0.1, max: 2 }; // Edges: 0.5-2px (thin for visual clarity)
return {
nodeSize: (totalChannels) => {
// Use channel count for sizing - more intuitive for Lightning Network
if (!totalChannels || !nodeStats.max) return NODE_SIZE_RANGE.min;
const normalizedValue = (Math.log(Math.max(totalChannels, 1)) - Math.log(Math.max(nodeStats.min, 1))) /
(Math.log(nodeStats.max) - Math.log(Math.max(nodeStats.min, 1)));
return NODE_SIZE_RANGE.min + normalizedValue * (NODE_SIZE_RANGE.max - NODE_SIZE_RANGE.min);
},
edgeWidth: (capacity) => {
// Use capacity-based sizing for channels
if (!capacity || !edgeStats.max) return EDGE_WIDTH_RANGE.min;
const normalizedValue = (Math.log(Math.max(capacity, 1)) - Math.log(Math.max(edgeStats.min, 1))) /
(Math.log(edgeStats.max) - Math.log(Math.max(edgeStats.min, 1)));
return EDGE_WIDTH_RANGE.min + normalizedValue * (EDGE_WIDTH_RANGE.max - EDGE_WIDTH_RANGE.min);
}
};
}
/**
* Converts satoshi amounts to Lightning Network standard display format
* Uses BTC for larger amounts (≥ 0.01 BTC) with sats conversion, and short form sats for smaller amounts
* @param {number} capacity - Capacity in satoshis
* @returns {string} Formatted capacity string with unit
*/
function formatCapacity(capacity) {
if (!capacity) return '0 sats';
// Lightning Network threshold: 0.01 BTC = 1,000,000 satoshis
const LIGHTNING_BTC_THRESHOLD = 1000000;
if (capacity >= LIGHTNING_BTC_THRESHOLD) {
const btcValue = capacity / CAPACITY_THRESHOLDS.BTC;
// Format sats in short form
let satsShort;
if (capacity >= 1000000000) {
satsShort = `${(capacity / 1000000000).toFixed(1)}B sats`;
} else if (capacity >= 1000000) {
satsShort = `${(capacity / 1000000).toFixed(1)}M sats`;
} else {
satsShort = `${(capacity / 1000).toFixed(0)}K sats`;
}
// For amounts ≥ 1 BTC, show 2 decimal places
if (capacity >= CAPACITY_THRESHOLDS.BTC) {
return `${btcValue.toFixed(2)} BTC (${satsShort})`;
}
// For amounts 0.01 - 1 BTC, show 3 decimal places
else {
return `${btcValue.toFixed(3)} BTC (${satsShort})`;
}
} else {
// For small amounts, show in short form satoshis only
if (capacity >= 1000) {
return `${(capacity / 1000).toFixed(0)}K sats`;
} else {
return `${capacity} sats`;
}
}
}
// =============================================================================
// EDGE COLORING SYSTEM
// =============================================================================
/**
* Gets edge color based on enhanced data attributes
* Uses pre-calculated colors from data when available
* @param {Object} edge - Edge data object
* @returns {string} Color hex code
*/
function getEdgeColor(edge) {
// Highlight important bridge channels
if (edge.is_important_bridge_channel) {
return EDGE_HIGHLIGHT.IMPORTANT_BRIDGE;
}
// Highlight regular bridge channels
if (edge.is_bridge_channel) {
return EDGE_HIGHLIGHT.REGULAR_BRIDGE;
}
// Default color
return EDGE_HIGHLIGHT.DEFAULT;
}
/**
* Gets node color based on cluster or pre-calculated color
* @param {Object} node - Node data object
* @returns {string} Color hex code
*/
function getNodeColor(node) {
// Use cluster-based coloring
if (node.cluster !== undefined && node.cluster !== null) {
return CLUSTER_COLORS[node.cluster] || CLUSTER_COLORS.DEFAULT;
}
// Default color
return CLUSTER_COLORS.DEFAULT;
}
// =============================================================================
// MAIN FUNCTIONS
// =============================================================================
/**
* Entry point: Loads JSON data from server and initializes the visualization
* Handles network errors and displays error messages to user
* @param {string} jsonFile - Path to JSON file containing graph data
* @returns {Promise} Resolves when visualization is complete
*/
async function initVisualization(jsonFile) {
// Destroy any existing visualization before creating a new one
await destroyVisualization();
// Load the JSON data
return fetch(jsonFile)
.then(response => {
if (!response.ok) {
throw new Error(`Failed to load ${jsonFile}: ${response.status} ${response.statusText}`);
}
return response.json();
})
.then(data => {
// Initialize the visualization with the loaded data
createVisualization(data, jsonFile);
console.log('📈 Visualization created');
})
.catch(error => {
console.error('Error loading JSON data:', error);
const graphContainer = document.getElementById('graph-container');
if (graphContainer) {
graphContainer.innerHTML =
`<div style="padding: 20px; color: red;">Error loading data: ${error.message}</div>`;
}
throw error;
});
}
// =============================================================================
// TOOLTIP AND SIDEBAR MANAGEMENT
// =============================================================================
/**
* Manages tooltip display and positioning for node/edge hover effects
* Shows enhanced network analysis metrics
* @param {HTMLElement} tooltipElement - DOM element for tooltip display
* @returns {Object} API for tooltip operations
*/
function createTooltipManager(tooltipElement) {
let currentHover = null;
function show(content, event) {
currentHover = true;
tooltipElement.innerHTML = content;
tooltipElement.style.display = 'block';
position(event);
}
function hide() {
currentHover = null;
tooltipElement.style.display = 'none';
}
function position(event) {
const x = event.x + TIMING.TOOLTIP_OFFSET;
const y = event.y + TIMING.TOOLTIP_OFFSET;
tooltipElement.style.left = x + 'px';
tooltipElement.style.top = y + 'px';
}
function createNodeTooltip(nodeAttributes) {
const attrs = nodeAttributes.attributes;
let bridgeInfo = '';
if (attrs.isImportantBridgeNode) {
bridgeInfo = '<div style="color: #EF4444; font-weight: bold;">🌉 Critical Bridge Node</div>';
} else if (attrs.isBridgeNode) {
bridgeInfo = '<div style="color: #FB923C; font-weight: bold;">🌉 Bridge Node</div>';
}
return `
<div><strong>${nodeAttributes.label}</strong></div>
${bridgeInfo}
<div>Capacity: ${attrs.totalCapacity}</div>
<div>Channels: ${attrs.totalChannels}</div>
<div>Pleb Rank: ${attrs.plebRank}</div>
<div>Type: ${attrs.nodeType || 'Unknown'}</div>
`;
}
function createEdgeTooltip(edgeAttributes, graph, edgeId) {
const attrs = edgeAttributes.attributes;
const sourceNode = graph.getNodeAttributes(graph.source(edgeId));
const targetNode = graph.getNodeAttributes(graph.target(edgeId));
let bridgeInfo = '';
if (attrs.isImportantBridgeChannel) {
bridgeInfo = '<div style="color: #B0B0B0; font-weight: bold;">🌉 Critical Bridge Channel</div>';
} else if (attrs.isBridgeChannel) {
bridgeInfo = '<div style="color: #C8C8C8; font-weight: bold;">🌉 Bridge Channel</div>';
}
// Multi-channel information (show when channel_count > 1)
let channelInfo = '';
const channelCount = attrs.channelCount;
const channels = attrs.channels;
if (channelCount && channelCount > 1 && channels && Array.isArray(channels)) {
// Multiple channels
let individualChannels = '';
channels.forEach((channel, index) => {
const birthTx = channel.birth_tx || 'N/A';
individualChannels += `
<div style="margin-bottom: 4px;">
<div><strong>Channel ${index + 1}</strong></div>
<div style="margin-left: 8px;">Capacity: ${formatCapacity(channel.capacity)}</div>
<div style="margin-left: 8px;">Birth Tx: ${birthTx}</div>
</div>
`;
});
channelInfo = `
<div style="margin-top: 5px; padding: 5px; background: rgba(96, 165, 250, 0.1); border-left: 2px solid #60A5FA;">
<div style="font-weight: bold; color: #60A5FA;">Multi-Channel (${channelCount})</div>
${individualChannels}
</div>
`;
} else {
// Single channel - get birth_tx from first channel in array or from edge ID
let birthTx = 'N/A';
if (channels && Array.isArray(channels) && channels.length > 0) {
birthTx = channels[0].birth_tx || 'N/A';
}
channelInfo = `<div>Birth Tx: ${birthTx}</div>`;
}
return `
<div><strong>Channel</strong></div>
${bridgeInfo}
<div>From: ${sourceNode.label}</div>
<div>To: ${targetNode.label}</div>
<div>Capacity: ${formatCapacity(attrs.capacity)}</div>
${channelInfo}
`;
}
return { show, hide, position, createNodeTooltip, createEdgeTooltip, get currentHover() { return currentHover; } };
}
/**
* Manages sidebar information panel updates when nodes/edges are clicked
* Shows enhanced network analysis metrics
* @returns {Object} API for sidebar operations
*/
function createSidebarManager() {
function getCategoryDefinition(category) {
const definitions = {
'Freeway': ' (> 1 BTC channel)',
'Highway': ' (> 5M sats channel)',
'My Way': ' (other)'
};
return definitions[category] || '';
}
function updateNodeInfo(nodeAttributes) {
const attrs = nodeAttributes.attributes;
let categoryCountsHtml = '';
try {
const categoryCountsObj = typeof attrs.categoryCount === 'string'
? JSON.parse(attrs.categoryCount)
: attrs.categoryCount;
if (categoryCountsObj && typeof categoryCountsObj === 'object') {
for (const [category, count] of Object.entries(categoryCountsObj)) {
const definition = getCategoryDefinition(category);
categoryCountsHtml += `<div><span class="info-label">${category}${definition}:</span> ${count}</div>`;
}
} else {
categoryCountsHtml = `<div>${attrs.categoryCount || 'N/A'}</div>`;
}
} catch (e) {
categoryCountsHtml = `<div>${attrs.categoryCount || 'N/A'}</div>`;
}
// Bridge node information
let bridgeInfo = '';
if (attrs.isImportantBridgeNode) {
bridgeInfo = `
<div style="margin-top: 10px; padding: 10px; background: rgba(239, 68, 68, 0.1); border-left: 3px solid #EF4444;">
<div style="font-weight: bold; color: #EF4444;">🌉 Critical Bridge Node</div>
<div><span class="info-label">Bridges Clusters:</span> ${attrs.bridgesClusters || 'N/A'}</div>
<div><span class="info-label">Cluster Connections:</span> ${attrs.clusterConnections || 'N/A'}</div>
</div>
`;
} else if (attrs.isBridgeNode) {
bridgeInfo = `
<div style="margin-top: 10px; padding: 10px; background: rgba(251, 146, 60, 0.1); border-left: 3px solid #FB923C;">
<div style="font-weight: bold; color: #FB923C;">🌉 Bridge Node</div>
<div><span class="info-label">Bridges Clusters:</span> ${attrs.bridgesClusters || 'N/A'}</div>
<div><span class="info-label">Cluster Connections:</span> ${attrs.clusterConnections || 'N/A'}</div>
</div>
`;
}
// Cluster information
let clusterInfo = '';
if (attrs.cluster !== undefined && attrs.cluster !== null) {
clusterInfo = `<div><span class="info-label">Cluster:</span> ${attrs.cluster}</div>`;
}
// Closed channels
let closedChannelsInfo = '';
if (attrs.closedChannelsCount !== undefined && attrs.closedChannelsCount !== null) {
closedChannelsInfo = `<div><span class="info-label">Closed Channels:</span> ${attrs.closedChannelsCount}</div>`;
}
document.getElementById('node-info').innerHTML = `
<div class="info-title">${nodeAttributes.label}</div>
<div class="info-content">
${clusterInfo}
<div><span class="info-label">Type:</span> ${attrs.nodeType || 'Unknown'}</div>
<div><span class="info-label">Total Capacity:</span> ${attrs.totalCapacity}</div>
<div><span class="info-label">Total Channels:</span> ${attrs.totalChannels}</div>
${closedChannelsInfo}
<div><span class="info-label">Pleb Rank:</span> ${attrs.plebRank}</div>
<div><span class="info-label">Capacity Rank:</span> ${attrs.capacityRank}</div>
<div><span class="info-label">Channels Rank:</span> ${attrs.channelsRank}</div>
<div><span class="info-label">Public Key:</span> ${attrs.pubKey}</div>
<div><span class="info-label">Birth Transaction:</span> ${attrs.birthTx || 'N/A'}</div>
${bridgeInfo}
<div style="margin-top: 10px;"><span class="info-label">Channel Categories:</span></div>
${categoryCountsHtml}
</div>
`;
}
function updateEdgeInfo(edgeAttributes, graph, edgeId) {