-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
3368 lines (2911 loc) · 158 KB
/
app.js
File metadata and controls
3368 lines (2911 loc) · 158 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
// State
const allEvents = [];
let timeRange = { start: 0, end: 0 };
let isLive = true;
let currentTime = Date.now() * 1_000_000;
let ws = null;
let reconnectTimeout = null;
let isDragging = false;
let filterText = '';
let selectedEvent = null;
let hoveredEvent = null; // Event currently being hovered for peer highlighting
let highlightedPeers = new Set();
let selectedPeerId = null; // For filtering events by peer
let selectedTxId = null; // For filtering events by transaction
let gatewayPeerId = null; // Gateway peer ID
let yourPeerId = null; // User's own peer ID
let yourIpHash = null; // User's IP hash
let youArePeer = false; // Whether user's IP matches a network peer
let yourName = null; // User's peer name (if set)
let peerNames = {}; // ip_hash -> name for all peers
let contractData = {}; // contract_key -> contract data (subscriptions, states, etc.)
let contractStates = {}; // contract_key -> {peer_id -> {hash, timestamp}}
let propagationData = {}; // contract_key -> {hash, first_seen, propagation_ms, peer_count, timeline}
let selectedContract = null; // Currently selected contract
let contractSearchText = ''; // Search filter for contracts
let opStats = null; // Operation statistics
let displayedEvents = []; // Events currently shown in the events panel
let allTransactions = []; // Transactions for timeline lanes
const transactionMap = new Map(); // tx_id -> index in allTransactions for quick lookup
let selectedTransaction = null; // Currently selected transaction for detail view
let initialStatePeers = []; // Peers from initial state message
let initialStateConnections = []; // Connections from initial state message
let peerLifecycle = null; // Peer lifecycle data (version, arch, OS)
let peerPresence = []; // Peer presence timeline for historical reconstruction
// Performance: RAF-based update batching (max 60fps)
let updateScheduled = false;
let pendingTimelineMarkers = []; // Queue timeline markers for batch insertion
// Performance: Cache state to avoid unnecessary rebuilds
let lastSvgState = null; // Serialized state for comparison
let lastEventsState = null; // Cache for events panel
let lastSvgRebuildTime = 0; // Throttle SVG rebuilds (expensive)
const SVG_REBUILD_INTERVAL_MS = 1000; // Max 1 SVG rebuild per second (topology doesn't change fast)
// Performance: Cache filtered events (avoid filtering 28k events every frame)
let cachedNearbyEvents = [];
let cachedFilterKey = null;
// Performance: Cache detail timeline state
let lastDetailTimelineKey = null;
// Performance: Canvas overlay for lightweight hover effects (separate from heavy SVG)
let hoverCanvas = null;
let hoverCtx = null;
let lastHoverState = null;
const SVG_SIZE = 450;
const SVG_WIDTH = 530; // Extra width for chart
const CENTER = SVG_SIZE / 2;
const RADIUS = 175;
// Performance: Track last update time for throttling
let lastUpdateTime = 0;
const MIN_UPDATE_INTERVAL_MS = 100; // Max 10 updates per second for background updates
// Schedule an update via requestAnimationFrame (batches multiple updates per frame)
function scheduleUpdate(isUserInteraction = false) {
if (updateScheduled) return;
// Throttle background updates (new events) to 10fps max
// User interactions (hover, click) get immediate updates
if (!isUserInteraction) {
const now = performance.now();
if (now - lastUpdateTime < MIN_UPDATE_INTERVAL_MS) {
// Schedule a delayed update instead
setTimeout(() => {
updateScheduled = false;
scheduleUpdate(false);
}, MIN_UPDATE_INTERVAL_MS);
updateScheduled = true;
return;
}
}
updateScheduled = true;
requestAnimationFrame(() => {
updateScheduled = false;
lastUpdateTime = performance.now();
// Flush pending timeline markers in batch
flushTimelineMarkers();
updateView();
});
}
// Batch insert timeline markers (avoid per-event DOM manipulation)
const MAX_TIMELINE_MARKERS = 500; // Limit DOM nodes in timeline
function flushTimelineMarkers() {
if (pendingTimelineMarkers.length === 0) return;
const container = document.getElementById('timeline-events');
if (!container) return;
const fragment = document.createDocumentFragment();
const duration = timeRange.end - timeRange.start;
if (duration <= 0) {
pendingTimelineMarkers.length = 0;
return;
}
for (const data of pendingTimelineMarkers) {
const pos = (data.timestamp - timeRange.start) / duration;
if (pos < 0 || pos > 1) continue;
const marker = document.createElement('div');
marker.className = `timeline-marker ${getEventClass(data.event_type)}`;
marker.style.left = `${pos * 100}%`;
marker.style.height = '20px';
marker.style.top = '30px';
marker.title = `${data.time_str} - ${data.event_type}`;
fragment.appendChild(marker);
}
container.appendChild(fragment);
pendingTimelineMarkers.length = 0;
// Limit total markers to prevent DOM bloat
const markers = container.querySelectorAll('.timeline-marker');
if (markers.length > MAX_TIMELINE_MARKERS) {
const toRemove = markers.length - MAX_TIMELINE_MARKERS;
for (let i = 0; i < toRemove; i++) {
markers[i].remove();
}
}
}
function getEventClass(eventType) {
if (!eventType) return 'other';
// Handle specific connect event types
if (eventType.includes('connect') || eventType === 'start_connection' || eventType === 'finished') return 'connect';
if (eventType.includes('put')) return 'put';
if (eventType.includes('get')) return 'get';
if (eventType.includes('update') || eventType.includes('broadcast')) return 'update';
if (eventType.includes('subscrib')) return 'subscribe';
return 'other';
}
function getEventLabel(eventType) {
// Return user-friendly labels for event types
const labels = {
'start_connection': 'connecting',
'connected': 'connected',
'finished': 'conn done',
'put_request': 'put req',
'put_success': 'put ok',
'get_request': 'get req',
'get_success': 'get ok',
'get_not_found': 'get 404',
'update_request': 'update req',
'update_success': 'update ok',
'subscribe_request': 'sub req',
'subscribed': 'subscribed',
'broadcast_emitted': 'broadcast',
'broadcast_applied': 'applied',
};
return labels[eventType] || eventType;
}
function locationToXY(location) {
const angle = location * 2 * Math.PI - Math.PI / 2;
return { x: CENTER + RADIUS * Math.cos(angle), y: CENTER + RADIUS * Math.sin(angle) };
}
// Initialize hover overlay canvas (lightweight updates separate from heavy SVG)
function initHoverCanvas() {
const container = document.getElementById('ring-container');
if (!container || hoverCanvas) return;
hoverCanvas = document.createElement('canvas');
hoverCanvas.width = SVG_WIDTH;
hoverCanvas.height = SVG_SIZE;
hoverCanvas.style.cssText = 'position:absolute;top:0;left:0;pointer-events:none;z-index:10;';
hoverCtx = hoverCanvas.getContext('2d');
container.style.position = 'relative';
container.appendChild(hoverCanvas);
}
// Update hover highlights on canvas (very fast, no DOM manipulation)
function updateHoverCanvas(peers) {
if (!hoverCtx || !hoveredEvent) {
if (hoverCtx) hoverCtx.clearRect(0, 0, SVG_WIDTH, SVG_SIZE);
return;
}
// Build set of peers to highlight
const highlightSet = new Set();
if (hoveredEvent.peer_id) highlightSet.add(hoveredEvent.peer_id);
if (hoveredEvent.from_peer) highlightSet.add(hoveredEvent.from_peer);
if (hoveredEvent.to_peer) highlightSet.add(hoveredEvent.to_peer);
if (hoveredEvent.connection) {
highlightSet.add(hoveredEvent.connection[0]);
highlightSet.add(hoveredEvent.connection[1]);
}
// Check if we need to redraw
const hoverState = Array.from(highlightSet).sort().join(',');
if (hoverState === lastHoverState) return;
lastHoverState = hoverState;
// Clear and redraw highlights
hoverCtx.clearRect(0, 0, SVG_WIDTH, SVG_SIZE);
peers.forEach((peer, id) => {
if (!highlightSet.has(id)) return;
const pos = locationToXY(peer.location);
// Glow effect
hoverCtx.beginPath();
hoverCtx.arc(pos.x, pos.y, 12, 0, Math.PI * 2);
hoverCtx.fillStyle = 'rgba(251, 191, 36, 0.4)';
hoverCtx.fill();
// Highlight circle
hoverCtx.beginPath();
hoverCtx.arc(pos.x, pos.y, 6, 0, Math.PI * 2);
hoverCtx.fillStyle = '#fbbf24';
hoverCtx.fill();
// Draw radial label for hovered peers
const peerName = peer.ip_hash ? peerNames[peer.ip_hash] : null;
const hoverLabel = peerName || (peer.ip_hash ? `#${peer.ip_hash}` : id.substring(0, 10));
const angle = peer.location * 2 * Math.PI - Math.PI / 2;
const labelR = RADIUS + 18;
const lx = CENTER + labelR * Math.cos(angle);
const ly = CENTER + labelR * Math.sin(angle);
const onLeft = Math.cos(angle) < 0;
const rotation = onLeft ? angle + Math.PI : angle;
hoverCtx.save();
hoverCtx.translate(lx, ly);
hoverCtx.rotate(rotation);
hoverCtx.font = 'bold 10px JetBrains Mono, monospace';
hoverCtx.fillStyle = '#fbbf24';
hoverCtx.textAlign = onLeft ? 'end' : 'start';
hoverCtx.textBaseline = 'middle';
hoverCtx.fillText(hoverLabel, 0, 0);
hoverCtx.restore();
});
// Draw message flow arrow if from/to peers exist
if (hoveredEvent.from_peer && hoveredEvent.to_peer && hoveredEvent.from_peer !== hoveredEvent.to_peer) {
const fromPeer = peers.get(hoveredEvent.from_peer);
const toPeer = peers.get(hoveredEvent.to_peer);
const fromLoc = fromPeer?.location ?? hoveredEvent.from_location;
const toLoc = toPeer?.location ?? hoveredEvent.to_location;
if (fromLoc != null && toLoc != null) {
const fromPos = locationToXY(fromLoc);
const toPos = locationToXY(toLoc);
// Shorten arrow to not overlap nodes
const dx = toPos.x - fromPos.x;
const dy = toPos.y - fromPos.y;
const dist = Math.sqrt(dx*dx + dy*dy);
if (dist > 20) {
const x1 = fromPos.x + dx * (15/dist);
const y1 = fromPos.y + dy * (15/dist);
const x2 = fromPos.x + dx * (1 - 20/dist);
const y2 = fromPos.y + dy * (1 - 20/dist);
hoverCtx.beginPath();
hoverCtx.moveTo(x1, y1);
hoverCtx.lineTo(x2, y2);
hoverCtx.strokeStyle = '#fbbf24';
hoverCtx.lineWidth = 2;
hoverCtx.stroke();
// Arrow head
const angle = Math.atan2(dy, dx);
hoverCtx.beginPath();
hoverCtx.moveTo(x2, y2);
hoverCtx.lineTo(x2 - 8*Math.cos(angle - 0.4), y2 - 8*Math.sin(angle - 0.4));
hoverCtx.lineTo(x2 - 8*Math.cos(angle + 0.4), y2 - 8*Math.sin(angle + 0.4));
hoverCtx.closePath();
hoverCtx.fillStyle = '#fbbf24';
hoverCtx.fill();
}
}
}
}
// Convert state hash to deterministic HSL color
function hashToColor(hash) {
if (!hash) return null;
// Use first 6 chars of hash for hue (0-360)
const hue = parseInt(hash.substring(0, 6), 16) % 360;
return {
fill: `hsl(${hue}, 70%, 50%)`,
glow: `hsla(${hue}, 70%, 50%, 0.3)`
};
}
// Base58 alphabet (Bitcoin style)
const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
// Decode Base58 string to byte array
function decodeBase58(str) {
const bytes = [];
for (let i = 0; i < str.length; i++) {
const c = str[i];
const charIndex = BASE58_ALPHABET.indexOf(c);
if (charIndex === -1) continue; // Skip invalid chars
let carry = charIndex;
for (let j = 0; j < bytes.length; j++) {
carry += bytes[j] * 58;
bytes[j] = carry & 0xff;
carry >>= 8;
}
while (carry > 0) {
bytes.push(carry & 0xff);
carry >>= 8;
}
}
// Handle leading '1's (zeros in Base58)
for (let i = 0; i < str.length && str[i] === '1'; i++) {
bytes.push(0);
}
return bytes.reverse();
}
// Convert contract key to ring location (matches Rust implementation)
function contractKeyToLocation(contractKey) {
if (!contractKey) return null;
const bytes = decodeBase58(contractKey);
if (bytes.length === 0) return null;
let value = 0.0;
let divisor = 256.0;
for (const byte of bytes) {
value += byte / divisor;
divisor *= 256.0;
}
return Math.min(Math.max(value, 0.0), 1.0);
}
// Calculate contract activity stats from events
function getContractActivity(contractKey) {
const contractEvents = allEvents.filter(e =>
e.contract_full === contractKey &&
(e.event_type === 'update_success' || e.event_type === 'update_broadcast_received' ||
e.event_type === 'put_success' || e.event_type === 'put_broadcast_received')
);
if (contractEvents.length === 0) {
return { lastUpdate: null, totalUpdates: 0, recentUpdates: 0 };
}
// Sort by timestamp descending to get latest
contractEvents.sort((a, b) => b.timestamp - a.timestamp);
const lastUpdate = contractEvents[0].timestamp;
const totalUpdates = contractEvents.length;
// Count recent updates (within 1 hour)
const oneHourAgo = Date.now() * 1_000_000 - (60 * 60 * 1000 * 1_000_000);
const recentUpdates = contractEvents.filter(e => e.timestamp > oneHourAgo).length;
return { lastUpdate, totalUpdates, recentUpdates };
}
// Compute proximity links: connected peers that both have the contract
// but may not be in the subscription tree (they can still exchange updates)
function computeProximityLinks(contractKey, peers, connections) {
if (!contractKey || !contractData[contractKey]) return [];
const subData = contractData[contractKey];
const peerStates = subData.peer_states || [];
// Build set of peer_ids that have this contract
const peersWithContract = new Set();
peerStates.forEach(ps => {
if (ps.peer_id) peersWithContract.add(ps.peer_id);
});
// Build set of subscription tree edges (for exclusion)
const subscriptionEdges = new Set();
const tree = subData.tree || {};
Object.entries(tree).forEach(([fromId, toIds]) => {
toIds.forEach(toId => {
// Store both directions since we check undirected
subscriptionEdges.add(`${fromId}|${toId}`);
subscriptionEdges.add(`${toId}|${fromId}`);
});
});
// Find proximity links: connections where both peers have the contract
// but aren't connected via subscription tree
const proximityLinks = [];
connections.forEach(connKey => {
const [id1, id2] = connKey.split('|');
const peer1 = peers.get(id1);
const peer2 = peers.get(id2);
if (!peer1 || !peer2) return;
// Check if both peers have the contract (using peer_id from topology)
const p1HasContract = peer1.peer_id && peersWithContract.has(peer1.peer_id);
const p2HasContract = peer2.peer_id && peersWithContract.has(peer2.peer_id);
if (p1HasContract && p2HasContract) {
// Check if this isn't already a subscription edge
// Need to map topology IDs to peer_ids for comparison
const edgeKey1 = `${peer1.peer_id}|${peer2.peer_id}`;
const edgeKey2 = `${peer2.peer_id}|${peer1.peer_id}`;
if (!subscriptionEdges.has(edgeKey1) && !subscriptionEdges.has(edgeKey2)) {
proximityLinks.push({ from: id1, to: id2, fromPeerId: peer1.peer_id, toPeerId: peer2.peer_id });
}
}
});
return proximityLinks;
}
// Check if subscription tree is connected using BFS
function checkTreeConnectivity(contractKey, peers) {
if (!contractKey || !contractData[contractKey]) {
return { connected: true, segments: 1, nodes: 0 };
}
const subData = contractData[contractKey];
const peerStates = subData.peer_states || [];
const tree = subData.tree || {};
if (peerStates.length === 0) {
return { connected: true, segments: 0, nodes: 0 };
}
// Build adjacency list (undirected) from subscription tree
const adjacency = new Map();
const allNodes = new Set();
// Add all peers with this contract as nodes
peerStates.forEach(ps => {
if (ps.peer_id) {
allNodes.add(ps.peer_id);
if (!adjacency.has(ps.peer_id)) adjacency.set(ps.peer_id, new Set());
}
});
// Add edges from tree (bidirectional)
Object.entries(tree).forEach(([fromId, toIds]) => {
if (!adjacency.has(fromId)) adjacency.set(fromId, new Set());
toIds.forEach(toId => {
if (!adjacency.has(toId)) adjacency.set(toId, new Set());
adjacency.get(fromId).add(toId);
adjacency.get(toId).add(fromId);
allNodes.add(fromId);
allNodes.add(toId);
});
});
if (allNodes.size === 0) {
return { connected: true, segments: 0, nodes: 0 };
}
// BFS to find connected components
const visited = new Set();
let segments = 0;
const segmentSizes = [];
for (const startNode of allNodes) {
if (visited.has(startNode)) continue;
segments++;
let segmentSize = 0;
const queue = [startNode];
while (queue.length > 0) {
const node = queue.shift();
if (visited.has(node)) continue;
visited.add(node);
segmentSize++;
const neighbors = adjacency.get(node) || new Set();
for (const neighbor of neighbors) {
if (!visited.has(neighbor)) {
queue.push(neighbor);
}
}
}
segmentSizes.push(segmentSize);
}
return {
connected: segments <= 1,
segments: segments,
nodes: allNodes.size,
segmentSizes: segmentSizes
};
}
// Get comprehensive subscription tree info for UI display
function getSubscriptionTreeInfo(contractKey, peers, connections) {
const connectivity = checkTreeConnectivity(contractKey, peers);
const proximityLinks = computeProximityLinks(contractKey, peers, connections);
// Check if proximity links bridge the segments
let bridged = false;
if (!connectivity.connected && proximityLinks.length > 0) {
// Simplified check: if there are proximity links and tree is fragmented,
// assume they might bridge (full check would require segment analysis)
bridged = true;
}
return {
...connectivity,
proximityLinks: proximityLinks,
bridgedByProximity: bridged
};
}
function formatRelativeTime(tsNano) {
if (!tsNano) return null;
const now = Date.now();
const then = tsNano / 1_000_000;
const diffMs = now - then;
if (diffMs < 60000) return 'just now';
if (diffMs < 3600000) return `${Math.floor(diffMs / 60000)}m ago`;
if (diffMs < 86400000) return `${Math.floor(diffMs / 3600000)}h ago`;
return `${Math.floor(diffMs / 86400000)}d ago`;
}
function formatTime(tsNano) {
return new Date(tsNano / 1_000_000).toLocaleTimeString();
}
function formatDate(tsNano) {
return new Date(tsNano / 1_000_000).toLocaleDateString(undefined, {
month: 'short', day: 'numeric'
});
}
/**
* Render a small SVG sparkline showing propagation timeline.
* @param {Array} timeline - Array of {t: ms_offset, peers: count}
* @param {number} maxPeers - Total peer count at end
* @returns {string} SVG markup
*/
function renderPropagationSparkline(timeline, maxPeers) {
if (!timeline || timeline.length === 0) return '';
const width = 50;
const height = 14;
const padding = 1;
// Normalize timeline to fit in the sparkline
const maxT = Math.max(timeline[timeline.length - 1].t, 1);
const maxP = Math.max(maxPeers, 1);
// Build SVG path
const points = timeline.map(pt => {
const x = padding + (pt.t / maxT) * (width - 2 * padding);
const y = height - padding - (pt.peers / maxP) * (height - 2 * padding);
return `${x},${y}`;
});
// Create step function (horizontal then vertical for each point)
let pathD = `M ${points[0]}`;
for (let i = 1; i < points.length; i++) {
const [prevX, prevY] = points[i - 1].split(',').map(Number);
const [x, y] = points[i].split(',').map(Number);
// Step: horizontal to new x, then vertical to new y
pathD += ` H ${x} V ${y}`;
}
// Extend to the end if propagation finished before max time
const lastX = padding + (width - 2 * padding);
pathD += ` H ${lastX}`;
// Fill area under the curve
const fillPath = pathD + ` V ${height - padding} H ${padding} Z`;
return `
<svg class="sparkline-svg" viewBox="0 0 ${width} ${height}" preserveAspectRatio="none">
<path d="${fillPath}" class="sparkline-fill"/>
<path d="${pathD}" class="sparkline-line"/>
</svg>
`;
}
function renderRuler() {
const ruler = document.getElementById('timeline-ruler');
ruler.innerHTML = '';
if (timeRange.end <= timeRange.start) return;
const duration = timeRange.end - timeRange.start;
const durationMs = duration / 1_000_000;
const durationMin = durationMs / 60000;
// Determine appropriate tick interval
let tickInterval;
if (durationMin <= 10) tickInterval = 60000; // 1 min
else if (durationMin <= 30) tickInterval = 300000; // 5 min
else if (durationMin <= 60) tickInterval = 600000; // 10 min
else if (durationMin <= 120) tickInterval = 900000; // 15 min
else tickInterval = 1800000; // 30 min
const startMs = Math.ceil((timeRange.start / 1_000_000) / tickInterval) * tickInterval;
const endMs = timeRange.end / 1_000_000;
for (let ms = startMs; ms <= endMs; ms += tickInterval) {
const pos = ((ms * 1_000_000) - timeRange.start) / duration;
if (pos < 0 || pos > 1) continue;
const tick = document.createElement('div');
tick.className = 'timeline-tick' + ((ms % (tickInterval * 2) === 0) ? ' major' : '');
tick.style.position = 'absolute';
tick.style.left = `${pos * 100}%`;
tick.style.transform = 'translateX(-50%)';
const time = new Date(ms);
tick.textContent = time.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
ruler.appendChild(tick);
}
}
function showTransactionDetail(tx) {
// Toggle: clicking same transaction clears the filter
if (selectedTxId === tx.tx_id) {
selectedTxId = null;
selectedTransaction = null;
highlightedPeers.clear();
} else {
selectedTransaction = tx;
selectedTxId = tx.tx_id;
// Highlight all peers involved in this transaction
highlightedPeers.clear();
const events = tx.events || [];
events.forEach(evt => {
if (evt.peer_id) highlightedPeers.add(evt.peer_id);
if (evt.from_peer) highlightedPeers.add(evt.from_peer);
if (evt.to_peer) highlightedPeers.add(evt.to_peer);
});
// Switch to Events tab to show filtered events
switchTab('events');
}
updateFilterBar();
updateView(); // Refresh events list with filter
updateURL();
return; // Events box now shows transaction details, no popup needed
const container = document.getElementById('tx-detail-container');
const titleEl = document.getElementById('tx-detail-title');
const ganttEl = document.getElementById('tx-detail-gantt');
// Update title with op badge
const opClass = tx.op || 'other';
titleEl.innerHTML = `<span class="op-badge ${opClass}">${(tx.op || 'unknown').toUpperCase()}</span>` +
`<span>Transaction ${tx.tx_id.substring(0, 8)}...</span>`;
// Build summary
const duration = tx.duration_ms ? `${tx.duration_ms.toFixed(1)}ms` : 'pending';
const events = tx.events || [];
let summaryHtml = `<div class="tx-detail-summary">
<span>Duration: <strong>${duration}</strong></span>
<span>Events: <strong>${events.length}</strong></span>
<span>Status: <strong>${tx.status || 'unknown'}</strong></span>
${tx.contract ? `<span>Contract: <strong>${tx.contract}</strong></span>` : ''}
</div>`;
// Build Gantt chart of events
if (events.length === 0) {
ganttEl.innerHTML = summaryHtml + '<div style="color:var(--text-muted);padding:12px;">No event details available</div>';
} else {
// Sort events by timestamp
const sortedEvents = [...events].sort((a, b) => a.timestamp - b.timestamp);
const txStart = sortedEvents[0].timestamp;
const txEnd = sortedEvents[sortedEvents.length - 1].timestamp;
const txDuration = Math.max(txEnd - txStart, 1); // Avoid division by zero
let eventsHtml = '';
// Use transaction's operation type for dot color
const opType = tx.op || 'other';
sortedEvents.forEach((evt, idx) => {
const relativeTime = (evt.timestamp - txStart) / 1_000_000; // Convert to ms
// Determine dot color: use op type, but mark failures red
let dotClass = opType;
if (evt.event_type.includes('fail') || evt.event_type.includes('error')) {
dotClass = 'failed';
}
// Create descriptive label based on operation type and event
let eventLabel = evt.event_type.replace(/_/g, ' ');
if (opType === 'connect') {
if (idx === 0 && !evt.peer_id) {
eventLabel = 'Initiated';
} else if (evt.peer_id) {
eventLabel = `→ ${evt.peer_id.substring(0, 12)}`;
}
} else if (opType === 'put') {
if (evt.event_type === 'put_request') eventLabel = 'Request sent';
else if (evt.event_type === 'put_success') eventLabel = 'Stored ✓';
else if (evt.event_type.includes('fail')) eventLabel = 'Failed ✗';
} else if (opType === 'get') {
if (evt.event_type === 'get_request') eventLabel = 'Request sent';
else if (evt.event_type === 'get_success') eventLabel = 'Retrieved ✓';
else if (evt.event_type === 'get_not_found') eventLabel = 'Not found';
else if (evt.event_type.includes('fail')) eventLabel = 'Failed ✗';
} else if (opType === 'update') {
if (evt.event_type === 'update_request') eventLabel = 'Update sent';
else if (evt.event_type === 'update_success') eventLabel = 'Updated ✓';
else if (evt.event_type.includes('broadcast')) eventLabel = 'Broadcast';
} else if (opType === 'subscribe') {
if (evt.event_type === 'subscribe_request') eventLabel = 'Subscribe sent';
else if (evt.event_type === 'subscribed') eventLabel = 'Subscribed ✓';
}
// For non-connect ops, show peer if available
const showPeer = opType !== 'connect' && evt.peer_id;
const peerInfo = showPeer ? `<span class="tx-event-peer">${evt.peer_id.substring(0, 12)}</span>` : '';
eventsHtml += `<div class="tx-event-row">
<span class="tx-event-time">+${relativeTime.toFixed(1)}ms</span>
<span class="tx-event-dot ${dotClass}"></span>
<span class="tx-event-type">${eventLabel}</span>
${peerInfo}
</div>`;
});
ganttEl.innerHTML = summaryHtml + eventsHtml;
}
container.classList.add('visible');
}
function closeTransactionDetail() {
selectedTransaction = null;
selectedTxId = null;
document.getElementById('tx-detail-container').classList.remove('visible');
updateFilterBar();
updateView();
}
// Peer naming prompt
function showPeerNamingPrompt() {
// Create modal overlay
const overlay = document.createElement('div');
overlay.id = 'peer-name-overlay';
overlay.className = 'peer-name-overlay';
overlay.innerHTML = `
<div class="peer-name-modal">
<div class="peer-name-header">Name Your Peer</div>
<div class="peer-name-body">
<p>You're running a Freenet peer! Give it a name that others will see on the network dashboard.</p>
<input type="text" id="peer-name-input" class="peer-name-input" placeholder="e.g., SpaceCowboy, Node42, PizzaNode" maxlength="20" autofocus>
<div class="peer-name-hint">Max 20 characters. Keep it friendly!</div>
</div>
<div class="peer-name-footer">
<button class="peer-name-btn secondary" onclick="closePeerNamingPrompt()">Maybe Later</button>
<button class="peer-name-btn primary" onclick="submitPeerName()">Set Name</button>
</div>
</div>
`;
document.body.appendChild(overlay);
// Focus input and handle enter key
const input = document.getElementById('peer-name-input');
input.focus();
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') submitPeerName();
if (e.key === 'Escape') closePeerNamingPrompt();
});
}
function closePeerNamingPrompt() {
const overlay = document.getElementById('peer-name-overlay');
if (overlay) overlay.remove();
}
function submitPeerName() {
const input = document.getElementById('peer-name-input');
const name = input?.value?.trim();
if (!name) return;
// Send to server
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'set_peer_name', name }));
}
closePeerNamingPrompt();
}
function renderDetailTimeline() {
const windowSize = timeWindowNs * 2;
let windowStart = currentTime - timeWindowNs;
let windowEnd = currentTime + timeWindowNs;
if (windowStart < timeRange.start) { windowStart = timeRange.start; windowEnd = Math.min(timeRange.end, timeRange.start + windowSize); }
if (windowEnd > timeRange.end) { windowEnd = timeRange.end; windowStart = Math.max(timeRange.start, timeRange.end - windowSize); }
const windowDuration = windowEnd - windowStart;
if (windowDuration <= 0) return;
// Performance: Cache key for detail timeline (quantized to 1-second buckets)
const timelineBucket = Math.floor(windowStart / 1_000_000_000);
const detailKey = `${timelineBucket}|${allTransactions.length}|${selectedTransaction?.tx_id || ''}`;
if (detailKey === lastDetailTimelineKey) {
return; // No changes, skip expensive rebuild
}
lastDetailTimelineKey = detailKey;
// Update range label
const fmt = { hour: '2-digit', minute: '2-digit', second: '2-digit' };
document.getElementById('detail-range').textContent =
`${new Date(windowStart / 1_000_000).toLocaleTimeString([], fmt)} to ${new Date(windowEnd / 1_000_000).toLocaleTimeString([], fmt)}`;
// Render ruler
const detailRuler = document.getElementById('detail-ruler');
detailRuler.innerHTML = '';
const durationSec = windowDuration / 1_000_000_000;
let tickIntervalMs = durationSec <= 60 ? 10000 : durationSec <= 300 ? 30000 : durationSec <= 600 ? 60000 : 120000;
const startMs = Math.ceil((windowStart / 1_000_000) / tickIntervalMs) * tickIntervalMs;
for (let ms = startMs; ms <= windowEnd / 1_000_000; ms += tickIntervalMs) {
const pos = ((ms * 1_000_000) - windowStart) / windowDuration;
if (pos < 0 || pos > 1) continue;
const tick = document.createElement('div');
tick.className = 'timeline-tick';
tick.style.cssText = `position:absolute;left:${pos*100}%;transform:translateX(-50%)`;
tick.textContent = new Date(ms).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
detailRuler.appendChild(tick);
}
// Filter transactions with events in window
const windowTx = allTransactions.filter(tx =>
tx.end_ns >= windowStart && tx.start_ns <= windowEnd && tx.events && tx.events.length > 0
);
// Organize by operation type to match main timeline lanes: PUT, GET, UPD, SUB, CONN
const opOrder = ['put', 'get', 'update', 'subscribe', 'connect'];
const lanesByOp = { put: [], get: [], update: [], subscribe: [], connect: [], other: [] };
windowTx.forEach(tx => {
const op = tx.op || 'other';
const targetLane = lanesByOp[op] || lanesByOp.other;
targetLane.push(tx);
});
const lanesContainer = document.getElementById('timeline-lanes');
lanesContainer.innerHTML = '';
const laneHeight = 18;
let currentTop = 0;
opOrder.forEach(op => {
const txList = lanesByOp[op];
if (txList.length === 0) return;
const laneDiv = document.createElement('div');
laneDiv.className = 'tx-lane';
laneDiv.style.top = `${currentTop}px`;
currentTop += laneHeight;
txList.forEach(tx => {
const events = tx.events || [];
if (events.length === 0) return;
// Calculate transaction position and width
const txStart = Math.max(windowStart, tx.start_ns);
const txEnd = Math.min(windowEnd, tx.end_ns || tx.start_ns);
const startPos = (txStart - windowStart) / windowDuration;
const endPos = (txEnd - windowStart) / windowDuration;
const opClass = tx.op || 'other';
const statusClass = tx.status === 'pending' ? ' pending' : tx.status === 'failed' ? ' failed' : '';
const duration = tx.duration_ms ? `${tx.duration_ms.toFixed(1)}ms` : 'pending';
const tooltip = `${tx.op}: ${tx.contract || 'no contract'}\nDuration: ${duration}\nEvents: ${events.length}`;
// Create container for the transaction
const txContainer = document.createElement('div');
txContainer.className = `tx-container ${opClass}${statusClass}`;
txContainer.style.cssText = `left:${startPos * 100}%;width:${(endPos - startPos) * 100}%;`;
txContainer.title = tooltip;
txContainer.onclick = (e) => { e.stopPropagation(); showTransactionDetail(tx); };
// Thin line showing transaction duration
const txLine = document.createElement('div');
txLine.className = `tx-line ${opClass}`;
txContainer.appendChild(txLine);
// Event pills positioned along the transaction
events.forEach(evt => {
const evtTime = evt.timestamp; // Already in nanoseconds
if (!evtTime || evtTime < windowStart || evtTime > windowEnd) return;
// Position within the transaction container (0-100%)
const txDuration = txEnd - txStart;
const evtPos = txDuration > 0 ? ((evtTime - txStart) / txDuration) * 100 : 50;
const pill = document.createElement('div');
pill.className = `tx-pill ${opClass}`;
pill.style.left = `${Math.max(0, Math.min(100, evtPos))}%`;
txContainer.appendChild(pill);
});
laneDiv.appendChild(txContainer);
});
lanesContainer.appendChild(laneDiv);
});
}
function selectEvent(event) {
highlightedPeers.clear();
// Toggle: clicking same event deselects it
if (selectedEvent === event) {
selectedEvent = null;
selectedContract = null; // Also clear contract selection
goLive(); // Return to live view when deselecting
return;
}
selectedEvent = event;
if (event) {
// Move playhead to event time
goToTime(event.timestamp);
// Highlight the event's peer
if (event.peer_id) {
highlightedPeers.add(event.peer_id);
}
// Also highlight connection peers
if (event.connection) {
highlightedPeers.add(event.connection[0]);
highlightedPeers.add(event.connection[1]);
}
// If event has a contract with subscription tree, select it to show the tree
if (event.contract_full && contractData[event.contract_full]) {
selectedContract = event.contract_full;
} else {
selectedContract = null; // Clear if no contract
}
}
updateView();
}
function selectPeer(peerId) {
if (selectedPeerId === peerId) {
// Clicking same peer clears selection
selectedPeerId = null;
} else {
selectedPeerId = peerId;
}
updateFilterBar();
updateView();
updateURL();
}
function togglePeerFilter(peerId) {
if (selectedPeerId === peerId) {
selectedPeerId = null;
} else {
selectedPeerId = peerId;
}
updateFilterBar();
updateView();
updateURL();
}
function toggleTxFilter(txId) {
if (selectedTxId === txId) {
selectedTxId = null;
} else {
selectedTxId = txId;
}
updateFilterBar();
updateView();
updateURL();
}
function clearPeerSelection() {
selectedPeerId = null;
updateView();
}
let contractDropdownOpen = false;
function toggleContractDropdown() {
contractDropdownOpen = !contractDropdownOpen;
document.getElementById('contract-menu').classList.toggle('open', contractDropdownOpen);
}
// Close dropdown when clicking outside
document.addEventListener('click', (e) => {
if (!e.target.closest('#contract-dropdown') && contractDropdownOpen) {
contractDropdownOpen = false;
document.getElementById('contract-menu').classList.remove('open');