feat(profiler): navigate and zoom the flame graph with the keyboard (#4294)

The flame graph had no keyboard focus target. It is now focusable with a current frame (outlined, announced via aria-activedescendant): Up/Down go to callee/caller, Left/Right to neighbours, Enter zooms, Escape resets, F4 opens the source. Fixes #4209.
This commit is contained in:
l0ng-ai
2026-11-18 19:45:37 +08:00
committed by GitHub
parent 893d9af6e6
commit 995a9563f7
5 changed files with 117 additions and 5 deletions
@@ -91,6 +91,13 @@
outline: 1px solid var(--fg-muted);
outline-offset: -1px;
}
.flame:focus {
outline: none;
}
.flame:focus .current {
outline: 2px solid var(--accent);
outline-offset: -2px;
}
.c1 {
background: var(--flame-1);
}
+21 -1
View File
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { render, screen, within } from "@testing-library/react";
import { fireEvent, render, screen, within } from "@testing-library/react";
import type { Profile, ProfileMode } from "@/platform/ipc";
import { useI18n } from "@/platform/i18n";
import { ProfilerTabs, ProfilerView } from "./ProfilerView";
@@ -48,6 +48,26 @@ describe("ProfilerView", () => {
expect(screen.getByText("async-profiler · 610.4 MB allocated")).toBeInTheDocument();
});
it("moves through the flame graph and zooms with the keyboard", () => {
addSnapshot("App", profile("cpu", 100));
render(<ProfilerView />);
const graph = screen.getByRole("tree", { name: "Flame graph" });
expect(graph.tabIndex).toBe(0);
const current = () =>
document.getElementById(graph.getAttribute("aria-activedescendant")!)?.getAttribute("aria-label");
expect(current()).toBe("all (100 ms)");
fireEvent.keyDown(graph, { key: "ArrowUp" });
expect(current()).toBe("Main.run");
fireEvent.keyDown(graph, { key: "Enter" });
expect(screen.getByText("Zoomed into Main.run")).toBeInTheDocument();
fireEvent.keyDown(graph, { key: "ArrowUp" });
expect(current()).toBe("Main.work");
fireEvent.keyDown(graph, { key: "ArrowDown" });
expect(current()).toBe("Main.run");
fireEvent.keyDown(graph, { key: "Escape" });
expect(screen.queryByText("Zoomed into Main.run")).toBeNull();
});
it("marks the allocated type in the flame graph and the method list", () => {
addSnapshot("App", profile("allocations", 640_000_000));
const flame = render(<ProfilerView />);
+41 -4
View File
@@ -3,12 +3,12 @@
* (click to zoom, search highlights), the call tree (top-down) and the method
* list (self / total). Double-click opens a frame's source when known.
*/
import { useLayoutEffect, useMemo, useRef, useState } from "react";
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import type { Profile } from "@/platform/ipc";
import { EmptyState, Icon, IconButton, Input, Tabs, Tree, T } from "@/ui";
import { editorService } from "@/workbench/contributions";
import { colorSlot, flameLayout, formatWeight, frameLocation, matchingFrames, share } from "./model";
import { colorSlot, flameLayout, flameStep, formatWeight, frameLocation, matchingFrames, share } from "./model";
import { activeSnapshot, closeSnapshot, useProfiler, type ProfilerTab } from "./store";
import styles from "./Profiler.module.css";
import { useTx } from "@/platform/i18n";
@@ -96,6 +96,28 @@ function FlameGraph({ profile, query }: { profile: Profile; query: string }) {
return () => ro.disconnect();
}, []);
const layout = useMemo(() => flameLayout(profile, focus, width > 0 ? 1 / width : 0.002), [profile, focus, width]);
// The frame the keyboard is on: arrows move it, Enter zooms into it, F4 opens its source.
const [current, setCurrent] = useState(0);
const shown = layout.rects.some((r) => r.node === current) ? current : focus;
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
const moves: Record<string, Parameters<typeof flameStep>[2]> = {
ArrowUp: "deeper",
ArrowDown: "shallower",
ArrowLeft: "previous",
ArrowRight: "next",
};
const move = moves[e.key];
if (move) setCurrent(flameStep(layout.rects, shown, move));
else if (e.key === "Enter") setFocus(shown);
else if (e.key === "Escape" && focus !== 0) setFocus(0);
else if (e.key === "F4") openFrame(profile, profile.nodes[shown]!.frame);
else return;
e.preventDefault();
e.stopPropagation();
};
useEffect(() => {
ref.current?.querySelector(`[data-node="${shown}"]`)?.scrollIntoView?.({ block: "nearest" });
}, [shown]);
const matches = useMemo(() => matchingFrames(profile, query), [profile, query]);
const unit = profile.unit;
const total = profile.total ?? 0;
@@ -109,7 +131,15 @@ function FlameGraph({ profile, query }: { profile: Profile; query: string }) {
</div>
)}
<div className={styles.flameScroll} ref={ref}>
<div className={styles.flame} style={{ height: layout.depth * ROW }} role="tree" aria-label={tx("Flame graph")}>
<div
className={styles.flame}
style={{ height: layout.depth * ROW }}
role="tree"
aria-label={tx("Flame graph")}
tabIndex={0}
aria-activedescendant={`flame-frame-${shown}`}
onKeyDown={onKeyDown}
>
{width > 0 &&
layout.rects.map((r) => {
const node = profile.nodes[r.node]!;
@@ -120,17 +150,24 @@ function FlameGraph({ profile, query }: { profile: Profile; query: string }) {
return (
<div
key={r.node}
id={`flame-frame-${r.node}`}
data-node={r.node}
role="treeitem"
aria-label={label}
aria-selected={r.node === shown}
className={clsx(
styles.frame,
r.node === shown && styles.current,
styles[`c${colorSlot(frame.name)}`],
frame.kind === "allocatedType" && styles.typeFrame,
matches && (matches.has(node.frame) ? styles.match : styles.dim),
)}
style={{ left: r.x * width, width: Math.max(w - 1, 1), bottom: r.depth * ROW }}
title={`${frame.kind === "allocatedType" ? `${tx("Allocated type")}\n` : ""}${frame.name}${location ? ` (${location})` : ""}\nTotal: ${formatWeight(node.total ?? 0, unit)} (${share(node.total ?? 0, total)})\nSelf: ${formatWeight(node.selfWeight ?? 0, unit)}`}
onClick={() => setFocus(r.node)}
onClick={() => {
setCurrent(r.node);
setFocus(r.node);
}}
onDoubleClick={() => openFrame(profile, node.frame)}
>
{w > 28 && <span className={styles.frameText}>{label}</span>}
+28
View File
@@ -110,6 +110,34 @@ export function flameLayout(profile: Profile, focus = 0, minWidth = 0.002): { re
return { rects, depth: maxDepth + 1 };
}
/**
* Keyboard moves in the flame graph from the frame `node`: `deeper` to its widest callee,
* `shallower` to its caller, `previous` / `next` to the neighbouring frame on its row.
*/
export function flameStep(
rects: readonly FlameRect[],
node: number,
move: "deeper" | "shallower" | "previous" | "next",
): number {
const at = rects.find((r) => r.node === node);
if (!at) return rects[0]?.node ?? node;
switch (move) {
case "deeper": {
const inside = rects.filter((r) => r.depth === at.depth + 1 && r.x >= at.x && r.x < at.x + at.width);
return inside.reduce<FlameRect | undefined>((a, r) => (!a || r.width > a.width ? r : a), undefined)?.node ?? node;
}
case "shallower":
// A callee starts inside its caller's span.
return rects.find((r) => r.depth === at.depth - 1 && r.x <= at.x && at.x < r.x + r.width)?.node ?? node;
case "previous":
case "next": {
const row = rects.filter((r) => r.depth === at.depth).sort((a, b) => a.x - b.x);
const i = row.indexOf(at) + (move === "next" ? 1 : -1);
return row[i]?.node ?? node;
}
}
}
const parentCache = new WeakMap<Profile, Int32Array>();
/** Parent node of every node (-1 for the root). */
+20
View File
@@ -4,6 +4,7 @@ import {
allocationProfilerSupports,
colorSlot,
flameLayout,
flameStep,
formatWeight,
frameLocation,
matchingFrames,
@@ -108,3 +109,22 @@ describe("profiler model", () => {
expect(colorSlot("main")).toBeGreaterThanOrEqual(1);
});
});
describe("flameStep", () => {
// root (0) → a (1, 60%) and b (2, 40%); a → c (3)
const rects = [
{ node: 0, depth: 0, x: 0, width: 1 },
{ node: 1, depth: 1, x: 0, width: 0.6 },
{ node: 2, depth: 1, x: 0.6, width: 0.4 },
{ node: 3, depth: 2, x: 0, width: 0.5 },
];
it("goes to the widest callee, the caller and the neighbours on a row", () => {
expect(flameStep(rects, 0, "deeper")).toBe(1);
expect(flameStep(rects, 1, "next")).toBe(2);
expect(flameStep(rects, 2, "next")).toBe(2);
expect(flameStep(rects, 2, "previous")).toBe(1);
expect(flameStep(rects, 2, "deeper")).toBe(2);
expect(flameStep(rects, 3, "shallower")).toBe(1);
expect(flameStep(rects, 2, "shallower")).toBe(0);
});
});