Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 07e5ec7c0b fix(profiler): keep Escape in the focused zoomed flame graph 2026-11-18 19:42:41 +08:00
l0ng-ai 6d42597038 fix(profiler): make flame graph frames keyboard navigable 2026-11-18 19:39:56 +08:00
5 змінених файлів з 209 додано та 16 видалено

No files matched your search

+9
Переглянути файл
@@ -91,6 +91,15 @@
outline: 1px solid var(--fg-muted);
outline-offset: -1px;
}
.flame:focus {
outline: none;
}
.flame:focus-visible .frame[aria-selected="true"] {
outline: 2px solid var(--focus-ring);
outline-offset: -2px;
opacity: 1;
z-index: 1;
}
.c1 {
background: var(--flame-1);
}
+98 -1
Переглянути файл
@@ -1,7 +1,10 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { registerAction } from "@/platform/actions";
import type { Profile, ProfileMode } from "@/platform/ipc";
import { useI18n } from "@/platform/i18n";
import { installKeyboardDispatcher } from "@/platform/keymap";
import { ProfilerTabs, ProfilerView } from "./ProfilerView";
import { addSnapshot, resetProfiler, useProfiler } from "./store";
@@ -35,6 +38,100 @@ beforeEach(() => {
afterEach(() => useI18n.setState({ texts: {} }));
describe("ProfilerView", () => {
it("reaches Flame Graph from Search frames and navigates and zooms with the keyboard", async () => {
const data = profile("cpu", 120);
data.frames.push({ name: "Main.wait", file: null, line: null, kind: "code" });
data.nodes[1]!.children.push(3);
data.nodes[2]!.total = data.nodes[2]!.selfWeight = 100;
data.nodes.push({ frame: 3, total: 20, selfWeight: 20, children: [] });
addSnapshot("App", data);
render(<ProfilerView />);
const user = userEvent.setup();
const search = screen.getByRole("textbox", { name: "Search frames" });
const graph = screen.getByRole("tree", { name: "Flame graph" });
const frame = (name: string | RegExp) => within(graph).getByRole("treeitem", { name });
const active = (name: string | RegExp) => expect(graph).toHaveAttribute("aria-activedescendant", frame(name).id);
search.focus();
await user.tab();
expect(graph).toHaveFocus();
active(/^all/);
expect(
within(graph)
.getAllByRole("treeitem")
.every((node) => node.tabIndex < 0),
).toBe(true);
await user.keyboard("{ArrowDown}");
active("Main.run");
await user.keyboard("{ArrowRight}");
active("Main.work");
await user.keyboard("{ArrowDown}");
active("Main.wait");
await user.keyboard("{ArrowLeft}");
active("Main.run");
await user.keyboard("{End}{Enter}");
expect(screen.getByText("Zoomed into Main.wait")).toBeInTheDocument();
expect(within(graph).queryByRole("treeitem", { name: "Main.work" })).not.toBeInTheDocument();
expect(graph).toHaveFocus();
active("Main.wait");
await user.keyboard("{Escape}");
expect(frame("Main.work")).toBeInTheDocument();
expect(graph).toHaveFocus();
await user.tab({ shift: true });
expect(search).toHaveFocus();
});
it("starts at a search match and restores focus to the graph after reset", async () => {
addSnapshot("App", profile("cpu", 120));
render(<ProfilerView />);
const user = userEvent.setup();
const search = screen.getByRole("textbox", { name: "Search frames" });
const graph = screen.getByRole("tree", { name: "Flame graph" });
await user.type(search, "work");
await user.tab();
const match = within(graph).getByRole("treeitem", { name: "Main.work" });
expect(graph).toHaveAttribute("aria-activedescendant", match.id);
await user.keyboard(" ");
expect(screen.getByText("Zoomed into Main.work")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Reset Zoom" }));
expect(graph).toHaveFocus();
expect(screen.queryByText("Zoomed into Main.work")).not.toBeInTheDocument();
await user.click(within(graph).getByRole("treeitem", { name: "Main.run" }));
expect(screen.getByText("Zoomed into Main.run")).toBeInTheDocument();
});
it("reserves Escape ahead of the workbench only when the zoomed graph has focus", async () => {
addSnapshot("App", profile("cpu", 120));
const focusEditor = vi.fn();
const unregister = registerAction({ id: "toolwindow.focusEditor", title: "Focus Editor", run: focusEditor });
const uninstall = installKeyboardDispatcher();
try {
render(<ProfilerView />);
const user = userEvent.setup();
const graph = screen.getByRole("tree", { name: "Flame graph" });
graph.focus();
await user.keyboard("{ArrowDown}{Enter}");
expect(screen.getByText("Zoomed into Main.run")).toBeInTheDocument();
screen.getByRole("textbox", { name: "Search frames" }).focus();
await user.keyboard("{Escape}");
expect(focusEditor).toHaveBeenCalledOnce();
expect(screen.getByText("Zoomed into Main.run")).toBeInTheDocument();
graph.focus();
await user.keyboard("{Escape}");
expect(screen.queryByText("Zoomed into Main.run")).not.toBeInTheDocument();
expect(focusEditor).toHaveBeenCalledOnce();
expect(graph).toHaveFocus();
await user.keyboard("{Escape}");
expect(focusEditor).toHaveBeenCalledTimes(2);
} finally {
uninstall();
unregister();
}
});
it("allocation profile shows bytes and marks type frames", () => {
addSnapshot("App", profile("allocations", 640_000_000));
useProfiler.setState({ tab: "tree" });
+93 -9
Переглянути файл
@@ -3,12 +3,13 @@
* (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 { useCallback, useId, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import type { Profile } from "@/platform/ipc";
import { registerKeyClaim } from "@/platform/keymap";
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, formatWeight, frameLocation, matchingFrames, parentIndex, share } from "./model";
import { activeSnapshot, closeSnapshot, useProfiler, type ProfilerTab } from "./store";
import styles from "./Profiler.module.css";
import { useTx } from "@/platform/i18n";
@@ -85,8 +86,11 @@ export function ProfilerTabs() {
function FlameGraph({ profile, query }: { profile: Profile; query: string }) {
const tx = useTx();
const ref = useRef<HTMLDivElement>(null);
const graphRef = useRef<HTMLDivElement>(null);
const graphId = useId();
const [width, setWidth] = useState(0);
const [focus, setFocus] = useState(0);
const [zoom, setZoom] = useState(0);
const [cursor, setCursor] = useState<{ node: number; query: string } | null>(null);
useLayoutEffect(() => {
const el = ref.current;
if (!el) return;
@@ -95,21 +99,98 @@ function FlameGraph({ profile, query }: { profile: Profile; query: string }) {
setWidth(el.clientWidth);
return () => ro.disconnect();
}, []);
const layout = useMemo(() => flameLayout(profile, focus, width > 0 ? 1 / width : 0.002), [profile, focus, width]);
const layout = useMemo(() => flameLayout(profile, zoom, width > 0 ? 1 / width : 0.002), [profile, zoom, width]);
const matches = useMemo(() => matchingFrames(profile, query), [profile, query]);
const parents = useMemo(() => parentIndex(profile), [profile]);
const active =
(cursor?.query === query ? layout.rects.find((r) => r.node === cursor.node) : undefined) ??
(matches ? layout.rects.find((r) => matches.has(profile.nodes[r.node]!.frame)) : undefined) ??
layout.rects.find((r) => r.node === zoom);
const activeId = width > 0 && active ? `${graphId}-${active.node}` : undefined;
const scrollToActive = useCallback(() => {
const graph = graphRef.current;
if (activeId && graph && graph.ownerDocument.activeElement === graph) {
graph.ownerDocument.getElementById(activeId)?.scrollIntoView({ block: "nearest", inline: "nearest" });
}
}, [activeId]);
useLayoutEffect(scrollToActive, [scrollToActive, layout.depth]);
useLayoutEffect(() => {
if (zoom === 0) return;
return registerKeyClaim((event, stroke) => stroke === "Escape" && event.target === graphRef.current);
}, [zoom]);
const zoomTo = (node: number) => {
setZoom(node);
setCursor({ node, query });
graphRef.current?.focus({ preventScroll: true });
};
const resetZoom = () => {
setZoom(0);
graphRef.current?.focus({ preventScroll: true });
};
const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (!active || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
const index = layout.rects.indexOf(active);
const next = layout.rects[index + 1];
let target: number | undefined;
switch (event.key) {
case "ArrowUp":
target = layout.rects[index - 1]?.node;
break;
case "ArrowDown":
target = next?.node;
break;
case "ArrowLeft":
target = parents[active.node];
break;
case "ArrowRight":
if (next && parents[next.node] === active.node) target = next.node;
break;
case "Home":
target = layout.rects[0]?.node;
break;
case "End":
target = layout.rects.at(-1)?.node;
break;
case "Enter":
case " ":
zoomTo(active.node);
break;
case "Escape":
if (zoom === 0) return;
resetZoom();
break;
default:
return;
}
if (target !== undefined && target >= 0) setCursor({ node: target, query });
event.preventDefault();
event.stopPropagation();
};
const unit = profile.unit;
const total = profile.total ?? 0;
return (
<div className={styles.flamePane}>
{focus !== 0 && (
{zoom !== 0 && (
<div className={styles.flameBar}>
<IconButton icon="close" size="small" title="Reset Zoom" onClick={() => setFocus(0)} />
<span className={styles.muted}>{tx`Zoomed into ${profile.frames[profile.nodes[focus]!.frame]!.name}`}</span>
<IconButton icon="close" size="small" title="Reset Zoom" onClick={resetZoom} />
<span className={styles.muted}>{tx`Zoomed into ${profile.frames[profile.nodes[zoom]!.frame]!.name}`}</span>
</div>
)}
<div className={styles.flameScroll} ref={ref}>
<div className={styles.flame} style={{ height: layout.depth * ROW }} role="tree" aria-label={tx("Flame graph")}>
<div
ref={graphRef}
className={styles.flame}
style={{ height: layout.depth * ROW }}
role="tree"
aria-label={tx("Flame graph")}
aria-activedescendant={activeId}
aria-keyshortcuts="ArrowUp ArrowDown ArrowLeft ArrowRight Home End Enter Space Escape"
tabIndex={activeId ? 0 : -1}
onFocus={scrollToActive}
onKeyDown={onKeyDown}
>
{width > 0 &&
layout.rects.map((r) => {
const node = profile.nodes[r.node]!;
@@ -120,8 +201,11 @@ function FlameGraph({ profile, query }: { profile: Profile; query: string }) {
return (
<div
key={r.node}
id={`${graphId}-${r.node}`}
role="treeitem"
aria-label={label}
aria-level={r.depth + 1}
aria-selected={r.node === active?.node}
className={clsx(
styles.frame,
styles[`c${colorSlot(frame.name)}`],
@@ -130,7 +214,7 @@ function FlameGraph({ profile, query }: { profile: Profile; query: string }) {
)}
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={() => zoomTo(r.node)}
onDoubleClick={() => openFrame(profile, node.frame)}
>
{w > 28 && <span className={styles.frameText}>{label}</span>}
+8 -6
Переглянути файл
@@ -78,9 +78,9 @@ export interface FlameRect {
}
/**
* Flame graph rectangles (root at depth 0, callees above their callers in rows
* below) for the subtree under `focus`, dropping those narrower than `minWidth`.
* The focused node's ancestors are shown full width above it, as in IDEA.
* Flame graph rectangles in tree order (callers before callees, siblings left
* to right), dropping those narrower than `minWidth`. The focused node's
* ancestors are shown full width below it, as in IDEA.
*/
export function flameLayout(profile: Profile, focus = 0, minWidth = 0.002): { rects: FlameRect[]; depth: number } {
const nodes = profile.nodes;
@@ -102,10 +102,12 @@ export function flameLayout(profile: Profile, focus = 0, minWidth = 0.002): { re
rects.push({ node, depth, x, width });
maxDepth = Math.max(maxDepth, depth);
let cx = x;
for (const c of n.children) {
stack.push({ node: c, depth: depth + 1, x: cx });
const children = n.children.map((c) => {
const child = { node: c, depth: depth + 1, x: cx };
cx += (nodes[c]!.total ?? 0) / total;
}
return child;
});
for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]!);
}
return { rects, depth: maxDepth + 1 };
}
+1
Переглянути файл
@@ -78,6 +78,7 @@ describe("profiler model", () => {
it("lays out the flame graph and zooms into a node", () => {
const { rects, depth } = flameLayout(profile);
expect(depth).toBe(3);
expect(rects.map((r) => r.node)).toEqual([0, 1, 2, 3]);
const at = (node: number) => rects.find((r) => r.node === node)!;
expect(at(0)).toEqual({ node: 0, depth: 0, x: 0, width: 1 });
expect(at(2)).toMatchObject({ depth: 2, x: 0, width: 0.6 });