-
-
Notifications
You must be signed in to change notification settings - Fork 34.4k
Expand file tree
/
Copy pathflamegraph.js
More file actions
1351 lines (1133 loc) · 44.7 KB
/
flamegraph.js
File metadata and controls
1351 lines (1133 loc) · 44.7 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
const EMBEDDED_DATA = {{FLAMEGRAPH_DATA}};
// Global string table for resolving string indices
let stringTable = [];
let normalData = null;
let invertedData = null;
let currentThreadFilter = 'all';
let isInverted = false;
let useModuleNames = true;
// Heat colors are now defined in CSS variables (--heat-1 through --heat-8)
// and automatically switch with theme changes - no JS color arrays needed!
// Opcode mappings - loaded from embedded data (generated by Python)
let OPCODE_NAMES = {};
let DEOPT_MAP = {};
// Initialize opcode mappings from embedded data
function initOpcodeMapping(data) {
if (data && data.opcode_mapping) {
OPCODE_NAMES = data.opcode_mapping.names || {};
DEOPT_MAP = data.opcode_mapping.deopt || {};
}
}
// Get opcode info from opcode number
function getOpcodeInfo(opcode) {
const opname = OPCODE_NAMES[opcode] || `<${opcode}>`;
const baseOpcode = DEOPT_MAP[opcode];
const isSpecialized = baseOpcode !== undefined;
const baseOpname = isSpecialized ? (OPCODE_NAMES[baseOpcode] || `<${baseOpcode}>`) : opname;
return {
opname: opname,
baseOpname: baseOpname,
isSpecialized: isSpecialized
};
}
// ============================================================================
// String Resolution
// ============================================================================
function resolveString(index) {
if (index === null || index === undefined) {
return null;
}
if (typeof index === 'number' && index >= 0 && index < stringTable.length) {
return stringTable[index];
}
return String(index);
}
function resolveStringIndices(node) {
if (!node) return node;
const resolved = { ...node };
if (typeof resolved.name === 'number') {
resolved.name = resolveString(resolved.name);
}
if (typeof resolved.filename === 'number') {
resolved.filename = resolveString(resolved.filename);
}
if (typeof resolved.funcname === 'number') {
resolved.funcname = resolveString(resolved.funcname);
}
if (typeof resolved.module_name === 'number') {
resolved.module_name = resolveString(resolved.module_name);
}
if (typeof resolved.name_module === 'number') {
resolved.name_module = resolveString(resolved.name_module);
}
if (Array.isArray(resolved.source)) {
resolved.source = resolved.source.map(index =>
typeof index === 'number' ? resolveString(index) : index
);
}
if (Array.isArray(resolved.children)) {
resolved.children = resolved.children.map(child => resolveStringIndices(child));
}
return resolved;
}
// Escape HTML special characters
function escapeHtml(str) {
return str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
}
// Get display path based on user preference (module name or basename)
function getDisplayName(moduleName, filename) {
if (useModuleNames) {
return moduleName || filename;
}
return filename ? filename.split('/').pop() : filename;
}
// ============================================================================
// Theme & UI Controls
// ============================================================================
function toggleTheme() {
toggleAndSaveTheme();
// Re-render flamegraph with new theme colors
if (window.flamegraphData && normalData) {
const currentData = isInverted ? invertedData : normalData;
const tooltip = createPythonTooltip(currentData);
const chart = createFlamegraph(tooltip, currentData.value);
renderFlamegraph(chart, window.flamegraphData);
}
}
function toggleSidebar() {
const sidebar = document.getElementById('sidebar');
if (sidebar) {
const isCollapsing = !sidebar.classList.contains('collapsed');
if (isCollapsing) {
// Save current width before collapsing
const currentWidth = sidebar.offsetWidth;
sidebar.dataset.expandedWidth = currentWidth;
localStorage.setItem('flamegraph-sidebar-width', currentWidth);
} else {
// Restore width when expanding
const savedWidth = sidebar.dataset.expandedWidth || localStorage.getItem('flamegraph-sidebar-width');
if (savedWidth) {
sidebar.style.width = savedWidth + 'px';
}
}
sidebar.classList.toggle('collapsed');
localStorage.setItem('flamegraph-sidebar', sidebar.classList.contains('collapsed') ? 'collapsed' : 'expanded');
// Resize chart after sidebar animation
setTimeout(() => {
resizeChart();
}, 300);
}
}
function resizeChart() {
if (window.flamegraphChart && window.flamegraphData) {
const chartArea = document.querySelector('.chart-area');
if (chartArea) {
window.flamegraphChart.width(chartArea.clientWidth - 32);
d3.select("#chart").datum(window.flamegraphData).call(window.flamegraphChart);
}
}
}
function toggleSection(sectionId) {
const section = document.getElementById(sectionId);
if (section) {
section.classList.toggle('collapsed');
// Save state
const collapsedSections = JSON.parse(localStorage.getItem('flamegraph-collapsed-sections') || '{}');
collapsedSections[sectionId] = section.classList.contains('collapsed');
localStorage.setItem('flamegraph-collapsed-sections', JSON.stringify(collapsedSections));
}
}
// Restore theme from localStorage, or use browser preference
function restoreUIState() {
applyTheme(getPreferredTheme());
// Restore sidebar state
const savedSidebar = localStorage.getItem('flamegraph-sidebar');
if (savedSidebar === 'collapsed') {
const sidebar = document.getElementById('sidebar');
if (sidebar) sidebar.classList.add('collapsed');
}
// Restore sidebar width
const savedWidth = localStorage.getItem('flamegraph-sidebar-width');
if (savedWidth) {
const sidebar = document.getElementById('sidebar');
if (sidebar) {
sidebar.style.width = savedWidth + 'px';
}
}
// Restore collapsed sections
const collapsedSections = JSON.parse(localStorage.getItem('flamegraph-collapsed-sections') || '{}');
for (const [sectionId, isCollapsed] of Object.entries(collapsedSections)) {
if (isCollapsed) {
const section = document.getElementById(sectionId);
if (section) section.classList.add('collapsed');
}
}
}
// ============================================================================
// Logo/Favicon Setup
// ============================================================================
function setupLogos() {
const logo = document.querySelector('.sidebar-logo-img img');
if (!logo) return;
const navbarLogoContainer = document.getElementById('navbar-logo');
if (navbarLogoContainer) {
const navbarLogo = logo.cloneNode(true);
navbarLogoContainer.appendChild(navbarLogo);
}
const favicon = document.createElement('link');
favicon.rel = 'icon';
favicon.type = 'image/png';
favicon.href = logo.src;
document.head.appendChild(favicon);
}
// ============================================================================
// Status Bar
// ============================================================================
function updateStatusBar(nodeData, rootValue) {
const funcname = resolveString(nodeData.funcname) || resolveString(nodeData.name) || "--";
const filename = resolveString(nodeData.filename) || "";
const moduleName = resolveString(nodeData.module_name) || "";
const lineno = nodeData.lineno;
const timeMs = (nodeData.value / 1000).toFixed(2);
const percent = rootValue > 0 ? ((nodeData.value / rootValue) * 100).toFixed(1) : "0.0";
const brandEl = document.getElementById('status-brand');
const taglineEl = document.getElementById('status-tagline');
if (brandEl) brandEl.style.display = 'none';
if (taglineEl) taglineEl.style.display = 'none';
const locationEl = document.getElementById('status-location');
const funcItem = document.getElementById('status-func-item');
const timeItem = document.getElementById('status-time-item');
const percentItem = document.getElementById('status-percent-item');
if (locationEl) locationEl.style.display = filename && filename !== "~" ? 'flex' : 'none';
if (funcItem) funcItem.style.display = 'flex';
if (timeItem) timeItem.style.display = 'flex';
if (percentItem) percentItem.style.display = 'flex';
const fileEl = document.getElementById('status-file');
if (fileEl && filename && filename !== "~") {
const displayName = getDisplayName(moduleName, filename);
fileEl.textContent = lineno ? `${displayName}:${lineno}` : displayName;
}
const funcEl = document.getElementById('status-func');
if (funcEl) funcEl.textContent = funcname.length > 40 ? funcname.substring(0, 37) + '...' : funcname;
const timeEl = document.getElementById('status-time');
if (timeEl) timeEl.textContent = `${timeMs} ms`;
const percentEl = document.getElementById('status-percent');
if (percentEl) percentEl.textContent = `${percent}%`;
}
function clearStatusBar() {
const ids = ['status-location', 'status-func-item', 'status-time-item', 'status-percent-item'];
ids.forEach(id => {
const el = document.getElementById(id);
if (el) el.style.display = 'none';
});
const brandEl = document.getElementById('status-brand');
const taglineEl = document.getElementById('status-tagline');
if (brandEl) brandEl.style.display = 'flex';
if (taglineEl) taglineEl.style.display = 'flex';
}
// ============================================================================
// Tooltip
// ============================================================================
function createPythonTooltip(data) {
const pythonTooltip = flamegraph.tooltip.defaultFlamegraphTooltip();
pythonTooltip.show = function (d, element) {
if (!this._tooltip) {
this._tooltip = d3.select("body")
.append("div")
.attr("class", "python-tooltip")
.style("opacity", 0);
}
const timeMs = (d.data.value / 1000).toFixed(2);
const percentage = ((d.data.value / data.value) * 100).toFixed(2);
const calls = d.data.calls || 0;
const childCount = d.children ? d.children.length : 0;
const source = d.data.source;
const funcname = resolveString(d.data.funcname) || resolveString(d.data.name);
const filename = resolveString(d.data.filename) || "";
const moduleName = resolveString(d.data.module_name) || "";
const displayName = escapeHtml(useModuleNames ? (moduleName || filename) : filename);
const isSpecialFrame = filename === "~";
// Build source section
let sourceSection = "";
if (source && Array.isArray(source) && source.length > 0) {
const sourceLines = source
.map((line) => {
const isCurrent = line.startsWith("→");
const escaped = escapeHtml(line);
return `<div class="tooltip-source-line${isCurrent ? ' current' : ''}">${escaped}</div>`;
})
.join("");
sourceSection = `
<div class="tooltip-source">
<div class="tooltip-source-title">Source Code:</div>
<div class="tooltip-source-code">${sourceLines}</div>
</div>`;
}
// Create bytecode/opcode section if available
let opcodeSection = "";
const opcodes = d.data.opcodes;
if (opcodes && typeof opcodes === 'object' && Object.keys(opcodes).length > 0) {
// Sort opcodes by sample count (descending)
const sortedOpcodes = Object.entries(opcodes)
.sort((a, b) => b[1] - a[1])
.slice(0, 8); // Limit to top 8
const totalOpcodeSamples = sortedOpcodes.reduce((sum, [, count]) => sum + count, 0);
const maxCount = sortedOpcodes[0][1] || 1;
const opcodeLines = sortedOpcodes.map(([opcode, count]) => {
const opcodeInfo = getOpcodeInfo(parseInt(opcode, 10));
const pct = ((count / totalOpcodeSamples) * 100).toFixed(1);
const barWidth = (count / maxCount) * 100;
const specializedBadge = opcodeInfo.isSpecialized
? '<span class="tooltip-opcode-badge">SPECIALIZED</span>'
: '';
const baseOpHint = opcodeInfo.isSpecialized
? `<span class="tooltip-opcode-base-hint">(${opcodeInfo.baseOpname})</span>`
: '';
const nameClass = opcodeInfo.isSpecialized
? 'tooltip-opcode-name specialized'
: 'tooltip-opcode-name';
return `
<div class="tooltip-opcode-row">
<div class="${nameClass}">
${opcodeInfo.opname}${baseOpHint}${specializedBadge}
</div>
<div class="tooltip-opcode-count">${count.toLocaleString()} (${pct}%)</div>
<div class="tooltip-opcode-bar">
<div class="tooltip-opcode-bar-fill" style="width: ${barWidth}%;"></div>
</div>
</div>`;
}).join('');
opcodeSection = `
<div class="tooltip-opcodes">
<div class="tooltip-opcodes-title">Bytecode Instructions:</div>
<div class="tooltip-opcodes-list">
${opcodeLines}
</div>
</div>`;
}
const fileLocationHTML = isSpecialFrame ? "" : `
<div class="tooltip-location">${displayName}${d.data.lineno ? ":" + d.data.lineno : ""}</div>`;
const tooltipHTML = `
<div class="tooltip-header">
<div class="tooltip-title">${funcname}</div>
${fileLocationHTML}
</div>
<div class="tooltip-stats">
<span class="tooltip-stat-label">Execution Time:</span>
<span class="tooltip-stat-value">${timeMs} ms</span>
<span class="tooltip-stat-label">Percentage:</span>
<span class="tooltip-stat-value accent">${percentage}%</span>
${calls > 0 ? `
<span class="tooltip-stat-label">Function Calls:</span>
<span class="tooltip-stat-value">${calls.toLocaleString()}</span>
` : ''}
${childCount > 0 ? `
<span class="tooltip-stat-label">Child Functions:</span>
<span class="tooltip-stat-value">${childCount}</span>
` : ''}
</div>
${sourceSection}
${opcodeSection}
<div class="tooltip-hint">
${childCount > 0 ? "Click to zoom into this function" : "Leaf function - no children"}
</div>
`;
// Position tooltip
const event = d3.event || window.event;
const mouseX = event.pageX || event.clientX;
const mouseY = event.pageY || event.clientY;
const padding = 12;
this._tooltip.html(tooltipHTML);
// Measure tooltip
const node = this._tooltip.style("display", "block").style("opacity", 0).node();
const tooltipWidth = node.offsetWidth || 320;
const tooltipHeight = node.offsetHeight || 200;
// Calculate position
let left = mouseX + padding;
let top = mouseY + padding;
if (left + tooltipWidth > window.innerWidth) {
left = mouseX - tooltipWidth - padding;
if (left < 0) left = padding;
}
if (top + tooltipHeight > window.innerHeight) {
top = mouseY - tooltipHeight - padding;
if (top < 0) top = padding;
}
this._tooltip
.style("left", left + "px")
.style("top", top + "px")
.transition()
.duration(150)
.style("opacity", 1);
// Update status bar
updateStatusBar(d.data, data.value);
};
pythonTooltip.hide = function () {
if (this._tooltip) {
this._tooltip.transition().duration(150).style("opacity", 0);
}
clearStatusBar();
};
return pythonTooltip;
}
// ============================================================================
// Flamegraph Creation
// ============================================================================
function ensureLibraryLoaded() {
if (typeof flamegraph === "undefined") {
console.error("d3-flame-graph library not loaded");
document.getElementById("chart").innerHTML =
'<div style="padding: 40px; text-align: center; color: var(--text-muted);">Error: d3-flame-graph library failed to load</div>';
throw new Error("d3-flame-graph library failed to load");
}
}
const HEAT_THRESHOLDS = [
[0.6, 8],
[0.35, 7],
[0.18, 6],
[0.12, 5],
[0.06, 4],
[0.03, 3],
[0.01, 2],
];
function getHeatLevel(percentage) {
for (const [threshold, level] of HEAT_THRESHOLDS) {
if (percentage >= threshold) return level;
}
return 1;
}
function getHeatColors() {
const style = getComputedStyle(document.documentElement);
const colors = {};
for (let i = 1; i <= 8; i++) {
colors[i] = style.getPropertyValue(`--heat-${i}`).trim();
}
return colors;
}
function createFlamegraph(tooltip, rootValue) {
const chartArea = document.querySelector('.chart-area');
const width = chartArea ? chartArea.clientWidth - 32 : window.innerWidth - 320;
const heatColors = getHeatColors();
let chart = flamegraph()
.width(width)
.cellHeight(20)
.transitionDuration(300)
.minFrameSize(1)
.tooltip(tooltip)
.inverted(true)
.getName(d => resolveString(useModuleNames ? d.data.name_module : d.data.name) || resolveString(d.data.name) || '')
.setColorMapper(function (d) {
// Root node should be transparent
if (d.depth === 0) return 'transparent';
const percentage = d.data.value / rootValue;
const level = getHeatLevel(percentage);
return heatColors[level];
});
return chart;
}
function renderFlamegraph(chart, data) {
d3.select("#chart").datum(data).call(chart);
window.flamegraphChart = chart;
window.flamegraphData = data;
populateStats(data);
}
// ============================================================================
// Search
// ============================================================================
function updateSearchHighlight(searchTerm, searchInput) {
d3.selectAll("#chart rect")
.classed("search-match", false)
.classed("search-dim", false);
// Clear active state from all hotspots
document.querySelectorAll('.hotspot').forEach(h => h.classList.remove('active'));
if (searchTerm && searchTerm.length > 0) {
let matchCount = 0;
d3.selectAll("#chart rect").each(function (d) {
if (d && d.data) {
const name = resolveString(d.data.name) || "";
const funcname = resolveString(d.data.funcname) || "";
const filename = resolveString(d.data.filename) || "";
const moduleName = resolveString(d.data.module_name) || "";
const displayName = getDisplayName(moduleName, filename);
const lineno = d.data.lineno;
const term = searchTerm.toLowerCase();
// Check if search term looks like path:line pattern
const fileLineMatch = term.match(/^(.+):(\d+)$/);
let matches = false;
if (fileLineMatch) {
const searchFile = fileLineMatch[1];
const searchLine = parseInt(fileLineMatch[2], 10);
matches = displayName.toLowerCase().includes(searchFile) && lineno === searchLine;
} else {
// Regular substring search
matches =
name.toLowerCase().includes(term) ||
funcname.toLowerCase().includes(term) ||
displayName.toLowerCase().includes(term);
}
if (matches) {
matchCount++;
d3.select(this).classed("search-match", true);
} else {
d3.select(this).classed("search-dim", true);
}
}
});
if (searchInput) {
searchInput.classList.remove("has-matches", "no-matches");
searchInput.classList.add(matchCount > 0 ? "has-matches" : "no-matches");
}
// Mark matching hotspot as active
document.querySelectorAll('.hotspot').forEach(h => {
if (h.dataset.searchterm && h.dataset.searchterm.toLowerCase() === searchTerm.toLowerCase()) {
h.classList.add('active');
}
});
} else if (searchInput) {
searchInput.classList.remove("has-matches", "no-matches");
}
}
function searchForHotspot(funcname) {
const searchInput = document.getElementById('search-input');
const searchWrapper = document.querySelector('.search-wrapper');
if (searchInput) {
// Toggle: if already searching for this term, clear it
if (searchInput.value.trim() === funcname) {
clearSearch();
} else {
searchInput.value = funcname;
if (searchWrapper) {
searchWrapper.classList.add('has-value');
}
performSearch();
}
}
}
function initSearchHandlers() {
const searchInput = document.getElementById("search-input");
const searchWrapper = document.querySelector(".search-wrapper");
if (!searchInput) return;
let searchTimeout;
function performSearch() {
const term = searchInput.value.trim();
updateSearchHighlight(term, searchInput);
// Toggle has-value class for clear button visibility
if (searchWrapper) {
searchWrapper.classList.toggle("has-value", term.length > 0);
}
}
searchInput.addEventListener("input", function () {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(performSearch, 150);
});
window.performSearch = performSearch;
}
function clearSearch() {
const searchInput = document.getElementById("search-input");
const searchWrapper = document.querySelector(".search-wrapper");
if (searchInput) {
searchInput.value = "";
searchInput.classList.remove("has-matches", "no-matches");
if (searchWrapper) {
searchWrapper.classList.remove("has-value");
}
// Clear highlights
d3.selectAll("#chart rect")
.classed("search-match", false)
.classed("search-dim", false);
// Clear active hotspot
document.querySelectorAll('.hotspot').forEach(h => h.classList.remove('active'));
}
}
// ============================================================================
// Resize Handler
// ============================================================================
function handleResize() {
let resizeTimeout;
window.addEventListener("resize", function () {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(resizeChart, 100);
});
}
function initSidebarResize() {
const sidebar = document.getElementById('sidebar');
const resizeHandle = document.getElementById('sidebar-resize-handle');
if (!sidebar || !resizeHandle) return;
let isResizing = false;
let startX = 0;
let startWidth = 0;
const minWidth = 200;
const maxWidth = 600;
resizeHandle.addEventListener('mousedown', function(e) {
isResizing = true;
startX = e.clientX;
startWidth = sidebar.offsetWidth;
resizeHandle.classList.add('resizing');
document.body.classList.add('resizing-sidebar');
e.preventDefault();
});
document.addEventListener('mousemove', function(e) {
if (!isResizing) return;
const deltaX = e.clientX - startX;
const newWidth = Math.min(Math.max(startWidth + deltaX, minWidth), maxWidth);
sidebar.style.width = newWidth + 'px';
e.preventDefault();
});
document.addEventListener('mouseup', function() {
if (isResizing) {
isResizing = false;
resizeHandle.classList.remove('resizing');
document.body.classList.remove('resizing-sidebar');
// Save the new width
const width = sidebar.offsetWidth;
localStorage.setItem('flamegraph-sidebar-width', width);
// Resize chart after sidebar resize
setTimeout(() => {
resizeChart();
}, 10);
}
});
}
// ============================================================================
// Thread Stats
// ============================================================================
// Mode constants (must match constants.py)
const PROFILING_MODE_WALL = 0;
const PROFILING_MODE_CPU = 1;
const PROFILING_MODE_GIL = 2;
const PROFILING_MODE_ALL = 3;
function populateThreadStats(data, selectedThreadId = null) {
const stats = data?.stats;
if (!stats || !stats.thread_stats) {
return;
}
const mode = stats.mode !== undefined ? stats.mode : PROFILING_MODE_WALL;
let threadStats;
if (selectedThreadId !== null && stats.per_thread_stats && stats.per_thread_stats[selectedThreadId]) {
threadStats = stats.per_thread_stats[selectedThreadId];
} else {
threadStats = stats.thread_stats;
}
if (!threadStats || typeof threadStats.total !== 'number' || threadStats.total <= 0) {
return;
}
const section = document.getElementById('thread-stats-bar');
if (!section) {
return;
}
section.style.display = 'block';
const gilHeldStat = document.getElementById('gil-held-stat');
const gilReleasedStat = document.getElementById('gil-released-stat');
const gilWaitingStat = document.getElementById('gil-waiting-stat');
if (mode === PROFILING_MODE_GIL) {
// In GIL mode, hide GIL-related stats
if (gilHeldStat) gilHeldStat.style.display = 'none';
if (gilReleasedStat) gilReleasedStat.style.display = 'none';
if (gilWaitingStat) gilWaitingStat.style.display = 'none';
} else {
// Show all stats
if (gilHeldStat) gilHeldStat.style.display = 'block';
if (gilReleasedStat) gilReleasedStat.style.display = 'block';
if (gilWaitingStat) gilWaitingStat.style.display = 'block';
const gilHeldPct = threadStats.has_gil_pct || 0;
const gilHeldPctElem = document.getElementById('gil-held-pct');
if (gilHeldPctElem) gilHeldPctElem.textContent = `${gilHeldPct.toFixed(1)}%`;
const gilHeldFill = document.getElementById('gil-held-fill');
if (gilHeldFill) gilHeldFill.style.width = `${gilHeldPct}%`;
// GIL Released = not holding GIL and not waiting for it
const gilReleasedPct = Math.max(0, 100 - (threadStats.has_gil_pct || 0) - (threadStats.gil_requested_pct || 0));
const gilReleasedPctElem = document.getElementById('gil-released-pct');
if (gilReleasedPctElem) gilReleasedPctElem.textContent = `${gilReleasedPct.toFixed(1)}%`;
const gilReleasedFill = document.getElementById('gil-released-fill');
if (gilReleasedFill) gilReleasedFill.style.width = `${gilReleasedPct}%`;
const gilWaitingPct = threadStats.gil_requested_pct || 0;
const gilWaitingPctElem = document.getElementById('gil-waiting-pct');
if (gilWaitingPctElem) gilWaitingPctElem.textContent = `${gilWaitingPct.toFixed(1)}%`;
const gilWaitingFill = document.getElementById('gil-waiting-fill');
if (gilWaitingFill) gilWaitingFill.style.width = `${gilWaitingPct}%`;
}
const gcPct = threadStats.gc_pct || 0;
const gcPctElem = document.getElementById('gc-pct');
if (gcPctElem) gcPctElem.textContent = `${gcPct.toFixed(1)}%`;
const gcFill = document.getElementById('gc-fill');
if (gcFill) gcFill.style.width = `${gcPct}%`;
// Exception stats
const excPct = threadStats.has_exception_pct || 0;
const excPctElem = document.getElementById('exc-pct');
if (excPctElem) excPctElem.textContent = `${excPct.toFixed(1)}%`;
const excFill = document.getElementById('exc-fill');
if (excFill) excFill.style.width = `${excPct}%`;
}
// ============================================================================
// Profile Summary Stats
// ============================================================================
function formatNumber(num) {
if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M';
if (num >= 1000) return (num / 1000).toFixed(1) + 'K';
return num.toLocaleString();
}
function formatDuration(seconds) {
if (seconds >= 3600) {
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
return `${h}h ${m}m`;
}
if (seconds >= 60) {
const m = Math.floor(seconds / 60);
const s = Math.floor(seconds % 60);
return `${m}m ${s}s`;
}
return seconds.toFixed(2) + 's';
}
function populateProfileSummary(data) {
const stats = data.stats || {};
const totalSamples = stats.total_samples || data.value || 0;
const duration = stats.duration_sec || 0;
const sampleRate = stats.sample_rate || (duration > 0 ? totalSamples / duration : 0);
const errorRate = stats.error_rate || 0;
const missedSamples= stats.missed_samples || 0;
const samplesEl = document.getElementById('stat-total-samples');
if (samplesEl) samplesEl.textContent = formatNumber(totalSamples);
const durationEl = document.getElementById('stat-duration');
if (durationEl) durationEl.textContent = duration > 0 ? formatDuration(duration) : '--';
const rateEl = document.getElementById('stat-sample-rate');
if (rateEl) rateEl.textContent = sampleRate > 0 ? formatNumber(Math.round(sampleRate)) : '--';
// Count unique functions
// Use normal (non-inverted) tree structure, but respect thread filtering
const uniqueFunctions = new Set();
function collectUniqueFunctions(node) {
if (!node) return;
const filename = resolveString(node.filename) || 'unknown';
const funcname = resolveString(node.funcname) || resolveString(node.name) || 'unknown';
const lineno = node.lineno || 0;
const key = `${filename}|${lineno}|${funcname}`;
uniqueFunctions.add(key);
if (node.children) node.children.forEach(collectUniqueFunctions);
}
// In inverted mode, use normalData (with thread filter if active)
// In normal mode, use the passed data (already has thread filter applied if any)
let functionCountSource;
if (!normalData) {
functionCountSource = data;
} else if (isInverted) {
if (currentThreadFilter !== 'all') {
functionCountSource = filterDataByThread(normalData, parseInt(currentThreadFilter));
} else {
functionCountSource = normalData;
}
} else {
functionCountSource = data;
}
collectUniqueFunctions(functionCountSource);
const functionsEl = document.getElementById('stat-functions');
if (functionsEl) functionsEl.textContent = formatNumber(uniqueFunctions.size);
// Efficiency bar
if (errorRate !== undefined && errorRate !== null) {
const efficiency = Math.max(0, Math.min(100, (100 - errorRate)));
const efficiencySection = document.getElementById('efficiency-section');
if (efficiencySection) efficiencySection.style.display = 'block';
const efficiencyValue = document.getElementById('stat-efficiency');
if (efficiencyValue) efficiencyValue.textContent = efficiency.toFixed(1) + '%';
const efficiencyFill = document.getElementById('efficiency-fill');
if (efficiencyFill) efficiencyFill.style.width = efficiency + '%';
}
// MissedSamples bar
if (missedSamples !== undefined && missedSamples !== null) {
const sampleEfficiency = Math.max(0, missedSamples);
const efficiencySection = document.getElementById('efficiency-section');
if (efficiencySection) efficiencySection.style.display = 'block';
const sampleEfficiencyValue = document.getElementById('stat-missed-samples');
if (sampleEfficiencyValue) sampleEfficiencyValue.textContent = sampleEfficiency.toFixed(1) + '%';
const sampleEfficiencyFill = document.getElementById('missed-samples-fill');
if (sampleEfficiencyFill) sampleEfficiencyFill.style.width = sampleEfficiency + '%';
}
}
// ============================================================================
// Hotspot Stats
// ============================================================================
function populateStats(data) {
// Populate profile summary
populateProfileSummary(data);
// Populate thread statistics if available
populateThreadStats(data);
// For hotspots: use normal (non-inverted) tree structure, but respect thread filtering.
// In inverted view, the tree structure changes but the hottest functions remain the same.
// However, if a thread filter is active, we need to show that thread's hotspots.
let hotspotSource;
if (!normalData) {
hotspotSource = data;
} else if (isInverted) {
// In inverted mode, use normalData (with thread filter if active)
if (currentThreadFilter !== 'all') {
hotspotSource = filterDataByThread(normalData, parseInt(currentThreadFilter));
} else {
hotspotSource = normalData;
}
} else {
// In normal mode, use the passed data (already has thread filter applied if any)
hotspotSource = data;
}
const totalSamples = hotspotSource.value || 0;
const functionMap = new Map();
function collectFunctions(node) {
if (!node) return;
let filename = resolveString(node.filename);
let funcname = resolveString(node.funcname);
let moduleName = resolveString(node.module_name);
if (!filename || !funcname) {
const nameStr = resolveString(node.name);
if (nameStr?.includes('(')) {
const match = nameStr.match(/^(.+?)\s*\((.+?):(\d+)\)$/);
if (match) {
funcname = funcname || match[1];
filename = filename || match[2];
}
}
}
filename = filename || 'unknown';
funcname = funcname || 'unknown';
moduleName = moduleName || 'unknown';
if (filename !== 'unknown' && funcname !== 'unknown' && node.value > 0) {
let childrenValue = 0;
if (node.children) {
childrenValue = node.children.reduce((sum, child) => sum + child.value, 0);
}
const directSamples = Math.max(0, node.value - childrenValue);
const funcKey = `${filename}:${node.lineno || '?'}:${funcname}`;
if (functionMap.has(funcKey)) {
const existing = functionMap.get(funcKey);
existing.directSamples += directSamples;
existing.directPercent = (existing.directSamples / totalSamples) * 100;
if (directSamples > existing.maxSingleSamples) {
existing.filename = filename;
existing.module_name = moduleName;
existing.lineno = node.lineno || '?';
existing.maxSingleSamples = directSamples;
}
} else {
functionMap.set(funcKey, {
filename: filename,
module_name: moduleName,
lineno: node.lineno || '?',
funcname: funcname,
directSamples,
directPercent: (directSamples / totalSamples) * 100,
maxSingleSamples: directSamples
});
}
}
if (node.children) {
node.children.forEach(child => collectFunctions(child));
}
}
collectFunctions(hotspotSource);
const hotSpots = Array.from(functionMap.values())
.filter(f => f.directPercent > 0.5)
.sort((a, b) => b.directPercent - a.directPercent)
.slice(0, 3);
// Populate and animate hotspot cards
for (let i = 0; i < 3; i++) {
const num = i + 1;
const card = document.getElementById(`hotspot-${num}`);
const funcEl = document.getElementById(`hotspot-func-${num}`);
const fileEl = document.getElementById(`hotspot-file-${num}`);
const percentEl = document.getElementById(`hotspot-percent-${num}`);
const samplesEl = document.getElementById(`hotspot-samples-${num}`);
if (i < hotSpots.length && hotSpots[i]) {
const h = hotSpots[i];
const filename = h.filename || 'unknown';
const lineno = h.lineno ?? '?';
const moduleName = h.module_name || 'unknown';
const isSpecialFrame = filename === '~' && (lineno === 0 || lineno === '?');
let funcDisplay = h.funcname || 'unknown';
if (funcDisplay.length > 28) funcDisplay = funcDisplay.substring(0, 25) + '...';