-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathflamegraph.js
More file actions
822 lines (744 loc) · 29.4 KB
/
flamegraph.js
File metadata and controls
822 lines (744 loc) · 29.4 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
// flamegraph.js - Shared flamegraph rendering with zoom and search
(function (exports) {
"use strict";
function getAnalysis() {
if (typeof require !== "undefined") return require("./trace_analysis.js");
if (typeof TraceAnalysis !== "undefined") return TraceAnalysis;
throw new Error(
"TraceAnalysis not found. Load trace_analysis.js before flamegraph.js"
);
}
const buildFlamegraphTree = getAnalysis().buildFlamegraphTree;
const FG_ROW_H = 18;
function flamegraphColor(name) {
let h = 0;
for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) | 0;
const hue = 10 + (Math.abs(h) % 40);
const sat = 60 + (Math.abs(h >> 8) % 30);
const lit = 40 + (Math.abs(h >> 16) % 15);
return `hsl(${hue},${sat}%,${lit}%)`;
}
// Like flattenFlamegraph in trace_analysis.js but attaches treeNode refs
// for click-to-zoom. Filters out nodes < 0.1% of total.
// `ancestors` is an optional array of tree nodes forming the parent chain
// from the tree root down to (but not including) `root`. When provided,
// they are rendered as full-width context bars below the zoom target.
function flattenFromNode(root, total, ancestors) {
ancestors = ancestors || [];
const nodes = [];
let maxD = 0;
const depthOffset = ancestors.length;
const zoomed = depthOffset > 0;
// Ancestor chain: full-width context bars at depths 0..N-1
for (let i = 0; i < ancestors.length; i++) {
nodes.push({
name: ancestors[i].name, depth: i, x: 0, w: 1,
count: ancestors[i].count, self: ancestors[i].self,
treeNode: ancestors[i], isAncestor: true,
});
if (i > maxD) maxD = i;
}
// Zoom target itself at depth N (full-width)
if (zoomed) {
nodes.push({
name: root.name, depth: depthOffset, x: 0, w: 1,
count: root.count, self: root.self, treeNode: root,
});
if (depthOffset > maxD) maxD = depthOffset;
}
const startDepth = zoomed ? depthOffset + 1 : 0;
function walk(treeNode, depth, xStart) {
const w = treeNode.count / total;
if (w < 0.001) return;
nodes.push({
name: treeNode.name,
depth,
x: xStart,
w,
count: treeNode.count,
self: treeNode.self,
treeNode,
});
if (depth > maxD) maxD = depth;
const kids = [...treeNode.children.values()].sort(
(a, b) => b.count - a.count
);
let cx = xStart;
for (const child of kids) {
walk(child, depth + 1, cx);
cx += child.count / total;
}
}
const kids = [...root.children.values()].sort(
(a, b) => b.count - a.count
);
let cx = 0;
for (const child of kids) {
walk(child, startDepth, cx);
cx += child.count / total;
}
return { nodes, maxDepth: maxD };
}
// Count matching frames and their self-samples for search stats.
function countSearchMatches(root, queryLower) {
let selfCount = 0;
let frameCount = 0;
function walk(node) {
if (node.name.toLowerCase().includes(queryLower) || (node.fullName && node.fullName.toLowerCase().includes(queryLower))) {
selfCount += node.self;
frameCount++;
}
for (const child of node.children.values()) walk(child);
}
walk(root);
return { selfCount, frameCount };
}
function filterCpuSamples(cpuSamples, startNs, endNs) {
let out = cpuSamples.filter((s) => s.callchain.length > 0 && s.source !== 1);
if (startNs != null) out = out.filter((s) => s.timestamp >= startNs);
if (endNs != null) out = out.filter((s) => s.timestamp <= endNs);
return out;
}
function createFlamegraph(container, onZoomChange) {
onZoomChange = onZoomChange || function () {};
let workerTree = null;
let offworkerTree = null;
let workerData = null;
let offworkerData = null;
let workerZoomStack = [];
let offworkerZoomStack = [];
let searchQuery = "";
let highlightName = null;
let repaintQueued = false;
let allSamples = [];
let currentSymbols = null;
const hitRegions = { worker: [], offworker: [] };
// DOM
const searchBar = document.createElement("div");
searchBar.className = "fg-search-bar";
const isMac = /Mac|iPhone|iPad/.test(navigator.platform);
searchBar.innerHTML =
'<input type="text" class="fg-search-input" placeholder="Search frames... (' +
(isMac ? '\u2318' : 'Ctrl') + ' + F or /)" />' +
'<span class="fg-search-clear" title="Clear search">\u00d7</span>' +
'<span class="fg-search-stats"></span>' +
'<select class="fg-spawn-filter"></select>' +
'<span class="fg-help-btn" tabindex="0" role="button" title="Keyboard shortcuts">\u2139\ufe0f</span>';
container.appendChild(searchBar);
const searchInput = searchBar.querySelector(".fg-search-input");
const searchClear = searchBar.querySelector(".fg-search-clear");
const searchStats = searchBar.querySelector(".fg-search-stats");
const spawnFilter = searchBar.querySelector(".fg-spawn-filter");
const helpBtn = searchBar.querySelector(".fg-help-btn");
const helpOverlay = document.createElement("div");
helpOverlay.className = "fg-help-overlay";
helpOverlay.innerHTML =
'<div class="fg-help-content">' +
'<h3>\u2328 Flamegraph Shortcuts</h3>' +
'<table>' +
'<tr><td class="fg-help-key">Click</td><td>Zoom into frame</td></tr>' +
'<tr><td class="fg-help-key">Option / Alt + click</td><td>Pin tooltip (selectable text, links)</td></tr>' +
'<tr><td class="fg-help-key">' + (isMac ? '\u2318' : 'Ctrl') + ' + click</td><td>Open docs.rs (when available)</td></tr>' +
'<tr><td class="fg-help-key">Right-click</td><td>Zoom out one level</td></tr>' +
'<tr><td class="fg-help-key">' + (isMac ? '\u2318' : 'Ctrl') + ' + F or /</td><td>Search frames</td></tr>' +
'<tr><td class="fg-help-key">Esc</td><td>Unpin \u2192 clear search \u2192 reset zoom \u2192 close</td></tr>' +
'</table>' +
'<div class="fg-help-dismiss">Press Esc or click outside to close</div>' +
'</div>';
helpOverlay.style.display = "none";
container.appendChild(helpOverlay);
helpBtn.addEventListener("click", function () {
helpOverlay.style.display = helpOverlay.style.display === "none" ? "flex" : "none";
});
helpOverlay.addEventListener("click", function (e) {
if (e.target === helpOverlay) helpOverlay.style.display = "none";
});
searchClear.style.display = "none";
searchClear.addEventListener("click", function () {
searchInput.value = "";
searchQuery = "";
searchClear.style.display = "none";
repaint();
searchInput.focus();
});
const breadcrumbBar = document.createElement("div");
breadcrumbBar.className = "fg-breadcrumb";
container.appendChild(breadcrumbBar);
container.style.position = container.style.position || "relative";
const body = document.createElement("div");
body.className = "fg-body";
container.appendChild(body);
const workerLabel = document.createElement("div");
workerLabel.className = "fg-section-label";
workerLabel.textContent = "Worker threads";
body.appendChild(workerLabel);
const workerCanvas = document.createElement("canvas");
workerCanvas.className = "fg-canvas";
body.appendChild(workerCanvas);
const offworkerLabel = document.createElement("div");
offworkerLabel.className = "fg-section-label";
offworkerLabel.textContent = "Off-worker (sampler thread)";
body.appendChild(offworkerLabel);
const offworkerCanvas = document.createElement("canvas");
offworkerCanvas.className = "fg-canvas";
body.appendChild(offworkerCanvas);
const tooltip = document.createElement("div");
tooltip.className = "fg-tooltip";
document.body.appendChild(tooltip);
function renderCanvas(canvas, data, hitKey) {
if (!data) {
canvas.width = 0;
canvas.height = 0;
hitRegions[hitKey] = [];
return;
}
const dpr = devicePixelRatio || 1;
const pw = canvas.parentElement.clientWidth;
const ph = (data.maxDepth + 2) * FG_ROW_H + 8;
canvas.width = pw * dpr;
canvas.height = ph * dpr;
canvas.style.width = pw + "px";
canvas.style.height = ph + "px";
const ctx = canvas.getContext("2d");
ctx.scale(dpr, dpr);
ctx.fillStyle = "#1a1a2e";
ctx.fillRect(0, 0, pw, ph);
const regions = [];
const padL = 4, padR = 4, drawW = pw - padL - padR;
const baseY = ph - 4;
ctx.font = "11px monospace";
ctx.textBaseline = "middle";
const qLower = searchQuery.toLowerCase();
const searching = searchQuery.length > 0;
for (const node of data.nodes) {
const x = padL + node.x * drawW;
const w = node.w * drawW;
const y = baseY - (node.depth + 1) * FG_ROW_H;
if (w < 0.5) continue;
const isAncestor = !!node.isAncestor;
const searchMatch = !searching || node.name.toLowerCase().includes(qLower) || (node.treeNode && node.treeNode.fullName && node.treeNode.fullName.toLowerCase().includes(qLower));
const highlighted = highlightName != null && node.name === highlightName;
const dimmed = (searching && !searchMatch) || (highlightName != null && !highlighted);
let alpha = 1.0;
if (dimmed) alpha = 0.25;
else if (isAncestor) alpha = 0.6;
ctx.globalAlpha = alpha;
ctx.fillStyle = flamegraphColor(node.name);
ctx.fillRect(x, y, Math.max(w - 0.5, 0.5), FG_ROW_H - 1);
regions.push({ x1: x, x2: x + w, y, node, totalSamples: data.totalSamples, rootTotal: data.rootTotal });
if (w > 30) {
ctx.fillStyle = "#fff";
const label = node.name.length * 7 > w - 4
? node.name.slice(0, Math.floor((w - 10) / 7)) + "\u2026"
: node.name;
ctx.save();
ctx.beginPath();
ctx.rect(x + 2, y, w - 4, FG_ROW_H);
ctx.clip();
ctx.fillText(label, x + 3, y + FG_ROW_H / 2);
ctx.restore();
}
}
ctx.globalAlpha = 1.0;
hitRegions[hitKey] = regions;
}
function rebuildData(key) {
const tree = key === "worker" ? workerTree : offworkerTree;
const stack = key === "worker" ? workerZoomStack : offworkerZoomStack;
if (!tree) return null;
const zoomed = stack.length > 0;
const zoomNode = zoomed ? stack[stack.length - 1] : tree;
// Find ancestor chain for zoomed view
let ancestors = [];
if (zoomed) {
const path = findAncestorPath(tree, zoomNode);
if (path) ancestors = path.slice(0, -1); // everything before the zoom target
}
const flat = flattenFromNode(zoomNode, zoomNode.count, ancestors);
return {
nodes: flat.nodes,
maxDepth: flat.maxDepth,
totalSamples: zoomNode.count,
rootTotal: tree.count,
};
}
function renderAll() {
workerData = rebuildData("worker");
offworkerData = rebuildData("offworker");
workerLabel.style.display = workerData ? "" : "none";
workerCanvas.style.display = workerData ? "" : "none";
offworkerLabel.style.display = offworkerData ? "" : "none";
offworkerCanvas.style.display = offworkerData ? "" : "none";
repaint();
renderBreadcrumb();
}
function repaint() {
renderCanvas(workerCanvas, workerData, "worker");
renderCanvas(offworkerCanvas, offworkerData, "offworker");
updateSearchStats();
}
function renderBreadcrumb() {
const wZoomed = workerZoomStack.length > 0;
const oZoomed = offworkerZoomStack.length > 0;
if (!wZoomed && !oZoomed) {
breadcrumbBar.style.display = "none";
return;
}
breadcrumbBar.style.display = "flex";
breadcrumbBar.innerHTML = "";
if (wZoomed) renderBreadcrumbFor("worker", workerZoomStack);
if (oZoomed) {
if (wZoomed) {
const sep = document.createElement("span");
sep.textContent = " | ";
sep.style.color = "#555";
breadcrumbBar.appendChild(sep);
}
renderBreadcrumbFor("offworker", offworkerZoomStack);
}
}
function renderBreadcrumbFor(key, stack) {
const rootSpan = document.createElement("span");
rootSpan.className = "fg-breadcrumb-item fg-breadcrumb-link";
rootSpan.textContent = "(all)";
rootSpan.addEventListener("click", () => {
if (key === "worker") workerZoomStack = [];
else offworkerZoomStack = [];
renderAll();
onZoomChange();
});
breadcrumbBar.appendChild(rootSpan);
for (let i = 0; i < stack.length; i++) {
const arrow = document.createElement("span");
arrow.className = "fg-breadcrumb-sep";
arrow.textContent = " \u203a ";
breadcrumbBar.appendChild(arrow);
const span = document.createElement("span");
const isLast = i === stack.length - 1;
span.className = "fg-breadcrumb-item" + (isLast ? "" : " fg-breadcrumb-link");
span.textContent = stack[i].name;
span.title = stack[i].name;
if (!isLast) {
const idx = i;
span.addEventListener("click", () => {
if (key === "worker") workerZoomStack = workerZoomStack.slice(0, idx + 1);
else offworkerZoomStack = offworkerZoomStack.slice(0, idx + 1);
renderAll();
onZoomChange();
});
}
breadcrumbBar.appendChild(span);
}
}
function updateSearchStats() {
if (!searchQuery) {
searchStats.textContent = "";
return;
}
const qLower = searchQuery.toLowerCase();
let matchedSelf = 0;
let matchedFrames = 0;
let totalSelf = 0;
const wRoot = workerZoomStack.length > 0 ? workerZoomStack[workerZoomStack.length - 1] : workerTree;
const oRoot = offworkerZoomStack.length > 0 ? offworkerZoomStack[offworkerZoomStack.length - 1] : offworkerTree;
if (wRoot) {
const m = countSearchMatches(wRoot, qLower);
matchedSelf += m.selfCount;
matchedFrames += m.frameCount;
totalSelf += wRoot.count;
}
if (oRoot) {
const m = countSearchMatches(oRoot, qLower);
matchedSelf += m.selfCount;
matchedFrames += m.frameCount;
totalSelf += oRoot.count;
}
if (matchedFrames === 0) {
searchStats.textContent = "no matches";
return;
}
let text = matchedFrames + (matchedFrames === 1 ? " frame" : " frames");
if (matchedSelf > 0 && totalSelf > 0) {
const pct = ((matchedSelf / totalSelf) * 100).toFixed(1);
text += ` \u00b7 ${pct}% of samples`;
}
searchStats.textContent = text;
}
searchInput.addEventListener("input", onSearchInput);
function onSearchInput() {
searchQuery = searchInput.value;
searchClear.style.display = searchQuery ? "" : "none";
repaint();
}
function zoomTo(key, treeNode) {
if (!treeNode || treeNode.children.size === 0) return;
if (key === "worker") workerZoomStack.push(treeNode);
else offworkerZoomStack.push(treeNode);
renderAll();
onZoomChange();
}
function resetZoom() {
workerZoomStack = [];
offworkerZoomStack = [];
renderAll();
onZoomChange();
}
function isZoomed() {
return workerZoomStack.length > 0 || offworkerZoomStack.length > 0;
}
let tooltipPinned = false;
function hitTest(e) {
const c = e.target;
const rect = c.getBoundingClientRect();
const mx = e.clientX - rect.left;
const my = e.clientY - rect.top;
const key = c === workerCanvas ? "worker" : "offworker";
const regions = hitRegions[key] || [];
for (let i = regions.length - 1; i >= 0; i--) {
const r = regions[i];
if (mx >= r.x1 && mx <= r.x2 && my >= r.y && my < r.y + FG_ROW_H) {
return { hit: r, hitKey: key };
}
}
return { hit: null, hitKey: key };
}
function buildTooltipHtml(hit, pinned) {
const node = hit.node;
const tn = node.treeNode || {};
const isAncestor = !!node.isAncestor;
// Ancestors belong to the full tree; show their % relative to the root total
const total = isAncestor ? (hit.rootTotal || hit.totalSamples || 1) : (hit.totalSamples || 1);
const pct = ((node.count / total) * 100).toFixed(1);
const selfPct = ((node.self / total) * 100).toFixed(1);
const nameElt = document.createElement("b");
nameElt.innerText = node.name;
let h = nameElt.outerHTML;
if (tn.fullName && tn.fullName !== node.name) {
const fullElt = document.createElement("span");
fullElt.innerText = tn.fullName;
h += '<br><span style="color:#aaa">' + fullElt.innerHTML + '</span>';
}
if (tn.location) {
const locShort = tn.location.replace(/^.*\/([^/]+(?::\d+)?)$/, "$1");
const hasFullPath = tn.location !== locShort;
if (hasFullPath) {
const locEsc = document.createElement("span");
locEsc.innerText = tn.location;
h += '<br><span class="fg-loc-toggle" style="color:#888;cursor:pointer">' +
locShort + ' <span style="color:#555">\u25b6</span></span>' +
'<span class="fg-loc-full" style="color:#888;display:none;overflow-wrap:anywhere">' +
locEsc.innerHTML + '</span>';
} else {
h += '<br><span style="color:#888">' + locShort + '</span>';
}
}
h += '<br>' + node.count + ' samples (' + pct + '%) \u00b7 ' + node.self + ' self (' + selfPct + '%)';
if (pinned && tn.docsUrl) {
h += '<br><a href="' + tn.docsUrl + '" target="_blank" rel="noopener" style="color:#6c63ff;text-decoration:underline">docs.rs \u2197</a>';
} else if (tn.docsUrl) {
h += '<br><span style="color:#6c63ff">docs.rs \u2197</span>' +
'<span style="color:#555"> (' + (isMac ? '\u2318' : 'Ctrl') + ' + click)</span>';
}
if (!pinned) {
h += '<br><span style="color:#555">' + (isMac ? '\u2325' : 'Alt') + ' + click to pin</span>';
}
return h;
}
function showTooltip(hit, x, y, pinned) {
tooltip.innerHTML = buildTooltipHtml(hit, pinned);
tooltip.style.pointerEvents = pinned ? "auto" : "none";
tooltip.style.display = "block";
// Position at top of the flamegraph container so it never covers hovered frames
const containerRect = container.getBoundingClientRect();
const tipX = Math.min(x + 12, window.innerWidth - tooltip.offsetWidth - 8);
const tipY = Math.max(8, containerRect.top);
tooltip.style.left = tipX + "px";
tooltip.style.top = tipY + "px";
if (pinned) {
// Wire up expandable location
const toggle = tooltip.querySelector(".fg-loc-toggle");
const full = tooltip.querySelector(".fg-loc-full");
if (toggle && full) {
const tn = hit.node.treeNode || {};
toggle.addEventListener("click", function () {
if (full.style.display === "none") {
full.textContent = tn.location;
full.style.display = "block";
toggle.querySelector("span").textContent = "\u25bc";
} else {
full.style.display = "none";
toggle.querySelector("span").textContent = "\u25b6";
}
});
}
}
}
function unpinTooltip() {
if (tooltipPinned) {
tooltipPinned = false;
tooltip.style.display = "none";
tooltip.style.pointerEvents = "none";
}
}
function canvasMouseMove(e) {
if (tooltipPinned) return;
const { hit } = hitTest(e);
const newHighlight = hit ? hit.node.name : null;
if (newHighlight !== highlightName) {
highlightName = newHighlight;
if (!repaintQueued) {
repaintQueued = true;
requestAnimationFrame(() => { repaintQueued = false; repaint(); });
}
}
if (hit) {
showTooltip(hit, e.clientX, e.clientY, false);
e.target.style.cursor = "pointer";
} else {
tooltip.style.display = "none";
e.target.style.cursor = "";
}
}
function canvasMouseLeave() {
if (!tooltipPinned) tooltip.style.display = "none";
if (highlightName !== null) {
highlightName = null;
if (!repaintQueued) {
repaintQueued = true;
requestAnimationFrame(() => { repaintQueued = false; repaint(); });
}
}
}
function canvasClick(e, hitKey) {
const { hit } = hitTest(e);
if (!hit) { unpinTooltip(); return; }
const tn = hit.node.treeNode || {};
if ((e.metaKey || e.ctrlKey) && tn.docsUrl) {
const w = window.open(tn.docsUrl, "_blank");
if (w) w.focus();
} else if (e.altKey) {
tooltipPinned = true;
showTooltip(hit, e.clientX, e.clientY, true);
} else {
unpinTooltip();
if (tn.children && tn.children.size > 0) {
if (hit.node.isAncestor) {
// Clicking an ancestor: zoom to that frame
if (hitKey === "worker") workerZoomStack = [tn];
else offworkerZoomStack = [tn];
renderAll();
onZoomChange();
} else {
zoomTo(hitKey, tn);
}
}
}
}
function canvasContextMenu(e, hitKey) {
e.preventDefault();
// Zoom out the canvas you right-clicked, fall back to the other
const primary = hitKey === "offworker" ? offworkerZoomStack : workerZoomStack;
const fallback = hitKey === "offworker" ? workerZoomStack : offworkerZoomStack;
const stack = primary.length > 0 ? primary : fallback;
if (stack.length > 0) {
stack.pop();
renderAll();
onZoomChange();
}
}
// Named handlers so destroy() can remove them
function onWorkerMove(e) { canvasMouseMove(e); }
function onOffworkerMove(e) { canvasMouseMove(e); }
function onWorkerClick(e) { canvasClick(e, "worker"); }
function onOffworkerClick(e) { canvasClick(e, "offworker"); }
function onWorkerContext(e) { canvasContextMenu(e, "worker"); }
function onOffworkerContext(e) { canvasContextMenu(e, "offworker"); }
workerCanvas.addEventListener("mousemove", onWorkerMove);
offworkerCanvas.addEventListener("mousemove", onOffworkerMove);
workerCanvas.addEventListener("mouseleave", canvasMouseLeave);
offworkerCanvas.addEventListener("mouseleave", canvasMouseLeave);
workerCanvas.addEventListener("click", onWorkerClick);
offworkerCanvas.addEventListener("click", onOffworkerClick);
workerCanvas.addEventListener("contextmenu", onWorkerContext);
offworkerCanvas.addEventListener("contextmenu", onOffworkerContext);
function onKeyDown(e) {
if (container.offsetHeight === 0) return;
if (((e.ctrlKey || e.metaKey) && e.key === "f") || (e.key === "/" && document.activeElement !== searchInput)) {
e.preventDefault();
searchInput.focus();
searchInput.select();
}
}
document.addEventListener("keydown", onKeyDown);
function onDocClick(e) {
if (tooltipPinned && !tooltip.contains(e.target) &&
e.target !== workerCanvas && e.target !== offworkerCanvas) {
unpinTooltip();
}
}
document.addEventListener("click", onDocClick);
// Returns true if consumed (search cleared or zoom reset),
// false if nothing to do (caller should close the panel).
function handleEscape() {
if (tooltipPinned) {
unpinTooltip();
return true;
}
if (helpOverlay.style.display !== "none") {
helpOverlay.style.display = "none";
return true;
}
if (searchQuery) {
searchInput.value = "";
searchQuery = "";
searchClear.style.display = "none";
renderAll();
return true;
}
if (isZoomed()) {
resetZoom(); // resetZoom already calls onZoomChange
return true;
}
return false;
}
function applySpawnFilter() {
const filterVal = spawnFilter.value;
const samples = filterVal
? allSamples.filter((s) => (s.spawnLoc || "(unknown)") === filterVal)
: allSamples;
const workerSamples = samples.filter((s) => s.workerId !== 255);
const offworkerSamples = samples.filter((s) => s.workerId === 255);
workerTree = workerSamples.length > 0
? buildFlamegraphTree(workerSamples, currentSymbols)
: null;
offworkerTree = offworkerSamples.length > 0
? buildFlamegraphTree(offworkerSamples, currentSymbols)
: null;
workerZoomStack = [];
offworkerZoomStack = [];
workerLabel.textContent =
`Worker threads \u2014 ${workerSamples.length} samples`;
offworkerLabel.textContent =
`Off-worker (sampler thread) \u2014 ${offworkerSamples.length} samples`;
renderAll();
}
spawnFilter.addEventListener("change", applySpawnFilter);
function setData(samples, callframeSymbols) {
allSamples = samples;
currentSymbols = callframeSymbols;
// Build spawn location dropdown
const locCounts = new Map();
for (const s of samples) {
const loc = s.spawnLoc || "(unknown)";
locCounts.set(loc, (locCounts.get(loc) || 0) + 1);
}
spawnFilter.innerHTML = '<option value="">All tasks (' + samples.length + ' samples)</option>';
const sorted = [...locCounts.entries()].sort((a, b) => b[1] - a[1]);
for (const [loc, count] of sorted) {
const short = loc.replace(/.*\//, "");
const opt = document.createElement("option");
opt.value = loc;
opt.textContent = short + " (" + count + ")";
opt.title = loc;
spawnFilter.appendChild(opt);
}
applySpawnFilter();
}
function resize() {
renderCanvas(workerCanvas, workerData, "worker");
renderCanvas(offworkerCanvas, offworkerData, "offworker");
}
function destroy() {
document.removeEventListener("keydown", onKeyDown);
document.removeEventListener("click", onDocClick);
workerCanvas.removeEventListener("mousemove", onWorkerMove);
offworkerCanvas.removeEventListener("mousemove", onOffworkerMove);
workerCanvas.removeEventListener("mouseleave", canvasMouseLeave);
offworkerCanvas.removeEventListener("mouseleave", canvasMouseLeave);
workerCanvas.removeEventListener("click", onWorkerClick);
offworkerCanvas.removeEventListener("click", onOffworkerClick);
workerCanvas.removeEventListener("contextmenu", onWorkerContext);
offworkerCanvas.removeEventListener("contextmenu", onOffworkerContext);
searchInput.removeEventListener("input", onSearchInput);
if (tooltip.parentNode) tooltip.parentNode.removeChild(tooltip);
container.innerHTML = "";
}
function getZoomPath() {
function fullPath(tree, stack) {
if (!tree || stack.length === 0) return [];
// If stack already has the full path (from zoomToPath restore), use it directly.
// Otherwise find the path from root to the zoom target.
const target = stack[stack.length - 1];
const path = findNodePath(tree, target.name);
return path ? path.map((n) => n.name) : stack.map((n) => n.name);
}
return {
worker: fullPath(workerTree, workerZoomStack),
offworker: fullPath(offworkerTree, offworkerZoomStack),
};
}
// Find a node by name anywhere in the tree via DFS, return path from root.
function findNodePath(tree, name) {
const path = [];
function dfs(node) {
path.push(node);
if (node.name === name) return true;
for (const child of node.children.values()) {
if (dfs(child)) return true;
}
path.pop();
return false;
}
for (const child of tree.children.values()) {
if (dfs(child)) return path;
}
return null;
}
// Like findNodePath but uses object identity instead of name matching.
function findAncestorPath(tree, target) {
const path = [];
function dfs(node) {
path.push(node);
if (node === target) return true;
for (const child of node.children.values()) {
if (dfs(child)) return true;
}
path.pop();
return false;
}
for (const child of tree.children.values()) {
if (dfs(child)) return path;
}
return null;
}
function zoomToPath(key, names) {
const tree = key === "worker" ? workerTree : offworkerTree;
if (!tree || !names.length) return;
const stack = key === "worker" ? workerZoomStack : offworkerZoomStack;
// Try walking child-by-child (works when names is a full path from root)
let node = tree;
for (let i = 0; i < names.length; i++) {
let found = null;
for (const child of node.children.values()) {
if (child.name === names[i]) { found = child; break; }
}
if (!found) {
// Path walk failed, fall back to DFS for the last name
const path = findNodePath(tree, names[names.length - 1]);
if (path) stack.push.apply(stack, path);
break;
}
stack.push(found);
node = found;
}
if (stack.length > 0) renderAll();
}
return { setData, resize, destroy, handleEscape, isZoomed, getZoomPath, zoomToPath };
}
const fgExports = { createFlamegraph: createFlamegraph, filterCpuSamples: filterCpuSamples };
if (typeof module !== "undefined" && module.exports) {
module.exports = fgExports;
} else {
exports.FlamegraphRenderer = fgExports;
}
})(typeof exports === "undefined" ? this : exports);