Compare commits

..
Author SHA1 Message Date
l0ng-ai 2066055077 test(maven): check that turning Always update snapshots off drops -U on a stored config
Maven settings are applied to the stored configuration at each launch; the test
re-applied them to the already-applied one and expected -U to go away, which
broke main's Rust checks.
2026-11-19 20:13:12 +08:00
66 changed files with 614 additions and 2571 deletions

No files matched your search

-8
View File
@@ -48,14 +48,6 @@ Latencies are measured from input to the start of the first frame that shows the
A scenario in `perf/scenarios.ts` has an `id`, a `title` and a `run(h)` that drives the page through the harness (`perf/lib/harness.ts`: open files, set the cursor, type and measure, read editor state) and returns metrics. Add a budget for each metric you want enforced as `"<scenario>.<metric>"` in `budgets.json`.
### Current-operation checks
An already-visible result is not evidence that the measured action worked. Interaction waits require a current input and the requested state transition; file opening checks the active full path, typing checks the resulting text/caret and key-sample count, and scroll/completion navigation checks its destination.
Code-intelligence evals also wait for successful action completion. Rename correctness uses the current matching request only: multi-file previews validate proposed edits, while applied local renames validate the edited document. Incomplete answers are degraded results. Clean-file diagnostics require a fresh backend publication for that document, including an explicitly empty publication; a quiet empty UI alone cannot pass.
Diagnostics acknowledgements match the path, backend source and local opening token. Backend publications carry no document version, so a delayed same-path publication after reopening cannot be distinguished from a newly computed one.
## Backend: `pnpm perf:rust`
`perf/rust.ts` runs `cargo bench` for `ide-text`, `ide-language`, `ide-index`, `ide-search`, `ide-host` and `ide-heap`, reads the Criterion results, and checks each bench's mean (in µs).
-8
View File
@@ -48,14 +48,6 @@ UI 构建和每次尝试都有独立于渲染器动画帧的五分钟墙钟期
`perf/scenarios.ts` 中的场景包含 `id`、`title` 和 `run(h)`:通过 harness(`perf/lib/harness.ts`:打开文件、设置光标、输入并测量、读取编辑器状态)驱动页面并返回指标。需要强制检查的指标,在 `budgets.json` 中以 `"<scenario>.<metric>"` 加上预算。
### 当前操作的正确性检查
已显示的结果不能证明被测操作成功。交互等待必须观察到当前输入及目标状态变化;打开文件会核对活动编辑器的完整路径,输入会核对最终文本、光标和按键样本数,滚动及补全导航会核对目标位置。
代码智能 eval 也会等待动作成功结束。重命名只使用当前匹配请求的结果:跨文件预览验证拟议的修改,已应用的局部重命名验证实际文档。不完整的答复按降级结果处理。干净文件的诊断必须收到针对该文档的新后端发布,包括明确的空发布;仅有安静且为空的 UI 不能通过。
诊断确认匹配路径、后端来源和本地打开令牌。后端发布不携带文档版本,因此重新打开后延迟到达的同路径发布,无法与新计算的发布区分。
## 后端:`pnpm perf:rust`
`perf/rust.ts` 对 `ide-text`、`ide-language`、`ide-index`、`ide-search`、`ide-host` 和 `ide-heap` 运行 `cargo bench`,读取 Criterion 结果,检查每个基准的平均值(µs)。
-56
View File
@@ -98,59 +98,3 @@ test("commit message history opens above the message without an empty icon colum
expect(Math.abs(menuBox!.x - messageBox!.x)).toBeLessThan(2);
await expect(row.locator("span")).toHaveCount(1);
});
test("the Commit changes toolbar fits a narrow side pane", async ({ workbench: page }) => {
await stubRepository(page);
await page.keyboard.press("Meta+k");
await page.evaluate(async () => {
const path = "/src/workbench/toolwindows/store.ts";
const layout = await import(/* @vite-ignore */ path);
layout.moveToolWindow("commit", "left");
layout.setToolWindowSize("left", 164);
});
const panel = page.getByRole("region", { name: "Commit", exact: true });
const toolbar = panel.getByRole("toolbar", { name: "Changes" });
await expect(toolbar).toBeVisible();
const clipped = await toolbar.evaluate((bar) => {
const bounds = bar.getBoundingClientRect();
return [...bar.querySelectorAll("button")].flatMap((button) => {
const box = button.getBoundingClientRect();
return box.right > bounds.right + 1 || box.bottom > bounds.bottom + 1 ? [button.ariaLabel] : [];
});
});
expect(clipped).toEqual([]);
const push = panel.getByRole("button", { name: "Commit and Push…" });
const overflow = await push.locator("span").evaluate((label) => label.scrollWidth - label.clientWidth);
expect(overflow).toBeLessThanOrEqual(1);
await toolbar.getByRole("button", { name: "Collapse All" }).click();
await expect(panel.getByRole("checkbox", { name: "Include build.gradle.kts in commit" })).toBeHidden();
});
test("the commit message uses the configured editor typography", async ({ workbench: page }) => {
await stubRepository(page);
await page.keyboard.press("Meta+k");
const message = page.getByRole("textbox", { name: "Commit message" });
await expect(message).toBeFocused();
await page.evaluate(async () => {
const path = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ path);
const settings = useProject.getState().settings;
useProject.setState({
settings: {
...settings,
editor: {
...settings?.editor,
fontFamily: "Fira Code",
fallbackFont: "Maple Mono NF CN",
fontSize: 17,
lineHeight: 28,
fontWeight: 500,
},
},
});
});
await expect(message).toHaveCSS("font-size", "17px");
await expect(message).toHaveCSS("line-height", "28px");
await expect(message).toHaveCSS("font-weight", "500");
await expect(message).toHaveCSS("font-family", /"Fira Code".*"Maple Mono NF CN"/);
});
+1 -1
View File
@@ -30,7 +30,7 @@ for (const kind of ["run", "debug", "services-run", "services-debug", "stacktrac
component = SessionPanel;
props = {
session: run.useRun.getState().sessions.find((s: { id: string }) => s.id === id),
showLifecycle: kind === "run",
...(kind === "services-run" ? { onRerun: null, onDebug: null } : {}),
};
} else if (kind === "debug" || kind === "services-debug") {
const statePath = "/src/features/debugger/state.ts";
-27
View File
@@ -1,27 +0,0 @@
import { expect, test } from "./fixtures";
test("keeps debug actions and views accessible when the Debug window is docked at the side", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 900, height: 760 });
await page.evaluate(async () => {
const debugModule = "/src/features/debugger/state.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const servicesModule = "/src/workbench/contributions.ts";
const { adoptSession } = await import(/* @vite-ignore */ debugModule);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
const { toolWindowService } = await import(/* @vite-ignore */ servicesModule);
adoptSession(91, { name: "Checkout service", adapter: "java-debug", status: "starting" });
moveToolWindow("debug", "right");
setToolWindowSize("right", 300);
toolWindowService().show("debug", true);
});
const pane = page.getByRole("region", { name: "Debug", exact: true });
const toolbar = pane.getByRole("toolbar", { name: "Debugger actions" });
const views = pane.getByRole("tablist", { name: "Debug views" });
await expect(toolbar.getByRole("button", { name: "More", exact: true })).toBeInViewport();
await expect(views.getByRole("tab", { name: "Console", exact: true })).toBeInViewport();
await views.getByRole("tab", { name: "Memory", exact: true }).click();
await expect(views.getByRole("tab", { name: "Memory", exact: true })).toHaveAttribute("aria-selected", "true");
});
-39
View File
@@ -1,39 +0,0 @@
import { expect, openFromTree, test } from "./fixtures";
test("fits a long wrapped tab and its close button inside a narrow editor group", async ({ workbench: page }) => {
const filename = "QuarterlyReconciliationAndCheckoutAllocation.test.ts";
await page.setViewportSize({ width: 720, height: 760 });
await openFromTree(page, "README.md");
await page.evaluate(async (filename) => {
const projectModule = "/src/platform/project.ts";
const projectFilesModule = "/src/features/project-tree/fs.ts";
const editorModule = "/src/editor/core/controller.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const { projectFs } = await import(/* @vite-ignore */ projectFilesModule);
const { editorController, useTabs } = await import(/* @vite-ignore */ editorModule);
const { project, settings } = useProject.getState();
useProject.setState({
settings: {
...settings,
editor: { ...settings?.editor, tabs: { ...settings?.editor?.tabs, multipleRows: true } },
},
});
const path = `${project.root}/${filename}`;
await projectFs(project.root).createFile(path);
await editorController().openFilesIn([path], useTabs.getState().activePane, "right");
}, filename);
const tab = page.getByRole("tab", { name: filename, exact: true });
await expect(tab).toHaveAttribute("aria-selected", "true");
await expect
.poll(() =>
tab.evaluate((element) => {
const close = element.parentElement?.querySelector("[data-tab-close]");
const strip = element.closest('[role="tablist"]');
return !!close && !!strip && close.getBoundingClientRect().right <= strip.getBoundingClientRect().right;
}),
)
.toBe(true);
await tab.locator("..").getByRole("button", { name: "Close Tab", exact: true }).click();
await expect(tab).toBeHidden();
});
-41
View File
@@ -76,47 +76,6 @@ test.beforeEach(async ({ workbench: page }) => {
});
});
test("fits a wide graph and saved columns without horizontal scrolling", async ({ workbench: page }) => {
await page.evaluate(async () => {
const module = "/src/features/vcs/logOptions.ts";
const { useLogOptions } = await import(/* @vite-ignore */ module);
useLogOptions.setState({
showColumnHeaders: true,
showHash: true,
showSignature: true,
columnWidths: { author: 400, date: 240 },
});
});
const list = page.getByRole("listbox", { name: "Commits" });
await expect(list.getByRole("separator", { name: "Resize Date column" })).toBeVisible();
for (const width of [1400, 620, 400]) {
await page.setViewportSize({ width, height: 900 });
await expect
.poll(() =>
list.evaluate((element) => {
const header = [...element.querySelectorAll("[data-log-column]")];
const row = [...element.querySelector('[role="option"]')!.children];
const right = element.getBoundingClientRect().right;
return {
fits: element.scrollWidth === element.clientWidth,
aligned: header.every((cell, i) => {
const heading = cell.getBoundingClientRect();
const data = row[i]!.getBoundingClientRect();
return heading.width > 0 && heading.right <= right && Math.abs(heading.right - data.right) < 1;
}),
};
}),
)
.toEqual({ fits: true, aligned: true });
}
await list.hover();
await page.mouse.wheel(450, 450);
await expect.poll(() => list.evaluate((element) => element.scrollTop)).toBeGreaterThan(0);
expect(await list.evaluate((element) => element.scrollLeft)).toBe(0);
});
test("keeps a wide Git graph filled during scrollbar drags and its edges interactive afterwards", async ({
workbench: page,
}) => {
-27
View File
@@ -94,30 +94,3 @@ test("a second click on a Git Log toolbar button closes its popup", async ({ wor
await expect(row).toBeHidden();
}
});
test("Git Log keeps filters and actions inside the commit pane at the minimum window width", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 400, height: 500 });
const toolbar = page.getByRole("toolbar", { name: "Log filters" });
const clippedButtons = () =>
toolbar.evaluate((el) => {
const bar = el.getBoundingClientRect();
return Array.from(el.querySelectorAll("button"))
.filter((button) => {
if (getComputedStyle(button).visibility === "hidden") return false;
const box = button.getBoundingClientRect();
return box.width > 0 && (box.right > bar.right + 1 || box.bottom > bar.bottom + 1);
})
.map((button) => button.getAttribute("aria-label"));
});
await expect.poll(clippedButtons).toEqual([]);
const search = toolbar.getByRole("textbox", { name: "Filter by message" });
await expect(search).toBeVisible();
expect((await search.boundingBox())!.width).toBeGreaterThan(12);
await toolbar.getByRole("button", { name: "View Options" }).click();
await expect(page.getByRole("menuitemcheckbox", { name: "Tag Names" })).toBeVisible();
await page.keyboard.press("Escape");
await toolbar.getByRole("button", { name: "More Filters" }).click();
await expect(page.getByRole("menuitem", { name: "Paths" })).toBeVisible();
});
-34
View File
@@ -1,34 +0,0 @@
import { expect, test } from "./fixtures";
test("keeps diagnostic text and file counts visible in a narrow Problems pane", async ({ workbench: page }) => {
await page.setViewportSize({ width: 720, height: 760 });
await page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const problemsModule = "/src/features/code-insight/problemsStore.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const { applyDiagnosticsEvent } = await import(/* @vite-ignore */ problemsModule);
const root = useProject.getState().project.root;
const path = `${root}/src/features/checkout/shared/services/with-a-long-directory-name/for-order-processing/orders.ts`;
const source = "typescript-eslint-application-rules-with-a-very-long-source-label";
applyDiagnosticsEvent(path, source, [
{
range: { start: { line: 2, col: 2 }, end: { line: 2, col: 9 } },
severity: "error",
source,
message: "Invalid order total",
},
]);
});
await page.getByRole("button", { name: "Problems", exact: true }).click();
const pane = page.locator('[data-toolwindow="problems"]');
await pane.getByRole("tab", { name: /Project Errors/ }).click();
await expect(pane.getByRole("toolbar", { name: "Problems actions" })).toHaveAttribute("aria-orientation", "vertical");
const tree = pane.getByRole("tree", { name: "Problems" });
const count = tree.getByText("1 error", { exact: true });
const message = tree.getByText("Invalid order total", { exact: true });
await expect(count).toBeVisible();
await expect(message).toBeVisible();
await expect.poll(() => message.evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(true);
await expect.poll(() => tree.evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(true);
});
-19
View File
@@ -1,19 +0,0 @@
import { expect, test } from "./fixtures";
test("gives the project name room before its path in a narrow tree", async ({ workbench: page }) => {
await page.evaluate(async () => {
const storeModule = "/src/features/project-tree/store.ts";
const { useProjectTree } = await import(/* @vite-ignore */ storeModule);
useProjectTree.setState({ name: "checkout-order-processing" });
});
const pane = page.getByRole("region", { name: "Project", exact: true });
await pane.getByRole("button", { name: "Options", exact: true }).click();
await page.getByRole("menuitemcheckbox", { name: "Horizontal Scrolling" }).click();
const tree = pane.getByRole("tree", { name: "Project" });
const name = tree.getByText("checkout-order-processing", { exact: true });
await expect(name).toBeVisible();
await expect.poll(() => name.evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(true);
await expect.poll(() => tree.evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(true);
});
-33
View File
@@ -81,39 +81,6 @@ test("⌘F2 stops a running process", async ({ workbench: page }) => {
await expect(run.getByRole("tab", { name: "dev" })).toHaveAttribute("data-tooltip", /exit code 143$/);
});
test("a short Run pane has room for the full toolbar above the output", async ({ workbench: page }) => {
await page.setViewportSize({ width: 400, height: 500 });
const output = "Watching for changes…";
await stubRun(page, [{ kind: "stdout", text: `${output}\n` }], null);
await page.keyboard.press("Control+r");
const run = page.getByRole("region", { name: "Run", exact: true });
await expect(run.getByText(output)).toBeVisible();
await page.evaluate(async () => {
const path = "/src/workbench/toolwindows/store.ts";
const { setToolWindowSize } = await import(/* @vite-ignore */ path);
setToolWindowSize("bottom", 160);
});
const toolbar = run.getByRole("toolbar", { name: "Run actions" });
const clipped = await toolbar.evaluate((el) => {
const bar = el.getBoundingClientRect();
return Array.from(el.querySelectorAll("button")).flatMap((button) => {
const box = button.getBoundingClientRect();
return box.left < bar.left - 1 || box.right > bar.right + 1 || box.bottom > bar.bottom + 1
? [button.getAttribute("aria-label")]
: [];
});
});
expect(clipped).toEqual([]);
await expect(toolbar).toHaveAttribute("aria-orientation", "horizontal");
const toolbarBox = (await toolbar.boundingBox())!;
const consoleBox = (await run.getByRole("log").boundingBox())!;
expect(consoleBox.y).toBeGreaterThanOrEqual(toolbarBox.y + toolbarBox.height - 1);
await toolbar.getByRole("button", { name: "Clear All" }).click();
await expect(run.getByText(output)).toBeHidden();
await toolbar.getByRole("button", { name: "Stop" }).click();
await expect.poll(() => ipcCalls(page, "run_stop")).toEqual([{ id: RUN_ID }]);
});
test("Go reruns keep each package's exact failures and the original configuration", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
+29 -68
View File
@@ -13,32 +13,6 @@ async function run(page: Page, id: string) {
}, id);
}
async function stubFindMatches(page: Page) {
await stubDesktop(page);
await page.evaluate(() => {
window.__ipc.handlers.search_validate = () => null;
window.__ipc.handlers.search_start = (args) => {
const send = (event: unknown) => window.__ipc.send(args.onEvent, event);
const text = "base=http://localhost:8080";
setTimeout(() => {
for (let i = 0; i < 12; i++) {
const relPath = `config/endpoint-${i}.txt`;
const matches = [{ line: 0, text, ranges: [[5, text.length]], textOffset: 0 }];
send({
type: "file",
file: { path: `/dev/acme-api/${relPath}`, relPath, matches },
});
}
send({
type: "done",
summary: { files: 12, matches: 12, limitHit: false, cancelled: false, elapsedMs: 4 },
});
}, 20);
return null;
};
});
}
async function expectControlsFit(page: Page) {
const dialog = page.getByRole("dialog");
await expect(dialog).toBeVisible();
@@ -68,7 +42,35 @@ test.describe("search popups at the minimum window width", () => {
for (const id of ["find.inPath", "find.replaceInPath"]) {
test(`${id} keeps its title, count and buttons visible`, async ({ workbench: page }) => {
await stubFindMatches(page);
await stubDesktop(page);
await page.evaluate(() => {
window.__ipc.handlers.search_validate = () => null;
window.__ipc.handlers.search_start = (args) => {
const send = (event: unknown) => window.__ipc.send(args.onEvent, event);
const text = "base=http://localhost:8080";
setTimeout(() => {
for (let i = 0; i < 12; i++) {
const relPath = `config/endpoint-${i}.txt`;
const matches = [{ line: 0, text, ranges: [[5, text.length]], textOffset: 0 }];
send({
type: "file",
file: { path: `/dev/acme-api/${relPath}`, relPath, matches },
});
}
send({
type: "done",
summary: {
files: 12,
matches: 12,
limitHit: false,
cancelled: false,
elapsedMs: 4,
},
});
}, 20);
return null;
};
});
await run(page, id);
await page.getByRole("dialog").getByPlaceholder("Search").fill("http://localhost:8080");
await expect(page.getByRole("dialog").locator("header [aria-live]")).toContainText(/match/);
@@ -93,19 +95,6 @@ test.describe("search popups at the minimum window width", () => {
});
}
test("directory scope gives the path field room at the minimum width", async ({ workbench: page }) => {
await stubDesktop(page);
await run(page, "find.inPath");
const dialog = page.getByRole("dialog", { name: "Find in Files" });
await dialog.getByRole("tab", { name: "Directory", exact: true }).click();
const input = dialog.getByRole("textbox", { name: "Directory", exact: true });
await expect(input).toBeVisible();
const { width } = (await input.boundingBox())!;
expect(width).toBeGreaterThan(200);
await expectControlsFit(page);
await dialog.getByRole("button", { name: /Browse/ }).click({ trial: true });
});
for (const id of [
"navigate.searchEverywhere",
"navigate.searchText",
@@ -122,31 +111,3 @@ test.describe("search popups at the minimum window width", () => {
});
}
});
test("Find in Files prioritizes the preview and remembers an adjusted split", async ({ workbench: page }) => {
await stubFindMatches(page);
await run(page, "find.inPath");
const dialog = page.getByRole("dialog", { name: "Find in Files" });
await dialog.getByPlaceholder("Search").fill("http://localhost:8080");
const results = dialog.locator("[data-panel][id=results]");
const preview = dialog.locator("[data-panel][id=preview]");
const handle = dialog.getByTestId("find-popup-split").getByRole("separator");
const resultsShare = async () => {
const resultHeight = (await results.boundingBox())!.height;
const previewHeight = (await preview.boundingBox())!.height;
return resultHeight / (resultHeight + previewHeight);
};
await expect(handle).toBeAttached();
await expect.poll(resultsShare).toBeCloseTo(0.33, 2);
await handle.press("ArrowUp");
await expect.poll(resultsShare).toBeLessThan(0.31);
const adjusted = await resultsShare();
await page.setViewportSize({ width: 400, height: 500 });
await expect.poll(resultsShare).toBeGreaterThan(adjusted + 0.02);
await dialog.getByPlaceholder("Search").press("Escape");
await expect(dialog).toBeHidden();
await page.setViewportSize({ width: 1400, height: 900 });
await run(page, "find.inPath");
await expect(handle).toBeAttached();
await expect.poll(resultsShare).toBeCloseTo(adjusted, 2);
});
-1
View File
@@ -72,7 +72,6 @@ test("settings sidebar resizes with mouse and keyboard and remembers its width",
await expect(handle).toBeVisible();
const sidebar = dialog.locator("#navigation");
const initial = (await sidebar.boundingBox())!.width;
expect(initial / (await dialog.getByTestId("settings").boundingBox())!.width).toBeCloseTo(0.225, 2);
const box = (await handle.boundingBox())!;
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
await page.mouse.down();
-37
View File
@@ -1,37 +0,0 @@
import { expect, test } from "./fixtures";
test("keeps the file count visible beside a long directory in the TODO pane", async ({ workbench: page }) => {
await page.setViewportSize({ width: 900, height: 760 });
await page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const todoModule = "/src/features/todo/store.ts";
const { useProject } = await import(/* @vite-ignore */ projectModule);
const { useTodos } = await import(/* @vite-ignore */ todoModule);
const directory = "src/features/checkout/shared/services/with-a-long-directory-name/for-order-processing";
const path = `${useProject.getState().project.root}/${directory}/orders.ts`;
useTodos.setState({
scannedOnce: true,
error: null,
scanned: new Map([[path, [{ path, line: 8, col: 3, keyword: "TODO", text: "TODO: validate orders" }]]]),
});
});
await page.getByRole("button", { name: "TODO" }).click();
const pane = page.locator('[data-toolwindow="todo"]');
const toolbar = pane.getByRole("toolbar", { name: "TODO actions" });
await expect(toolbar).toHaveAttribute("aria-orientation", "vertical");
const tree = pane.getByRole("tree", { name: "TODO items" });
const fileName = tree.getByText("orders.ts", { exact: true });
await expect(fileName).toBeVisible();
await expect.poll(() => fileName.evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(true);
const count = tree.getByText("1 item", { exact: true });
await expect(count).toBeVisible();
await expect
.poll(() =>
count.evaluate(
(element) =>
element.getBoundingClientRect().right <= element.closest('[role="tree"]')!.getBoundingClientRect().right,
),
)
.toBe(true);
});
+36 -69
View File
@@ -7,8 +7,6 @@ import { join } from "node:path";
import { track } from "../lib/measure.ts";
import { normalizePath, type EvalScenario, type Measured } from "../lib/scenario.ts";
import type { Session } from "../lib/session.ts";
import { renameFinished, renameResult, type RenameStep } from "../lib/renameObservation.ts";
import type { Renamed } from "../../src/bindings.ts";
const SRC = "src/main/java/com/example/orders";
const TEST = "src/test/java/com/example/orders";
@@ -19,7 +17,7 @@ const LONG_TIMEOUT = 60_000;
interface ProbeWindow {
__openideaPerf: {
editorState(): { doc: number; path: string; head: number; line: number; col: number; word: string } | null;
editorState(): { path: string; head: number; line: number; word: string } | null;
editorText(): string | null;
setCursor(offset: number): void;
insertAfter(after: string, text: string): number;
@@ -27,8 +25,6 @@ interface ProbeWindow {
completionPending(): boolean;
diagnostics(): Array<{ line: number; severity: string; message: string }>;
lineAtY(y: number): number;
openFileForDiagnostics(path: string, source: string): Promise<number>;
diagnosticsPublished(generation: number): boolean;
};
}
@@ -377,21 +373,10 @@ function diagnosticsOnOpen(project: string, id: string, title: string, file: str
async setup() {},
async step(s): Promise<Measured> {
const timing = await track(s.page, {
run: async (arg) => {
const w = window as unknown as ProbeWindow;
arg.generation = await w.__openideaPerf.openFileForDiagnostics(arg.path, "jdtls");
},
arg: { path: join(s.root, file), generation: 0 },
first: (arg) => {
const w = window as unknown as ProbeWindow;
return (
w.__openideaPerf.diagnosticsPublished(arg.generation) && !!document.querySelector(".cm-content .cm-line")
);
},
done: (arg) => {
const w = window as unknown as ProbeWindow;
return w.__openideaPerf.diagnosticsPublished(arg.generation);
},
openFile: join(s.root, file),
arg: null,
first: () => !!document.querySelector(".cm-content .cm-line"),
done: () => true,
signature: problems,
settleMs: 3000,
timeoutMs: TIMEOUT,
@@ -529,19 +514,12 @@ function quickDoc(project: string, id: string, title: string, at: Place): EvalSc
};
}
interface RenameAnswer {
edit: { files: Array<{ path?: string; edits?: Array<{ range: { start: { line: number } }; new_text: string }> }> };
}
/** Rename in place to `newName`, then ↵: every edit it makes (a preview is left unapplied). */
function rename(
project: string,
id: string,
title: string,
at: Place,
newName: string,
mode: RenameStep["mode"],
): EvalScenario {
const prepared = new WeakMap<
Session,
{ doc: number; path: string; pos: { line: number; col: number }; original: string }
>();
function rename(project: string, id: string, title: string, at: Place, newName: string): EvalScenario {
return {
id,
title,
@@ -550,39 +528,23 @@ function rename(
conditions: ["warm"],
async setup(s) {
await reach(s, at);
const before = await s.page.evaluate(() => {
const w = window as unknown as ProbeWindow;
const state = w.__openideaPerf.editorState();
const original = w.__openideaPerf.editorText();
if (!state || original === null) throw new Error("no active editor before rename");
return { doc: state.doc, path: state.path, pos: { line: state.line, col: state.col }, original };
});
prepared.set(s, before);
await s.keepText();
await s.runAction("refactor.rename");
await s.page.waitForSelector(".cm-lsp-inplace-primary", { timeout: TIMEOUT });
await s.page.keyboard.type(newName);
},
async step(s): Promise<Measured> {
const before = prepared.get(s);
if (!before) throw new Error("rename was not prepared");
const scope = s.renameObservations.begin({ doc: before.doc, pos: before.pos, newName });
const arg: RenameStep = {
scope,
root: s.root,
path: before.path,
original: before.original,
oldName: at.word,
newName,
mode,
answer: null,
const answered = (newName: string) => {
if (document.querySelector('[data-testid="refactor-preview"]')) return true;
if (document.querySelector(".cm-lsp-hint:not([data-pending]):not(.cm-lsp-inplace-hint)")) return true;
return (
!document.querySelector(".cm-lsp-inplace") &&
!!(window as unknown as ProbeWindow).__openideaPerf.editorText()?.includes(newName)
);
};
const timing = await track(s.page, {
run: async (arg) => {
const w = window as unknown as { __openideaEvalRenameAnswer(scope: number): Promise<Renamed> };
const content = document.querySelector(".cm-content");
if (!content) throw new Error("no editor for rename");
content.dispatchEvent(
run: () =>
document.querySelector(".cm-content")?.dispatchEvent(
new KeyboardEvent("keydown", {
key: "Enter",
code: "Enter",
@@ -590,17 +552,25 @@ function rename(
bubbles: true,
cancelable: true,
}),
);
arg.answer = await w.__openideaEvalRenameAnswer(arg.scope);
},
arg,
first: renameFinished,
done: renameFinished,
),
arg: newName,
first: answered,
done: answered,
timeoutMs: TIMEOUT,
});
const answer = s.renameObservations.completed(scope) as Renamed | null;
if (!answer) throw new Error("rename did not receive a current successful response");
return { timing, ...renameResult(s.root, answer, newName) };
// The preview only counts per file: where the name lands is in the answer it shows. A server
// may merge nearby occurrences into one edit, so every line of its new text counts.
const answer = s.lastAnswer.get("lsp_rename") as RenameAnswer | undefined;
const changes = (answer?.edit.files ?? []).flatMap((f) =>
(f.edits ?? []).flatMap((e) =>
e.new_text
.split("\n")
.flatMap((l, i) =>
l.includes(newName) ? [`${normalizePath(s.root, f.path!)}:${e.range.start.line + i + 1}`] : [],
),
),
);
return { timing, results: { changes } };
},
};
}
@@ -778,7 +748,6 @@ export const JAVA_SCENARIOS: EvalScenario[] = [
"Rename: method used across files",
{ file: `${SRC}/Order.java`, line: "public long totalCents() {", word: "totalCents" },
"orderTotalCents",
"preview",
),
rename(
APP,
@@ -786,7 +755,6 @@ export const JAVA_SCENARIOS: EvalScenario[] = [
"Rename: local variable",
{ file: BOOK, line: "Order order = new Order(customer, product, quantity, unitPriceCents);", word: "order" },
"placedOrder",
"applied",
),
declaration(
@@ -869,6 +837,5 @@ export const JAVA_SCENARIOS: EvalScenario[] = [
"Rename: entity method used across controllers and tests",
{ file: `${PET}/owner/Owner.java`, line: "public void addVisit(Integer petId, Visit visit) {", word: "addVisit" },
"recordVisit",
"preview",
),
];
-91
View File
@@ -1,91 +0,0 @@
import { describe, expect, test } from "vitest";
import { RenameObservations } from "./commandObservation.ts";
const target = { doc: 7, pos: { line: 2, col: 8 }, newName: "renamed" };
const answer = { edit: { files: [] }, incomplete: null };
function deferred() {
let resolve!: (value: unknown) => void;
// The harness TypeScript project targets ES2023.
const promise = new Promise<unknown>((done) => {
resolve = done;
});
return { promise, resolve };
}
describe("rename command observations", () => {
test("consumes only a matching command in the current operation", async () => {
const capture = new RenameObservations();
const scope = capture.begin(target);
await capture.invoke("lsp_rename", { ...target, doc: 8, request: 1 }, async () => answer);
await capture.invoke("lsp_rename", { ...target, newName: "other", request: 2 }, async () => answer);
await capture.invoke("lsp_rename", { ...target, pos: { line: 3, col: 8 }, request: 3 }, async () => answer);
expect(capture.completed(scope)).toBeNull();
await capture.invoke("lsp_rename", { ...target, request: 4 }, async () => answer);
expect(await capture.wait(scope)).toEqual(answer);
});
test("reset and failure cannot supply a preceding success", async () => {
const capture = new RenameObservations();
const previous = capture.begin(target);
await capture.invoke("lsp_rename", { ...target, request: 1 }, async () => answer);
capture.reset();
expect(capture.completed(previous)).toBeNull();
await expect(capture.wait(previous)).rejects.toThrow("operation expired");
const current = capture.begin(target);
const waiting = capture.wait(current);
const rejected = expect(waiting).rejects.toThrow("rename failed");
await expect(
capture.invoke("lsp_rename", { ...target, request: 2 }, async () => {
throw new Error("rename failed");
}),
).rejects.toThrow("rename failed");
await rejected;
expect(capture.completed(current)).toBeNull();
});
test("a failed retry clears a success in the same operation", async () => {
const capture = new RenameObservations();
const scope = capture.begin(target);
await capture.invoke("lsp_rename", { ...target, request: 1 }, async () => answer);
expect(capture.completed(scope)).toEqual(answer);
await expect(
capture.invoke("lsp_rename", { ...target, request: 2 }, async () => {
throw new Error("retry failed");
}),
).rejects.toThrow("retry failed");
expect(capture.completed(scope)).toBeNull();
await expect(capture.wait(scope)).rejects.toThrow("retry failed");
});
test("a delayed result from before reset cannot win over a new request", async () => {
const capture = new RenameObservations();
capture.begin(target);
const old = deferred();
const sending = capture.invoke("lsp_rename", { ...target, request: 1 }, () => old.promise);
capture.reset();
const current = capture.begin(target);
old.resolve(answer);
await sending;
expect(capture.completed(current)).toBeNull();
const fresh = { ...answer, preview: true };
await capture.invoke("lsp_rename", { ...target, request: 2 }, async () => fresh);
expect(await capture.wait(current)).toEqual(fresh);
});
test("a superseded in-flight request cannot overwrite the latest failure", async () => {
const capture = new RenameObservations();
const scope = capture.begin(target);
const old = deferred();
const sending = capture.invoke("lsp_rename", { ...target, request: 1 }, () => old.promise);
await expect(
capture.invoke("lsp_rename", { ...target, request: 2 }, async () => {
throw new Error("latest failed");
}),
).rejects.toThrow("latest failed");
old.resolve(answer);
await sending;
expect(capture.completed(scope)).toBeNull();
await expect(capture.wait(scope)).rejects.toThrow("latest failed");
});
});
-74
View File
@@ -1,74 +0,0 @@
/** Command capture shared by the Session relay and rename's measured operation. */
export interface RenameTarget {
doc: number;
pos: { line: number; col: number };
newName: string;
}
interface Operation {
scope: number;
target: RenameTarget;
request: number;
result: { ok: true; value: unknown } | { ok: false; error: unknown } | null;
listeners: Array<{ resolve(value: unknown): void; reject(error: unknown): void }>;
}
export class RenameObservations {
private generation = 0;
private operation: Operation | null = null;
begin(target: RenameTarget): number {
this.reset();
this.operation = { scope: this.generation, target, request: 0, result: null, listeners: [] };
return this.generation;
}
reset() {
this.generation++;
for (const listener of this.operation?.listeners ?? []) listener.reject(new Error("rename operation expired"));
this.operation = null;
}
/** Captures the invocation, not just its answer: old requests retain their original scope. */
async invoke<T>(cmd: string, args: unknown, send: () => Promise<T>): Promise<T> {
const op = this.operation;
const actual = args as Partial<RenameTarget> | null;
const matching =
cmd === "lsp_rename" &&
op &&
actual &&
actual.doc === op.target.doc &&
actual.newName === op.target.newName &&
actual.pos?.line === op.target.pos.line &&
actual.pos?.col === op.target.pos.col;
const request = matching ? ++op.request : 0;
if (matching) op.result = null;
try {
const value = await send();
if (matching && this.operation === op && op.request === request) {
op.result = { ok: true, value };
for (const listener of op.listeners.splice(0)) listener.resolve(value);
}
return value;
} catch (error) {
if (matching && this.operation === op && op.request === request) {
op.result = { ok: false, error };
for (const listener of op.listeners.splice(0)) listener.reject(error);
}
throw error;
}
}
completed(scope: number): unknown | null {
const op = this.operation;
return op?.scope === scope && op.result?.ok ? op.result.value : null;
}
wait(scope: number): Promise<unknown> {
const op = this.operation;
if (!op || op.scope !== scope) return Promise.reject(new Error("rename operation expired"));
if (op.result) return op.result.ok ? Promise.resolve(op.result.value) : Promise.reject(op.result.error);
// ES2023 harnesses cannot use Promise.withResolvers().
return new Promise((resolve, reject) => op.listeners.push({ resolve, reject }));
}
}
-77
View File
@@ -1,77 +0,0 @@
// @vitest-environment node
import { chromium, type Browser, type Page } from "@playwright/test";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { track } from "./measure.ts";
let browser: Browser;
let page: Page;
beforeAll(async () => {
browser = await chromium.launch({ headless: true });
});
beforeEach(async () => {
page = await browser.newPage();
await page.setContent('<div role="dialog">Previous dialog</div><div id="result">Previous result</div>');
await page.evaluate(() => {
Object.assign(window, {
__openideaPerf: {
editorState: () => null,
runAction: async () => false,
},
});
});
});
afterEach(async () => {
await page.close();
});
afterAll(async () => {
await browser.close();
});
const existingResult = () => document.querySelector("#result") !== null;
describe("tracking the current action", () => {
it("rejects an action that declines to run even with an old result visible", async () => {
await expect(
track(page, { action: "unavailable", arg: null, first: existingResult, done: existingResult, timeoutMs: 1000 }),
).rejects.toThrow(/did not run/);
});
it("cannot report success before an asynchronous action later rejects", async () => {
await expect(
track(page, {
// Real browser frames exercise ordering against track's rAF observer; no elapsed-time guess.
run: () =>
new Promise((_, reject) => {
requestAnimationFrame(() => requestAnimationFrame(() => reject(new Error("operation failed"))));
}),
arg: null,
first: existingResult,
done: existingResult,
timeoutMs: 1000,
}),
).rejects.toThrow("operation failed");
});
it("waits for successful action completion and observes its current result", async () => {
const timing = await track(page, {
run: () =>
new Promise<void>((resolve) => {
requestAnimationFrame(() => {
document.querySelector("#result")!.textContent = "Current result";
requestAnimationFrame(() => {
document.querySelector("#result")!.setAttribute("data-completed", "true");
resolve();
});
});
}),
arg: null,
first: () => document.querySelector("#result")?.textContent === "Current result",
done: () => document.querySelector("#result")?.textContent === "Current result",
timeoutMs: 1000,
});
expect(await page.locator("#result").textContent()).toBe("Current result");
expect(timing.completeMs).toBeGreaterThanOrEqual(timing.firstResultMs);
expect(timing.feedbackMs).toBeGreaterThanOrEqual(timing.firstResultMs);
expect(await page.locator("#result").getAttribute("data-completed")).toBe("true");
});
});
+13 -43
View File
@@ -76,57 +76,26 @@ export async function track<A>(page: Page, spec: TrackSpec<A>): Promise<Tracked>
let lastSig: string | null = null;
let lastChange = 0;
const before = w.__openideaPerf.editorState();
const feedbackSelector = '.cm-lsp-hint, [data-testid="usages-popup"], [role="dialog"], [role="listbox"]';
const beforeFeedback = new Map<Element, { text: string | null; loading: string | null; busy: string | null }>();
for (const el of document.querySelectorAll(feedbackSelector)) {
if (el.getClientRects().length) {
beforeFeedback.set(el, {
text: el.textContent,
loading: el.getAttribute("data-loading"),
busy: el.getAttribute("aria-busy"),
});
}
}
const visible = (sel: string) =>
[...document.querySelectorAll(sel)].some((el) => (el as HTMLElement).getClientRects().length > 0);
const anyFeedback = () => {
for (const el of document.querySelectorAll(feedbackSelector)) {
if (!el.getClientRects().length) continue;
const previous = beforeFeedback.get(el);
if (
!previous ||
previous.text !== el.textContent ||
previous.loading !== el.getAttribute("data-loading") ||
previous.busy !== el.getAttribute("aria-busy")
)
return true;
}
if (visible('.cm-lsp-hint, [data-testid="usages-popup"], [role="dialog"], [role="listbox"]')) return true;
const now = w.__openideaPerf.editorState();
if ((now?.path ?? null) !== (before?.path ?? null) || (now && before && now.head !== before.head)) return true;
return checks.feedback?.(arg, before) ?? false;
};
const times: { feedbackMs?: number; firstResultMs?: number; completeMs?: number } = {};
const t0 = performance.now();
let completed = false;
let failed: string | null = null;
const started = Promise.resolve().then<unknown>(() =>
run
? make(run)!(arg, before)
: openFile
? w.__openideaPerf.openFile(openFile)
: w.__openideaPerf.runAction(action!, actionArg),
);
void started.then(
(value) => {
if (!run && !openFile && value !== true) failed = "action did not run";
else completed = true;
},
(error: unknown) => {
failed = error instanceof Error ? error.message : String(error);
},
);
let failed: unknown = null;
const started = run
? new Promise((resolve) => resolve(make(run)!(arg, before)))
: openFile
? w.__openideaPerf.openFile(openFile)
: w.__openideaPerf.runAction(action!, actionArg);
void started.catch((e: unknown) => (failed = e));
return new Promise<{ times: typeof times; timedOut: boolean; error: string | null }>((resolve) => {
const tick = () => {
const t = performance.now() - t0;
if (failed !== null) return resolve({ times, timedOut: false, error: failed });
try {
if (times.feedbackMs === undefined && anyFeedback()) times.feedbackMs = t;
if (times.firstResultMs === undefined && checks.first(arg, before)) times.firstResultMs = t;
@@ -138,7 +107,7 @@ export async function track<A>(page: Page, spec: TrackSpec<A>): Promise<Tracked>
}
}
const settled = !sign || t - lastChange >= (settleMs ?? 0);
if (completed && times.firstResultMs !== undefined && settled && checks.done(arg, before)) {
if (times.firstResultMs !== undefined && settled && checks.done(arg, before)) {
// Session.reset waits out the time in which invoking it again widens it.
if (action === "find.showUsages")
(window as unknown as { __openideaEvalShowUsagesAt?: number }).__openideaEvalShowUsagesAt =
@@ -150,6 +119,7 @@ export async function track<A>(page: Page, spec: TrackSpec<A>): Promise<Tracked>
} catch (e) {
return resolve({ times, timedOut: false, error: String(e) });
}
if (failed) return resolve({ times, timedOut: false, error: String((failed as Error).message ?? failed) });
if (t > timeoutMs) return resolve({ times, timedOut: true, error: null });
requestAnimationFrame(tick);
};
@@ -172,7 +142,7 @@ export async function track<A>(page: Page, spec: TrackSpec<A>): Promise<Tracked>
);
const r = await withDeadline(operation, spec.timeoutMs + 1000, "page measurement");
const what = spec.action ?? (spec.openFile ? `open ${spec.openFile}` : "step");
if (r.error !== null) throw new Error(`${what}: ${r.error}`);
if (r.error) throw new Error(`${what}: ${r.error}`);
if (r.timedOut) {
const seen =
r.times.firstResultMs !== undefined
-104
View File
@@ -1,104 +0,0 @@
import { afterEach, expect, test } from "vitest";
import { renameFinished, renameResult, type RenameStep } from "./renameObservation.ts";
import type { Renamed } from "../../src/bindings.ts";
const original = "int order = 1;\nuse(order);";
const answer: Renamed = {
edit: {
files: [
{
kind: "edit",
path: "/p/A.java",
edits: [
{ range: { start: { line: 0, col: 4 }, end: { line: 0, col: 9 } }, new_text: "placedOrder" },
{ range: { start: { line: 1, col: 4 }, end: { line: 1, col: 9 } }, new_text: "placedOrder" },
],
},
],
},
incomplete: null,
};
const step: RenameStep = {
scope: 1,
path: "/p/A.java",
root: "/p",
oldName: "order",
newName: "placedOrder",
original,
mode: "applied",
answer,
};
let text = original;
let state = { path: step.path, word: "order", head: 9, line: 0 };
const w = window as unknown as { __openideaPerf?: unknown };
function fixture() {
w.__openideaPerf = { editorText: () => text, editorState: () => state };
document.body.innerHTML = '<div class="cm-content"><div class="cm-line"></div></div>';
}
afterEach(() => {
document.body.innerHTML = "";
delete w.__openideaPerf;
text = original;
state = { path: step.path, word: "order", head: 9, line: 0 };
});
test("a successful response and typed new name are not an applied rename", () => {
fixture();
document.body.insertAdjacentHTML("beforeend", '<span class="cm-lsp-hint">Rename failed</span>');
text = original.replace("order", "placedOrder");
expect(renameFinished(step)).toBe(false);
text = original.replaceAll("order", "placedOrder");
state = { ...state, word: "placedOrder", head: 14 };
expect(renameFinished(step)).toBe(false);
document.querySelector(".cm-lsp-hint")!.remove();
expect(renameFinished(step)).toBe(true);
expect(renameFinished({ ...step, answer: null })).toBe(false);
state = { ...state, path: "/p/other.java" };
expect(renameFinished(step)).toBe(false);
});
test("preview requires the matching title, files and counts without applying text", () => {
fixture();
const preview: RenameStep = { ...step, mode: "preview" };
document.body.insertAdjacentHTML(
"beforeend",
'<div role="dialog"><h2>Rename \'order\' to \'placedOrder\'</h2><ul data-testid="refactor-preview"><li><span title="A.java">A.java</span><span>2 occurrences</span></li></ul></div>',
);
expect(renameFinished(preview)).toBe(true);
expect(renameFinished(step)).toBe(false);
text = original.replaceAll("order", "placedOrder");
expect(renameFinished(preview)).toBe(false);
text = original;
document.querySelector("[title]")!.setAttribute("title", "other.java");
expect(renameFinished(preview)).toBe(false);
});
test("incomplete responses retain warning identity instead of claiming local application", () => {
fixture();
text = original.replaceAll("order", "placedOrder");
state = { ...state, word: "placedOrder", head: 14 };
expect(renameFinished({ ...step, answer: { ...answer, incomplete: "indexing" } })).toBe(false);
const incomplete: Renamed = { ...answer, incomplete: "indexing" };
expect(renameResult("/p", incomplete, "placedOrder")).toEqual({
results: { changes: ["A.java:1", "A.java:2"] },
degraded: "Rename may be incomplete: indexing",
});
text = original;
document.body.insertAdjacentHTML(
"beforeend",
'<div role="dialog"><h2>Rename \'order\' to \'placedOrder\'</h2><div role="note">May be incomplete: the language server is still indexing</div><ul data-testid="refactor-preview"><li><span title="A.java">A.java</span><span>2 occurrences</span></li></ul></div>',
);
expect(renameFinished({ ...step, answer: incomplete })).toBe(true);
expect(renameResult("/p", answer, "placedOrder").degraded).toBeNull();
});
test("an incomplete empty answer reports degradation only with its warning, never a terminal error", () => {
fixture();
const incomplete: Renamed = { edit: { files: [] }, incomplete: "indexing" };
document.body.insertAdjacentHTML("beforeend", '<span class="cm-lsp-hint">Rename failed</span>');
expect(renameFinished({ ...step, answer: incomplete })).toBe(false);
document.querySelector(".cm-lsp-hint")!.textContent = "May be incomplete: the language server is still indexing";
expect(renameFinished({ ...step, answer: incomplete })).toBe(true);
expect(renameResult("/p", incomplete, "placedOrder").degraded).toBe("Rename may be incomplete: indexing");
expect(renameFinished({ ...step, answer: { edit: { files: [] }, incomplete: null } })).toBe(false);
});
-121
View File
@@ -1,121 +0,0 @@
import { normalizePath } from "./scenario.ts";
import type { Renamed } from "../../src/bindings.ts";
export interface RenameStep {
scope: number;
root: string;
path: string;
original: string;
oldName: string;
newName: string;
mode: "preview" | "applied";
answer: Renamed | null;
}
/** Self-contained: track serializes this check into the measured page. */
export function renameFinished(arg: RenameStep): boolean {
const answer = arg.answer;
if (!answer || document.querySelector(".cm-lsp-inplace")) return false;
type ProbeWindow = {
__openideaPerf: {
editorText(): string | null;
editorState(): { path: string; head: number; word: string } | null;
};
};
const w = window as unknown as ProbeWindow;
const probe = w.__openideaPerf;
const state = probe.editorState();
const text = probe.editorText();
if (state?.path !== arg.path || text === null) return false;
if (!answer.edit.files.length) {
return (
text === arg.original &&
!!answer.incomplete &&
/may be incomplete/i.test(document.querySelector(".cm-lsp-hint:not([data-pending])")?.textContent ?? "")
);
}
if (document.querySelector(".cm-lsp-hint:not([data-pending]):not(.cm-lsp-inplace-hint)")) return false;
const preview = document.querySelector('[data-testid="refactor-preview"]');
if (arg.mode === "preview" || answer.incomplete) {
if (!preview || text !== arg.original) return false;
const dialog = preview.closest('[role="dialog"]');
const title = dialog?.querySelector('h1, h2, [data-slot="dialog-title"]')?.textContent ?? dialog?.textContent ?? "";
if (!title.includes(`'${arg.oldName}'`) || !title.includes(`'${arg.newName}'`)) return false;
if (answer.incomplete && !dialog?.querySelector('[role="note"]')) return false;
const entries = new Map<string, { edits: number; operation?: string; to?: string }>();
for (const file of answer.edit.files) {
const path = file.kind === "rename" ? file.from : file.path;
let entry = entries.get(path);
if (!entry) entries.set(path, (entry = { edits: 0 }));
if (file.kind === "edit") entry.edits += file.edits.length;
else {
entry.operation = file.kind;
if (file.kind === "rename") entry.to = file.to;
}
}
const expected = [...entries].filter(([, entry]) => entry.edits || entry.operation);
const rows = [...preview.querySelectorAll("li")];
return (
rows.length === expected.length &&
expected.every(([path, entry]) => {
const relative = path.startsWith(arg.root + "/") ? path.slice(arg.root.length + 1) : path;
const row = rows.find((row) =>
[...row.querySelectorAll("[title]")].some((el) => el.getAttribute("title") === relative),
);
if (!row) return false;
const count = `${entry.edits} ${entry.edits === 1 ? "occurrence" : "occurrences"}`;
if (entry.edits && ![...row.querySelectorAll("span")].some((el) => el.textContent === count)) return false;
if (entry.operation === "rename")
return !!entry.to && !!row.textContent?.includes(`→ ${entry.to.slice(entry.to.lastIndexOf("/") + 1)}`);
return !entry.operation || !!row.textContent?.includes(entry.operation);
})
);
}
if (preview || answer.preview || answer.edit.files.some((file) => file.kind !== "edit" || file.path !== arg.path))
return false;
const edits = answer.edit.files.flatMap((file) => (file.kind === "edit" ? file.edits : []));
if (!edits.length) return false;
const lines = arg.original.split("\n");
const offset = (pos: { line: number; col: number }) => {
if (pos.line < 0 || pos.line >= lines.length || pos.col < 0 || pos.col > lines[pos.line]!.length) return -1;
let at = pos.col;
for (let i = 0; i < pos.line; i++) at += lines[i]!.length + 1;
return at;
};
const changes = edits
.map((edit) => ({ from: offset(edit.range.start), to: offset(edit.range.end), text: edit.new_text }))
.sort((a, b) => b.from - a.from);
let expected = arg.original;
let previous = expected.length;
for (const change of changes) {
if (change.from < 0 || change.to < change.from || change.to > previous) return false;
expected = expected.slice(0, change.from) + change.text + expected.slice(change.to);
previous = change.from;
}
// Exact edit application excludes the temporary, optimistically typed in-place name.
return (
expected !== arg.original &&
text === expected &&
state.word === arg.newName &&
state.head >= 0 &&
state.head <= text.length
);
}
export function renameResult(root: string, answer: Renamed, newName: string) {
const changes = answer.edit.files.flatMap((file) =>
file.kind === "edit"
? file.edits.flatMap((edit) =>
edit.new_text
.split("\n")
.flatMap((line, i) =>
line.includes(newName) ? [`${normalizePath(root, file.path)}:${edit.range.start.line + i + 1}`] : [],
),
)
: [],
);
return {
results: { changes },
degraded: answer.incomplete ? `Rename may be incomplete: ${answer.incomplete}` : null,
};
}
+18 -10
View File
@@ -12,8 +12,6 @@ import { withDeadline } from "../../perf/lib/lifecycle.ts";
import { Server } from "../../smoke/server.ts";
import { copyProject } from "./projects.ts";
import { installTauriShim, type ShimWindow } from "../../smoke/tauriShim.ts";
import { RenameObservations } from "./commandObservation.ts";
import { openFileMeasured } from "../../perf/lib/editing.ts";
/** How long after its answer Show Usages invoked again widens it (`HINT_MS` in code-insight/usages.ts), plus a margin. */
const SHOW_USAGES_HINT_MS = 4200;
@@ -128,7 +126,8 @@ export class Session {
private server!: Server;
private relayQueue: Promise<unknown> = Promise.resolve();
private pendingNotes: Array<[kind: "channel" | "event", a: unknown, b: unknown]> = [];
readonly renameObservations = new RenameObservations();
/** The last answer to each command that succeeded, for what the UI only summarises. */
readonly lastAnswer = new Map<string, unknown>();
/** Editors changed by a scenario: path → the text to put back. */
private readonly edited = new Map<string, string>();
readonly pageErrors: string[] = [];
@@ -181,15 +180,12 @@ export class Session {
await withDeadline(this.context.close(), 5000, "late session context close");
throw new Error("session already closed");
}
await this.context.exposeFunction("__openideaEvalRenameAnswer", (scope: number) =>
this.renameObservations.wait(scope),
);
await this.context.exposeFunction("__openideaRelay", async (cmd: string, args: unknown) => {
const start = this.timeline.now();
this.timeline.inFlight++;
const answered = this.timeline.sent(cmd, start);
try {
const value = await this.renameObservations.invoke(cmd, args, () => this.server.invoke(cmd, args));
const value = await this.server.invoke(cmd, args);
this.record(cmd, start, true, value);
return { ok: value ?? null };
} catch (err) {
@@ -248,6 +244,7 @@ export class Session {
? (value as { locations: unknown[] }).locations.length
: undefined;
this.timeline.calls.push({ cmd, start, ms: this.timeline.now() - start, ok, bytes, items });
if (ok) this.lastAnswer.set(cmd, value);
}
/** Delivers server notifications in order, batched per turn of the event loop. */
@@ -289,7 +286,20 @@ export class Session {
/** Opens `rel` (project-relative, or a URI) in an editor and waits until its text is shown. */
async openFile(rel: string) {
const path = /^[a-z]+:\/\//.test(rel) ? rel : join(this.root, rel);
await this.page.evaluate(openFileMeasured, { path, timeoutMs: 30_000 });
const bare = rel.replace(/[?#].*$/, "");
const name = bare.slice(bare.lastIndexOf("/") + 1);
await this.page.evaluate(
async ({ path, name }) => {
const w = window as unknown as {
__perf: { waitShown(s: string, t: string | null, ms: number): Promise<number> };
__openideaPerf: { openFile(p: string): Promise<void> };
};
await w.__openideaPerf.openFile(path);
await w.__perf.waitShown('[role="tab"][aria-selected="true"]', name, 30_000);
await w.__perf.waitShown(".cm-content .cm-line", null, 30_000);
},
{ path, name },
);
}
/**
@@ -412,7 +422,6 @@ export class Session {
/** Back to an idle workbench: popups dismissed, edits undone, every editor closed. */
async reset() {
this.renameObservations.reset();
// Show Usages invoked again within 4 s of its hint widens the previous search: wait it out.
const since = await this.page.evaluate(() => {
const at = (window as unknown as { __openideaEvalShowUsagesAt?: number }).__openideaEvalShowUsagesAt;
@@ -434,7 +443,6 @@ export class Session {
async close() {
this.closed = true;
this.renameObservations.reset();
const results = await Promise.allSettled([
this.context ? withDeadline(this.context.close(), 5000, "session context close") : Promise.resolve(),
this.server?.close(),
+1 -1
View File
@@ -3,7 +3,7 @@ import type { KnipConfig } from "knip";
const config: KnipConfig = {
// Entries come from the Vite (index.html), Vitest, Playwright and package.json script plugins;
// standalone browser fixtures are loaded by their own HTML pages.
entry: ["e2e/*.fixture.{ts,tsx}", "perf/**/*.fixture.{ts,tsx}"],
entry: ["e2e/*.fixture.{ts,tsx}"],
project: [
"src/**/*.{ts,tsx,css}",
"!src/editor/core/cm/angular/parser.terms.ts",
-124
View File
@@ -1,124 +0,0 @@
import { EditorSelection, EditorState, Prec } from "@codemirror/state";
import { EditorView, keymap } from "@codemirror/view";
import { defaultKeymap, indentWithTab } from "@codemirror/commands";
import { autocompletion, closeBrackets, closeBracketsKeymap } from "@codemirror/autocomplete";
import { javascript } from "@codemirror/lang-javascript";
import { indentOnInput } from "@codemirror/language";
import type { InPage } from "./inpage.ts";
import type { EditorProbe } from "./editing.ts";
// The fixture owns both browser globals and exposes the same editor observation boundary as the app.
const w = window as unknown as {
__fixture: Record<string, boolean>;
__openideaPerf: EditorProbe;
__perf?: InPage;
__releaseOpen?: () => void;
};
const flags: Record<string, boolean> = {};
w.__fixture = flags;
const files = new Map<string, string>();
let path = "";
let view: EditorView;
const style = document.createElement("style");
style.textContent = ".cm-editor { height: 240px; width: 700px; } .cm-scroller { overflow: auto; }";
document.head.append(style);
// Registered before the measurement listener, so a lost recording is tested independently of editing.
window.addEventListener(
"keydown",
() => {
if (flags.missingSample && w.__perf) w.__perf.recordKeys = false;
},
true,
);
function mount(text: string) {
view?.destroy();
view = new EditorView({
parent: document.querySelector("#editor")!,
state: EditorState.create({
doc: text,
extensions: [
javascript(),
indentOnInput(),
closeBrackets(),
Prec.highest(
keymap.of([
{ key: "Mod-End", run: () => !!flags.disableJump },
{ key: "ArrowDown", run: () => !!flags.disableArrows },
{ key: "x", run: () => !!flags.swallowTyping },
]),
),
keymap.of([...closeBracketsKeymap, ...defaultKeymap, indentWithTab]),
autocompletion({
// Test movement itself, without CodeMirror's accidental-key guard after opening.
interactionDelay: 0,
override: [
(ctx) => {
const word = ctx.matchBefore(/\w*/);
return {
from: word?.from ?? ctx.pos,
options: Array.from({ length: 50 }, (_, i) => ({ label: `getOrder${String(i).padStart(2, "0")}` })),
};
},
],
}),
EditorView.updateListener.of((update) => {
if (flags.wrongCaret && update.docChanged)
queueMicrotask(() => view.dispatch({ selection: EditorSelection.cursor(0) }));
if (flags.mutateDistant && update.docChanged) {
flags.mutateDistant = false;
const end = view.state.doc.length;
queueMicrotask(() => view.dispatch({ changes: { from: end - 1, to: end, insert: "z" } }));
}
}),
],
}),
});
view.focus();
}
w.__openideaPerf = {
seed: (p, text) => {
files.set(p, text);
},
async openFile(p) {
if (flags.rejectOpen) throw new Error("open failed");
if (flags.ignoreOpen) return;
if (flags.delayOpen)
await new Promise<void>((resolve) => {
w.__releaseOpen = resolve;
});
path = p;
mount(flags.wrongContents ? view.state.doc.toString() : (files.get(p) ?? ""));
let tab = document.querySelector<HTMLElement>('[role="tab"]');
if (!tab) {
tab = document.createElement("div");
tab.setAttribute("role", "tab");
tab.setAttribute("aria-selected", "true");
document.body.prepend(tab);
}
tab.textContent = p.slice(p.lastIndexOf("/") + 1);
},
editorText: (from = 0, to) => view?.state.doc.sliceString(from, to) ?? null,
editorState() {
if (!view) return null;
const head = view.state.selection.main.head;
return {
path,
head,
length: view.state.doc.length,
lines: view.state.doc.lines,
line: view.state.doc.lineAt(head).number - 1,
word: "",
};
},
lineAtY(y) {
const block = view.lineBlockAtHeight(y - view.documentTop);
return view.state.doc.lineAt(block.from).number - 1;
},
setCursor(head) {
view.dispatch({ selection: EditorSelection.cursor(head), scrollIntoView: true });
view.focus();
},
};
-215
View File
@@ -1,215 +0,0 @@
// @vitest-environment node
import { fileURLToPath } from "node:url";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { chromium, type Browser, type BrowserContext, type Page } from "@playwright/test";
import { createServer, type ViteDevServer } from "vite";
import { Harness } from "./harness.ts";
import { installInPage } from "./inpage.ts";
let server: ViteDevServer;
let browser: Browser;
let context: BrowserContext;
let page: Page;
let h: Harness;
beforeAll(async () => {
server = await createServer({
configFile: false,
root: fileURLToPath(new URL("../../", import.meta.url)),
server: { host: "127.0.0.1", port: 0 },
optimizeDeps: { entries: ["perf/lib/causality.fixture.ts"] },
plugins: [
{
name: "causality-fixture",
configureServer(s) {
s.middlewares.use((req, res, next) => {
if (req.url !== "/") return next();
res.setHeader("Content-Type", "text/html");
res.end(
'<div id="editor"></div><input id="other"><div id="result">ready</div><script type="module" src="/perf/lib/causality.fixture.ts"></script>',
);
});
},
},
],
});
await server.listen();
browser = await chromium.launch({ channel: process.env.OPENIDEA_PERF_CHANNEL ?? "chromium" });
}, 30_000);
beforeEach(async () => {
context = await browser.newContext();
page = await context.newPage();
await page.goto(server.resolvedUrls!.local[0]!);
await page.waitForFunction(() => "__openideaPerf" in window);
await page.evaluate(installInPage);
const cdp = await context.newCDPSession(page);
h = new Harness(page, cdp);
});
afterEach(async () => {
await context?.close();
});
afterAll(async () => {
await browser?.close();
await server?.close();
});
async function mode(name: string) {
await page.evaluate((name) => {
const w = window as unknown as { __fixture: Record<string, boolean> };
w.__fixture[name] = true;
}, name);
}
async function fixtureFile(text = "start\nend") {
await h.openFile("/one/Same.ts", text);
await h.setCursor(0);
}
describe("current-operation UI measurements", () => {
it("observes startup without input, but rejects pre-existing DOM even after a no-op key", async () => {
expect(await h.inPage((p) => p.waitShown("#result", "ready", 500))).toBeGreaterThanOrEqual(0);
await expect(h.measure(async () => {}, "#result", "ready", 80)).rejects.toThrow("timed out");
await expect(
h.measure(
() =>
page.evaluate(() => {
document.querySelector("#result")!.textContent = "ready before input";
}),
"#result",
"ready",
80,
),
).rejects.toThrow("timed out");
await expect(
h.measure(
async () => {
await page.evaluate(() => {
document.querySelector("#result")!.textContent = "ready changed before input";
});
await page.keyboard.press("Shift");
},
"#result",
"ready",
80,
),
).rejects.toThrow("timed out");
await expect(h.measure(() => page.keyboard.press("Shift"), "#result", "ready", 80)).rejects.toThrow("timed out");
});
it("waits for input and the resulting target change, not an earlier frame", async () => {
let changedAt = 0;
const result = h.measure(
async () => {
await h.inPage((p) => p.afterNextPaint());
await page.keyboard.press("a");
await h.inPage((p) => p.afterNextPaint());
changedAt = await page.evaluate(() => {
document.querySelector("#result")!.textContent = "ready now";
return performance.now();
});
},
"#result",
"ready",
1_000,
);
const latency = await result;
expect((await h.inPage((p) => p.lastInput)) + latency).toBeGreaterThanOrEqual(changedAt);
});
it("propagates trigger failure and cancels its waiter without browser rejection", async () => {
const errors: string[] = [];
page.on("pageerror", (error) => errors.push(error.message));
await expect(
h.measure(
async () => {
throw new Error("trigger failed");
},
"#missing",
null,
80,
),
).rejects.toThrow("trigger failed");
await expect(h.measure(async () => false, "#missing", null, 80)).rejects.toThrow("returned false");
await h.inPage(async (p) => {
await p.afterNextPaint();
await p.afterNextPaint();
});
expect(errors).toEqual([]);
expect(await h.inPage((p) => p.waitShown("#result", "ready", 80))).toBeGreaterThanOrEqual(0);
});
it.each(["ignoreOpen", "wrongContents"])("requires the requested path and seeded contents with %s", async (fault) => {
await fixtureFile();
await mode(fault);
await expect(h.openFile("/two/Same.ts", "different", 100)).rejects.toThrow("requested editor");
});
it("does not finish before the open action succeeds, even with matching existing contents", async () => {
await fixtureFile();
await mode("delayOpen");
let completed = false;
const opening = h.openFile("/one/Same.ts", "start\nend").finally(() => {
completed = true;
});
await page.waitForFunction(() => "__releaseOpen" in window);
try {
await h.inPage((p) => p.afterNextPaint());
expect(completed).toBe(false);
} finally {
await page.evaluate(() => {
if (!("__releaseOpen" in window) || typeof window.__releaseOpen !== "function")
throw new Error("open action was not held");
window.__releaseOpen();
});
await opening;
}
});
it("awaits the open action and rejects failed actions even with a matching editor", async () => {
await fixtureFile();
await mode("rejectOpen");
await expect(h.openFile("/one/Same.ts")).rejects.toThrow("open failed");
});
it("measures real typing, including automatic brackets, indentation and backspace", async () => {
await fixtureFile("function f() {\n}\n");
await h.setCursor(14);
expect(await h.typeMeasured("const n = (1 + 2);\n\b", 0)).toHaveLength(20);
});
it.each(["swallowTyping", "wrongCaret", "missingSample", "wrongFocus"])("rejects typing with %s", async (fault) => {
await fixtureFile();
if (fault === "wrongFocus") await page.locator("#other").click();
else await mode(fault);
await expect(h.typeMeasured("x", 0)).rejects.toThrow(/typing|caret|sample|focus/);
});
it("checks the whole document after bounded per-key observations", async () => {
await fixtureFile("start\n" + "unchanged\n".repeat(200) + "end");
expect(await h.typeMeasured("ok", 0)).toHaveLength(2);
await mode("mutateDistant");
await expect(h.typeMeasured("x", 0)).rejects.toThrow("outside the intended insertion");
});
it("requires both cursor destination and viewport displacement for the jump", async () => {
await fixtureFile(Array.from({ length: 1_000 }, (_, i) => `export class Repository${i} {}`).join("\n"));
await mode("disableJump");
await expect(h.jumpToEnd(100)).rejects.toThrow("timed out");
await page.evaluate(() => {
const w = window as unknown as { __fixture: Record<string, boolean> };
w.__fixture.disableJump = false;
});
expect(await h.jumpToEnd(1_000)).toBeGreaterThanOrEqual(0);
expect((await h.editorState())!.head).toBe((await h.editorState())!.length);
});
it("requires each completion arrow to advance exactly one selected item", async () => {
await fixtureFile("");
await h.measure(() => page.keyboard.press("g"), ".cm-tooltip-autocomplete li", "getOrder", 2_000);
await page.waitForSelector('.cm-tooltip-autocomplete li[aria-selected="true"]');
expect(await h.completionArrowsMeasured(3, 0)).toHaveLength(3);
await mode("disableArrows");
await expect(h.completionArrowsMeasured(1, 0)).rejects.toThrow("completion selection");
});
});
-133
View File
@@ -1,133 +0,0 @@
export interface EditorProbe {
seed(path: string, text: string): void;
openFile(path: string): Promise<void>;
editorState(): { path: string; length: number; lines: number; head: number; line: number; word: string } | null;
editorText(from?: number, to?: number): string | null;
setCursor(offset: number): void;
lineAtY(y: number): number;
}
export interface EditableSnapshot {
kind: "editor" | "input";
target: string;
text: string;
head: number;
from: number;
to: number;
}
export interface EditableRange {
from: number;
to: number;
length: number;
}
/** Runs in the page: a key latency is not evidence that the intended editable received it. */
export function readEditable(range?: EditableRange): EditableSnapshot {
const active = document.activeElement;
if (active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement) {
if (active.selectionStart === null || active.selectionEnd === null)
throw new Error("typing focus is not a text input");
return {
kind: "input",
target: active.id || active.getAttribute("aria-label") || active.tagName,
text: active.value,
head: active.selectionEnd,
from: active.selectionStart,
to: active.selectionEnd,
};
}
if (!active?.closest(".cm-content")) throw new Error("typing focus is not in the editor");
// The app and browser fixture expose this typed, in-process observation boundary.
const w = window as unknown as { __openideaPerf: EditorProbe };
const state = w.__openideaPerf.editorState();
if (!state) throw new Error("typing editor is unavailable");
const text = w.__openideaPerf.editorText(range?.from, range ? range.to + state.length - range.length : undefined);
if (text === null) throw new Error("typing editor is unavailable");
const head = state.head - (range?.from ?? 0);
return { kind: "editor", target: state.path, text, head, from: head, to: head };
}
export function assertTypedKey(before: EditableSnapshot, after: EditableSnapshot, key: string) {
const fail = () => {
throw new Error(`typing ${JSON.stringify(key)} did not produce the expected text and caret in ${before.target}`);
};
if (before.kind !== after.kind || before.target !== after.target) fail();
const left = before.text.slice(0, before.from);
const right = before.text.slice(before.to);
if (before.kind === "input") {
const from = key === "\b" && before.from === before.to ? Math.max(0, before.from - 1) : before.from;
const inserted = key === "\b" ? "" : key;
if (after.text !== before.text.slice(0, from) + inserted + right || after.head !== from + inserted.length) fail();
return;
}
const afterLeft = after.text.slice(0, after.head);
const afterRight = after.text.slice(after.head);
if (key === "\b") {
const removed = left.slice(afterLeft.length);
const pair = ({ "(": ")", "[": "]", "{": "}", '"': '"', "'": "'" } as Record<string, string>)[removed];
if (
after.head >= before.head ||
!left.startsWith(afterLeft) ||
!removed ||
([...removed].length !== 1 && !/^[\t ]+$/.test(removed)) ||
(afterRight !== right && !(pair && right.startsWith(pair) && afterRight === right.slice(pair.length)))
)
fail();
return;
}
// CodeMirror may adjust indentation, insert a matching bracket, or step over an auto-inserted closer.
// All non-indentation text, the insertion point, and the remaining document must still match.
const unindent = (text: string) => text.replace(/^[\t ]+/gm, "");
if (after.head === before.head || unindent(afterLeft) !== unindent(left + key)) fail();
const closers: Record<string, string> = { "(": ")", "[": "]", "{": "}", '"': '"', "'": "'", "`": "`" };
const closer = closers[key];
const suffix = unindent(afterRight);
const previous = unindent(right);
if (suffix === previous) return;
if (closer && suffix === closer + previous) return;
if (
/[)\]}"'`]/.test(key) &&
right.startsWith(key) &&
unindent(after.text) === unindent(before.text) &&
suffix === unindent(right.slice(key.length))
)
return;
if (key === "\n" && suffix === "\n" + previous) return;
fail();
}
/** Runs in the page; shared by UI performance scenarios and code-intelligence evals. */
export async function openFileMeasured({ path, text, timeoutMs }: { path: string; text?: string; timeoutMs: number }) {
const w = window as unknown as { __openideaPerf: EditorProbe };
const t0 = performance.now();
let timer: number | undefined;
const expired = new Promise<never>((_, reject) => {
timer = window.setTimeout(() => reject(new Error(`open action timed out for ${path}`)), timeoutMs);
});
let result: unknown;
try {
result = await Promise.race([w.__openideaPerf.openFile(path), expired]);
} finally {
window.clearTimeout(timer);
}
if (result === false) throw new Error(`open action failed for ${path}`);
while (performance.now() - t0 <= timeoutMs) {
await new Promise(requestAnimationFrame);
const state = w.__openideaPerf.editorState();
const content = w.__openideaPerf.editorText();
const editor = document.activeElement?.closest(".cm-editor");
const lines = [...(editor?.querySelectorAll<HTMLElement>(".cm-content .cm-line") ?? [])];
if (
state?.path === path &&
content !== null &&
state.length === content.length &&
(text === undefined || content === text) &&
lines.length &&
lines.some((line) => line.getClientRects().length && content.includes(line.textContent ?? ""))
) {
return performance.now() - t0;
}
}
throw new Error(`requested editor ${path} did not show its contents`);
}
+38 -164
View File
@@ -2,7 +2,6 @@
import type { CDPSession, Page } from "@playwright/test";
import type { InPage } from "./inpage.ts";
import { median } from "./stats.ts";
import { assertTypedKey, openFileMeasured, readEditable, type EditableRange, type EditorProbe } from "./editing.ts";
export type Metrics = Record<string, number>;
@@ -70,182 +69,45 @@ export class Harness {
for (const k of await this.keysFor(actionId)) await this.page.keyboard.press(k);
}
/** Measures a current input and a changed, matching target at frame start. */
async measure<A = undefined>(
trigger: () => Promise<unknown>,
selector: string,
text: string | null = null,
timeoutMs = 10_000,
check?: (arg: A) => boolean,
arg?: A,
) {
const token = await this.inPage((p) => p.arm());
// Attach both handlers immediately: a failed trigger must not strand a rejecting page evaluation.
const done = this.inPage(
(p, a) => {
const condition = a.check ? new Function("arg", `return (${a.check})(arg)`) : null;
return p.waitShown(a.selector, a.text, a.timeoutMs, a.token, condition ? () => condition(a.arg) : undefined);
},
{ selector, text, timeoutMs, token, check: check?.toString(), arg },
).then(
(value) => ({ ok: true as const, value }),
(error: unknown) => ({ ok: false as const, error }),
);
try {
if ((await trigger()) === false) throw new Error("measurement trigger returned false");
const result = await done;
if (!result.ok) throw result.error;
return result.value;
} finally {
await this.inPage((p, token) => p.cancel(token), token);
}
/** Arms latency capture: the next input starts the clock, the paint showing `selector` stops it. */
async measure(trigger: () => Promise<unknown>, selector: string, text: string | null = null, timeoutMs = 10_000) {
await this.inPage((p) => p.arm());
const done = this.inPage((p, a) => p.waitShown(a.selector, a.text, a.timeoutMs), { selector, text, timeoutMs });
await trigger();
return done;
}
/**
* Types `text` one key at a time, `intervalMs` apart, recording keydown → next
* frame for each key. `\n` presses Enter, `\b` Backspace.
*/
async typeMeasured(text: string, intervalMs: number, target: "editor" | "input" = "editor"): Promise<number[]> {
const initial = await this.page.evaluate(readEditable, undefined);
if (initial.kind !== target) throw new Error(`typing focus is not in the expected ${target}`);
const characters = [...text];
let range: EditableRange | undefined;
let before = initial;
if (initial.kind === "editor") {
let from = initial.text.lastIndexOf("\n", initial.head - 1) + 1;
// A Backspace can cross at most one existing line; indentation deletion stays within it.
for (const character of characters) {
if (character === "\b" && from > 0) from = initial.text.lastIndexOf("\n", from - 2) + 1;
}
const nextLine = initial.text.indexOf("\n", Math.min(initial.text.length, initial.head + characters.length + 1));
const to = nextLine < 0 ? initial.text.length : nextLine + 1;
range = { from, to, length: initial.text.length };
const head = initial.head - from;
before = { ...initial, text: initial.text.slice(from, to), head, from: head, to: head };
}
const latencies = await this.pressMeasured(
characters.map((ch) => (ch === "\n" ? "Enter" : ch === "\b" ? "Backspace" : ch)),
async typeMeasured(text: string, intervalMs: number): Promise<number[]> {
return this.pressMeasured(
[...text].map((ch) => (ch === "\n" ? "Enter" : ch === "\b" ? "Backspace" : ch)),
intervalMs,
async (_, index) => {
const after = await this.page.evaluate(readEditable, range);
assertTypedKey(before, after, characters[index]!);
before = after;
},
);
const after = await this.page.evaluate(readEditable, range);
if (
after.kind !== before.kind ||
after.target !== before.target ||
after.text !== before.text ||
after.head !== before.head
) {
throw new Error("typing text or caret changed after the measured keys");
}
if (range) {
const final = await this.page.evaluate(readEditable, undefined);
const to = range.to + final.text.length - initial.text.length;
if (
final.kind !== initial.kind ||
final.target !== initial.target ||
final.head !== before.head + range.from ||
final.text.slice(0, range.from) !== initial.text.slice(0, range.from) ||
final.text.slice(range.from, to) !== before.text ||
final.text.slice(to) !== initial.text.slice(range.to)
) {
throw new Error("typing changed text outside the intended insertion or left an incorrect caret");
}
}
return latencies;
}
/** Presses `keys` `intervalMs` apart and returns keydown → next frame for each. */
async pressMeasured(
keys: string[],
intervalMs: number,
afterKey?: (key: string, index: number) => Promise<void>,
): Promise<number[]> {
async pressMeasured(keys: string[], intervalMs: number): Promise<number[]> {
await this.inPage((p) => {
p.keyLatencies = [];
p.recordKeys = true;
});
try {
for (const [index, key] of keys.entries()) {
const started = Date.now();
await this.page.keyboard.press(key);
await afterKey?.(key, index);
const wait = intervalMs - (Date.now() - started);
if (wait > 0) await this.page.waitForTimeout(wait);
}
await this.inPage((p) => p.afterNextPaint().then(() => p.afterNextPaint()));
const latencies = await this.inPage((p) => p.keyLatencies);
if (latencies.length !== keys.length || latencies.some((latency) => !Number.isFinite(latency) || latency < 0)) {
throw new Error(`key sample count mismatch: expected ${keys.length}, received ${latencies.length}`);
}
return latencies;
} finally {
await this.inPage((p) => {
p.recordKeys = false;
});
for (const key of keys) {
const started = Date.now();
await this.page.keyboard.press(key);
const wait = intervalMs - (Date.now() - started);
if (wait > 0) await this.page.waitForTimeout(wait);
}
}
/** Checks the actual selected option after every ArrowDown, including virtualized lists. */
async completionArrowsMeasured(count: number, intervalMs: number) {
const selection = () =>
this.page.evaluate(() => {
const selected = document.querySelector('.cm-tooltip-autocomplete li[aria-selected="true"]');
const index = selected?.id.match(/-(\d+)$/)?.[1];
if (!selected || index === undefined) throw new Error("completion selection is unavailable");
return { id: selected.id, index: Number(index) };
});
let before = await selection();
return this.pressMeasured(Array(count).fill("ArrowDown"), intervalMs, async () => {
const after = await selection();
if (after.id === before.id || after.index !== before.index + 1) {
throw new Error(`completion selection did not advance from ${before.index} to ${before.index + 1}`);
}
before = after;
// Let the last frames land.
await this.inPage((p) => p.afterNextPaint().then(() => p.afterNextPaint()));
return this.inPage((p) => {
p.recordKeys = false;
return p.keyLatencies;
});
}
/** A far jump must move both the active caret and its viewport to the document end. */
async jumpToEnd(timeoutMs = 5_000) {
await this.inPage((p) => p.afterNextPaint());
const start = await this.page.evaluate(() => {
const w = window as unknown as { __openideaPerf: EditorProbe };
const state = w.__openideaPerf.editorState();
const scroller = document.activeElement?.closest(".cm-editor")?.querySelector(".cm-scroller");
if (!state || !scroller || state.head === state.length || scroller.scrollHeight <= scroller.clientHeight) {
throw new Error("jump start must be outside the destination in a scrollable editor");
}
return { path: state.path, head: state.head, scrollTop: scroller.scrollTop };
});
return this.measure(
() => this.page.keyboard.press("ControlOrMeta+End"),
".cm-content",
null,
timeoutMs,
(start) => {
const w = window as unknown as { __openideaPerf: EditorProbe };
const state = w.__openideaPerf.editorState();
const editor = document.activeElement?.closest(".cm-editor");
const scroller = editor?.querySelector(".cm-scroller");
const bottom = scroller?.getBoundingClientRect().bottom;
return (
!!state &&
state.path === start.path &&
state.head === state.length &&
state.head !== start.head &&
!!scroller &&
scroller.scrollTop > start.scrollTop + scroller.clientHeight &&
bottom !== undefined &&
w.__openideaPerf.lineAtY(bottom - 4) === state.lines - 1
);
},
start,
);
}
/** Display refresh interval measured over idle frames. */
async refreshMs(): Promise<number> {
await this.inPage((p) => p.startFrames());
@@ -300,9 +162,20 @@ export class Harness {
}
/** Seeds a file into the in-memory backend and opens it, returning open → painted ms. */
async openFile(path: string, text?: string, timeoutMs = 15_000): Promise<number> {
async openFile(path: string, text?: string): Promise<number> {
if (text !== undefined) await this.seed(path, text);
return this.page.evaluate(openFileMeasured, { path, text, timeoutMs });
const name = path.slice(path.lastIndexOf("/") + 1);
return this.page.evaluate(
async ({ path, name }) => {
const w = window as never as { __perf: InPage; __openideaPerf: { openFile(p: string): Promise<void> } };
const t0 = performance.now();
void w.__openideaPerf.openFile(path);
await w.__perf.waitShown('[role="tab"][aria-selected="true"]', name, 15_000);
await w.__perf.waitShown(".cm-content .cm-line", null, 15_000);
return performance.now() - t0;
},
{ path, name },
);
}
/** Waits until the active editor's background parse has caught up (steady-state editing). */
@@ -322,9 +195,10 @@ export class Harness {
}
async editorState() {
return this.page.evaluate(() => {
const w = window as unknown as { __openideaPerf: EditorProbe };
return w.__openideaPerf.editorState();
});
return this.page.evaluate(() =>
(
window as never as { __openideaPerf: { editorState(): { length: number; lines: number; head: number } | null } }
).__openideaPerf.editorState(),
);
}
}
+19 -78
View File
@@ -20,23 +20,16 @@ export interface InPage {
afterNextPaint(): Promise<number>;
startFrames(): void;
stopFrames(): number[];
/** Arms a current-input transition; unarmed waits remain navigation observations. */
arm(): number;
cancel(token: number): void;
waitShown(
selector: string,
text: string | null,
timeoutMs: number,
token?: number,
check?: () => boolean,
): Promise<number>;
/** Resolves with (frame start − first input after `arm`) once `selector` (and `text`) is rendered. */
arm(): void;
waitShown(selector: string, text: string | null, timeoutMs: number): Promise<number>;
}
export function installInPage() {
const w = window as unknown as { __perf: InPage };
if (w.__perf) return;
let nextToken = 0;
let operation: { token: number; input: number; capture?: () => void; cancel?: () => void } | null = null;
let armedAt = -1;
let firstInputAfterArm = -1;
const afterNextPaint = () =>
new Promise<number>((resolve) =>
@@ -50,10 +43,7 @@ export function installInPage() {
const onInput = (e: Event) => {
const t = e.timeStamp;
h.lastInput = t;
if (operation && operation.input < 0) {
operation.input = t;
operation.capture?.();
}
if (armedAt >= 0 && firstInputAfterArm < 0) firstInputAfterArm = t;
if (e.type === "keydown" && h.recordKeys) requestAnimationFrame(() => h.keyLatencies.push(performance.now() - t));
};
// `input` covers `keyboard.insertText`, which dispatches no keydown.
@@ -86,74 +76,25 @@ export function installInPage() {
return f;
},
arm() {
if (operation) throw new Error("a measurement is already armed");
const token = ++nextToken;
operation = { token, input: -1 };
return token;
armedAt = performance.now();
firstInputAfterArm = -1;
},
cancel(token) {
if (operation?.token !== token) return;
operation.cancel?.();
operation = null;
},
waitShown(selector, text, timeoutMs, token, check) {
const current = token === undefined ? null : operation;
if (token !== undefined && current?.token !== token) return Promise.reject(new Error("measurement is not armed"));
waitShown(selector, text, timeoutMs) {
const deadline = performance.now() + timeoutMs;
const snapshot = () => {
if (check && !check()) return [];
return [...document.querySelectorAll<HTMLElement>(selector)]
.filter(
(el) =>
el.getClientRects().length > 0 &&
getComputedStyle(el).visibility === "visible" &&
!el.closest('[aria-hidden="true"]') &&
(text === null || (el.textContent ?? "").includes(text)),
)
.map((el) => ({
el,
text: el.textContent,
value: el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement ? el.value : null,
selected: el.getAttribute("aria-selected"),
}));
const matches = () => {
const el = document.querySelector(selector) as HTMLElement | null;
if (!el || el.getClientRects().length === 0) return false;
return text === null || (el.textContent ?? "").includes(text);
};
let baseline = snapshot();
if (current)
current.capture = () => {
baseline = snapshot();
};
return new Promise<number>((resolve, reject) => {
let stopped = false;
const finish = () => {
stopped = true;
if (operation === current) operation = null;
};
if (current)
current.cancel = () => {
finish();
reject(new Error("measurement cancelled"));
};
const tick = () => {
if (stopped) return;
const frameStart = performance.now();
const shown = snapshot();
const changed = shown.some(
(now) =>
!baseline.some(
(old) =>
old.el === now.el &&
old.text === now.text &&
old.value === now.value &&
old.selected === now.selected,
),
);
// Keep the endpoint at frame start, but only credit this input's target transition.
if (shown.length && (!current || (current.input >= 0 && changed))) {
const start = current?.input ?? 0;
finish();
resolve(frameStart - start);
// Checked at the start of a frame: a match here is painted by this frame.
if (matches()) {
const start = firstInputAfterArm >= 0 ? firstInputAfterArm : armedAt;
armedAt = -1;
resolve(performance.now() - start);
} else if (performance.now() > deadline) {
finish();
armedAt = -1;
reject(new Error(`timed out waiting for ${selector}${text ? ` containing "${text}"` : ""}`));
} else requestAnimationFrame(tick);
};
+9 -5
View File
@@ -136,7 +136,7 @@ const completion: Scenario = {
const before = await h.counters();
const narrow = await h.typeMeasured("etOrd", 150);
const work = Harness.delta(before, await h.counters());
const arrows = await h.completionArrowsMeasured(20, 60);
const arrows = await h.pressMeasured(Array(20).fill("ArrowDown"), 60);
await h.page.keyboard.press("Escape");
return {
openMs,
@@ -310,9 +310,13 @@ const scroll: Scenario = {
const smooth = frameSummary(await wheel(160, 120), refresh);
const tbtMs = totalBlockingTime(await h.longTasksSince(t0));
const fling = frameSummary(await wheel(60, 600), refresh);
// Jump far: document-end repositioning.
await h.setCursor(0);
const jumpMs = await h.jumpToEnd();
// Jump far: scrollbar drag / Ctrl+End style repositioning.
const jumpMs = await h.measure(
() => h.page.keyboard.press("Control+End"),
".cm-content",
"export class Repository",
5_000,
);
return {
...smooth,
tbtMs,
@@ -669,7 +673,7 @@ const popups: Scenario = {
);
// Editing the query: Backspace → list re-filtered and painted.
const refresh = await h.refreshMs();
const keyLat = await h.typeMeasured("\b\b\b\b\b\b", 80, "input");
const keyLat = await h.typeMeasured("\b\b\b\b\b\b", 80);
await h.page.keyboard.press("Escape");
await h.page.locator('[role="dialog"]').waitFor({ state: "detached" });
-11
View File
@@ -18,16 +18,6 @@ pub async fn window_group_merge(window: WebviewWindow) -> IdeResult<()> {
groups::persist(window.app_handle()).await
}
/// Adds window `label` to this window's group as a new project tab and selects it. Unlike
/// [`window_group_merge`], unrelated windows keep their own group.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn window_group_join(window: WebviewWindow, label: String) -> IdeResult<()> {
groups::join(window.app_handle(), window.label(), &label)?;
groups::persist(window.app_handle()).await
}
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
@@ -96,7 +86,6 @@ ide_command::desktop_domain!(
window_group_close_tabs,
window_group_current,
window_group_detach,
window_group_join,
window_group_merge,
window_group_reorder,
window_group_restore,
+1
View File
@@ -105,6 +105,7 @@ fn native_select(app: &AppHandle, group: &Group, to: &WebviewWindow) -> IdeResul
crate::macos::sync_tab_group(members, &anchor, to).map_err(|e| IdeError::internal(e.to_string()))
}
#[cfg(target_os = "macos")]
pub fn join(app: &AppHandle, anchor: &str, new_window: &str) -> IdeResult<()> {
let state = app.state::<WindowsState>();
state.groups.lock().join(anchor, new_window)?;
-1
View File
@@ -726,7 +726,6 @@ window_group_close always desktop bin
window_group_close_tabs always desktop bindings sync
window_group_current always desktop bindings sync
window_group_detach always desktop bindings async
window_group_join always desktop bindings async
window_group_merge always desktop bindings async
window_group_reorder always desktop bindings async
window_group_restore always desktop bindings async
-5
View File
@@ -1918,11 +1918,6 @@ export const commands = {
windowGroupCloseTabs: (keep: string, labels: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("window_group_close_tabs", { keep, labels })),
windowGroupCurrent: () => typedError<WindowTab[], IdeError>(__TAURI_INVOKE("window_group_current")),
windowGroupDetach: (label: string) => typedError<null, IdeError>(__TAURI_INVOKE("window_group_detach", { label })),
/**
* Adds window `label` to this window's group as a new project tab and selects it. Unlike
* [`window_group_merge`], unrelated windows keep their own group.
*/
windowGroupJoin: (label: string) => typedError<null, IdeError>(__TAURI_INVOKE("window_group_join", { label })),
windowGroupMerge: () => typedError<null, IdeError>(__TAURI_INVOKE("window_group_merge")),
windowGroupReorder: (labels: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("window_group_reorder", { labels })),
windowGroupRestore: () => typedError<null, IdeError>(__TAURI_INVOKE("window_group_restore")),
+1 -35
View File
@@ -8,7 +8,6 @@ const workspaceUpdate = vi.fn();
const projectCurrent = vi.fn();
const windowOpenProject = vi.fn();
const windowOpenFiles = vi.fn();
const windowGroupJoin = vi.fn();
const windowTakeLaunch = vi.fn();
const windowCompleteLaunch = vi.fn();
const wslResolve = vi.fn();
@@ -45,7 +44,6 @@ vi.mock("@/platform/ipc", async (orig) => {
projectCurrent: () => projectCurrent(),
windowOpenProject: (...a: unknown[]) => windowOpenProject(...a),
windowOpenFiles: (...a: unknown[]) => windowOpenFiles(...a),
windowGroupJoin: (...a: unknown[]) => windowGroupJoin(...a),
windowTakeLaunch: () => windowTakeLaunch(),
windowCompleteLaunch: () => windowCompleteLaunch(),
wslResolve: (p: string) => wslResolve(p),
@@ -113,8 +111,7 @@ beforeEach(() => {
workspaceAttach.mockReset();
workspaceUpdate.mockReset();
projectCurrent.mockReset();
for (const f of [windowOpenProject, windowOpenFiles, windowGroupJoin, windowTakeLaunch, wslResolve]) f.mockReset();
windowGroupJoin.mockResolvedValue(ok(null));
for (const f of [windowOpenProject, windowOpenFiles, windowTakeLaunch, wslResolve]) f.mockReset();
windowTakeLaunch.mockResolvedValue(null);
windowCompleteLaunch.mockReset().mockResolvedValue(ok(null));
wslResolve.mockResolvedValue(null);
@@ -697,37 +694,6 @@ describe("Attach", () => {
});
});
describe("Project tabs", () => {
it("opens the project in its own window and joins that window into this window's group", async () => {
useProject.setState(projectState("/p/a"));
vi.mocked(ask).mockResolvedValueOnce({ button: "tab", checked: false });
windowOpenProject.mockResolvedValue(ok({ kind: "opened", label: "main-2" }));
await openProjectWithPolicy("/p/b", ["/p/b/file.txt"]);
expect(confirmProjectTrust).toHaveBeenCalledWith("/p/b", "local");
expect(windowOpenProject).toHaveBeenCalledWith("/p/b", true, ["/p/b/file.txt"]);
expect(windowGroupJoin).toHaveBeenCalledWith("main-2");
// The new window opens its own files, and this window keeps its project.
expect(opened).toEqual([]);
expect(openProject).not.toHaveBeenCalled();
expect(confirmLeaveProject).not.toHaveBeenCalled();
});
it("groups the window that already has the project", async () => {
useProject.setState(projectState("/p/a"));
vi.mocked(ask).mockResolvedValueOnce({ button: "tab", checked: false });
windowOpenProject.mockResolvedValue(ok({ kind: "focused", label: "main-3" }));
await openProjectWithPolicy("/p/b");
expect(windowGroupJoin).toHaveBeenCalledWith("main-3");
});
it("reports a window it could not group", async () => {
useProject.setState(projectState("/p/a"));
vi.mocked(ask).mockResolvedValueOnce({ button: "tab", checked: false });
windowOpenProject.mockResolvedValue(ok({ kind: "opened", label: "main-2" }));
windowGroupJoin.mockRejectedValueOnce(new Error("Window closed"));
await openProjectWithPolicy("/p/b");
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ level: "error", body: "Window closed" }));
});
});
it("removes the first workspace member while retaining the workspace state root", async () => {
const project = {
root: "/workspace",
-17
View File
@@ -186,10 +186,6 @@ export async function openProjectWithPolicy(path: string, files: readonly string
await attachProject(path, files);
return;
}
if (mode === "tab") {
await openProjectTab(path, files);
return;
}
try {
// A window that already has the project is focused instead.
const outcome = await call(commands.windowOpenProject(path, false, [...files]));
@@ -220,19 +216,6 @@ async function attachProject(path: string, files: readonly string[] = []): Promi
}
}
/** Opens `path` as a new project tab of this window: a window of its own, joined into this window's group. */
async function openProjectTab(path: string, files: readonly string[]): Promise<void> {
try {
// `new_window` always answers with the window holding the project, focused or just created;
// either way that window becomes this window's tab.
const outcome = await openProjectWindow(path, true, files);
if (outcome.kind === "current") return;
await call(commands.windowGroupJoin(outcome.label));
} catch (e) {
openFailed(path, e);
}
}
/** LightEdit: opens the current file's folder as a project ("Open project in" applies) and the file there. */
export async function openLightEditFileAsProject(): Promise<void> {
if (!useProject.getState().lightEdit) return;
@@ -14,24 +14,6 @@
flex: 1;
min-height: 0;
}
.results {
display: flex;
min-height: 0;
height: 100%;
}
.toolbar {
flex: none;
display: flex;
flex-direction: column;
gap: var(--space-1);
padding: var(--space-1);
border-inline-end: 1px solid var(--border);
overflow-y: auto;
}
.tree {
flex: 1;
min-width: 0;
}
.tabs {
min-width: 0;
border: 0;
@@ -56,21 +38,10 @@
flex: none;
color: var(--fg-muted);
}
.fileLocation {
display: flex;
gap: var(--space-1-5);
min-width: 0;
overflow: hidden;
}
.fileName {
flex: none;
max-inline-size: 100%;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-strong);
}
.fileError {
padding-block: var(--space-0-5);
text-decoration-line: underline;
text-decoration-style: wavy;
text-decoration-color: var(--danger);
@@ -80,25 +51,18 @@
.selectedText {
color: var(--fg-strong);
}
.directory {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
.muted {
flex: none;
color: var(--fg-subtle);
}
.count {
flex: none;
max-inline-size: 50%;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-subtle);
margin-left: 4px;
}
.source {
min-width: 0;
max-inline-size: 25%;
margin-inline-start: auto;
overflow: hidden;
text-overflow: ellipsis;
flex: none;
margin-left: auto;
padding-right: 8px;
color: var(--fg-faint);
}
.message {
@@ -113,7 +77,6 @@
.position {
flex: none;
color: var(--fg-subtle);
font-variant-numeric: tabular-nums;
}
.sev-error {
flex: none;
+19 -42
View File
@@ -22,7 +22,6 @@ import {
SplitHandle,
SplitPanel,
Tabs,
Toolbar,
Tree,
fileIconName,
showContextMenu,
@@ -214,11 +213,11 @@ function useCurrentPath(): string | null {
return currentProblemsPath(text, useSyncExternalStore(subscribeActiveInput, activeInput));
}
function ProblemsToolbar() {
export function ProblemsHeaderActions() {
const show = useProblemsView((s) => s.show);
const toggle = useProblemsView((s) => s.toggle);
return (
<Toolbar aria-label="Problems actions" orientation="vertical" className={styles.toolbar}>
<>
<IconButton icon="arrow-up" action="navigate.prevOccurrence" size="small" />
<IconButton icon="arrow-down" action="navigate.nextOccurrence" size="small" />
<IconButton icon="error" title="Show Errors" size="small" pressed={show.error} onClick={() => toggle("error")} />
@@ -236,7 +235,7 @@ function ProblemsToolbar() {
pressed={show.info}
onClick={() => toggle("info")}
/>
</Toolbar>
</>
);
}
@@ -338,44 +337,33 @@ export function ProblemsView() {
const renderNode = (n: Node, state: TreeRowState) => {
if (n.kind === "file") {
const name = basename(n.path);
const directory = relativeDir(root, n.path);
const c = countSeverities(n.items);
const counts = [plural(c.error, "error"), plural(c.warning, "warning"), plural(c.info + c.hint, "info")]
.filter(Boolean)
.join(", ");
const parts = [plural(c.error, "error"), plural(c.warning, "warning"), plural(c.info + c.hint, "info")].filter(
Boolean,
);
return (
<span className={styles.row}>
<Icon name={fileIconName(name, n.path)} size={16} className={styles.fileIcon} />
<span className={styles.fileLocation}>
<span
className={clsx(styles.fileName, c.error > 0 && styles.fileError, state.selected && styles.selectedText)}
title={name}
>
{name}
</span>
{directory && (
<span className={styles.directory} title={directory}>
{directory}
</span>
)}
</span>
<span className={styles.count} title={counts}>
{counts}
<Icon name={fileIconName(basename(n.path), n.path)} size={16} className={styles.fileIcon} />
<span
className={clsx(styles.fileName, c.error > 0 && styles.fileError, state.selected && styles.selectedText)}
>
{basename(n.path)}
</span>
<span className={styles.muted}>{relativeDir(root, n.path)}</span>
<span className={styles.count}>{parts.join(", ")}</span>
</span>
);
}
const d = n.d;
const source = d.source && (d.code ? `${d.source}(${d.code})` : d.source);
return (
<span className={styles.row} title={d.message}>
<Icon name={SEVERITY_ICON[d.severity]} size={14} className={styles[`sev-${d.severity}`]} />
<span className={clsx(styles.message, d.deprecated && styles.deprecated)}>{d.message.split("\n")[0]}</span>
<span className={styles.position}>:{d.range.start.line + 1}</span>
{source && (
<span className={styles.source} title={source}>
{source}
{d.source && (
<span className={styles.source}>
{d.source}
{d.code ? `(${d.code})` : ""}
</span>
)}
</span>
@@ -390,10 +378,9 @@ export function ProblemsView() {
);
const selected = target(lead);
const treeView = (
const list = (
<Tree<Node>
aria-label="Problems"
className={styles.tree}
handleRef={tree}
roots={roots}
getKey={(n) => n.key}
@@ -441,11 +428,7 @@ export function ProblemsView() {
run: () => copy(n),
},
...inspectionMenu(n.kind === "diag" ? diagInspection(map, n.path, n.d) : null),
...menuGroupItems("problems", {
paths: [t.path],
line: t.d.range.start.line,
column: t.d.range.start.col,
}),
...menuGroupItems("problems", { paths: [t.path], line: t.d.range.start.line, column: t.d.range.start.col }),
]);
}}
activateExpandable={false}
@@ -453,12 +436,6 @@ export function ProblemsView() {
empty={empty}
/>
);
const list = (
<div className={styles.results}>
<ProblemsToolbar />
{treeView}
</div>
);
return (
<div className={styles.view}>
+2 -1
View File
@@ -15,7 +15,7 @@ import {
import { getContext } from "@/platform/context";
import { clearProblems, installProblemsEvents, problemsReport, useProblems } from "./problemsStore";
import { installProblemDecorations } from "./decorations";
import { ProblemsTabs, ProblemsView, useProblemsHeaderMenu } from "./ProblemsView";
import { ProblemsHeaderActions, ProblemsTabs, ProblemsView, useProblemsHeaderMenu } from "./ProblemsView";
import { UsagesTabs, UsagesView, useUsagesHeaderMenu } from "./UsagesView";
import { UsagesPopup } from "./UsagesPopup";
import { findUsages, rerunActiveUsages, resetUsages, showUsageResults, showUsagesPopup } from "./usages";
@@ -79,6 +79,7 @@ export function activate(): () => void {
order: 30,
component: ProblemsView,
headerContent: ProblemsTabs,
headerActions: ProblemsHeaderActions,
headerMenu: useProblemsHeaderMenu,
useBadge: useErrorBadge,
}),
@@ -19,28 +19,20 @@
}
.toolbar {
min-height: 32px;
height: 32px;
flex: none;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-0-5) var(--space-2);
padding: var(--space-0-5) var(--space-2) var(--space-0-5) var(--space-1);
border-bottom: 1px solid var(--border);
min-width: 0;
}
.actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-0-5);
padding: 0 8px 0 4px;
border-bottom: 1px solid var(--border);
min-width: 0;
overflow: hidden;
}
.tool {
width: var(--h-control);
height: var(--h-control);
width: 26px;
height: 26px;
flex: none;
}
@@ -54,21 +46,17 @@
.tabs {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-0-5);
min-width: 0;
flex: none;
}
.tab {
height: 24px;
max-inline-size: 100%;
padding: 0 8px;
border-radius: var(--radius-small);
color: var(--fg);
font-size: var(--fs-ui);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tab:hover {
+37 -38
View File
@@ -16,7 +16,6 @@ import {
SplitHandle,
SplitPanel,
Tabs,
Toolbar,
showContextMenu,
type MenuItem,
type TabItem,
@@ -219,43 +218,43 @@ export function DebugToolWindow() {
return (
<div className={styles.root}>
<div className={styles.toolbar}>
<Toolbar className={styles.actions} aria-label="Debugger actions">
<ToolButton action="debug.rerun" icon="rerun" />
<ToolButton action="debug.stop" icon="stop" tone="danger" />
<span className={styles.sep} aria-hidden />
<ToolButton action="debug.resume" icon="resume" />
<ToolButton action="debug.pause" icon="pause" />
<ToolButton action="debug.stepOver" icon="step-over" />
<ToolButton action="debug.stepInto" icon="step-into" />
<ToolButton action="debug.stepOut" icon="step-out" />
<span className={styles.sep} aria-hidden />
{rootOf(active).adapter === "dart" && (
<>
<ToolButton action="debug.hotReload" icon="hot-reload" />
<ToolButton action="debug.hotRestart" icon="refresh" />
{rootOf(active).vmServiceUri && <ToolButton action="debug.openDevTools" icon="external-link" />}
<span className={styles.sep} aria-hidden />
</>
)}
<IconButton
icon="view-breakpoints"
action="debug.viewBreakpoints"
size="small"
iconSize={16}
className={styles.tool}
/>
<IconButton
icon="mute-breakpoint"
title={muted ? "Unmute Breakpoints" : "Mute Breakpoints"}
pressed={muted}
size="small"
iconSize={16}
className={styles.tool}
onClick={() => setMuted(!muted)}
/>
<MoreActions />
</Toolbar>
<div className={styles.toolbar} role="toolbar" aria-label={tx("Debugger actions")}>
{/* IDEA's XDebugger.ToolWindow.TopToolbar3 (+ its "More" group), then the views. */}
<ToolButton action="debug.rerun" icon="rerun" />
<ToolButton action="debug.stop" icon="stop" tone="danger" />
<span className={styles.sep} aria-hidden />
<ToolButton action="debug.resume" icon="resume" />
<ToolButton action="debug.pause" icon="pause" />
<ToolButton action="debug.stepOver" icon="step-over" />
<ToolButton action="debug.stepInto" icon="step-into" />
<ToolButton action="debug.stepOut" icon="step-out" />
<span className={styles.sep} aria-hidden />
{rootOf(active).adapter === "dart" && (
<>
<ToolButton action="debug.hotReload" icon="hot-reload" />
<ToolButton action="debug.hotRestart" icon="refresh" />
{rootOf(active).vmServiceUri && <ToolButton action="debug.openDevTools" icon="external-link" />}
<span className={styles.sep} aria-hidden />
</>
)}
<IconButton
icon="view-breakpoints"
action="debug.viewBreakpoints"
size="small"
iconSize={16}
className={styles.tool}
/>
<IconButton
icon="mute-breakpoint"
title={muted ? "Unmute Breakpoints" : "Mute Breakpoints"}
pressed={muted}
size="small"
iconSize={16}
className={styles.tool}
onClick={() => setMuted(!muted)}
/>
<MoreActions />
<span className={styles.sep} aria-hidden />
<div role="tablist" aria-label={tx("Debug views")} className={styles.tabs}>
{(
[
@@ -21,7 +21,7 @@
height: 100%;
display: flex;
align-items: center;
gap: var(--space-1);
gap: 5px;
border-radius: var(--radius-row);
}
@@ -41,16 +41,9 @@
overflow: hidden;
text-overflow: ellipsis;
}
.labelGroup {
display: flex;
align-items: center;
gap: var(--space-1);
min-width: 0;
overflow: hidden;
}
.labelGroup .label {
.rootName {
flex: none;
max-inline-size: 100%;
max-width: 60%;
}
.rootLabel {
color: var(--fg-strong);
@@ -67,7 +60,6 @@
text-decoration-line: line-through;
}
.error {
padding-block: var(--space-0-5);
text-decoration-line: underline;
text-decoration-style: wavy;
text-decoration-color: var(--danger);
@@ -96,7 +88,7 @@
}
.detail {
min-width: 0;
margin-inline-start: var(--space-1);
margin-left: 4px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
+21 -30
View File
@@ -338,29 +338,26 @@ const Row = memo(function Row({
/>
) : (
<>
<span className={styles.labelGroup}>
<HighlightedText
className={clsx(
styles.label,
// Project and module roots use semibold labels.
node.root && !node.icon && styles.rootLabel,
moduleFolder && styles.moduleLabel,
faded && !deco.color && styles.excluded,
file?.deprecated && styles.deprecated,
deco.error && styles.error,
)}
style={deco.color ? { color: deco.color } : undefined}
text={node.label}
indices={matches}
tone="accent"
/>
{deco.suffix && <DecorationSuffix segments={deco.suffix} color={deco.suffixColor} />}
{detail && (
<span className={styles.detail} title={detail}>
{detail}
</span>
<HighlightedText
className={clsx(
styles.label,
node.root && styles.rootName,
// Only the project itself is bold (IDEA); contributed roots like Scratches are not.
node.root && !node.icon && styles.rootLabel,
// Maven / Gradle module folders are bold too, as in IDEA.
moduleFolder && styles.moduleLabel,
faded && !deco.color && styles.excluded,
// IDEA strikes out deprecated classes.
file?.deprecated && styles.deprecated,
deco.error && styles.error,
)}
</span>
style={deco.color ? { color: deco.color } : undefined}
text={node.label}
indices={matches}
tone="accent"
/>
{deco.suffix && <DecorationSuffix segments={deco.suffix} color={deco.suffixColor} />}
{detail && <span className={styles.detail}>{detail}</span>}
{deco.badge && <span className={styles.badge}>{deco.badge}</span>}
</>
)}
@@ -424,14 +421,8 @@ const MemberRow = memo(function MemberRow({
onPointerDown={(e) => onPointerDown(node, e)}
>
<SymbolBadge kind={badgeKind(item.kind)} className={styles.icon} />
<span className={styles.labelGroup}>
<HighlightedText className={styles.label} text={item.name} indices={matches} tone="accent" />
{item.detail && (
<span className={styles.detail} title={item.detail}>
{item.detail}
</span>
)}
</span>
<HighlightedText className={styles.label} text={item.name} indices={matches} tone="accent" />
{item.detail && <span className={styles.detail}>{item.detail}</span>}
</span>
);
});
+1 -29
View File
@@ -51,10 +51,6 @@
min-width: 0;
}
.topToolbarSession {
flex-direction: column;
}
.toolbar {
flex: none;
width: 32px;
@@ -73,36 +69,12 @@
.toolbar::-webkit-scrollbar {
display: none;
}
.toolbarGroup {
display: flex;
flex: none;
flex-direction: inherit;
align-items: center;
gap: var(--space-0-5);
max-width: 100%;
}
.toolbarGroup + .toolbarGroup::before {
content: "";
.toolbarSep {
width: 16px;
height: 1px;
margin: 3px 0;
background: var(--border-strong);
}
.topToolbarSession .toolbar {
width: auto;
flex-direction: row;
flex-wrap: wrap;
gap: var(--space-0-5) var(--space-2);
padding: var(--space-0-5) var(--space-1);
border-right: none;
border-bottom: 1px solid var(--border);
}
.topToolbarSession .toolbarGroup {
flex-wrap: wrap;
}
.topToolbarSession .toolbarGroup::before {
display: none;
}
.sessionBody {
flex: 1;
+30 -38
View File
@@ -1,5 +1,4 @@
import { useEffect, useMemo, useRef, useState } from "react";
import clsx from "clsx";
import type { RunConfig } from "@/platform/ipc";
import type { RunTargetValid } from "@/platform/remoteSettings";
import { useAgentRunSettings, useWorkflowSettings } from "@/platform/workflowSettings";
@@ -182,15 +181,10 @@ export function SessionPanel({
);
return (
<div className={clsx(styles.session, showLifecycle && styles.topToolbarSession)}>
<div
className={styles.toolbar}
role="toolbar"
aria-orientation={showLifecycle ? "horizontal" : "vertical"}
aria-label={tx("Run actions")}
>
<div className={styles.session}>
<div className={styles.toolbar} role="toolbar" aria-orientation="vertical" aria-label={tx("Run actions")}>
{showLifecycle && (
<div className={styles.toolbarGroup}>
<>
<IconButton
icon="rerun"
title="Rerun"
@@ -248,36 +242,34 @@ export function SessionPanel({
/>
</>
)}
</div>
<div className={styles.toolbarSep} />
</>
)}
<div className={styles.toolbarGroup}>
{!rt.terminal && (
<>
<IconButton
icon="search"
title="Find…"
shortcut={formatBinding(hostBinding("Meta+F"))}
pressed={findOpen}
onClick={() => setFindOpen((v) => !v)}
/>
<IconButton
icon="scroll-to-end"
title="Scroll to End"
pressed={follow}
onClick={() => setFollow((v) => !v)}
/>
<IconButton icon="soft-wrap" title="Soft-Wrap" pressed={softWrap} onClick={toggleWrap} />
</>
)}
<IconButton icon="trash" title="Clear All" onClick={() => clearConsole(session.id)} />
</div>
<div className={styles.toolbarGroup}>
<IconButton
icon="settings"
title="Edit Configurations…"
onClick={() => void executeAction("run.editConfigs", session.config.id)}
/>
</div>
{!rt.terminal && (
<>
<IconButton
icon="search"
title="Find…"
shortcut={formatBinding(hostBinding("Meta+F"))}
pressed={findOpen}
onClick={() => setFindOpen((v) => !v)}
/>
<IconButton
icon="scroll-to-end"
title="Scroll to End"
pressed={follow}
onClick={() => setFollow((v) => !v)}
/>
<IconButton icon="soft-wrap" title="Soft-Wrap" pressed={softWrap} onClick={toggleWrap} />
</>
)}
<IconButton icon="trash" title="Clear All" onClick={() => clearConsole(session.id)} />
<div className={styles.toolbarSep} />
<IconButton
icon="settings"
title="Edit Configurations…"
onClick={() => void executeAction("run.editConfigs", session.config.id)}
/>
</div>
<div className={styles.sessionBody}>
{rt.tests ? (
@@ -106,22 +106,18 @@
--border-tab-selected: transparent;
flex: none;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1) var(--space-3);
gap: var(--space-3);
padding: 8px 14px 4px 20px;
}
.scopeDetail {
flex: 1 1 200px;
flex: 1;
min-width: 0;
display: flex;
align-items: center;
justify-content: flex-end;
gap: var(--space-1);
}
.scopeDetail:empty {
display: none;
}
.dirInput {
width: 100%;
max-width: 420px;
+9 -3
View File
@@ -67,7 +67,6 @@ import {
import { SINGLE_FIRST, isRowSelected, selectRow, selectedRows, type RowSelection } from "./rowSelection";
import { FindSession, IDLE, matchRows, type FindState, type MatchRow } from "./session";
import {
FIND_POPUP_SPLIT_KEY,
SEARCH_CONTEXTS,
buildQuery,
customScopeName,
@@ -83,7 +82,9 @@ import {
resolveFindScope,
setFindPopupCommandHandler,
loadFindPopupSize,
loadFindPopupSplit,
saveFindPopupSize,
saveFindPopupSplit,
setFindPopupNewTab,
setFindPopupPinned,
useFindPopup,
@@ -164,6 +165,11 @@ function FindInFilesDialog() {
const [previewMode, setPreviewMode] = useState(false);
const [diffPreview, setDiffPreview] = useState<{ key: string; lines: PreviewLine[] } | null>(null);
const [initialSize] = useState(loadFindPopupSize);
const [split, setSplit] = useState(loadFindPopupSplit);
const keepSplit = (layout: Record<string, number>) => {
setSplit(layout);
saveFindPopupSplit(layout);
};
const [marks, setMarks] = useState<ReplaceMarks>(NO_MARKS);
const [running, setRunning] = useState<ReplaceRun | null>(null);
const [progress, setProgress] = useState<ReplaceProgress | null>(null);
@@ -863,8 +869,8 @@ function FindInFilesDialog() {
</div>
<div className={styles.split}>
{rows.length ? (
<SplitGroup orientation="vertical" id="find-popup-split" storageKey={FIND_POPUP_SPLIT_KEY}>
<SplitPanel id="results" minSize={ROW * 3} defaultSize="33%">
<SplitGroup orientation="vertical" id="find-popup-split" defaultLayout={split} onLayoutChanged={keepSplit}>
<SplitPanel id="results" minSize={ROW * 3} defaultSize="48%">
{resultsBox}
</SplitPanel>
<SplitHandle hairline={false} />
+13 -1
View File
@@ -98,8 +98,9 @@ export function setFindPopupNewTab(newTab: boolean) {
}
const SIZE_KEY = "openidea.search.findPopupSize.v1";
export const FIND_POPUP_SPLIT_KEY = "openidea.search.findPopupSplit.v1";
const SPLIT_KEY = "openidea.search.findPopupSplit.v1";
/** The popup's size and its results / preview split, remembered like IDEA's. */
export function loadFindPopupSize(): { w: number; h: number } | null {
const v = loadJson<{ w?: unknown; h?: unknown } | null>(SIZE_KEY, null);
return typeof v?.w === "number" && typeof v.h === "number" ? { w: v.w, h: v.h } : null;
@@ -109,6 +110,17 @@ export function saveFindPopupSize(size: { w: number; h: number }) {
saveJson(SIZE_KEY, size);
}
export function loadFindPopupSplit(): Record<string, number> | undefined {
const v = loadJson<unknown>(SPLIT_KEY, null);
return v && typeof v === "object" && Object.values(v).every((n) => typeof n === "number")
? (v as Record<string, number>)
: undefined;
}
export function saveFindPopupSplit(layout: Record<string, number>) {
saveJson(SPLIT_KEY, layout);
}
/**
* Keys the popup handles that are also global shortcuts (⌘G / ⇧⌘G, F4 / ⌘↓, ⌥↓):
* hidden actions bound later in the keymap win while the popup is open and
@@ -321,7 +321,7 @@ export function SettingsLayout() {
return (
<SplitGroup id="settings" orientation="horizontal" storageKey="openidea.settings.layout" className={styles.layout}>
<SplitPanel id="navigation" defaultSize="22.5%" minSize="160px" maxSize="40%" className={styles.sidebar}>
<SplitPanel id="navigation" defaultSize="240px" minSize="160px" maxSize="40%" className={styles.sidebar}>
<SearchField
data-autofocus
className={styles.search}
+17 -38
View File
@@ -1,27 +1,18 @@
.view {
height: 100%;
display: flex;
min-height: 0;
}
.toolbar {
flex: none;
display: flex;
flex-direction: column;
gap: var(--space-1);
padding: var(--space-1);
border-inline-end: 1px solid var(--border);
overflow-y: auto;
}
.content {
flex: 1;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
}
.body {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
.body > * {
flex: 1;
min-height: 0;
}
.tabs {
min-width: 0;
@@ -46,12 +37,13 @@
display: flex;
align-items: center;
gap: var(--space-1-5);
padding: var(--space-1) var(--space-2);
height: 32px;
padding: 0 8px;
border-bottom: 1px solid var(--border);
}
.scopeSelect {
flex: 0 1 224px;
min-width: 0;
min-width: 200px;
max-width: 360px;
}
.row {
display: flex;
@@ -65,17 +57,7 @@
flex: none;
color: var(--fg-muted);
}
.fileLocation {
display: flex;
gap: var(--space-1-5);
min-width: 0;
overflow: hidden;
}
.fileName {
flex: none;
max-inline-size: 100%;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-emphasis);
}
.selectedText {
@@ -84,31 +66,28 @@
.muted {
flex: none;
color: var(--fg-subtle);
}
.directory {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.count {
flex: none;
color: var(--fg-subtle);
font-size: var(--fs-small);
margin-left: 4px;
}
.position {
flex: none;
min-inline-size: 3ch;
text-align: end;
font-variant-numeric: tabular-nums;
font-family: var(--font-mono);
font-size: var(--fs-small);
color: var(--fg-subtle);
}
.text {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
font-style: italic;
}
.keyword {
font-weight: 600;
font-style: normal;
}
.loading {
display: flex;
+2 -2
View File
@@ -29,7 +29,7 @@ describe("TodoView", () => {
render(<TodoView />);
expect(screen.getByText("a.ts")).toBeInTheDocument();
expect(screen.getByText("2 items")).toBeInTheDocument();
expect(screen.getByText("5")).toHaveAttribute("title", "(5, 4)");
expect(screen.getByText("(5, 4)")).toBeInTheDocument();
expect(screen.getByText(": wire it")).toBeInTheDocument();
act(() => useTodoView.getState().toggleKeyword("FIXME"));
expect(screen.getByText("1 item")).toBeInTheDocument();
@@ -135,7 +135,7 @@ describe("TodoView", () => {
render(<TodoView />);
// Select the file group so the preview has an item (trees select on mousedown).
fireEvent.mouseDown(screen.getByText("a.ts").closest("[role=treeitem]")!);
await screen.findByText("5");
await screen.findByText("(5, 4)");
// No editing switch: the preview is simply an editor, like IntelliJ's.
expect(screen.queryByLabelText("Allow editing")).toBeNull();
// No document attacher in tests: the editable pane degrades to its error
+18 -32
View File
@@ -19,7 +19,6 @@ import {
SplitPanel,
Spinner,
Tabs,
Toolbar,
Tree,
fileIconName,
type MenuItem,
@@ -292,16 +291,14 @@ function ItemText({ item }: { item: TodoItem }) {
const kwLen = item.keyword.length;
const color = colorFor(item.keyword);
return (
<span className={styles.text}>
<strong className={styles.keyword} style={{ color }}>
{item.text.slice(0, kwLen)}
</strong>
<span className={styles.text} style={{ color }}>
<strong className={styles.keyword}>{item.text.slice(0, kwLen)}</strong>
{item.text.slice(kwLen)}
</span>
);
}
function TodoToolbar() {
export function TodoHeaderActions() {
const settings = useTodoSettings();
const hidden = useTodoView((s) => s.hidden);
const toggleKeyword = useTodoView((s) => s.toggleKeyword);
@@ -319,7 +316,7 @@ function TodoToolbar() {
})),
];
return (
<Toolbar aria-label="TODO actions" orientation="vertical" className={styles.toolbar}>
<>
<IconButton icon="arrow-up" action="navigate.prevOccurrence" size="small" />
<IconButton icon="arrow-down" action="navigate.nextOccurrence" size="small" />
<IconButton
@@ -338,7 +335,7 @@ function TodoToolbar() {
onClick={() => updateTodoSettings({ caseSensitive: !settings.caseSensitive })}
/>
<IconButton icon="refresh" size="small" title="Refresh" disabled={scanning} onClick={() => void scanProject()} />
</Toolbar>
</>
);
}
@@ -424,20 +421,11 @@ export function TodoView() {
const renderNode = (n: Node, state: TreeRowState) => {
if (n.kind === "file") {
const name = basename(n.group.path);
const directory = relativeDir(root, n.group.path);
return (
<span className={styles.row}>
<Icon name={fileIconName(name)} size={16} className={styles.fileIcon} />
<span className={styles.fileLocation}>
<span className={clsx(styles.fileName, state.selected && styles.selectedText)} title={name}>
{name}
</span>
{directory && (
<span className={styles.directory} title={directory}>
{directory}
</span>
)}
</span>
<span className={clsx(styles.fileName, state.selected && styles.selectedText)}>{name}</span>
<span className={styles.muted}>{relativeDir(root, n.group.path)}</span>
<span className={styles.count}>
{n.group.items.length === 1 ? tx`${n.group.items.length} item` : tx`${n.group.items.length} items`}
</span>
@@ -446,8 +434,8 @@ export function TodoView() {
}
return (
<span className={styles.row} title={n.item.text}>
<span className={styles.position} title={`(${n.item.line + 1}, ${n.item.col + 1})`}>
{n.item.line + 1}
<span className={styles.position}>
({n.item.line + 1}, {n.item.col + 1})
</span>
<ItemText item={n.item} />
</span>
@@ -481,20 +469,18 @@ export function TodoView() {
return (
<div className={styles.view}>
<TodoToolbar />
<div className={styles.content}>
{tab === "project" && limitHit && (
<div className={styles.banner}>
<T>Too many matches; showing the first 10 000.</T>
</div>
)}
{tab === "scope" && <ScopeBar />}
{tab === "changes" && <ChangelistBar />}
{tab === "project" && limitHit && (
<div className={styles.banner}>
<T>Too many matches; showing the first 10 000.</T>
</div>
)}
{tab === "scope" && <ScopeBar />}
{tab === "changes" && <ChangelistBar />}
<div className={styles.body}>
<SplitGroup
orientation="horizontal"
id="todo-preview-split"
storageKey={showPreview ? "openidea.todo.previewSplit" : undefined}
className={styles.body}
>
<SplitPanel id="items" minSize={160} className={styles.panel}>
<Tree<Node>
@@ -533,7 +519,7 @@ export function TodoView() {
{showPreview && (
<>
<SplitHandle />
<SplitPanel id="preview" minSize={160} defaultSize="50%" className={styles.panel}>
<SplitPanel id="preview" minSize={160} defaultSize="45%" className={styles.panel}>
<TodoPreview node={lead} />
</SplitPanel>
</>
+2 -1
View File
@@ -4,7 +4,7 @@ import { registerEditorContribution } from "@/editor/api";
import { registerToolWindow, toolWindowService } from "@/workbench/contributions";
import { hasIcon } from "@/ui";
import { activateSettingsPages } from "./settingsPages";
import { TodoTabs, TodoView, useTodoBadge, useTodoHeaderMenu, useTodoView } from "./TodoView";
import { TodoHeaderActions, TodoTabs, TodoView, useTodoBadge, useTodoHeaderMenu, useTodoView } from "./TodoView";
import { todoEditorExtension } from "./highlight";
import { installTodoIndex, scanProject, syncTodoSettingsFromStorage } from "./store";
@@ -21,6 +21,7 @@ export function activate(): () => void {
order: 40,
component: TodoView,
headerContent: TodoTabs,
headerActions: TodoHeaderActions,
headerMenu: useTodoHeaderMenu,
useBadge: useTodoBadge,
}),
+10 -25
View File
@@ -26,20 +26,6 @@
gap: var(--space-0-5);
padding: 0 6px;
}
.changesToolbar {
height: auto;
min-height: 32px;
flex-wrap: wrap;
column-gap: var(--space-2);
padding-block: var(--space-0-5);
}
.changesTools {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-0-5);
max-width: 100%;
}
.sep {
width: 1px;
height: 16px;
@@ -120,12 +106,13 @@
}
.commitBar {
flex: none;
min-height: 32px;
height: 32px;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-0-5) var(--space-1);
padding: var(--space-0-5) 6px var(--space-0-5) 12px;
gap: var(--space-1);
padding: 0 6px 0 12px;
white-space: nowrap;
overflow: hidden;
}
.grow {
flex: 1;
@@ -134,7 +121,6 @@
color: var(--fg-faint);
font-family: var(--font-mono);
font-size: var(--fs-tiny);
white-space: nowrap;
}
.lineLenWarn {
color: var(--warning);
@@ -150,6 +136,8 @@
border-top: 1px solid var(--border);
outline: none;
color: var(--fg-strong);
font-family: var(--font-mono);
font-size: var(--fs-code);
line-height: var(--lh-code);
-webkit-user-select: text;
user-select: text;
@@ -176,6 +164,7 @@
display: flex;
align-items: center;
gap: var(--space-2);
/* A narrow panel moves Commit and Push… to its own row rather than cutting its label. */
flex-wrap: wrap;
padding: 8px 6px 10px 10px;
white-space: nowrap;
@@ -186,14 +175,10 @@
.commitActions > .pushButton {
flex: 0 1 auto;
min-width: 0;
min-height: var(--h-button, 28px);
height: auto;
padding: var(--space-1) var(--space-3);
line-height: 1.3;
}
.pushButton > span {
white-space: normal;
overflow-wrap: anywhere;
overflow: hidden;
text-overflow: ellipsis;
}
.stashList {
flex: 1;
+61 -82
View File
@@ -18,9 +18,7 @@ import {
import { tx, txTemplate } from "@/platform/i18n";
import clsx from "clsx";
import { executeAction } from "@/platform/actions";
import { fontWeightOf } from "@/platform/editorSettings";
import { resolveMonoFont } from "@/platform/fonts";
import { basename, dirname, useProject } from "@/platform/project";
import { basename, dirname } from "@/platform/project";
import { isTestFile, useEffectiveRoots } from "@/platform/projectRoots";
import {
Button,
@@ -765,79 +763,68 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
return (
<div className={styles.changes}>
<div className={clsx(styles.toolbar, styles.changesToolbar)} role="toolbar" aria-label={tx("Changes")}>
<div className={styles.changesTools}>
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => void refreshNow()} />
{mode === "local" && <IconButton icon="commit" action="vcs.commit" size="small" />}
<IconButton icon="undo" action="vcs.rollback" size="small" />
{mode === "local" && <IconButton icon="changelist" action="vcs.changelist.new" size="small" />}
{mode !== "dialog" && <IconButton icon="git-pull" action="vcs.update" size="small" />}
<div className={styles.toolbar} role="toolbar" aria-label={tx("Changes")}>
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => void refreshNow()} />
{mode === "local" && <IconButton icon="commit" action="vcs.commit" size="small" />}
<IconButton icon="undo" action="vcs.rollback" size="small" />
{mode === "local" && <IconButton icon="changelist" action="vcs.changelist.new" size="small" />}
{mode !== "dialog" && <IconButton icon="git-pull" action="vcs.update" size="small" />}
<IconButton
ref={viewRef}
icon="eye"
title="View Options"
size="small"
aria-haspopup="menu"
onClick={() =>
viewRef.current &&
showContextMenu(bottomLeft(viewRef.current), [
{ kind: "header", label: "Group By" },
{ label: "Directory", checked: groupByDir, run: () => setGroupByDir(!groupByDir) },
// IDEA offers it once the project has several repositories.
...(repos.length > 1
? [{ label: "Repository", checked: groupByRepo, run: () => setGroupByRepo(!groupByRepo) }]
: []),
...(staging
? []
: [{ label: "Staging State", checked: groupByStaging, run: () => setGroupByStaging(!groupByStaging) }]),
{ kind: "separator" },
{
label: "Show Unversioned Files Separately",
checked: showUnversionedSeparately,
run: () => setShowUnversionedSeparately(!showUnversionedSeparately),
},
...(mode === "local"
? [
{ kind: "separator" } as const,
{ label: "Show Diff Preview", checked: diffPreview, run: () => setDiffPreview(!diffPreview) },
]
: []),
// Not in the Commit dialog, whose files always open as source.
...(mode === "dialog" ? [] : doubleClickMenu(doubleClickOpensDiff)),
])
}
/>
{/* WebStorm's Preview Diff: an embedded diff of the selection beside the changes (#1599). */}
{mode === "commit" && (
<IconButton
ref={viewRef}
icon="eye"
title="View Options"
icon="editor-preview"
title="Preview Diff"
size="small"
aria-haspopup="menu"
onClick={() =>
viewRef.current &&
showContextMenu(bottomLeft(viewRef.current), [
{ kind: "header", label: "Group By" },
{ label: "Directory", checked: groupByDir, run: () => setGroupByDir(!groupByDir) },
// IDEA offers it once the project has several repositories.
...(repos.length > 1
? [{ label: "Repository", checked: groupByRepo, run: () => setGroupByRepo(!groupByRepo) }]
: []),
...(staging
? []
: [
{
label: "Staging State",
checked: groupByStaging,
run: () => setGroupByStaging(!groupByStaging),
},
]),
{ kind: "separator" },
{
label: "Show Unversioned Files Separately",
checked: showUnversionedSeparately,
run: () => setShowUnversionedSeparately(!showUnversionedSeparately),
},
...(mode === "local"
? [
{ kind: "separator" } as const,
{ label: "Show Diff Preview", checked: diffPreview, run: () => setDiffPreview(!diffPreview) },
]
: []),
// Not in the Commit dialog, whose files always open as source.
...(mode === "dialog" ? [] : doubleClickMenu(doubleClickOpensDiff)),
])
}
pressed={commitDiffPreview}
onClick={() => setCommitDiffPreview(!commitDiffPreview)}
/>
{/* WebStorm's Preview Diff: an embedded diff of the selection beside the changes (#1599). */}
{mode === "commit" && (
<IconButton
icon="editor-preview"
title="Preview Diff"
size="small"
pressed={commitDiffPreview}
onClick={() => setCommitDiffPreview(!commitDiffPreview)}
/>
)}
</div>
<div className={styles.changesTools}>
{mode !== "dialog" && (
<IconButton icon="locate" title="Select Opened File" size="small" onClick={selectOpened} />
)}
<IconButton icon="expand-all" title="Expand All" size="small" onClick={() => setCollapsed(new Set())} />
<IconButton
icon="collapse-all"
title="Collapse All"
size="small"
onClick={() =>
setCollapsed(new Set([...byKey.values()].filter((n) => n.type !== "file").map((n) => n.key)))
}
/>
</div>
)}
<span className={styles.sep} />
{mode !== "dialog" && (
<IconButton icon="locate" title="Select Opened File" size="small" onClick={selectOpened} />
)}
<IconButton icon="expand-all" title="Expand All" size="small" onClick={() => setCollapsed(new Set())} />
<IconButton
icon="collapse-all"
title="Collapse All"
size="small"
onClick={() => setCollapsed(new Set([...byKey.values()].filter((n) => n.type !== "file").map((n) => n.key)))}
/>
</div>
{mode !== "dialog" && <OperationBanner />}
<div
@@ -1146,8 +1133,6 @@ export function CommitMessageField({
}
const cfg = useWorkflowSettings((s) => s.vcs.commit);
const editor = useProject((s) => s.settings?.editor);
const { family, size } = resolveMonoFont(undefined, editor);
const first = message.split("\n")[0] ?? "";
const tooLong = cfg.limitSubject && first.length > cfg.subjectLimit;
const problems = messageProblems(message, cfg).filter((p) => !p.startsWith("Subject line"));
@@ -1197,13 +1182,7 @@ export function CommitMessageField({
data-autofocus={autoFocus ? "" : undefined}
className={clsx(styles.message, !showMargin && styles.noMargin, emptyError && styles.messageError)}
aria-invalid={emptyError || undefined}
style={{
["--guide" as string]: `${margin}ch`,
fontFamily: family,
fontSize: size,
fontWeight: fontWeightOf(editor?.fontWeight, 400),
lineHeight: editor?.lineHeight ? `${editor.lineHeight}px` : undefined,
}}
style={{ ["--guide" as string]: `${margin}ch` }}
value={message}
placeholder={tx("Commit Message")}
aria-label={tx("Commit message")}
+11 -48
View File
@@ -14,7 +14,6 @@
min-height: 0;
}
.log {
container: git-log / inline-size;
height: 100%;
min-height: 0;
display: flex;
@@ -76,32 +75,14 @@
/* filters */
.filters {
height: auto;
min-height: 32px;
flex-wrap: wrap;
justify-content: flex-end;
gap: var(--space-0-5) var(--space-1);
padding: var(--space-0-5) 8px var(--space-0-5) 6px;
min-width: 0;
}
.filterControls,
.filterActions {
display: flex;
align-items: center;
gap: var(--space-1);
}
.filterControls {
flex: 1 1 260px;
padding: 0 8px 0 6px;
min-width: 0;
}
.filterActions {
flex-wrap: wrap;
justify-content: flex-end;
max-width: 100%;
overflow: hidden;
}
.textFilter {
flex: 0 1 260px;
min-width: min(100px, 60%);
min-width: 100px;
}
.filterGroup {
position: relative;
@@ -115,20 +96,6 @@
.filterHidden {
visibility: hidden;
}
@container git-log (max-width: 320px) {
.filterControls,
.filterActions {
display: contents;
}
.textFilter {
flex: 1 0 100%;
}
/* Keep the filters measurable for the overflow menu. */
.filterGroup {
position: absolute;
width: 0;
}
}
.filterButton {
flex: none;
height: 24px;
@@ -201,7 +168,7 @@
.list {
flex: 1;
min-height: 0;
overflow: hidden auto;
overflow: auto;
outline: none;
/* Rows coming and going while scrolling relay out the list alone, not the workbench. */
contain: strict;
@@ -214,8 +181,8 @@
height: 26px;
display: flex;
align-items: center;
gap: min(var(--space-2), 2%);
padding: 0 min(var(--space-2), 2%);
gap: var(--space-2);
padding: 0 8px;
white-space: nowrap;
cursor: default;
font-size: var(--fs-ui);
@@ -232,18 +199,18 @@
background: var(--bg-app);
}
.columnCell {
flex: 0 1 auto;
min-width: 0;
flex: none;
overflow: hidden;
text-overflow: ellipsis;
/* Keep the first glyph clear of the divider on this column's left edge.
box-sizing: border-box keeps the width and boundary position unchanged. */
padding-inline-start: min(var(--space-2), 2%);
padding-inline-start: var(--space-2);
/* Anchor for the full-height column resize strip (IDEA's invisible divider). */
position: relative;
}
.columnHeading {
position: relative;
padding-inline-end: 6px;
cursor: grab;
touch-action: none;
}
@@ -347,7 +314,7 @@
--log-row-bg: var(--bg-tree-selected);
}
.colSubject {
flex: 1 0 min(220px, 50%);
flex: 1;
min-width: 0;
display: flex;
align-items: center;
@@ -398,12 +365,9 @@
}
.graph {
flex: none;
/* Leave room for the subject when the graph has many lanes: the lanes past it are cut off, not squeezed. */
max-width: calc(100% - min(120px, 50%));
fill: none;
stroke-width: 1.6;
overflow: visible;
clip-path: inset(-50% 0);
}
.refs {
flex: 0 1 auto;
@@ -796,8 +760,7 @@
}
.colRepository {
flex: 0 1 100px;
min-width: 0;
flex: 0 0 100px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
+13 -2
View File
@@ -26,7 +26,15 @@ const HIDDEN_COLUMN_OPTION: Record<string, keyof LogOptions> = {
repository: "showRepository",
};
export function ColumnHeaders({ columns, options }: { columns: LogColumn[]; options: LogOptions }) {
export function ColumnHeaders({
columns,
options,
minWidth,
}: {
columns: LogColumn[];
options: LogOptions;
minWidth: number;
}) {
const [drag, setDrag] = useState<ColumnDrag | null>(null);
const ids = columnSequence(options.columnOrder, columns);
const cancel = useCallback(() => setDrag(null), []);
@@ -39,7 +47,10 @@ export function ColumnHeaders({ columns, options }: { columns: LogColumn[]; opti
};
const visibleIds = ids.filter((id) => id === SUBJECT_COLUMN.id || columns.some((column) => column.id === id));
return (
<div className={clsx(styles.row, styles.columnHeader, options.showColumnDividers && styles.showDividers)}>
<div
className={clsx(styles.row, styles.columnHeader, options.showColumnDividers && styles.showDividers)}
style={{ minWidth }}
>
{options.showRepository && useVcs.getState().roots.length > 1 && (
<span className={styles.colRepository}>{tx("Repository")}</span>
)}
+12 -3
View File
@@ -43,7 +43,7 @@ import { currentRepo, currentRepoRoot, useVcs } from "../store";
import { ColumnHeaders } from "./ColumnHeaders";
import { CommitSignature } from "./CommitMessage";
import { CommitRow } from "./CommitRow";
import { ROW, type LogColumn, type RowEvents } from "./shared";
import { LANE, ROW, type LogColumn, type RowEvents } from "./shared";
const remoteNameSets = new WeakMap<readonly string[], ReadonlySet<string>>();
@@ -197,6 +197,15 @@ export function CommitList() {
),
};
}, [hoverColor, linear, displayedGraph, headKeys]);
const minWidth = useMemo(
() =>
rows.reduce((width, row) => Math.max(width, row.width * LANE), 100) +
columns.reduce(
(width, column) => width + (opts.columnWidths[column.id] ?? column.width ?? 120),
opts.showRepository && useVcs.getState().roots.length > 1 ? 220 : 120,
),
[rows, columns, opts.columnWidths, opts.showRepository],
);
const filterBranches = useGitLog((s) => s.filters.branches);
const currentBranch = useVcs((s) => s.branch?.head ?? null);
// Nothing to tell apart when the log is filtered to the current branch.
@@ -572,11 +581,11 @@ export function CommitList() {
);
}}
>
{opts.showColumnHeaders && <ColumnHeaders columns={columns} options={opts} />}
{opts.showColumnHeaders && <ColumnHeaders columns={columns} options={opts} minWidth={minWidth} />}
{!commits.length && !loading && finished && (
<div className={styles.message}>{headCommit ? tx("No commits match the filters") : tx("No commits yet")}</div>
)}
<div style={{ height: virtualizer.getTotalSize(), position: "relative" }}>
<div style={{ height: virtualizer.getTotalSize(), position: "relative", minWidth }}>
{items.map((v) => {
const c = commits[v.index];
if (!c)
+128 -131
View File
@@ -293,57 +293,55 @@ export function FilterBar() {
return (
<div className={styles.filters} role="toolbar" aria-label={tx("Log filters")}>
<div className={styles.filterControls}>
{!showBranches && (
<IconButton icon="chevron-right" title="Show Branches" size="small" action="vcs.log.showBranches" />
)}
<SearchField
className={styles.textFilter}
value={text}
onChange={setText}
placeholder="Text or hash"
aria-label="Filter by message"
toggles={[
{
id: "regex",
icon: "regex",
title: "Regex",
pressed: filters.regex,
onToggle: (regex) => setLogFilters({ regex }),
},
{
id: "case",
icon: "case",
title: "Match Case",
pressed: filters.matchCase,
onToggle: (matchCase) => setLogFilters({ matchCase }),
},
]}
{!showBranches && (
<IconButton icon="chevron-right" title="Show Branches" size="small" action="vcs.log.showBranches" />
)}
<SearchField
className={styles.textFilter}
value={text}
onChange={setText}
placeholder="Text or hash"
aria-label="Filter by message"
toggles={[
{
id: "regex",
icon: "regex",
title: "Regex",
pressed: filters.regex,
onToggle: (regex) => setLogFilters({ regex }),
},
{
id: "case",
icon: "case",
title: "Match Case",
pressed: filters.matchCase,
onToggle: (matchCase) => setLogFilters({ matchCase }),
},
]}
/>
<span ref={groupRef} className={styles.filterGroup}>
{logFilters.map((f, i) => (
<FilterButton key={f.label} {...f} hidden={i >= hiddenFrom} />
))}
</span>
{hiddenFrom < logFilters.length && (
<IconButton
icon="chevron-right"
title="More Filters"
size="small"
aria-haspopup="menu"
onClick={(e) => {
const anchor = e.currentTarget;
menuBelow(
anchor,
logFilters.slice(hiddenFrom).map((f) => ({
label: f.value ? `${tx(f.label)}: ${f.value}` : f.label,
run: () => f.onOpen(anchor),
})),
);
}}
/>
<span ref={groupRef} className={styles.filterGroup}>
{logFilters.map((f, i) => (
<FilterButton key={f.label} {...f} hidden={i >= hiddenFrom} />
))}
</span>
{hiddenFrom < logFilters.length && (
<IconButton
icon="chevron-right"
title="More Filters"
size="small"
aria-haspopup="menu"
onClick={(e) => {
const anchor = e.currentTarget;
menuBelow(
anchor,
logFilters.slice(hiddenFrom).map((f) => ({
label: f.value ? `${tx(f.label)}: ${f.value}` : f.label,
run: () => f.onOpen(anchor),
})),
);
}}
/>
)}
</div>
)}
{dropdown}
{branchAnchor && (
<BranchFilterPopup
@@ -358,89 +356,88 @@ export function FilterBar() {
onSelectMany={() => void selectBranches()}
/>
)}
<div className={styles.filterActions}>
<IconButton
icon="bookmark"
title="Bookmarked Commits"
size="small"
disabled={!Object.keys(bookmarks).length}
onClick={(e) =>
menuBelow(
e,
Object.entries(bookmarks).map(([key, summary]) => ({
label: summary,
run: () => {
const split = key.lastIndexOf("\0");
void goToRef(key.slice(split + 1), split >= 0 ? key.slice(0, split) : undefined);
},
})),
)
}
/>
<IconButton
icon="plus"
title="Open Another Log Tab"
size="small"
onClick={(e) =>
menuBelow(e, [
{
label: "In Tool Window",
run: () => {
openLogTab("log", `Log ${useGitLog.getState().logTabs.length + 1}`);
},
<span className={styles.grow} />
<IconButton
icon="bookmark"
title="Bookmarked Commits"
size="small"
disabled={!Object.keys(bookmarks).length}
onClick={(e) =>
menuBelow(
e,
Object.entries(bookmarks).map(([key, summary]) => ({
label: summary,
run: () => {
const split = key.lastIndexOf("\0");
void goToRef(key.slice(split + 1), split >= 0 ? key.slice(0, split) : undefined);
},
{
label: "In Editor",
run: () => {
openLogTab("log", `Log ${useGitLog.getState().logTabs.length + 1}`, "editor");
},
})),
)
}
/>
<IconButton
icon="plus"
title="Open Another Log Tab"
size="small"
onClick={(e) =>
menuBelow(e, [
{
label: "In Tool Window",
run: () => {
openLogTab("log", `Log ${useGitLog.getState().logTabs.length + 1}`);
},
{ label: "External Repository…", run: openExternalLog },
])
}
/>
<IconButton
icon="clock"
title="Recent Filters"
size="small"
onClick={(e) =>
menuBelow(
e,
recentLogFilters().map((filters) => ({
label:
[
filters.range,
filters.branches.join(", "),
filters.authors.join(", "),
filters.text,
filters.path,
filters.paths?.join(", "),
filters.date?.label,
]
.filter(Boolean)
.join(" · ") || tx("All commits"),
run: () => setLogFilters(filters),
})),
)
}
/>
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => void reloadLog({ preserve: true })} />
<IconButton
icon="sort"
title="Graph Options"
size="small"
aria-haspopup="menu"
onClick={(e) => menuBelow(e, graphOptionsMenu(useLogOptions.getState()))}
/>
<IconButton
icon="eye"
title="View Options"
size="small"
aria-haspopup="menu"
onClick={(e) => menuBelow(e, viewOptionsMenu(useLogOptions.getState()))}
/>
<IconButton icon="search" title="Go to Hash/Branch/Tag" size="small" action="vcs.log.goToRef" />
</div>
},
{
label: "In Editor",
run: () => {
openLogTab("log", `Log ${useGitLog.getState().logTabs.length + 1}`, "editor");
},
},
{ label: "External Repository…", run: openExternalLog },
])
}
/>
<IconButton
icon="clock"
title="Recent Filters"
size="small"
onClick={(e) =>
menuBelow(
e,
recentLogFilters().map((filters) => ({
label:
[
filters.range,
filters.branches.join(", "),
filters.authors.join(", "),
filters.text,
filters.path,
filters.paths?.join(", "),
filters.date?.label,
]
.filter(Boolean)
.join(" · ") || tx("All commits"),
run: () => setLogFilters(filters),
})),
)
}
/>
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => void reloadLog({ preserve: true })} />
<IconButton
icon="sort"
title="Graph Options"
size="small"
aria-haspopup="menu"
onClick={(e) => menuBelow(e, graphOptionsMenu(useLogOptions.getState()))}
/>
<IconButton
icon="eye"
title="View Options"
size="small"
aria-haspopup="menu"
onClick={(e) => menuBelow(e, viewOptionsMenu(useLogOptions.getState()))}
/>
<IconButton icon="search" title="Go to Hash/Branch/Tag" size="small" action="vcs.log.goToRef" />
</div>
);
}
+1 -2
View File
@@ -39,7 +39,6 @@ export function GraphCell({
interactive?: boolean;
}) {
const cy = ROW / 2;
const width = row.width * LANE;
const draw = (s: GraphSegment, i: number, up: boolean) => {
const fromX = x(s.fromX ?? s.from);
const toX = x(s.toX ?? s.to);
@@ -113,7 +112,7 @@ export function GraphCell({
return (
<svg
className={styles.graph}
width={width}
width={row.width * LANE}
height={ROW}
aria-label={tx("Commit graph")}
onMouseLeave={() => onHover?.(null)}
-4
View File
@@ -1,6 +1,4 @@
{
"Problems actions": "Problems actions",
"TODO actions": "TODO actions",
"Same as the existing configuration '{existing}'": "Same as the existing configuration '{existing}'",
"Windows file and folder names cannot end with a period or space": "Windows file and folder names cannot end with a period or space",
"Use URL template": "Use URL template",
@@ -2625,8 +2623,6 @@
"Hot reload on save": "Hot reload on save",
"Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.",
"Hot reload on save failed: {0}": "Hot reload on save failed: {0}",
"Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?",
"New Tab": "New Tab",
"Show Only Widgets": "Show Only Widgets",
"Update failed": "Update failed",
"Updating branches": "Updating branches",
-3
View File
@@ -1,5 +1,4 @@
{
"Problems actions": "问题操作",
"Windows file and folder names cannot end with a period or space": "Windows 文件和文件夹名称不能以句点或空格结尾",
"Use URL template": "使用 URL 模板",
"Use Driver": "使用驱动程序",
@@ -2945,7 +2944,6 @@
"System-Dependent": "取决于系统",
"Tests failed: {detail}": "测试失败:{detail}",
"TODO comment": "TODO 注释",
"TODO actions": "TODO 操作",
"TODO filters": "TODO 筛选器",
"TODO items": "TODO 项",
"TODO items unavailable": "TODO 项不可用",
@@ -9004,7 +9002,6 @@
"Hot reload on save": "保存时热重载",
"Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "保存正在运行的 Flutter 调试会话里的 Dart 文件时重新加载应用,文件有错误时跳过。",
"Hot reload on save failed: {0}": "保存时热重载失败:{0}",
"Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "项目可以在新窗口中打开、替换当前项目、附加到已打开的项目,或以新标签页在当前窗口中打开。\n要如何打开“{name}”?",
"Show Only Widgets": "仅显示 Widget",
"Update failed": "更新失败",
"Updating branches": "正在更新分支",
+2 -9
View File
@@ -13,7 +13,6 @@
}
/* Islands tabs: the selected tab is a rounded pill (tab-selected-bg / -border); no underline, no separators. */
.editor {
--tab-inline-padding: var(--space-2);
height: var(--h-header);
padding: 0 4px;
}
@@ -77,7 +76,7 @@
display: flex;
align-items: center;
gap: var(--space-1-5);
padding: 0 var(--tab-inline-padding, 10px);
padding: 0 10px;
border-radius: inherit;
white-space: nowrap;
color: inherit;
@@ -208,12 +207,6 @@
.wrap .tab {
height: calc(var(--h-header) - 6px);
}
.editor.wrap .tab {
max-inline-size: 100%;
}
.editor.wrap .tabButton {
min-inline-size: 0;
}
/* Vertical strip (editor tabs placed left / right): a scrolling column of full-width tabs. */
.vertical {
@@ -273,7 +266,7 @@
margin: 0 0 0 4px;
}
.closeLeft .closable .tabButton {
padding: 0 var(--tab-inline-padding, 10px) 0 2px;
padding: 0 10px 0 2px;
}
/* drag & drop: the dragged tab is an empty slot the other tabs make room for (IDEA) */
-62
View File
@@ -1,62 +0,0 @@
import { afterEach, expect, test, vi } from "vitest";
import { emitLocalIdeEvent } from "@/platform/ipc";
import { installDiagnosticsEvents, setFileDiagnostics } from "@/editor/lsp/diagnostics";
import { installPerfProbe, type PerfProbe } from "@/workbench/perfProbe";
import type * as EditorApi from "@/editor/api";
import type * as Contributions from "@/workbench/contributions";
const fixture = vi.hoisted(() => ({ active: null as null | { ctx: { path: string; doc: number } }, nextDoc: 0 }));
vi.mock("@/editor/api", async (importOriginal) => ({
...(await importOriginal<typeof EditorApi>()),
activeEditor: () => fixture.active,
}));
vi.mock("@/workbench/contributions", async (importOriginal) => ({
...(await importOriginal<typeof Contributions>()),
editorService: () => ({
openFile: async (path: string) => {
fixture.active = { ctx: { path, doc: ++fixture.nextDoc } };
},
}),
}));
let disposeProbe: (() => void) | undefined;
let disposeEvents: (() => void) | undefined;
afterEach(() => {
disposeProbe?.();
disposeEvents?.();
fixture.active = null;
});
test("the probe acknowledges only a fresh empty publication in the current temporal opening, not cached state", async () => {
disposeEvents = installDiagnosticsEvents();
disposeProbe = installPerfProbe();
const w = window as unknown as { __openideaPerf: PerfProbe };
const probe = w.__openideaPerf;
emitLocalIdeEvent({ type: "diagnostics", path: "/p/A.java", source: "jdtls", items: [] });
const first = await probe.openFileForDiagnostics("/p/A.java", "jdtls");
expect(probe.diagnosticsPublished(first)).toBe(false);
setFileDiagnostics("/p/A.java", "jdtls", [
{
range: { start: { line: 0, col: 0 }, end: { line: 0, col: 1 } },
severity: "error",
message: "Local inspection",
source: null,
code: null,
},
]);
setFileDiagnostics("/p/A.java", "jdtls", []);
emitLocalIdeEvent({ type: "diagnostics", path: "/p/other.java", source: "jdtls", items: [] });
emitLocalIdeEvent({ type: "diagnostics", path: "/p/A.java", source: "other-server", items: [] });
expect(probe.diagnosticsPublished(first)).toBe(false);
emitLocalIdeEvent({ type: "diagnostics", path: "/p/A.java", source: "jdtls", items: [] });
expect(probe.diagnosticsPublished(first)).toBe(true);
const second = await probe.openFileForDiagnostics("/p/A.java", "jdtls");
expect(probe.diagnosticsPublished(first)).toBe(false);
expect(probe.diagnosticsPublished(second)).toBe(false);
emitLocalIdeEvent({ type: "diagnostics", path: "/p/A.java", source: "jdtls", items: [] });
expect(probe.diagnosticsPublished(second)).toBe(true);
fixture.active = { ctx: { path: "/p/A.java", doc: 99 } };
expect(probe.diagnosticsPublished(second)).toBe(false);
fixture.active = { ctx: { path: "/p/other.java", doc: 99 } };
expect(probe.diagnosticsPublished(second)).toBe(false);
});
+5 -61
View File
@@ -10,7 +10,6 @@ import { executeAction } from "@/platform/actions";
import { bindingsFor } from "@/platform/keymap";
import { activeEditor } from "@/editor/api";
import { docBackend, type MemoryBackend } from "@/editor/core/backend";
import { subscribeDiagnostics } from "@/editor/lsp/diagnostics";
import type { Commit, CompletionItem, CompletionKind, LogQuery } from "@/bindings";
import { openProject } from "@/platform/project";
import { setInvokeRoute } from "@/platform/tauriCore";
@@ -20,10 +19,6 @@ export interface PerfProbe {
/** Seeds file contents for the in-memory document backend (plain-browser mode). */
seed(path: string, text: string): void;
openFile(path: string): Promise<void>;
/** Opens a document while observing fresh backend publications, excluding cached/local diagnostics. */
openFileForDiagnostics(path: string, source: string): Promise<number>;
/** Whether the current opening has received its producer's publication and is still active. */
diagnosticsPublished(generation: number): boolean;
/** Opens project `path` in this window (as the welcome screen does), without the window chooser. */
openProject(path: string): Promise<void>;
runAction(id: string, arg?: unknown): Promise<boolean>;
@@ -33,8 +28,8 @@ export interface PerfProbe {
setCursor(offset: number): void;
/** True while the active editor's background syntax parser still has work. */
parsing(): boolean;
/** The active editor's text, optionally restricted to a UTF-16 offset range. */
editorText(from?: number, to?: number): string | null;
/** The active editor's text. */
editorText(): string | null;
/** Inserts `text` after the first `after` in the active editor, as an edit of the user's; the offset after it. */
insertAfter(after: string, text: string): number;
/** Replaces the active editor's whole text, as an edit of the user's. */
@@ -48,16 +43,7 @@ export interface PerfProbe {
/** 0-based line of the active editor shown at viewport `y` (e.g. a gutter marker's), or -1. */
lineAtY(y: number): number;
/** Document length and caret (offset, 0-based line, the word around it) of the active editor. */
editorState(): {
doc: number;
path: string;
length: number;
lines: number;
head: number;
line: number;
col: number;
word: string;
} | null;
editorState(): { path: string; length: number; lines: number; head: number; line: number; word: string } | null;
/**
* Answers code completion with `items` generated items (a language server's
* list); other language server requests report no server. `0` removes it.
@@ -166,9 +152,6 @@ function requireView() {
}
export function installPerfProbe(): () => void {
let diagnosticGeneration = 0;
let diagnosticOpening: { generation: number; path: string; doc: number | null; published: boolean } | null = null;
let stopDiagnostics: (() => void) | null = null;
const probe: PerfProbe = {
seed(path, text) {
const backend = docBackend() as Partial<MemoryBackend>;
@@ -176,40 +159,6 @@ export function installPerfProbe(): () => void {
backend.files.set(path, text);
},
openFile: (path) => editorService().openFile(path),
async openFileForDiagnostics(path, source) {
stopDiagnostics?.();
const opening = { generation: ++diagnosticGeneration, path, doc: null as number | null, published: false };
diagnosticOpening = opening;
stopDiagnostics = subscribeDiagnostics(path, (publication) => {
if (diagnosticOpening === opening && publication?.source === source) opening.published = true;
});
try {
await editorService().openFile(path);
const editor = activeEditor();
if (diagnosticOpening !== opening || editor?.ctx.path !== path)
throw new Error("diagnostics opening was superseded");
opening.doc = editor.ctx.doc;
return opening.generation;
} catch (error) {
if (diagnosticOpening === opening) {
stopDiagnostics?.();
stopDiagnostics = null;
diagnosticOpening = null;
}
throw error;
}
},
diagnosticsPublished(generation) {
const opening = diagnosticOpening;
const editor = activeEditor();
return (
!!opening &&
opening.generation === generation &&
opening.published &&
editor?.ctx.path === opening.path &&
editor.ctx.doc === opening.doc
);
},
openProject: async (path) => void (await openProject(path)),
runAction: (id, arg) => executeAction(id, arg),
bindings: (id) => bindingsFor(id),
@@ -253,7 +202,7 @@ export function installPerfProbe(): () => void {
: null,
);
},
editorText: (from = 0, to) => activeEditor()?.view.state.doc.sliceString(from, to) ?? null,
editorText: () => activeEditor()?.view.state.doc.toString() ?? null,
insertAfter(after, text) {
const view = requireView();
const at = view.state.doc.toString().indexOf(after);
@@ -291,20 +240,15 @@ export function installPerfProbe(): () => void {
const word = e.view.state.wordAt(head);
return {
path: e.ctx.path,
doc: e.ctx.doc,
length: doc.length,
lines: doc.lines,
head,
line: doc.lineAt(head).number - 1,
col: head - doc.lineAt(head).from,
word: word ? doc.sliceString(word.from, word.to) : "",
};
},
};
const w = window as unknown as { __openideaPerf?: PerfProbe };
w.__openideaPerf = probe;
return () => {
stopDiagnostics?.();
delete w.__openideaPerf;
};
return () => void delete w.__openideaPerf;
}
+6 -6
View File
@@ -23,15 +23,15 @@ beforeEach(() => {
lightEdit: false,
});
});
it.each(["attach", "tab"] as const)("offers %s for this open without remembering it", async (button) => {
vi.mocked(ask).mockResolvedValue({ button, checked: true });
expect(await chooseProjectWindow("B")).toBe(button);
it("offers Attach for this open without remembering it", async () => {
vi.mocked(ask).mockResolvedValue({ button: "attach", checked: true });
expect(await chooseProjectWindow("B")).toBe("attach");
const prompt = vi.mocked(ask).mock.calls[0]![0];
expect(prompt.buttons.map((b) => b.id)).toEqual(["cancel", "attach", "tab", "new", "same"]);
expect(prompt.buttons.map((b) => b.id)).toEqual(["cancel", "attach", "new", "same"]);
expect(prompt.buttons.filter((b) => b.primary).map((b) => b.id)).toEqual(["same"]);
expect(commands.settingsSet).not.toHaveBeenCalled();
expect(openPolicy()).toBe("ask");
expect(await chooseProjectWindow("C")).toBe(button);
expect(await chooseProjectWindow("C")).toBe("attach");
expect(ask).toHaveBeenCalledTimes(2);
});
it("does not attach without a project or when opening a remote project", async () => {
@@ -40,7 +40,7 @@ it("does not attach without a project or when opening a remote project", async (
});
vi.mocked(ask).mockResolvedValue({ button: "cancel", checked: false });
expect(await chooseProjectWindow("remote", false)).toBeNull();
expect(vi.mocked(ask).mock.calls[0]![0].buttons.map((b) => b.id)).toEqual(["cancel", "new", "same"]);
expect(vi.mocked(ask).mock.calls[0]![0].buttons.map((b) => b.id)).not.toContain("attach");
useProject.setState({ project: null });
expect(await chooseProjectWindow("B")).toBe("same");
});
+8 -20
View File
@@ -1,5 +1,5 @@
/** Where a project opens when this window already has one: System Settings › Project › "Open project in". */
import { t, tx } from "@/platform/i18n";
import { t } from "@/platform/i18n";
import { call, commands, type RemoteTarget } from "@/platform/ipc";
import { confirmLeaveProject, useProject } from "@/platform/project";
import { connectRemote, isRemoteWindow } from "@/platform/remote";
@@ -17,38 +17,26 @@ export function openPolicy(): "ask" | "new" | "same" {
* per "Open project in", asking when set to (and remembering "Don't ask again").
* `null`: cancelled.
*/
export async function chooseProjectWindow(
name: string,
allowAttach = true,
): Promise<"new" | "same" | "attach" | "tab" | null> {
export async function chooseProjectWindow(name: string, allowAttach = true): Promise<"new" | "same" | "attach" | null> {
const { project, lightEdit } = useProject.getState();
if (!project && !lightEdit) return "same";
// Both ways of keeping this window's project: a workspace folder, or a project tab of this window.
const canAdd = allowAttach && !!project && !isRemoteWindow();
const canAttach = allowAttach && !!project && !isRemoteWindow();
const mode = openPolicy();
if (mode !== "ask") return mode;
const r = await ask({
title: t("app.window.askTitle"),
width: canAdd ? 640 : undefined,
body: canAdd
? tx`Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open "${name}"?`
: t("app.window.askBody", { name }),
width: canAttach ? 640 : undefined,
body: t("app.window.askBody", { name }),
buttons: [
{ id: "cancel", label: t("common.cancel") },
...(canAdd
? [
{ id: "attach", label: t("app.window.askAttach") },
{ id: "tab", label: tx`New Tab` },
]
: []),
...(canAttach ? [{ id: "attach", label: t("app.window.askAttach") }] : []),
{ id: "new", label: t("app.window.askNew") },
{ id: "same", label: t("app.window.askThis"), primary: true },
],
checkbox: t("app.window.askRemember"),
});
// "Attach" and "New Tab" are one-off: "Open project in" has no value for them, so Don't ask again ignores both.
if (r.button !== "same" && r.button !== "new" && r.button !== "attach" && r.button !== "tab") return null;
if (r.checked && (r.button === "same" || r.button === "new")) {
if (r.button !== "same" && r.button !== "new" && r.button !== "attach") return null;
if (r.checked && r.button !== "attach") {
try {
useProject.setState({
settings: await call(commands.settingsSet("global", "general.openProjectIn", JSON.stringify(r.button))),