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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 29f8955b38 test(settings): check the Markdown preview font size by field
#4530 added the command settings to the validated Markdown settings, so the
preview font size test no longer matches the whole object. Check that field, and
cover the new defaults and validation.
2026-11-19 21:45:19 +08:00
l0ng-ai 00871ab971 fix(build): give build output more room and honor console fonts (#4536)
The Build tool window gives its output two thirds of the width by default, and the build console and message details use the console font (Tools > Terminal > Font, or the editor font) with its row height, like the Run and Debug consoles.
2026-11-19 21:40:05 +08:00
l0ng-ai 5aba5e0629 fix(diff): keep toolbar status visible in narrow editors (#4527)
In a diff editor narrower than 380px the toolbar wraps and keeps the change count visible; the viewer-mode, collapse and scroll-sync toggles move out of the toolbar there and stay in the gear menu.
2026-11-19 21:39:29 +08:00
l0ng-ai eec447872c fix(services): give service details more room (#4524)
Services gives the details pane 70% of the width by default, and when the tool window is docked left or right it stacks the tree above the details; each orientation remembers its own split.
2026-11-19 21:37:55 +08:00
l0ng-ai 98418d727b fix(database): refine console and data editor layout (#4520)
Database console and data editor layout: console tabs show the console name with its data source and database (and the source icon) through new tabTitle/tabIcon file decorations, results tabs, the data source dialog, table editor and schema compare use the spacing scale and fit narrow panes.
2026-11-19 21:37:20 +08:00
l0ng-ai 2265497b18 fix(navigation): keep File Structure filters readable (#4522)
The File Structure popup is 540px wide and its filter options wrap onto further rows instead of being clipped at narrow window widths; the filter field uses the UI font.
2026-11-19 21:34:39 +08:00
l0ng-ai 7f33640895 feat(markdown): run code blocks and command lines from the gutter (#4530)
Markdown files get gutter run icons like IDEA's Markdown command runner: shell code blocks run in a new terminal tab from their fence, and code block lines run when a Run Anything provider recognizes them (Maven/Gradle lines, run configuration names; providers gain accepts()). Languages & Frameworks > Markdown > Commands toggles detection and picks the folder (asking when unset and the project and file folder differ). Untrusted projects get no icons.
2026-11-19 21:17:16 +08:00
l0ng-ai a57e12dbc5 fix(http): don't rescan Spring routes on every keystroke (#4525)
Typing in a Java/Kotlin file rescanned every Spring mapping source once per keystroke: Feign navigation dropped the route index on each docChanged (it already overlays unsaved text), and editor endpoint icons re-queried every provider, Spring included, on each change though they show only plugin endpoints. Typing now keeps the disk index; icons ask only plugin providers after typing pauses.
2026-11-19 21:07:43 +08:00
l0ng-ai b3f8cec272 fix(updates): don't hold the update lock while asking which window is focused (#4523)
The automatic update announcement held updates.ready while asking a window whether it is focused (a main-thread round trip); a window starting up ran app_update_window_ready on the main thread and waited for the same lock, freezing startup with no window. The focused and live windows are now read before taking the lock.
2026-11-19 21:01:13 +08:00
l0ng-ai e44e389571 fix(vcs): improve Commit panel layout and message typography (#4518)
The Commit panel wraps change actions into groups when the pane is narrow, so Expand All and Collapse All stay visible, and Commit and Push… wraps its label instead of cutting it. The commit message uses the editor's font family, size, weight and line height.
2026-11-19 20:58:36 +08:00
l0ng-ai 0cf0e93d92 fix(settings): give settings forms more room (#4515)
Settings starts with 22.5% of its width for navigation instead of a fixed 240px, giving the current form more room at the default window size while leaving space for long labels such as Build, Execution, Deployment. A user-resized divider is still remembered.
2026-11-19 20:56:59 +08:00
l0ng-ai c7ad3459c4 fix(vcs): fit Git Log controls in narrow panes (#4512)
Git Log gives the text filter its own row when the commit pane gets narrow; the other filters stay in More Filters and the action buttons wrap inside the pane, so Refresh, View Options and Go to Hash/Branch/Tag stay usable with the branch and details panes open.
2026-11-19 20:56:31 +08:00
l0ng-ai af281341b1 fix(run): keep console actions visible in short panes (#4511)
Run session controls move above the console: Rerun, Stop, Clear All and configuration controls fit together in a short docked pane, the console gets the full width, and the toolbar wraps by action group in narrow panes. Sessions without lifecycle controls (services, debugger console) keep the vertical toolbar.
2026-11-19 20:55:10 +08:00
l0ng-ai 313a5f3a14 fix(search): give Find in Files previews and scope controls room (#4510)
Find in Files starts with a 33/67 results-to-preview split and remembers the user's split through the splitter's own storage, so a temporarily constrained window no longer overwrites it. Scope controls wrap below the tabs when they need more room.
2026-11-19 20:53:41 +08:00
l0ng-ai 18cd2ef63b fix(debugger): keep controls visible in narrow tool windows (#4507)
Debug controls and view tabs wrap onto separate rows as the tool window narrows, and the action buttons use the standard control size, so every action and view stays reachable in a side pane.
2026-11-19 20:51:55 +08:00
l0ng-ai 4fc55f7520 fix(editor): fit wrapped tabs inside narrow splits (#4505)
Wrapped editor tabs fit inside their own split: a tab never grows past the strip, long labels truncate before the close button, and editor tabs use the 8px inline inset from the spacing scale.
2026-11-19 20:51:03 +08:00
l0ng-ai 795413c366 fix(project-view): prioritize names over paths in narrow trees (#4498)
Project tree rows give file, folder and symbol names priority over secondary text: a long project name can use the row width while paths and details truncate (full text on hover). Row icon spacing uses the spacing token.
2026-11-19 20:49:22 +08:00
l0ng-ai dd3c9c7b0a fix(problems): keep diagnostics readable in narrow panes (#4495)
The Problems tool window moves navigation and severity filters into a vertical toolbar left of the diagnostic list. Long directories, counts and diagnostic sources truncate (full text on hover) so file names and messages stay readable in a narrow split; line numbers use tabular digits.
2026-11-19 20:48:31 +08:00
l0ng-ai 361ca01cc0 fix(todo): improve tool window layout and result typography (#4492)
The TODO tool window moves its actions into a vertical toolbar beside the results, so the scope tabs get the full width. Results use the standard text size with right-aligned line numbers (the full position stays in the tooltip), long directories truncate so file names and counts stay visible, and the list and preview start at equal width.
2026-11-19 20:47:25 +08:00
Mr0Bread 1b9c330613 fix(bench): require current operation postconditions (#4491)
UI benchmarks and Java evals now arm their observation before triggering an action and wait for that action's own postcondition (current file, text, caret, completion/navigation outcome, rename scope, fresh diagnostics publication) instead of accepting editor or result state left by an earlier step. Budgets and goldens are unchanged.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-19 20:45:53 +08:00
wangfeiтаhapput 2d7bb56a8d feat(workbench): open a project as a new tab of this window (#4508)
Adds a New Tab choice to the Open Project prompt: the project opens in its own window, which joins this window's group as a selected project tab (new window_group_join command; window_groups::join is no longer macOS-only, since select handles every platform). The prompt keeps its original text when Attach and New Tab aren't offered (remote projects).

Co-authored-by: happut <[email protected]>
2026-11-19 20:43:26 +08:00
Shohruh Ismoilovтаshohruh-genius 2c8a029939 fix(vcs): fit Git Log commits to the available width (#4517)
Git Log sized its table for the widest graph row plus the saved column widths, so in a narrow pane columns went out of view behind a horizontal scrollbar. The header and rows now fit the pane: the columns shrink, the subject keeps a minimum share, and graph lanes past the room left for the subject are cut off rather than squeezed.

Co-authored-by: shohruh-genius <[email protected]>
2026-11-19 20:37:19 +08:00
l0ng-ai 6e2c19846c test(maven): fix the Always update snapshots test on main (#4514)
always_update_snapshots_adds_dash_u_once (from #4484) turned the setting off and re-applied it to the already-applied configuration, expecting -U to be removed, which failed main's Rust checks on every platform. Maven settings are applied to the stored configuration at each launch, so the test now checks a stored configuration with the setting off.
2026-11-19 20:13:26 +08:00
l0ng-ai 6c2ae13387 fix(vcs): select the best-matching branch while filtering the branches popup (#4509)
Typing a filter in the branches popup selected the first selectable row, the Local group header, so Enter did not act on the branch it found. While filtering, the popup now selects the best match of the first kind that has one: a matching action, then local branches, remote ones and tags (for several repositories: repositories, common branches, then one repository's). A match at the start of the name's last segment or at a word start ranks higher.
2026-11-19 19:44:53 +08:00
122 змінених файлів з 3913 додано та 948 видалено

No files matched your search

+21 -1
Переглянути файл
@@ -1194,11 +1194,31 @@ pub struct ArduinoSettings {
}
/// Languages & Frameworks › Markdown. Like IDEA's, it is application-level only.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct MarkdownSettings {
/// Preview (and notebook Markdown cell) font size in px; unset follows the editor font size.
pub preview_font_size: Option<u32>,
/// "Detect commands that can be run right from Markdown files": gutter run icons on
/// shell code blocks and on command lines in code blocks.
pub run_commands: bool,
/// Where those commands run; unset asks when the project and the file's folder differ.
pub command_directory: Option<MarkdownCommandDirectory>,
}
impl Default for MarkdownSettings {
fn default() -> Self {
Self { preview_font_size: None, run_commands: true, command_directory: None }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "lowercase")]
pub enum MarkdownCommandDirectory {
/// The project's root folder.
Project,
/// The Markdown file's parent folder.
File,
}
impl LanguagesSettings {
+4 -2
Переглянути файл
@@ -902,9 +902,11 @@ fn always_update_snapshots_adds_dash_u_once() {
apply_to_run_configs(&mut own, tmp.path(), &s);
assert_eq!(own[0].args, ["--update-snapshots", "package"]);
// Settings apply to the stored configuration at each launch, so turning it off drops -U.
s.languages.java.maven.update_snapshots = false;
apply_to_run_configs(&mut configs, tmp.path(), &s);
assert_eq!(configs[0].args, ["package"]);
let mut stored = vec![run("maven", "./mvnw", &["package"])];
apply_to_run_configs(&mut stored, tmp.path(), &s);
assert_eq!(stored[0].args, ["package"]);
}
#[test]
+8
Переглянути файл
@@ -48,6 +48,14 @@ 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
Переглянути файл
@@ -48,6 +48,14 @@ 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)。
+72
Переглянути файл
@@ -0,0 +1,72 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function showBuild(page: Page) {
await page.evaluate(async () => {
const storePath = "/src/features/build/store.ts";
const layoutPath = "/src/workbench/toolwindows/store.ts";
const { useBuildRun } = await import(/* @vite-ignore */ storePath);
const { showToolWindow } = await import(/* @vite-ignore */ layoutPath);
useBuildRun.setState({
title: "Build Project",
system: "typescript",
status: "failed",
durationMs: 1200,
selected: null,
lines: [
{ kind: "out", text: "Compiling TypeScript" },
{ kind: "err", text: "Expected a number" },
],
messages: [{ severity: "error", text: "Expected a number", path: null, range: null, code: null }],
});
showToolWindow("build", true);
});
const build = page.getByRole("region", { name: "Build", exact: true });
await expect(build.getByRole("log", { name: "Build output" })).toBeVisible();
return build;
}
test("Build gives about two thirds of the initial split to output", async ({ workbench: page }) => {
const build = await showBuild(page);
const tree = build.locator("[data-panel][id=build-tree]");
const console = build.locator("[data-panel][id=build-console]");
const treeWidth = (await tree.boundingBox())!.width;
const consoleWidth = (await console.boundingBox())!.width;
expect(treeWidth / (treeWidth + consoleWidth)).toBeCloseTo(0.33, 2);
});
test("Build output and diagnostics respond to a console font change", async ({ workbench: page }) => {
const build = await showBuild(page);
const log = build.getByRole("log", { name: "Build output" });
const rowGap = async () => {
const first = (await log.getByText("Compiling TypeScript", { exact: true }).boundingBox())!;
const second = (await log.getByText("Expected a number", { exact: true }).boundingBox())!;
return second.y - first.y;
};
await expect.poll(rowGap).toBe(20);
await page.evaluate(async () => {
const path = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ path);
const { settings } = useProject.getState();
useProject.setState({
settings: {
...settings,
terminal: {
...settings?.terminal,
useEditorFont: false,
fontFamily: "Fira Code",
fallbackFontFamily: "Maple Mono NF CN",
fontSize: 18,
},
},
});
});
await expect(log).toHaveCSS("font-size", "18px");
await expect(log).toHaveCSS("font-family", /"Fira Code".*"Maple Mono NF CN"/);
await expect.poll(rowGap).toBe(27);
await build.getByRole("treeitem", { name: "Expected a number", exact: true }).click();
const diagnostic = build.getByRole("document", { name: "Build message" });
await expect(diagnostic).toContainText("Expected a number");
await expect(diagnostic).toHaveCSS("font-size", "18px");
await expect(diagnostic).toHaveCSS("line-height", "27px");
});
+56
Переглянути файл
@@ -98,3 +98,59 @@ 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
Переглянути файл
@@ -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),
...(kind === "services-run" ? { onRerun: null, onDebug: null } : {}),
showLifecycle: kind === "run",
};
} else if (kind === "debug" || kind === "services-debug") {
const statePath = "/src/features/debugger/state.ts";
+24
Переглянути файл
@@ -1,5 +1,29 @@
import { expect, test } from "./fixtures";
test("data source tabs share a stable layout and scroll within a short window", async ({ workbench: page }) => {
await page.setViewportSize({ width: 560, height: 480 });
await page.evaluate(async () => {
const path = "/src/features/database/store.ts";
const { openSourceDialog } = await import(/* @vite-ignore */ path);
openSourceDialog(null, { name: "Local development", driver: "postgres", host: "localhost" });
});
const dialog = page.getByRole("dialog", { name: "New Data Source" });
const panel = dialog.getByRole("tabpanel");
const dialogSize = () => dialog.evaluate((element) => [element.offsetWidth, element.offsetHeight]);
await expect(panel.getByRole("textbox", { name: "Host:" })).toBeVisible();
const size = await dialogSize();
await dialog.getByRole("tab", { name: "SSH/SSL" }).click();
await expect(dialog.getByRole("tab", { name: "SSH/SSL" })).toHaveAttribute("aria-selected", "true");
expect(await dialogSize()).toEqual(size);
await dialog.getByRole("tab", { name: "General" }).click();
const canScroll = await panel.evaluate((element) => element.scrollHeight > element.clientHeight);
expect(canScroll).toBe(true);
await panel.getByRole("textbox", { name: "URL:" }).scrollIntoViewIfNeeded();
await expect(dialog.getByRole("button", { name: "Cancel" })).toBeInViewport();
});
for (const kind of ["password", "sshSecret", "params"] as const) {
test(`database ${kind} dialog keeps its fields inside the window`, async ({ workbench: page }) => {
await page.evaluate(async (kind) => {
+34
Переглянути файл
@@ -1,6 +1,40 @@
import type { Page } from "@playwright/test";
import { expect, openFromTree, test } from "./fixtures";
test("managed console tabs identify their data source and ordinary SQL tabs keep the file name", async ({
workbench: page,
}) => {
await page.evaluate(async () => {
const database = "/src/features/database/store.ts";
const workbench = "/src/workbench/contributions.ts";
const { useDatabase, bindConsole } = await import(database);
const { editorService } = await import(workbench);
const console = "/app-data/consoles/db/demo/console.sql";
useDatabase.setState({ loaded: true, sources: [{ id: "demo", name: "Shop Demo", driver: "sqlite" }] });
bindConsole(console, "demo");
bindConsole("/acme-api/console.sql", "demo");
await editorService().openFile("/acme-api/console.sql", { focus: true });
await editorService().openFile(console, { focus: true });
});
const consoleTab = page.getByRole("tab", { name: "console [Shop Demo]", exact: true });
await expect(consoleTab).toHaveAttribute("aria-selected", "true");
await expect(page.getByRole("tab", { name: "console.sql", exact: true })).toBeVisible();
await expect(page.getByRole("toolbar", { name: "Query Console", exact: true })).toContainText("main");
await page.evaluate(async () => {
const path = "/src/features/database/store.ts";
const { useDatabase } = await import(path);
useDatabase.setState((state: { sources: Array<{ name: string }> }) => ({
sources: state.sources.map((source) => ({ ...source, name: "Shop QA" })),
}));
});
await expect(page.getByRole("tab", { name: "console [Shop QA]", exact: true })).toHaveAttribute(
"aria-selected",
"true",
);
});
const edgeTitle = "Result 3 — a long query result at the edge of the Services pane";
const bindings = { "alpha-console.sql": "alpha", "beta-console.sql": "beta" };
+27
Переглянути файл
@@ -0,0 +1,27 @@
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");
});
+27
Переглянути файл
@@ -19,6 +19,33 @@ async function openChain(page: Page) {
return toolbar;
}
test("a narrow diff keeps navigation, settings and the difference count visible", async ({ workbench: page }) => {
const toolbar = await openChain(page);
await page.setViewportSize({ width: 400, height: 600 });
const clipped = await toolbar.evaluate((bar) => {
const bounds = bar.getBoundingClientRect();
const items = [...bar.querySelectorAll("button, span")].filter(
(el) => el.matches("button") || el.textContent === "1 difference",
);
return items.flatMap((el) => {
const box = el.getBoundingClientRect();
if (el.matches("button") && !box.width) return [];
return !box.width ||
box.right > bounds.right + 1 ||
box.bottom > bounds.bottom + 1 ||
el.scrollWidth > el.clientWidth + 1
? [el.getAttribute("aria-label") || el.textContent]
: [];
});
});
expect(clipped).toEqual([]);
await toolbar.getByRole("button", { name: "Settings", exact: true }).click();
await page.getByRole("menuitemcheckbox", { name: "Unified Viewer", exact: true }).click();
await expect(toolbar.locator("..").locator(".cm-editor")).toHaveCount(1);
await toolbar.getByRole("button", { name: "Next Difference", exact: true }).click();
await expect(toolbar).toContainText("1 of 1 differences");
});
test("maximizes a diff preview tab and restores its previous layout", async ({ workbench: page }) => {
const toolbar = await openChain(page);
const viewer = toolbar.locator("..");
+39
Переглянути файл
@@ -0,0 +1,39 @@
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();
});
+54
Переглянути файл
@@ -0,0 +1,54 @@
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
test("File Structure keeps symbol filters readable at desktop and minimum window widths", async ({
workbench: page,
}) => {
await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate(async () => {
const range = { start: { line: 0, col: 0 }, end: { line: 1, col: 1 } };
const field = {
name: "orderCount",
kind: "field",
visibility: "private",
range,
selection_range: range,
children: [],
};
window.__ipc.handlers.doc_outline = () => [
{ name: "OrderController", kind: "class", range, selection_range: range, children: [field] },
];
window.__ipc.handlers.lsp_type_hierarchy = () => [];
const path = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ path);
await executeAction("navigate.fileStructure");
});
const dialog = page.getByRole("dialog", { name: "File Structure" });
const fields = dialog.getByRole("checkbox", { name: "Show fields" });
await expect(dialog.getByRole("checkbox", { name: "Show inherited members" })).toBeVisible();
for (const width of [400, 1000]) {
await page.setViewportSize({ width, height: 600 });
const clipped = await dialog.evaluate((element) => {
const labels = [...element.querySelectorAll("label")].filter((label) =>
label.querySelector('input[type="checkbox"]'),
);
const row = labels[0]!.parentElement!.getBoundingClientRect();
return labels.flatMap((label) => {
const range = document.createRange();
range.selectNodeContents(label);
const box = range.getBoundingClientRect();
return box.top < row.top - 1 || box.right > row.right + 1 || box.bottom > row.bottom + 1
? [label.textContent]
: [];
});
});
expect(clipped).toEqual([]);
}
// The dialog scales in when it opens: wait for its settled width.
await expect.poll(async () => Math.round((await dialog.boundingBox())!.width)).toBe(540);
const field = dialog.getByRole("treeitem", { name: "orderCount" });
await expect(field).toBeVisible();
await fields.uncheck();
await expect(field).toBeHidden();
});
+41
Переглянути файл
@@ -76,6 +76,47 @@ 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
Переглянути файл
@@ -94,3 +94,30 @@ 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
Переглянути файл
@@ -0,0 +1,34 @@
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
Переглянути файл
@@ -0,0 +1,19 @@
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
Переглянути файл
@@ -81,6 +81,39 @@ 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 () => {
+68 -29
Переглянути файл
@@ -13,6 +13,32 @@ 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();
@@ -42,35 +68,7 @@ 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 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 stubFindMatches(page);
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/);
@@ -95,6 +93,19 @@ 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",
@@ -111,3 +122,31 @@ 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);
});
+45
Переглянути файл
@@ -48,6 +48,51 @@ async function move(page: Page, source: string, target: string) {
await page.mouse.up();
}
test("Services favors details and stacks the panes when docked to the side", async ({ workbench: page }) => {
await configure(page);
const services = page.getByRole("region", { name: "Services", exact: true });
const items = services.locator("[data-panel][id=services-items]");
const detail = services.locator("[data-panel][id=services-detail]");
const handle = services.locator("[data-separator]");
const share = async (axis: "width" | "height") => {
const treeSize = (await items.boundingBox())![axis];
return treeSize / (treeSize + (await detail.boundingBox())![axis]);
};
const dock = (anchor: "bottom" | "right" | "left") =>
page.evaluate(async (anchor) => {
const path = "/src/workbench/toolwindows/store.ts";
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ path);
moveToolWindow("services", anchor);
if (anchor !== "bottom") setToolWindowSize(anchor, 280);
}, anchor);
await expect(handle).toHaveAttribute("aria-orientation", "vertical");
await expect.poll(() => share("width")).toBeCloseTo(0.3, 2);
await handle.press("ArrowRight");
await expect.poll(() => share("width")).toBeGreaterThan(0.31);
const bottom = await share("width");
for (const anchor of ["right", "left"] as const) {
await dock(anchor);
await expect(handle).toHaveAttribute("aria-orientation", "horizontal");
const treeBox = (await items.boundingBox())!;
const detailBox = (await detail.boundingBox())!;
expect(detailBox.width).toBeCloseTo(treeBox.width, 0);
expect(detailBox.y).toBeGreaterThanOrEqual(treeBox.y + treeBox.height - 1);
await expect.poll(() => share("height")).toBeCloseTo(0.3, 2);
}
await handle.press("ArrowDown");
await expect.poll(() => share("height")).toBeGreaterThan(0.31);
const side = await share("height");
await dock("bottom");
await expect(handle).toHaveAttribute("aria-orientation", "vertical");
await expect.poll(() => share("width")).toBeCloseTo(bottom, 2);
await dock("right");
await expect(handle).toHaveAttribute("aria-orientation", "horizontal");
await expect.poll(() => share("height")).toBeCloseTo(side, 2);
});
test("service pointer ordering works for Java and npm and survives reload", async ({ workbench: page }) => {
await configure(page);
const tree = page.getByRole("tree", { name: "Services", exact: true });
+1
Переглянути файл
@@ -72,6 +72,7 @@ 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
Переглянути файл
@@ -0,0 +1,37 @@
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);
});
+69 -36
Переглянути файл
@@ -7,6 +7,8 @@ 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";
@@ -17,7 +19,7 @@ const LONG_TIMEOUT = 60_000;
interface ProbeWindow {
__openideaPerf: {
editorState(): { path: string; head: number; line: number; word: string } | null;
editorState(): { doc: number; path: string; head: number; line: number; col: number; word: string } | null;
editorText(): string | null;
setCursor(offset: number): void;
insertAfter(after: string, text: string): number;
@@ -25,6 +27,8 @@ 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;
};
}
@@ -373,10 +377,21 @@ function diagnosticsOnOpen(project: string, id: string, title: string, file: str
async setup() {},
async step(s): Promise<Measured> {
const timing = await track(s.page, {
openFile: join(s.root, file),
arg: null,
first: () => !!document.querySelector(".cm-content .cm-line"),
done: () => true,
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);
},
signature: problems,
settleMs: 3000,
timeoutMs: TIMEOUT,
@@ -514,12 +529,19 @@ 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): EvalScenario {
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 }
>();
return {
id,
title,
@@ -528,23 +550,39 @@ function rename(project: string, id: string, title: string, at: Place, newName:
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 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 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 timing = await track(s.page, {
run: () =>
document.querySelector(".cm-content")?.dispatchEvent(
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(
new KeyboardEvent("keydown", {
key: "Enter",
code: "Enter",
@@ -552,25 +590,17 @@ function rename(project: string, id: string, title: string, at: Place, newName:
bubbles: true,
cancelable: true,
}),
),
arg: newName,
first: answered,
done: answered,
);
arg.answer = await w.__openideaEvalRenameAnswer(arg.scope);
},
arg,
first: renameFinished,
done: renameFinished,
timeoutMs: TIMEOUT,
});
// 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 } };
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) };
},
};
}
@@ -748,6 +778,7 @@ export const JAVA_SCENARIOS: EvalScenario[] = [
"Rename: method used across files",
{ file: `${SRC}/Order.java`, line: "public long totalCents() {", word: "totalCents" },
"orderTotalCents",
"preview",
),
rename(
APP,
@@ -755,6 +786,7 @@ export const JAVA_SCENARIOS: EvalScenario[] = [
"Rename: local variable",
{ file: BOOK, line: "Order order = new Order(customer, product, quantity, unitPriceCents);", word: "order" },
"placedOrder",
"applied",
),
declaration(
@@ -837,5 +869,6 @@ 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
Переглянути файл
@@ -0,0 +1,91 @@
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
Переглянути файл
@@ -0,0 +1,74 @@
/** 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
Переглянути файл
@@ -0,0 +1,77 @@
// @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");
});
});
+43 -13
Переглянути файл
@@ -76,26 +76,57 @@ 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 visible = (sel: string) =>
[...document.querySelectorAll(sel)].some((el) => (el as HTMLElement).getClientRects().length > 0);
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 anyFeedback = () => {
if (visible('.cm-lsp-hint, [data-testid="usages-popup"], [role="dialog"], [role="listbox"]')) return true;
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;
}
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 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));
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);
},
);
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;
@@ -107,7 +138,7 @@ export async function track<A>(page: Page, spec: TrackSpec<A>): Promise<Tracked>
}
}
const settled = !sign || t - lastChange >= (settleMs ?? 0);
if (times.firstResultMs !== undefined && settled && checks.done(arg, before)) {
if (completed && 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 =
@@ -119,7 +150,6 @@ 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);
};
@@ -142,7 +172,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) throw new Error(`${what}: ${r.error}`);
if (r.error !== null) throw new Error(`${what}: ${r.error}`);
if (r.timedOut) {
const seen =
r.times.firstResultMs !== undefined
+104
Переглянути файл
@@ -0,0 +1,104 @@
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
Переглянути файл
@@ -0,0 +1,121 @@
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,
};
}
+10 -18
Переглянути файл
@@ -12,6 +12,8 @@ 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;
@@ -126,8 +128,7 @@ export class Session {
private server!: Server;
private relayQueue: Promise<unknown> = Promise.resolve();
private pendingNotes: Array<[kind: "channel" | "event", a: unknown, b: unknown]> = [];
/** The last answer to each command that succeeded, for what the UI only summarises. */
readonly lastAnswer = new Map<string, unknown>();
readonly renameObservations = new RenameObservations();
/** Editors changed by a scenario: path → the text to put back. */
private readonly edited = new Map<string, string>();
readonly pageErrors: string[] = [];
@@ -180,12 +181,15 @@ 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.server.invoke(cmd, args);
const value = await this.renameObservations.invoke(cmd, args, () => this.server.invoke(cmd, args));
this.record(cmd, start, true, value);
return { ok: value ?? null };
} catch (err) {
@@ -244,7 +248,6 @@ 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. */
@@ -286,20 +289,7 @@ 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);
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 },
);
await this.page.evaluate(openFileMeasured, { path, timeoutMs: 30_000 });
}
/**
@@ -422,6 +412,7 @@ 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;
@@ -443,6 +434,7 @@ 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
Переглянути файл
@@ -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}"],
entry: ["e2e/*.fixture.{ts,tsx}", "perf/**/*.fixture.{ts,tsx}"],
project: [
"src/**/*.{ts,tsx,css}",
"!src/editor/core/cm/angular/parser.terms.ts",
+124
Переглянути файл
@@ -0,0 +1,124 @@
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
Переглянути файл
@@ -0,0 +1,215 @@
// @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
Переглянути файл
@@ -0,0 +1,133 @@
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`);
}
+164 -38
Переглянути файл
@@ -2,6 +2,7 @@
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>;
@@ -69,45 +70,182 @@ export class Harness {
for (const k of await this.keysFor(actionId)) await this.page.keyboard.press(k);
}
/** 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;
/** 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);
}
}
/**
* 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): Promise<number[]> {
return this.pressMeasured(
[...text].map((ch) => (ch === "\n" ? "Enter" : ch === "\b" ? "Backspace" : ch)),
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)),
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): Promise<number[]> {
async pressMeasured(
keys: string[],
intervalMs: number,
afterKey?: (key: string, index: number) => Promise<void>,
): Promise<number[]> {
await this.inPage((p) => {
p.keyLatencies = [];
p.recordKeys = true;
});
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);
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;
});
}
// Let the last frames land.
await this.inPage((p) => p.afterNextPaint().then(() => p.afterNextPaint()));
return this.inPage((p) => {
p.recordKeys = false;
return p.keyLatencies;
}
/** 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;
});
}
/** 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());
@@ -162,20 +300,9 @@ export class Harness {
}
/** Seeds a file into the in-memory backend and opens it, returning open → painted ms. */
async openFile(path: string, text?: string): Promise<number> {
async openFile(path: string, text?: string, timeoutMs = 15_000): Promise<number> {
if (text !== undefined) await this.seed(path, text);
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 },
);
return this.page.evaluate(openFileMeasured, { path, text, timeoutMs });
}
/** Waits until the active editor's background parse has caught up (steady-state editing). */
@@ -195,10 +322,9 @@ export class Harness {
}
async editorState() {
return this.page.evaluate(() =>
(
window as never as { __openideaPerf: { editorState(): { length: number; lines: number; head: number } | null } }
).__openideaPerf.editorState(),
);
return this.page.evaluate(() => {
const w = window as unknown as { __openideaPerf: EditorProbe };
return w.__openideaPerf.editorState();
});
}
}
+78 -19
Переглянути файл
@@ -20,16 +20,23 @@ export interface InPage {
afterNextPaint(): Promise<number>;
startFrames(): void;
stopFrames(): 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>;
/** 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>;
}
export function installInPage() {
const w = window as unknown as { __perf: InPage };
if (w.__perf) return;
let armedAt = -1;
let firstInputAfterArm = -1;
let nextToken = 0;
let operation: { token: number; input: number; capture?: () => void; cancel?: () => void } | null = null;
const afterNextPaint = () =>
new Promise<number>((resolve) =>
@@ -43,7 +50,10 @@ export function installInPage() {
const onInput = (e: Event) => {
const t = e.timeStamp;
h.lastInput = t;
if (armedAt >= 0 && firstInputAfterArm < 0) firstInputAfterArm = t;
if (operation && operation.input < 0) {
operation.input = t;
operation.capture?.();
}
if (e.type === "keydown" && h.recordKeys) requestAnimationFrame(() => h.keyLatencies.push(performance.now() - t));
};
// `input` covers `keyboard.insertText`, which dispatches no keydown.
@@ -76,25 +86,74 @@ export function installInPage() {
return f;
},
arm() {
armedAt = performance.now();
firstInputAfterArm = -1;
if (operation) throw new Error("a measurement is already armed");
const token = ++nextToken;
operation = { token, input: -1 };
return token;
},
waitShown(selector, text, timeoutMs) {
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"));
const deadline = performance.now() + timeoutMs;
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);
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"),
}));
};
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 = () => {
// 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);
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);
} else if (performance.now() > deadline) {
armedAt = -1;
finish();
reject(new Error(`timed out waiting for ${selector}${text ? ` containing "${text}"` : ""}`));
} else requestAnimationFrame(tick);
};
+5 -9
Переглянути файл
@@ -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.pressMeasured(Array(20).fill("ArrowDown"), 60);
const arrows = await h.completionArrowsMeasured(20, 60);
await h.page.keyboard.press("Escape");
return {
openMs,
@@ -310,13 +310,9 @@ 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: scrollbar drag / Ctrl+End style repositioning.
const jumpMs = await h.measure(
() => h.page.keyboard.press("Control+End"),
".cm-content",
"export class Repository",
5_000,
);
// Jump far: document-end repositioning.
await h.setCursor(0);
const jumpMs = await h.jumpToEnd();
return {
...smooth,
tbtMs,
@@ -673,7 +669,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);
const keyLat = await h.typeMeasured("\b\b\b\b\b\b", 80, "input");
await h.page.keyboard.press("Escape");
await h.page.locator('[role="dialog"]').waitFor({ state: "detached" });
+11
Переглянути файл
@@ -18,6 +18,16 @@ 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]
@@ -86,6 +96,7 @@ 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,
+5 -2
Переглянути файл
@@ -139,11 +139,14 @@ fn announce_available(app: &AppHandle) {
return;
}
let state = app.state::<AppState>();
// Asking a window whether it is focused waits for the main thread, where
// `app_update_window_ready` takes `ready`: never hold the lock across it.
let focused = crate::windows::target_window(app);
let live = crate::windows::project_window_labels(app);
let owner = {
let mut ready = state.updates.ready.lock();
ready.retain(|label| app.get_webview_window(label).is_some());
let focused = crate::windows::target_window(app);
ready_owner(focused.as_ref().map(|window| window.label()), &crate::windows::project_window_labels(app), &ready)
ready_owner(focused.as_ref().map(|window| window.label()), &live, &ready)
};
let Some(owner) = owner else { return };
let update = {
-1
Переглянути файл
@@ -105,7 +105,6 @@ 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
Переглянути файл
@@ -726,6 +726,7 @@ 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
+18
Переглянути файл
@@ -1918,6 +1918,11 @@ 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")),
@@ -8232,10 +8237,23 @@ export type ManifestDependency = {
to: number,
};
export type MarkdownCommandDirectory =
/** The project's root folder. */
"project" |
/** The Markdown file's parent folder. */
"file";
/** Languages & Frameworks › Markdown. Like IDEA's, it is application-level only. */
export type MarkdownSettings = {
/** Preview (and notebook Markdown cell) font size in px; unset follows the editor font size. */
previewFontSize?: number | null,
/**
* "Detect commands that can be run right from Markdown files": gutter run icons on
* shell code blocks and on command lines in code blocks.
*/
runCommands?: boolean,
/** Where those commands run; unset asks when the project and the file's folder differ. */
commandDirectory?: MarkdownCommandDirectory | null,
};
/** A marketplace entry with what is installed. */
+2 -2
Переглянути файл
@@ -15,10 +15,10 @@ function parents(path: string): string[] {
* For every path whose file name occurs more than once in `paths`, the
* distinguishing directory hint. Paths with a unique name are absent.
*/
export function disambiguateTitles(paths: readonly string[]): Map<string, string> {
export function disambiguateTitles(paths: readonly string[], titleOf = baseName): Map<string, string> {
const groups = new Map<string, string[]>();
for (const p of new Set(paths)) {
const name = baseName(p);
const name = titleOf(p);
const list = groups.get(name);
if (list) list.push(p);
else groups.set(name, [p]);
+11 -3
Переглянути файл
@@ -161,7 +161,11 @@ function useTitleHints(): Map<string, string> {
return out.sort();
}),
);
return useMemo(() => disambiguateTitles(paths), [paths]);
const labels = useFileDecorations(useShallow(() => paths.map((p) => getFileDecoration(p)?.tabTitle ?? basename(p))));
return useMemo(() => {
const byPath = new Map(paths.map((p, i) => [p, labels[i]!]));
return disambiguateTitles(paths, (p) => byPath.get(p) ?? basename(p));
}, [paths, labels]);
}
const virtualData = (input: EditorInput) => input.data as VirtualInputData | undefined;
@@ -180,6 +184,8 @@ function PaneView({ paneId }: { paneId: string }) {
const dirty = tabs.map((tab, i) => inputDirty(tab.input, kinds) ?? textDirty[i] ?? false);
const colors = useFileDecorations(useShallow(() => paths.map((p) => (p ? (getFileDecoration(p)?.color ?? "") : ""))));
const tints = useFileDecorations(useShallow(() => paths.map((p) => (p ? (getFileDecoration(p)?.tint ?? "") : ""))));
const tabLabels = useFileDecorations(useShallow(() => paths.map((p) => getFileDecoration(p)?.tabTitle)));
const tabIcons = useFileDecorations(useShallow(() => paths.map((p) => getFileDecoration(p)?.tabIcon)));
const errors = useFileDecorations(useShallow(() => paths.map((p) => !!p && !!getFileDecoration(p)?.error)));
const fileColors = useFileColors("editorTabs");
@@ -200,7 +206,7 @@ function PaneView({ paneId }: { paneId: string }) {
return tabs.map((t, i) => {
const full = names[i]!;
const dot = full.lastIndexOf(".");
const name = t.input.kind === "file" && !showExtension && dot > 0 ? full.slice(0, dot) : full;
const name = tabLabels[i] ?? (t.input.kind === "file" && !showExtension && dot > 0 ? full.slice(0, dot) : full);
const dupe = !showDirectoryForNonUnique
? null
: t.input.kind === "file" && t.input.path
@@ -223,7 +229,7 @@ function PaneView({ paneId }: { paneId: string }) {
text: dupe ? `${name} — ${dupe}` : name,
icon: showFileIcon
? t.input.kind === "file" && t.input.path
? file?.icon
? (tabIcons[i] ?? file?.icon)
: tabIcon(t.input, kinds)
: undefined,
italic: t.preview,
@@ -255,6 +261,8 @@ function PaneView({ paneId }: { paneId: string }) {
colors,
errors,
tints,
tabLabels,
tabIcons,
fileColors,
hints,
showExtension,
+35 -1
Переглянути файл
@@ -8,6 +8,7 @@ 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();
@@ -44,6 +45,7 @@ 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),
@@ -111,7 +113,8 @@ beforeEach(() => {
workspaceAttach.mockReset();
workspaceUpdate.mockReset();
projectCurrent.mockReset();
for (const f of [windowOpenProject, windowOpenFiles, windowTakeLaunch, wslResolve]) f.mockReset();
for (const f of [windowOpenProject, windowOpenFiles, windowGroupJoin, windowTakeLaunch, wslResolve]) f.mockReset();
windowGroupJoin.mockResolvedValue(ok(null));
windowTakeLaunch.mockResolvedValue(null);
windowCompleteLaunch.mockReset().mockResolvedValue(ok(null));
wslResolve.mockResolvedValue(null);
@@ -694,6 +697,37 @@ 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
Переглянути файл
@@ -186,6 +186,10 @@ 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]));
@@ -216,6 +220,19 @@ 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;
+4
Переглянути файл
@@ -97,4 +97,8 @@ export const buildToolsRunAnything: RunAnythingProvider = {
const tool = lineTool(line);
return !!tool && executeBuildLine(tool, line);
},
accepts(line) {
const tool = lineTool(line);
return !!tool && (tool === "maven" ? parseGoalLine(line) : parseTaskLine(line)).length > 0;
},
};
-6
Переглянути файл
@@ -76,8 +76,6 @@
overflow: auto;
position: relative;
padding: 4px 0;
font-family: var(--font-mono);
font-size: var(--fs-code);
color: var(--fg);
background: var(--bg-app);
-webkit-user-select: text;
@@ -99,7 +97,6 @@
left: 0;
min-width: 100%;
padding: 0 12px;
line-height: 20px;
white-space: pre;
tab-size: 4;
}
@@ -141,9 +138,6 @@
.detail {
overflow: auto;
padding: 4px 12px;
font-family: var(--font-mono);
font-size: var(--fs-code);
line-height: 20px;
color: var(--fg);
background: var(--bg-app);
-webkit-user-select: text;
+34 -12
Переглянути файл
@@ -5,7 +5,16 @@
* its source (as IDEA: selection shows, navigation jumps).
*/
import { copySelectionOnKeyDown } from "@/ui/selectableText";
import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent, type ReactNode } from "react";
import {
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
type MouseEvent,
type ReactNode,
} from "react";
import clsx from "clsx";
import { useVirtualizer } from "@tanstack/react-virtual";
import { basename, relativeDir, useProject } from "@/platform/project";
@@ -41,6 +50,7 @@ import { openTarget, openUrl } from "@/features/run/navigate";
import { navigateToMessage, rerunBuild, selectBuildNode, useBuildRun } from "./store";
import styles from "./Build.module.css";
import { WidestColumns } from "@/platform/consoleColumns";
import { useConsoleFont } from "@/platform/consoleFont";
import { tx } from "@/platform/i18n";
const SEVERITY_ICON: Record<Severity, string> = { error: "error", warning: "warning", info: "info", hint: "info" };
@@ -203,8 +213,6 @@ function BuildTree() {
);
}
const LINE_HEIGHT = 20;
/**
* One console line: file locations and URLs (compiler diagnostics, stack
* frames) are links, resolved against the directory of the step that printed
@@ -242,7 +250,7 @@ function ConsoleLineText({ line, root }: { line: ConsoleLine; root: string }) {
return <>{out}</>;
}
function BuildConsole() {
function BuildConsole({ rowHeight }: { rowHeight: number }) {
const root = useProject((s) => s.project?.root ?? "/");
const lines = useBuildRun((s) => s.lines);
const ref = useRef<HTMLDivElement>(null);
@@ -252,12 +260,15 @@ function BuildConsole() {
const virtualizer = useVirtualizer({
count: lines.length,
getScrollElement: () => ref.current,
estimateSize: () => LINE_HEIGHT,
estimateSize: () => rowHeight,
overscan: 20,
});
useLayoutEffect(() => {
virtualizer.measure();
}, [rowHeight, virtualizer]);
useEffect(() => {
if (stick.current && lines.length) virtualizer.scrollToIndex(lines.length - 1, { align: "end" });
}, [lines.length, virtualizer]);
}, [lines.length, rowHeight, virtualizer]);
return (
<div
ref={ref}
@@ -268,7 +279,7 @@ function BuildConsole() {
aria-label={tx("Build output")}
onScroll={(e) => {
const el = e.currentTarget;
stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < LINE_HEIGHT * 2;
stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < rowHeight * 2;
}}
>
<div
@@ -319,15 +330,16 @@ function MessageDetail({ message }: { message: BuildMessage }) {
);
}
function BuildOutput() {
function BuildOutput({ rowHeight }: { rowHeight: number }) {
const selected = useBuildRun((s) => s.selected);
const messages = useBuildRun((s) => s.messages);
const node = useMemo(() => (selected ? findNode(messages, selected) : undefined), [selected, messages]);
return node?.kind === "message" ? <MessageDetail message={node.message} /> : <BuildConsole />;
return node?.kind === "message" ? <MessageDetail message={node.message} /> : <BuildConsole rowHeight={rowHeight} />;
}
export function BuildView() {
const hasBuild = useBuildRun((s) => s.status !== null);
const font = useConsoleFont();
if (!hasBuild) {
return (
<div className={styles.view}>
@@ -345,12 +357,22 @@ export function BuildView() {
id="build-view-split"
storageKey="openidea.build.split"
>
<SplitPanel id="build-tree" defaultSize="38%" minSize="120px" className={styles.pane}>
<SplitPanel id="build-tree" defaultSize="33%" minSize="120px" className={styles.pane}>
<BuildTree />
</SplitPanel>
<SplitHandle />
<SplitPanel id="build-console" minSize="120px" className={styles.pane}>
<BuildOutput />
<SplitPanel
id="build-console"
minSize="120px"
className={styles.pane}
style={{
fontFamily: font.family,
fontSize: font.size,
fontWeight: font.weight,
lineHeight: `${font.rowHeight}px`,
}}
>
<BuildOutput rowHeight={font.rowHeight} />
</SplitPanel>
</SplitGroup>
</div>
+43 -6
Переглянути файл
@@ -14,6 +14,24 @@
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;
@@ -38,10 +56,21 @@
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);
@@ -51,18 +80,25 @@
.selectedText {
color: var(--fg-strong);
}
.muted {
flex: none;
.directory {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-subtle);
}
.count {
flex: none;
max-inline-size: 50%;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-subtle);
margin-left: 4px;
}
.source {
flex: none;
margin-left: auto;
padding-right: 8px;
min-width: 0;
max-inline-size: 25%;
margin-inline-start: auto;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-faint);
}
.message {
@@ -77,6 +113,7 @@
.position {
flex: none;
color: var(--fg-subtle);
font-variant-numeric: tabular-nums;
}
.sev-error {
flex: none;
+42 -19
Переглянути файл
@@ -22,6 +22,7 @@ import {
SplitHandle,
SplitPanel,
Tabs,
Toolbar,
Tree,
fileIconName,
showContextMenu,
@@ -213,11 +214,11 @@ function useCurrentPath(): string | null {
return currentProblemsPath(text, useSyncExternalStore(subscribeActiveInput, activeInput));
}
export function ProblemsHeaderActions() {
function ProblemsToolbar() {
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")} />
@@ -235,7 +236,7 @@ export function ProblemsHeaderActions() {
pressed={show.info}
onClick={() => toggle("info")}
/>
</>
</Toolbar>
);
}
@@ -337,33 +338,44 @@ 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 parts = [plural(c.error, "error"), plural(c.warning, "warning"), plural(c.info + c.hint, "info")].filter(
Boolean,
);
const counts = [plural(c.error, "error"), plural(c.warning, "warning"), plural(c.info + c.hint, "info")]
.filter(Boolean)
.join(", ");
return (
<span className={styles.row}>
<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)}
<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}
</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>
{d.source && (
<span className={styles.source}>
{d.source}
{d.code ? `(${d.code})` : ""}
{source && (
<span className={styles.source} title={source}>
{source}
</span>
)}
</span>
@@ -378,9 +390,10 @@ export function ProblemsView() {
);
const selected = target(lead);
const list = (
const treeView = (
<Tree<Node>
aria-label="Problems"
className={styles.tree}
handleRef={tree}
roots={roots}
getKey={(n) => n.key}
@@ -428,7 +441,11 @@ 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}
@@ -436,6 +453,12 @@ export function ProblemsView() {
empty={empty}
/>
);
const list = (
<div className={styles.results}>
<ProblemsToolbar />
{treeView}
</div>
);
return (
<div className={styles.view}>
+1 -2
Переглянути файл
@@ -15,7 +15,7 @@ import {
import { getContext } from "@/platform/context";
import { clearProblems, installProblemsEvents, problemsReport, useProblems } from "./problemsStore";
import { installProblemDecorations } from "./decorations";
import { ProblemsHeaderActions, ProblemsTabs, ProblemsView, useProblemsHeaderMenu } from "./ProblemsView";
import { ProblemsTabs, ProblemsView, useProblemsHeaderMenu } from "./ProblemsView";
import { UsagesTabs, UsagesView, useUsagesHeaderMenu } from "./UsagesView";
import { UsagesPopup } from "./UsagesPopup";
import { findUsages, rerunActiveUsages, resetUsages, showUsageResults, showUsagesPopup } from "./usages";
@@ -79,7 +79,6 @@ export function activate(): () => void {
order: 30,
component: ProblemsView,
headerContent: ProblemsTabs,
headerActions: ProblemsHeaderActions,
headerMenu: useProblemsHeaderMenu,
useBadge: useErrorBadge,
}),
+8 -1
Переглянути файл
@@ -210,7 +210,14 @@ export function ImportDialog({ id, schema, table }: { id: string; schema: string
<T>File:</T>
</span>
<div className={styles.formRow}>
<Input readOnly aria-label="File" value={file ?? ""} placeholder="Choose a CSV or TSV file" />
<Input
className={styles.fill}
readOnly
aria-label="File"
value={file ?? ""}
placeholder="Choose a CSV or TSV file"
title={file ?? undefined}
/>
<IconButton icon="folder" title="Choose File…" onClick={() => void choose()} />
</div>
<span className={styles.formLabel}>
+3 -1
Переглянути файл
@@ -5,7 +5,7 @@
* Record / Value / Aggregates side panel following the selection.
*/
import { writeClipboardText } from "@/platform/clipboard";
import { useMemo, useRef, useState, type KeyboardEvent, type RefObject } from "react";
import { useMemo, useRef, useState, type KeyboardEvent, type ReactNode, type RefObject } from "react";
import clsx from "clsx";
import { Button, Checkbox, Icon, IconButton, Input, Popup, SearchField, Select, Tabs, T, type MenuItem } from "@/ui";
import { EXPORT_FORMATS, exportData, type ExportData, type ExportFormat } from "./export";
@@ -99,6 +99,7 @@ export interface DataViewProps extends Pick<
/** Rows from here on (the table editor's added rows) are never filtered or sorted. */
fixedRows?: number;
firstRowNumber?: number;
pager?: ReactNode;
/** The side panel shown (`null`: hidden). */
panel: DataPanel | null;
onPanelChange: (panel: DataPanel | null) => void;
@@ -247,6 +248,7 @@ export function DataView(props: DataViewProps) {
</div>
)}
</div>
{props.pager && <div className={styles.pagerDock}>{props.pager}</div>}
</div>
{filterAt && (
<FilterPopup
+116 -48
Переглянути файл
@@ -73,10 +73,11 @@
display: flex;
align-items: center;
justify-content: flex-end;
padding: 0 6px;
padding: 0 var(--space-1);
color: var(--fg-line-number);
background: var(--bg-editor-gutter);
border-right: 1px solid var(--border);
border-bottom: 1px solid var(--border);
user-select: none;
}
.cell {
@@ -139,9 +140,10 @@
.toolbar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-0-5);
height: var(--h-header);
padding: 0 6px;
min-height: 32px;
padding: var(--space-0-5) var(--space-2);
flex: none;
border-bottom: 1px solid var(--border);
}
@@ -233,14 +235,16 @@
flex-direction: column;
}
.dbToolbar {
height: 32px;
min-height: 32px;
flex: none;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-0-5);
padding: 0 6px;
padding: var(--space-0-5) var(--space-2);
}
.dbToolbarSep {
flex: none;
width: 1px;
height: 16px;
margin: 0 4px;
@@ -286,15 +290,22 @@
.consoleBar {
display: flex;
align-items: center;
gap: var(--space-1);
height: var(--h-header);
padding: 0 8px;
flex-wrap: wrap;
gap: var(--space-0-5);
min-height: 32px;
padding: var(--space-0-5) var(--space-2);
background: var(--bg-editor);
border-bottom: 1px solid var(--border);
font-family: var(--font-ui);
font-size: var(--fs-ui);
color: var(--fg-secondary);
}
.consoleSchema {
display: inline-flex;
align-items: center;
gap: var(--space-1);
padding-inline: var(--space-2);
}
/* Inline statement errors in consoles. */
:global(.cm-openidea-db-error) {
@@ -307,9 +318,9 @@
/* Table editor. */
/* The table editor's WHERE | ORDER BY row (IDEA). */
.filterBar {
display: flex;
display: grid;
grid-template-columns: minmax(0, 2fr) minmax(0, 3fr);
flex: none;
height: var(--h-header);
border-bottom: 1px solid var(--border);
}
.filterField {
@@ -318,29 +329,26 @@
display: flex;
align-items: center;
gap: var(--space-1-5);
padding: 0 8px;
padding: 0 var(--space-2);
color: var(--fg-muted);
font-family: var(--font-mono);
font-size: var(--fs-small);
white-space: nowrap;
}
.filterField + .filterField {
border-left: 1px solid var(--border);
}
.filterField > input {
flex: 1;
min-width: 0;
.filterField:focus-within {
box-shadow: inset 0 -1px var(--focus-ring);
}
.pager {
display: flex;
align-items: center;
gap: var(--space-0-5);
color: var(--fg-secondary);
font-size: var(--fs-small);
white-space: nowrap;
.filterField:has(input[aria-invalid="true"]) {
box-shadow: inset 0 -1px var(--danger);
}
.notice {
padding: 4px 8px;
padding: var(--space-1) var(--space-2);
font-size: var(--fs-small);
color: var(--fg-secondary);
background: var(--bg-editor-banner);
background: var(--bg-elev);
border-bottom: 1px solid var(--border);
}
@@ -427,6 +435,28 @@
display: none;
}
/* Data source dialog. */
.sourceLayout {
display: grid;
grid-template-rows: auto auto minmax(0, 1fr) auto;
height: clamp(220px, calc(100dvh - 150px), 560px);
}
.sourceLayout .form {
grid-template-columns: minmax(112px, 19%) minmax(0, 1fr);
align-content: start;
padding: var(--space-3) var(--space-4);
}
.sourceLayout .formLabel {
text-align: left;
}
.sourceLayout .formRow {
flex-wrap: wrap;
}
.sourceLayout .formRow > .fill {
flex: 1 1 160px;
}
.sourcePanel {
overflow: auto;
}
.formSection {
grid-column: 1 / -1;
display: flex;
@@ -549,10 +579,16 @@
font-size: var(--fs-small);
}
.testResult {
grid-column: 1 / -1;
font-size: var(--fs-small);
min-height: 16px;
word-break: break-word;
max-height: 25vh;
padding: var(--space-2) var(--space-4);
overflow: auto;
overflow-wrap: anywhere;
border-top: 1px solid var(--border);
}
.testResult:empty {
padding: 0;
border: 0;
}
.ok {
color: var(--success);
@@ -737,17 +773,28 @@
.modifyBody {
display: flex;
flex-direction: column;
gap: 10px;
padding: 14px;
gap: var(--space-2);
height: clamp(320px, 68vh, 560px);
padding: var(--space-4);
}
.modifyMain {
flex: 1;
display: grid;
grid-template-columns: 260px 1fr;
height: 240px;
grid-template-columns: minmax(108px, 34%) minmax(0, 1fr);
min-height: 0;
border: 1px solid var(--border);
border-radius: var(--radius-small);
overflow: hidden;
}
.modifyBody > .previewBlock {
flex: 0 0 38%;
min-height: 0;
}
.modifyBody .sqlPreview {
flex: 1;
min-height: 0;
max-height: none;
}
.modifyColumns {
display: flex;
flex-direction: column;
@@ -786,13 +833,17 @@
}
.modifyProps {
display: grid;
grid-template-columns: max-content 1fr;
grid-template-columns: minmax(0, 27%) minmax(0, 1fr);
align-content: start;
align-items: center;
gap: var(--space-2) var(--space-3);
padding: 12px;
overflow: auto;
}
.modifyProps .formLabel {
text-align: left;
overflow-wrap: anywhere;
}
.quickDoc {
width: 460px;
max-width: calc(100vw - 32px);
@@ -831,9 +882,6 @@
height: 100%;
min-height: 0;
}
.dataView > .fill {
min-width: 0;
}
.headerFilter {
flex: none;
display: inline-flex;
@@ -938,7 +986,8 @@
flex: none;
display: flex;
flex-direction: column;
width: 320px;
width: clamp(160px, 38%, 300px);
max-width: 50%;
min-height: 0;
border-left: 1px solid var(--border);
}
@@ -1165,29 +1214,42 @@
/* Export / history / import dialogs. */
.exportDialog {
display: flex;
display: grid;
grid-template-columns: minmax(0, 5fr) minmax(0, 6fr);
gap: var(--space-4);
height: 420px;
padding: 14px;
height: min(440px, 65vh);
min-height: 340px;
padding: var(--space-4);
}
.exportOptions {
display: flex;
flex-direction: column;
gap: var(--space-2);
width: 300px;
flex: none;
}
.exportOptions .formRow > input {
flex: 1;
}
.exportOptions .formLabel,
.exportPreview .formLabel {
text-align: left;
}
.exportPreview {
flex: 1;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
gap: var(--space-2);
}
@media (max-width: 620px) {
.exportDialog {
grid-template-columns: minmax(0, 1fr);
height: auto;
}
.exportPreviewText {
height: 200px;
flex: none;
}
}
.exportPreviewText,
.historyPreview {
flex: 1;
@@ -1368,6 +1430,7 @@
flex: none;
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-1);
padding: 4px 8px;
background: var(--bg-elev);
@@ -1375,8 +1438,8 @@
font-size: var(--fs-ui);
}
.gridSearchField {
flex: 0 1 360px;
min-width: 160px;
flex: 0 1 320px;
min-width: min(100%, 160px);
}
.gridSearchCount {
font-family: var(--font-mono);
@@ -1396,14 +1459,19 @@
background: var(--bg-text-search-result-current);
}
/* IDEA's floating pager at the bottom of a result: |< < 1-500 of 501+ > >| and the page size. */
.pagerDock {
flex: none;
display: flex;
justify-content: center;
padding: var(--space-1) var(--space-2) var(--space-2);
background: var(--bg-editor);
}
.resultPager {
position: absolute;
left: 50%;
bottom: 12px;
transform: translateX(-50%);
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
max-width: 100%;
gap: var(--space-0-5);
padding: 2px 4px;
border: 1px solid var(--border-popup, var(--border));
+4 -2
Переглянути файл
@@ -16,6 +16,7 @@ import {
Icon,
IconButton,
Menu,
Toolbar,
Tree,
showContextMenu,
tooltipAttrs,
@@ -523,6 +524,7 @@ export function DatabaseView() {
return color ? `var(--db-color-${color})` : undefined;
}}
speedSearchField
horizontalScroll
renderNode={(n: Node, state) => {
const i = icon(n);
const d = detail(n);
@@ -611,7 +613,7 @@ function DatabaseToolbar() {
const active = !!target && [...connected].some((t) => splitTarget(t).id === splitTarget(target).id);
const button = { size: "small", iconSize: 16 } as const;
return (
<div className={styles.dbToolbar} role="toolbar" aria-label={tx("Database actions")}>
<Toolbar className={styles.dbToolbar} aria-label="Database actions">
<IconButton
ref={plus}
{...button}
@@ -648,7 +650,7 @@ function DatabaseToolbar() {
>
<T>DDL</T>
</button>
</div>
</Toolbar>
);
}
+5 -5
Переглянути файл
@@ -118,7 +118,6 @@ interface Sel {
}
const ROW_H = 24;
const NUM_W = 48;
/** Wide enough for the whole header (icon, name, filter, sort) and the longest sampled value. */
function initialWidth(c: GridColumn, sample: Cell[], decorations: number): number {
@@ -169,6 +168,7 @@ export function Grid(props: GridProps) {
copyFormat = "tsv",
} = props;
const scrollRef = useRef<HTMLDivElement>(null);
const numberWidth = Math.max(40, String(firstRowNumber + rowCount - 1).length * 8 + 8);
const [sel, setSel] = useState<Sel | null>(null);
const dragging = useRef(false);
useEffect(() => {
@@ -225,8 +225,8 @@ export function Grid(props: GridProps) {
const scrollColumnIntoView = (c: number) => {
const el = scrollRef.current;
if (!el || c < 0 || c >= widths.length) return;
const left = c ? NUM_W + widths.slice(0, c).reduce((a, b) => a + b, 0) : 0;
const right = NUM_W + widths.slice(0, c + 1).reduce((a, b) => a + b, 0);
const left = c ? numberWidth + widths.slice(0, c).reduce((a, b) => a + b, 0) : 0;
const right = numberWidth + widths.slice(0, c + 1).reduce((a, b) => a + b, 0);
if (left < el.scrollLeft) el.scrollLeft = left;
else if (right > el.scrollLeft + el.clientWidth) el.scrollLeft = Math.min(left, right - el.clientWidth);
};
@@ -252,8 +252,8 @@ export function Grid(props: GridProps) {
// Runs once per request.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [revealColumn]);
const totalWidth = useMemo(() => NUM_W + widths.reduce((a, b) => a + b, 0), [widths]);
const template = `${NUM_W}px ${widths.map((w) => `${w}px`).join(" ")}`;
const totalWidth = useMemo(() => numberWidth + widths.reduce((a, b) => a + b, 0), [numberWidth, widths]);
const template = `${numberWidth}px ${widths.map((w) => `${w}px`).join(" ")}`;
const selected = (r: number, c: number) => {
if (!sel) return false;
+3 -3
Переглянути файл
@@ -577,7 +577,7 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
{notice}
</div>
)}
<div className={clsx(styles.fill, styles.gridHost)}>
<div className={styles.fill}>
<DataView
columns={gridColumns}
rowCount={rowCount}
@@ -590,6 +590,7 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
searchOpen={searchOpen}
onSearchOpenChange={setSearchOpen}
firstRowNumber={(tab.page ?? 0) * (tab.pageSize ?? 0) + 1}
pager={<Pager tab={busy ? { ...tab, busy: true } : tab} />}
aria-label={tab.title}
rowState={(row) => (row >= loaded ? "inserted" : edits.deletes.has(row) ? "deleted" : null)}
isModified={(row, col) => !!edits.updates.get(row)?.has(resultNames[col]!)}
@@ -611,7 +612,6 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
: []
}
/>
<Pager tab={busy ? { ...tab, busy: true } : tab} />
</div>
</>
)}
@@ -817,7 +817,7 @@ export function ResultsView() {
...results.map((r) => ({
id: String(r.id),
label: r.title,
icon: r.plan ? "db-plan" : "database",
icon: r.plan ? "db-plan" : "db-table",
closable: true,
pinned: r.pinned,
tooltip: r.outcome.statement.text,
+16 -5
Переглянути файл
@@ -2,8 +2,8 @@
display: flex;
flex-direction: column;
gap: var(--space-2);
height: 560px;
padding: 14px;
height: clamp(350px, 68vh, 620px);
padding: var(--space-4);
}
.pickers {
display: flex;
@@ -35,7 +35,8 @@
color: var(--fg-muted);
}
.panes {
display: flex;
display: grid;
grid-template-rows: minmax(0, 5fr) minmax(0, 4fr);
gap: var(--space-2);
flex: 1;
min-height: 0;
@@ -43,7 +44,6 @@
.tree {
display: flex;
flex-direction: column;
flex: 1.2;
min-width: 0;
border: 1px solid var(--border);
border-radius: var(--radius-control);
@@ -54,8 +54,19 @@
min-height: 0;
}
.preview {
flex: 1;
display: flex;
flex-direction: column;
gap: var(--space-1);
min-width: 0;
min-height: 0;
}
.previewLabel {
color: var(--fg-secondary);
font-size: var(--fs-small);
}
.preview > :last-child {
flex: 1;
min-height: 0;
}
.row {
display: inline-flex;
+6 -1
Переглянути файл
@@ -328,7 +328,12 @@ export function SchemaCompareDialog({ initial }: { initial: Side | null }) {
/>
)}
</div>
<CodePreview sql className={styles.preview} aria-label="Migration script" text={sql} />
<div className={styles.preview}>
<span className={styles.previewLabel}>
<T>Migration script</T>
</span>
<CodePreview sql aria-label="Migration script" text={sql} />
</div>
</div>
</div>
</Dialog>
+69 -67
Переглянути файл
@@ -1404,7 +1404,7 @@ export function SourceDialog({
open
onClose={closeDialog}
title={initial ? tx`Data Source: ${initial.name}` : "New Data Source"}
width={640}
width={760}
footerStart={
<Button onClick={() => void runTest()} disabled={busy || !valid}>
<T>Test Connection</T>
@@ -1415,74 +1415,76 @@ export function SourceDialog({
{ label: "OK", role: "default", disabled: busy || !valid, onClick: () => void save() },
]}
>
<div className={styles.form}>
<label className={styles.formLabel} htmlFor="db-name">
<T>Name:</T>
</label>
<div className={styles.formRow}>
<Input
id="db-name"
className={styles.fill}
value={s.name ?? ""}
placeholder={name}
onChange={(e) => set({ name: e.target.value })}
/>
<span className={styles.formLabel}>
<T>Color:</T>
</span>
<Select
aria-label="Color"
className={styles.narrowSelect}
value={s.color ?? "none"}
options={COLORS}
onChange={(c) => set({ color: c === "none" ? null : c })}
renderValue={(o) => (
<span className={styles.colorValue}>
{o && o.value !== "none" && (
<span className={styles.colorSwatch} style={{ background: colorVar(o.value as DbColor) }} />
)}
<T>{o?.label ?? "No color"}</T>
</span>
)}
/>
{/* IDEA's Make Global: stored with the IDE and listed in every project. */}
<span title={tx("Available in all projects")}>
<Checkbox
checked={!!s.global}
disabled={!!s.pluginOwner}
onChange={(global) => set({ global })}
label="Global"
<div className={styles.sourceLayout}>
<div className={styles.form}>
<label className={styles.formLabel} htmlFor="db-name">
<T>Name:</T>
</label>
<div className={styles.formRow}>
<Input
id="db-name"
className={styles.fill}
value={s.name ?? ""}
placeholder={name}
onChange={(e) => set({ name: e.target.value })}
/>
</span>
<span className={styles.formLabel}>
<T>Color:</T>
</span>
<Select
aria-label="Color"
className={styles.narrowSelect}
value={s.color ?? "none"}
options={COLORS}
onChange={(c) => set({ color: c === "none" ? null : c })}
renderValue={(o) => (
<span className={styles.colorValue}>
{o && o.value !== "none" && (
<span className={styles.colorSwatch} style={{ background: colorVar(o.value as DbColor) }} />
)}
<T>{o?.label ?? "No color"}</T>
</span>
)}
/>
{/* IDEA's Make Global: stored with the IDE and listed in every project. */}
<span title={tx("Available in all projects")}>
<Checkbox
checked={!!s.global}
disabled={!!s.pluginOwner}
onChange={(global) => set({ global })}
label="Global"
/>
</span>
</div>
<span />
{showComment ? (
<textarea
className={styles.textArea}
aria-label={tx("Comment")}
autoFocus={!s.comment}
rows={2}
value={s.comment ?? ""}
placeholder={tx("Comment")}
onChange={(e) => set({ comment: e.target.value })}
/>
) : (
<button type="button" className={styles.linkButton} onClick={() => setShowComment(true)}>
<T>Add comment</T>
</button>
)}
</div>
<Tabs
variant="compact"
className={styles.dialogTabs}
activeId={current}
onSelect={(id) => setTab(id as Tab)}
aria-label="Data source settings"
panelIdPrefix="db-source"
items={tabs}
/>
<div className={`${styles.form} ${styles.sourcePanel}`} role="tabpanel" id={`db-source-panel-${current}`}>
{body[current]}
</div>
<span />
{showComment ? (
<textarea
className={styles.textArea}
aria-label={tx("Comment")}
autoFocus={!s.comment}
rows={2}
value={s.comment ?? ""}
placeholder={tx("Comment")}
onChange={(e) => set({ comment: e.target.value })}
/>
) : (
<button type="button" className={styles.linkButton} onClick={() => setShowComment(true)}>
<T>Add comment</T>
</button>
)}
</div>
<Tabs
variant="compact"
className={styles.dialogTabs}
activeId={current}
onSelect={(id) => setTab(id as Tab)}
aria-label="Data source settings"
panelIdPrefix="db-source"
items={tabs}
/>
<div className={styles.form} role="tabpanel" id={`db-source-panel-${current}`}>
{body[current]}
<div className={`${styles.testResult} ${test?.ok ? styles.ok : styles.bad}`} role="status">
{busy && !test ? tx("Connecting…") : test?.text}
{test?.trust && (
-1
Переглянути файл
@@ -101,7 +101,6 @@ export function SqlFilterInput({
variant="bare"
mono
aria-label={kind === "where" ? "WHERE filter" : "ORDER BY"}
placeholder={kind === "where" ? "WHERE" : "ORDER BY"}
invalid={invalid}
value={value}
onChange={(e) => {
+73 -54
Переглянути файл
@@ -14,7 +14,7 @@ import {
type DbTablePage,
type RequestId,
} from "@/platform/ipc";
import { Button, EmptyState, Icon, IconButton, Select, Spinner, T, showContextMenu, tooltipAttrs } from "@/ui";
import { EmptyState, Icon, IconButton, Select, Spinner, Toolbar, showContextMenu } from "@/ui";
import { notifications, type EditorInput } from "@/workbench/contributions";
import { SqlFilterInput } from "./SqlFilterInput";
import { ColumnsPopup } from "./ColumnsPopup";
@@ -35,6 +35,7 @@ import styles from "./Database.module.css";
import { registerTableEditor, tableEditorChanged, type TableEditorHandle } from "./tableEditorFocus";
import { tx } from "@/platform/i18n";
import { shortcutLabel } from "@/platform/keymap";
import { pageWindow } from "./resultView";
const PAGE_SIZES = ["100", "500", "1000", "5000"];
@@ -283,9 +284,18 @@ export function TableEditor({ input }: { input: EditorInput }) {
useEffect(() => registerTableEditor(viewRef.current!, handle), [handle]);
useEffect(() => tableEditorChanged(handle), [handle, dirty, editable]);
const orderInvalid = orderDraft !== null && !parseOrderBy(orderDraft, names);
const hasMore = page?.result.hasMore ?? false;
const { first, last, total } = pageWindow({
page: offset / limit,
pageSize: limit,
rows: loaded,
hasMore,
total: null,
});
const singlePage = offset === 0 && !hasMore;
return (
<div className={styles.view} ref={viewRef} data-db-table-editor="">
<div className={styles.toolbar}>
<Toolbar className={styles.toolbar} aria-label="Table actions">
<IconButton
icon="refresh"
title="Reload Page"
@@ -293,55 +303,31 @@ export function TableEditor({ input }: { input: EditorInput }) {
onClick={reload}
disabled={loading}
/>
<div className={styles.pager}>
<IconButton
icon="chevron-left"
title="Previous Page"
shortcut={shortcutLabel("db.previousPage")}
disabled={!canPrevious}
onClick={() => setOffset(Math.max(0, offset - limit))}
/>
<span>
{loaded ? `${offset + 1}–${offset + loaded}` : "0"}
{page?.result.hasMore ? " of more" : ""}
</span>
<IconButton
icon="chevron-right"
title="Next Page"
shortcut={shortcutLabel("db.nextPage")}
disabled={!canNext}
onClick={() => setOffset(offset + limit)}
/>
<Select
aria-label="Page size"
value={String(limit)}
options={PAGE_SIZES.map((v) => ({ value: v, label: v }))}
onChange={(v) => {
setOffset(0);
setLimit(Number(v));
}}
/>
</div>
<IconButton
icon="search"
title="Search"
shortcut={shortcutLabel("find.inFile")}
aria-pressed={searchOpen}
onClick={() => setSearchOpen(!searchOpen)}
/>
{editable && (
<>
<span className={styles.toolbarSeparator} />
<IconButton icon="plus" title="Add Row" shortcut={shortcutLabel("db.addRow")} onClick={addRow} />
<Button
size="small"
variant="primary"
disabled={!dirty}
onClick={() => void submit()}
{...tooltipAttrs("Submit", shortcutLabel("db.submitChanges"))}
>
<T>Submit</T>
</Button>
<Button
size="small"
<IconButton
icon="revert"
title="Revert"
shortcut={shortcutLabel("db.revertChanges")}
disabled={!dirty}
onClick={() => setEdits(emptyEdits())}
{...tooltipAttrs("Revert", shortcutLabel("db.revertChanges"))}
>
<T>Revert</T>
</Button>
/>
<IconButton
icon="arrow-up"
title="Submit"
shortcut={shortcutLabel("db.submitChanges")}
disabled={!dirty}
onClick={() => void submit()}
/>
</>
)}
{loading && <Spinner size={12} />}
@@ -361,18 +347,12 @@ export function TableEditor({ input }: { input: EditorInput }) {
disabled={!editable}
onClick={() => openDialog({ kind: "import", id: ref.id, schema: ref.schema, table: ref.table })}
/>
<IconButton
icon="search"
title="Search"
shortcut={shortcutLabel("find.inFile")}
aria-pressed={searchOpen}
onClick={() => setSearchOpen(!searchOpen)}
/>
<PanelToggle panel={panel} onChange={setPanel} />
</div>
</Toolbar>
<div className={styles.filterBar}>
<label className={styles.filterField}>
<Icon name="filter" size={14} />
<span aria-hidden="true">WHERE</span>
<SqlFilterInput
kind="where"
schema={ref.schema}
@@ -391,6 +371,7 @@ export function TableEditor({ input }: { input: EditorInput }) {
</label>
<label className={styles.filterField}>
<Icon name="db-sort" size={14} />
<span aria-hidden="true">ORDER BY</span>
<SqlFilterInput
kind="order"
schema={ref.schema}
@@ -451,6 +432,44 @@ export function TableEditor({ input }: { input: EditorInput }) {
driver={source?.driver}
sort={sort}
onSort={onSort}
pager={
<Toolbar className={styles.resultPager} aria-label="Table pages">
{!singlePage && (
<>
<IconButton
size="small"
icon="chevron-left"
title="Previous Page"
shortcut={shortcutLabel("db.previousPage")}
disabled={!canPrevious}
onClick={() => setOffset(Math.max(0, offset - limit))}
/>
<span className={styles.resultPagerRange}>
{loaded ? tx`${first}-${last} of ${total ?? `${last + 1}+`}` : tx`${loaded} rows`}
</span>
<IconButton
size="small"
icon="chevron-right"
title="Next Page"
shortcut={shortcutLabel("db.nextPage")}
disabled={!canNext}
onClick={() => setOffset(offset + limit)}
/>
</>
)}
<Select
variant="ghost"
aria-label="Page size"
value={String(limit)}
options={PAGE_SIZES.map((v) => ({ value: v, label: v }))}
renderValue={singlePage ? () => tx`${loaded} rows` : undefined}
onChange={(v) => {
setOffset(0);
setLimit(Number(v));
}}
/>
</Toolbar>
}
rowMenu={(rows) =>
editable
? [
+57 -51
Переглянути файл
@@ -45,9 +45,9 @@ import type { EditorDocContext } from "@/editor/api";
import { iconNode } from "@/ui/iconNode";
import { call, commands, type DbDriver, type DbSessionContext, type DbStatementOutcome } from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
import { IconButton, Select, lazyComponent } from "@/ui";
import { Icon, IconButton, Select, Toolbar, lazyComponent } from "@/ui";
import { useProject } from "@/platform/project";
import { activeSchema, schemaSwitchable, sourceLabel, splitTarget, targetOf } from "./model";
import { activeSchema, schemaSwitchable, sourceIcon, sourceLabel, splitTarget, targetOf } from "./model";
import { loadSavedCatalog, offerIntrospection } from "./introspection";
import { analyze, templateContexts, valuesSlot } from "./sql/analyze";
import {
@@ -477,10 +477,11 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
// SQL resolution scopes in the settings can move the console to another data source.
useProject((s) => s.settings);
const boundId = bound ? splitTarget(bound).id : null;
const jdbc = sourceById(boundId)?.driver === "jdbc";
const supportsTransactions = sourceById(boundId)?.driver !== "clickhouse" && !jdbc;
const sqlServer = sourceById(boundId)?.driver === "sqlServer";
const switchable = schemaSwitchable(sourceById(boundId)?.driver);
const driver = sources.find((s) => s.id === boundId)?.driver;
const jdbc = driver === "jdbc";
const supportsTransactions = driver !== "clickhouse" && !jdbc;
const sqlServer = driver === "sqlServer";
const switchable = schemaSwitchable(driver);
// The console's active schema: its pick, else the connection's default (`completion.defaultSchema`).
const pickedSchema = useDatabase((s) => s.consoleSchemas[path]);
const defaultSchema = useDatabase((s) => (bound ? s.completion[bound]?.defaultSchema : undefined));
@@ -503,9 +504,10 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
: schemaList?.status === "ok"
? schemaList.value
: [];
const out = names.map((n) => ({ value: n, label: n }));
const out = names.map((n) => ({ value: n, label: n, icon: "db-schema" }));
// The connection's default is offered even before its schema list loads.
if (defaultSchema && !names.includes(defaultSchema)) out.unshift({ value: defaultSchema, label: defaultSchema });
if (defaultSchema && !names.includes(defaultSchema))
out.unshift({ value: defaultSchema, label: defaultSchema, icon: "db-schema" });
return out;
}, [switchable, schemaList, defaultSchema, sqlServer, boundId, databases]);
const targets = useMemo(() => {
@@ -520,9 +522,9 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
value: targetOf(id, name, dbs.value.current),
label: `${s.name ?? ""}: ${name}`,
detail: host,
icon: "database",
icon: sourceIcon(s),
});
} else out.push({ value: id, label: s.name ?? "", detail: host, icon: "db-schema" });
} else out.push({ value: id, label: s.name ?? "", detail: host, icon: sourceIcon(s) });
}
// A console bound to a database whose list is not loaded yet still shows it.
if (bound && !out.some((o) => o.value === bound))
@@ -536,7 +538,7 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
if (bound) void loadCompletion(bound);
}, [bound]);
return (
<div className={styles.consoleBar}>
<Toolbar className={styles.consoleBar} aria-label="Query Console">
<IconButton
icon="run"
title="Execute"
@@ -550,6 +552,8 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
disabled={!bound || running}
onClick={() => void executeScriptInView(view, path)}
/>
<span className={styles.toolbarSeparator} />
<IconButton icon="history" title="Browse Query History" disabled={!bound} onClick={() => openHistory(path)} />
{!jdbc && (
<IconButton
icon="db-plan"
@@ -558,14 +562,6 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
onClick={() => void explainInView(view, path)}
/>
)}
<IconButton
icon="stop"
title="Cancel Running Statement"
disabled={!running}
onClick={() => cancelConsole(path)}
/>
<span className={styles.toolbarSeparator} />
<IconButton icon="history" title="Browse Query History" disabled={!bound} onClick={() => openHistory(path)} />
<IconButton
icon="db-in-editor-results"
title="In-Editor Results"
@@ -573,28 +569,18 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
onClick={() => void setInEditorResults(!inEditor)}
/>
<span className={styles.toolbarSeparator} />
<Select
variant="ghost"
aria-label="Row limit"
value={String(maxRows)}
options={ROW_LIMITS.map((v) => ({ value: v, label: tx`${Number(v).toLocaleString("en")} rows` }))}
onChange={(v) => useDatabase.setState({ maxRows: Number(v) })}
/>
{supportsTransactions && (
<>
<span className={styles.toolbarSeparator} />
<Select
variant="ghost"
aria-label="Transaction mode"
value={manual ? "manual" : "auto"}
options={[
{ value: "auto", label: "Tx: Auto" },
{ value: "manual", label: "Tx: Manual" },
]}
onChange={(v) => bound && void setManualCommit(bound, v === "manual")}
disabled={!bound}
/>
</>
<Select
variant="ghost"
aria-label="Transaction mode"
value={manual ? "manual" : "auto"}
options={[
{ value: "auto", label: "Tx: Auto" },
{ value: "manual", label: "Tx: Manual" },
]}
onChange={(v) => bound && void setManualCommit(bound, v === "manual")}
disabled={!bound}
/>
)}
{supportsTransactions && manual && (
<>
@@ -612,8 +598,31 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
/>
</>
)}
<IconButton
icon="stop"
title="Cancel Running Statement"
disabled={!running}
onClick={() => cancelConsole(path)}
/>
<span className={styles.toolbarSeparator} />
<Select
variant="ghost"
aria-label="Row limit"
value={String(maxRows)}
options={ROW_LIMITS.map((v) => ({ value: v, label: tx`${Number(v).toLocaleString("en")} rows` }))}
onChange={(v) => useDatabase.setState({ maxRows: Number(v) })}
/>
<span className={styles.spacer} />
{bound && sourceById(boundId)?.driver === "snowflake" && <SnowflakeSession target={bound} idle={!running} />}
{bound && driver === "snowflake" && <SnowflakeSession target={bound} idle={!running} />}
<Select
variant="ghost"
aria-label="Data source"
value={bound ?? null}
placeholder={sources.length ? "<data source>" : "None configured"}
options={targets}
onChange={(id) => bindConsole(path, id)}
disabled={!sources.length}
/>
{switchable && (
<Select
variant="ghost"
@@ -626,16 +635,13 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
disabled={!bound}
/>
)}
<Select
variant="ghost"
aria-label="Data source"
value={bound ?? null}
placeholder={sources.length ? "<data source>" : "None configured"}
options={targets}
onChange={(id) => bindConsole(path, id)}
disabled={!sources.length}
/>
</div>
{driver === "sqlite" && (
<span className={styles.consoleSchema} title={tx("Schema")}>
<Icon name="db-schema" size={14} />
{schema || "main"}
</span>
)}
</Toolbar>
);
}
+3 -3
Переглянути файл
@@ -38,7 +38,7 @@ import {
DB_TOOL_WINDOW,
RESULTS_VIEW,
consoleSource,
consoleTints,
consoleDecorations,
inEditorResults,
setInEditorResults,
loadSources,
@@ -161,9 +161,9 @@ export function activate(): () => void {
newMenuOpen: false,
});
}),
// Consoles of coloured data sources get a tinted tab.
useDatabase.subscribe((s, prev) => {
if (s.consoles !== prev.consoles || s.sources !== prev.sources) setFileDecorations("database", consoleTints(s));
if (s.consoles !== prev.consoles || s.sources !== prev.sources)
setFileDecorations("database", consoleDecorations(s));
}),
() => setFileDecorations("database", new Map()),
watchIdleConnections(),
+14 -5
Переглянути файл
@@ -45,6 +45,7 @@ import {
effectiveSsh,
idleTargets,
newSourceId,
sourceIcon,
splitTarget,
targetOf,
} from "./model";
@@ -601,13 +602,21 @@ export function watchIdleConnections(everyMs = 5000): () => void {
return () => clearInterval(timer);
}
/** Console files of coloured data sources, tinted like IDEA's (file decorations). */
export function consoleTints(s: Pick<DatabaseState, "consoles" | "sources">): Map<string, FileDecoration> {
/** Managed consoles show their source in the tab. Ordinary SQL files can also inherit a source tint. */
export function consoleDecorations(s: Pick<DatabaseState, "consoles" | "sources">): Map<string, FileDecoration> {
const out = new Map<string, FileDecoration>();
for (const [path, target] of Object.entries(s.consoles)) {
const id = splitTarget(target).id;
const tint = colorVar(s.sources.find((x) => x.id === id)?.color);
if (tint) out.set(path, { tint });
const { id, database } = splitTarget(target);
const source = s.sources.find((x) => x.id === id);
if (!source) continue;
const tint = colorVar(source.color);
// db_console_path and db_consoles own this directory, including already saved consoles.
const consoleName = /(?:^|\/)consoles\/db\/[^/]+\/(console(?:_\d+)?)\.sql$/.exec(path.replaceAll("\\", "/"))?.[1];
if (consoleName) {
const name = source.name || id;
const label = database ? `${name}: ${database}` : name;
out.set(path, { tint, tabTitle: `${consoleName} [${label}]`, tabIcon: sourceIcon(source) });
} else if (tint) out.set(path, { tint });
}
return out;
}
+19 -7
Переглянути файл
@@ -19,20 +19,28 @@
}
.toolbar {
height: 32px;
min-height: 32px;
flex: none;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-0-5);
padding: 0 8px 0 4px;
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;
overflow: hidden;
}
.actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-0-5);
min-width: 0;
}
.tool {
width: 26px;
height: 26px;
width: var(--h-control);
height: var(--h-control);
flex: none;
}
@@ -46,17 +54,21 @@
.tabs {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-0-5);
flex: none;
min-width: 0;
}
.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 {
+38 -37
Переглянути файл
@@ -16,6 +16,7 @@ import {
SplitHandle,
SplitPanel,
Tabs,
Toolbar,
showContextMenu,
type MenuItem,
type TabItem,
@@ -218,43 +219,43 @@ export function DebugToolWindow() {
return (
<div className={styles.root}>
<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 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 role="tablist" aria-label={tx("Debug views")} className={styles.tabs}>
{(
[
+32 -2
Переглянути файл
@@ -1,9 +1,10 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { CompletionContext } from "@codemirror/autocomplete";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { useProject } from "@/platform/project";
import { registerEndpointProvider, searchEndpoints, type EndpointEntry } from "@/workbench/contributions";
import { completionTarget, endpointCompletion, renderEndpoint } from "./endpoints";
import { completionTarget, endpointCompletion, endpointEditorExtension, renderEndpoint } from "./endpoints";
const route: EndpointEntry = {
method: "GET",
@@ -70,4 +71,33 @@ describe("shared HTTP endpoints", () => {
useProject.setState(previous);
}
});
it("asks only plugin providers for editor icons, once typing pauses", async () => {
vi.useFakeTimers();
const previous = useProject.getState();
useProject.setState({ project: { root: "/p" } as NonNullable<typeof previous.project> });
const scan = vi.fn(async () => [route]);
const plugin = vi.fn(async () => [{ ...route, pluginId: "demo", path: "/p/Users.java" }]);
const disposeScan = registerEndpointProvider({ id: "http.spring", endpoints: scan });
const disposePlugin = registerEndpointProvider({ id: "plugin:demo", endpoints: plugin });
const ctx = { doc: 1, path: "/p/Users.java", language: "java", uiMode: null, readOnly: false };
const view = new EditorView({
state: EditorState.create({ doc: "class Users {}", extensions: endpointEditorExtension(ctx) }),
});
try {
await vi.runAllTimersAsync();
plugin.mockClear();
for (const ch of "abc") view.dispatch({ changes: { from: 0, insert: ch } });
expect(plugin).not.toHaveBeenCalled();
await vi.runAllTimersAsync();
expect(plugin).toHaveBeenCalledTimes(1);
expect(scan).not.toHaveBeenCalled();
} finally {
view.destroy();
disposeScan();
disposePlugin();
useProject.setState(previous);
vi.useRealTimers();
}
});
});
+14 -3
Переглянути файл
@@ -72,6 +72,9 @@ export async function endpointCompletion(context: CompletionContext): Promise<Co
};
}
const REFRESH_DELAY = 300;
const isPluginProvider = (id: string) => id.startsWith("plugin:");
type Mark = { pos: number; endpoints: EndpointEntry[] };
const setMarks = StateEffect.define<Mark[]>();
const marks = StateField.define<Mark[]>({
@@ -112,18 +115,25 @@ export function endpointEditorExtension(ctx: EditorDocContext): Extension {
destroyed = false;
unsubscribe: () => void;
projectUnsubscribe: () => void;
timer: ReturnType<typeof setTimeout> | undefined;
constructor(readonly view: EditorView) {
this.unsubscribe = onEndpointsChanged(() => this.refresh());
this.projectUnsubscribe = useProject.subscribe(() => this.refresh());
this.projectUnsubscribe = useProject.subscribe((state, previous) => {
if (state.project !== previous.project) this.refresh();
});
this.refresh();
}
update(u: { docChanged: boolean }) {
if (u.docChanged) this.refresh();
if (!u.docChanged) return;
clearTimeout(this.timer);
this.timer = setTimeout(() => this.refresh(), REFRESH_DELAY);
}
refresh() {
clearTimeout(this.timer);
const seq = ++this.seq;
const root = useProject.getState().project?.root ?? null;
void searchEndpoints(root).then((entries) => {
// Only plugin endpoints get icons here; built-in providers (Spring) scan the project.
void searchEndpoints(root, isPluginProvider).then((entries) => {
if (this.destroyed || seq !== this.seq) return;
const byLine = new Map<number, EndpointEntry[]>();
for (const e of entries) {
@@ -136,6 +146,7 @@ export function endpointEditorExtension(ctx: EditorDocContext): Extension {
}
destroy() {
this.destroyed = true;
clearTimeout(this.timer);
this.unsubscribe();
this.projectUnsubscribe();
}
+9
Переглянути файл
@@ -101,6 +101,15 @@ describe("core service-aware Feign navigation", () => {
expect(await resolve()).toEqual([]); // Current source revalidation rejects the cached target.
});
it("keeps the disk index while a controller is edited", async () => {
await resolve();
for (let version = 2; version < 6; version++) {
_emitEditorEvent({ type: "docChanged", doc: 9, path: users, baseVersion: version - 1, version, changes: [] });
await resolve();
}
expect(commands.springRouteSources).toHaveBeenCalledTimes(1);
});
it("overlays recently edited unsaved controllers absent from the disk index", async () => {
await resolve();
const path = "/p/users/src/main/kotlin/Added.kt";
+13 -5
Переглянути файл
@@ -39,12 +39,16 @@ function inside(project: ProjectInfo, path: string): boolean {
async function read(path: string): Promise<string> {
return editorsFor(path)[0]?.view.state.doc.toString() ?? (await call(commands.fsReadText(path)));
}
function invalidate() {
/** Forgets resolved targets and service names; the disk route index stays. */
function refresh() {
epoch++;
serviceNames.clear();
clearRouteIndex();
invalidateNavigationProviders();
}
function invalidate() {
refresh();
clearRouteIndex();
}
function named(module: string): Promise<string | null> {
let pending = serviceNames.get(module);
@@ -155,9 +159,13 @@ export function registerFeignNavigation(): () => void {
(!isRouteSource(event.path) && !isServiceConfiguration(event.path))
)
return;
if (event.type === "docChanged" && isRouteSource(event.path)) {
if (changedSources.size < 256) changedSources.add(event.path);
} else if (event.type === "docClosed" || event.type === "docSaved") changedSources.delete(event.path);
if (event.type === "docChanged") {
if (isRouteSource(event.path) && changedSources.size < 256) changedSources.add(event.path);
// Unsaved text is overlaid on the disk index: typing must not rescan the project.
refresh();
return;
}
changedSources.delete(event.path);
invalidate();
});
const projects = useProject.subscribe((state, previous) => {
+12 -4
Переглянути файл
@@ -21,7 +21,7 @@
height: 100%;
display: flex;
align-items: center;
gap: 5px;
gap: var(--space-1);
border-radius: var(--radius-row);
}
@@ -41,9 +41,16 @@
overflow: hidden;
text-overflow: ellipsis;
}
.rootName {
.labelGroup {
display: flex;
align-items: center;
gap: var(--space-1);
min-width: 0;
overflow: hidden;
}
.labelGroup .label {
flex: none;
max-width: 60%;
max-inline-size: 100%;
}
.rootLabel {
color: var(--fg-strong);
@@ -60,6 +67,7 @@
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);
@@ -88,7 +96,7 @@
}
.detail {
min-width: 0;
margin-left: 4px;
margin-inline-start: var(--space-1);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
+30 -21
Переглянути файл
@@ -338,26 +338,29 @@ const Row = memo(function Row({
/>
) : (
<>
<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 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>
)}
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>}
</span>
{deco.badge && <span className={styles.badge}>{deco.badge}</span>}
</>
)}
@@ -421,8 +424,14 @@ const MemberRow = memo(function MemberRow({
onPointerDown={(e) => onPointerDown(node, e)}
>
<SymbolBadge kind={badgeKind(item.kind)} className={styles.icon} />
<HighlightedText className={styles.label} text={item.name} indices={matches} tone="accent" />
{item.detail && <span className={styles.detail}>{item.detail}</span>}
<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>
</span>
);
});
+29 -1
Переглянути файл
@@ -51,6 +51,10 @@
min-width: 0;
}
.topToolbarSession {
flex-direction: column;
}
.toolbar {
flex: none;
width: 32px;
@@ -69,12 +73,36 @@
.toolbar::-webkit-scrollbar {
display: none;
}
.toolbarSep {
.toolbarGroup {
display: flex;
flex: none;
flex-direction: inherit;
align-items: center;
gap: var(--space-0-5);
max-width: 100%;
}
.toolbarGroup + .toolbarGroup::before {
content: "";
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;
+38 -30
Переглянути файл
@@ -1,4 +1,5 @@
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";
@@ -181,10 +182,15 @@ export function SessionPanel({
);
return (
<div className={styles.session}>
<div className={styles.toolbar} role="toolbar" aria-orientation="vertical" aria-label={tx("Run actions")}>
<div className={clsx(styles.session, showLifecycle && styles.topToolbarSession)}>
<div
className={styles.toolbar}
role="toolbar"
aria-orientation={showLifecycle ? "horizontal" : "vertical"}
aria-label={tx("Run actions")}
>
{showLifecycle && (
<>
<div className={styles.toolbarGroup}>
<IconButton
icon="rerun"
title="Rerun"
@@ -242,34 +248,36 @@ export function SessionPanel({
/>
</>
)}
<div className={styles.toolbarSep} />
</>
</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 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>
</div>
<div className={styles.sessionBody}>
{rt.tests ? (
+2
Переглянути файл
@@ -71,6 +71,7 @@ import { hotReload, hotReloadSession, hotRestart } from "./flutterHotReload";
import { npmGutter } from "./npmGutter";
import { launchSettingsGutter } from "./launchSettingsGutter";
import { runGutter } from "./runGutter";
import { markdownCommandGutter } from "./markdownCommands";
import { gradleDelegation } from "./gradleRun";
import { activateStackTrace, useStackTraces } from "./stackTrace";
import { clearRuntimeCache } from "./runtimes";
@@ -485,6 +486,7 @@ export function activate(): () => void {
}),
registerEditorContribution({ id: "run.targets", order: 55, extensions: runGutter }),
registerEditorContribution({ id: "run.npmScripts", order: 58, extensions: npmGutter }),
registerEditorContribution({ id: "run.markdownCommands", order: 58, extensions: markdownCommandGutter }),
registerEditorContribution({ id: "run.launchSettings", order: 58, extensions: launchSettingsGutter }),
registerMenuGroup({
id: "run.context",
+70
Переглянути файл
@@ -0,0 +1,70 @@
import { afterEach, describe, expect, it } from "vitest";
import { useProject } from "@/platform/project";
import { commandMenuItems, markdownCommands, trimPrompt, type CommandEntry } from "./markdownCommands";
const accepts = (line: string) => /^(mvn|\.\/gradlew) /.test(line);
describe("Markdown commands", () => {
it("runs shell blocks from their fence and recognized command lines from any block", () => {
const text = [
"## Setup",
"```shell",
"$ mise install # tools",
"",
"mvn test",
"```",
"```java",
"mvn not a command here? still a recognized line",
"```",
"~~~text",
"./gradlew build",
"~~~",
].join("\n");
expect(markdownCommands(text, accepts).map((e) => [e.kind, e.line, e.lines])).toEqual([
["block", 1, ["mise install", "mvn test"]],
["line", 4, ["mvn test"]],
["line", 7, ["mvn not a command here? still a recognized line"]],
["line", 10, ["./gradlew build"]],
]);
});
it("ignores blocks without commands, other languages and unclosed fences' closing rules", () => {
expect(markdownCommands("```bash\n# only a comment\n```", accepts)).toEqual([]);
expect(markdownCommands("```python\nprint(1)\n```", accepts)).toEqual([]);
// A shorter closing fence doesn't close a longer one.
expect(markdownCommands("````sh\nls\n```\npwd\n````", accepts)[0]?.lines).toEqual(["ls", "```", "pwd"]);
});
it("keeps quoted # and PowerShell lines as written", () => {
expect(trimPrompt(['echo "a # b" # note', "$ git log #x", "#!/bin/sh"])).toEqual(['echo "a # b"', "git log"]);
expect(markdownCommands("```powershell\n$env:X = 1 # keep\n```", accepts)[0]?.lines).toEqual(["$env:X = 1 # keep"]);
});
});
describe("Markdown command menu", () => {
const block: CommandEntry = { kind: "block", name: "block:1", line: 1, lines: ["make build"] };
afterEach(() => useProject.setState({ project: null, settings: null }));
const open = (commandDirectory?: string) =>
useProject.setState({
project: { root: "/p", name: "p", settings: {}, trusted: true, isGit: false },
settings: { languages: { markdown: { commandDirectory } } } as never,
});
it("asks for the folder when the project and the file's folder differ", async () => {
open();
expect((await commandMenuItems(block, "/p/docs/README.md")).map((i) => "label" in i && i.label)).toEqual([
"Run from Project Root Directory",
"Run from Parent Directory of Current File (docs)",
]);
expect((await commandMenuItems(block, "/p/README.md")).map((i) => "label" in i && i.label)).toEqual([
"Run in Terminal",
]);
});
it("uses the configured folder", async () => {
open("file");
expect((await commandMenuItems(block, "/p/docs/README.md")).map((i) => "label" in i && i.label)).toEqual([
"Run in Terminal",
]);
});
});
+135
Переглянути файл
@@ -0,0 +1,135 @@
/**
* Run icons in Markdown files, like IDEA's Markdown command runner: ▶ on a shell
* code block's opening fence runs the block in a new terminal tab, and ▶ on a
* line of any code block runs it when a Run Anything provider recognizes the
* command (`mvn test`, `./gradlew build`, a run configuration's name).
*/
import type { Extension } from "@codemirror/state";
import type { EditorDocContext } from "@/editor/api";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { markdownCommandSettings } from "@/platform/languageSettings";
import { useProject } from "@/platform/project";
import type { MenuItem } from "@/ui";
import { runAnythingProviderList } from "@/workbench/contributions";
import { entryGutter, type ScriptEntry } from "./npmGutter";
const SHELL = new Set(["sh", "bash", "zsh", "shell", "shellscript", "shell-script", "console"]);
const POWERSHELL = new Set(["powershell", "pwsh", "ps1"]);
const FENCE = /^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)/;
export interface CommandEntry extends ScriptEntry {
kind: "block" | "line";
/** What runs: the block's commands, or the line's. */
lines: string[];
}
/** `line` without a trailing `# comment` outside quotes. */
function stripComment(line: string): string {
let single = false;
let double = false;
for (let i = 0; i < line.length; i++) {
const c = line[i];
if (c === "'" && !double) single = !single;
else if (c === '"' && !single) double = !double;
else if (c === "#" && !single && !double && (i === 0 || /\s/.test(line[i - 1]!))) return line.slice(0, i).trimEnd();
}
return line;
}
/** Shell lines without a leading `$` prompt or trailing comments; empty lines dropped. */
export function trimPrompt(lines: readonly string[]): string[] {
return lines.map((line) => stripComment(line.startsWith("$") ? line.slice(1) : line).trim()).filter(Boolean);
}
/**
* The runnable places of Markdown `text`: shell code blocks (on their opening fence)
* and code block lines `accepts` recognizes as commands.
*/
export function markdownCommands(text: string, accepts: (line: string) => boolean): CommandEntry[] {
const lines = text.split("\n");
const out: CommandEntry[] = [];
for (let i = 0; i < lines.length; i++) {
const open = FENCE.exec(lines[i]!);
if (!open) continue;
const marker = open[1]!;
const language = open[2]!.toLowerCase();
const close = new RegExp(`^ {0,3}${marker[0] === "`" ? "`" : "~"}{${marker.length},}\\s*$`);
let end = i + 1;
while (end < lines.length && !close.test(lines[end]!)) end++;
const body = lines.slice(i + 1, end).map((l) => l.replace(/\r$/, ""));
if (SHELL.has(language) || POWERSHELL.has(language)) {
const commands = POWERSHELL.has(language) ? body.filter((l) => l.trim()) : trimPrompt(body);
if (commands.length) out.push({ kind: "block", name: `block:${i}`, line: i, lines: commands });
}
body.forEach((raw, k) => {
const [command] = trimPrompt([raw]);
if (command && accepts(command))
out.push({ kind: "line", name: `line:${command}`, line: i + 1 + k, lines: [command] });
});
i = end;
}
return out;
}
/** Whether a Run Anything provider runs `line` as a command it recognizes. */
function accepted(line: string): boolean {
return runAnythingProviderList().some((p) => !!p.accepts?.(line));
}
async function runLine(line: string) {
for (const p of runAnythingProviderList()) if (p.accepts?.(line) && p.execute && (await p.execute(line))) return;
}
const parentDir = (path: string) => path.slice(0, Math.max(path.lastIndexOf("/"), 0)) || "/";
/** The folders a block may run in: the setting's, or both when it asks and they differ. */
function directories(path: string): { project: string; file: string } | string | null {
const { project, settings } = useProject.getState();
if (!project?.root) return null;
const file = parentDir(path);
const choice = markdownCommandSettings(settings).commandDirectory;
if (choice === "file") return file;
if (choice === "project" || file === project.root) return project.root;
return { project: project.root, file };
}
function runBlock(lines: string[], cwd: string) {
void executeAction("terminal.runLines", { lines, cwd });
}
export async function commandMenuItems(entry: ScriptEntry, path: string): Promise<MenuItem[]> {
const command = entry as CommandEntry;
if (command.kind === "line") {
const line = command.lines[0]!;
return [{ label: tx`Run '${line}'`, icon: "run", run: () => void runLine(line) }];
}
const dirs = directories(path);
if (!dirs) return [];
const shown = typeof dirs === "string" ? "" : dirs.file.slice(dirs.project.length + 1) || dirs.file;
if (typeof dirs === "string")
return [{ label: tx`Run in Terminal`, icon: "terminal", run: () => runBlock(command.lines, dirs) }];
return [
{ label: tx`Run from Project Root Directory`, icon: "terminal", run: () => runBlock(command.lines, dirs.project) },
{
label: tx`Run from Parent Directory of Current File (${shown})`,
icon: "terminal",
run: () => runBlock(command.lines, dirs.file),
},
];
}
export function markdownCommandGutter(ctx: EditorDocContext): Extension {
const { project, settings } = useProject.getState();
if (!project?.trusted || !markdownCommandSettings(settings).runCommands) return [];
return entryGutter(
ctx,
/\.(md|markdown)$/i,
(text) => markdownCommands(text, accepted),
commandMenuItems,
(entry) => {
const command = entry as CommandEntry;
return command.kind === "block" ? tx`Run in Terminal` : tx`Run '${command.lines[0]!}'`;
},
);
}
+4 -2
Переглянути файл
@@ -312,6 +312,7 @@ class ScriptMarker extends GutterMarker {
readonly entry: ScriptEntry,
readonly path: string,
readonly menu: EntryMenu,
readonly title: (entry: ScriptEntry) => string,
) {
super();
}
@@ -322,7 +323,7 @@ class ScriptMarker extends GutterMarker {
const el = document.createElement("button");
el.type = "button";
el.className = styles.runMarker ?? "";
el.title = tx`Run '${this.entry.name}'`;
el.title = this.title(this.entry);
el.setAttribute("aria-label", el.title);
el.innerHTML = gutterIconMarkup("gutter-run") ?? "";
el.addEventListener("click", () => {
@@ -350,6 +351,7 @@ export function entryGutter(
file: RegExp,
entries: (text: string) => ScriptEntry[],
menu: EntryMenu,
title: (entry: ScriptEntry) => string = (entry) => tx`Run '${entry.name}'`,
): Extension {
const path = ctx.path;
if (ctx.virtual || !file.test(path) || !useProject.getState().project?.root) return [];
@@ -394,7 +396,7 @@ export function entryGutter(
markers: (view) =>
runIconsShown()
? RangeSet.of(
view.state.field(entriesField).map((e) => new ScriptMarker(e, path, menu).range(e.pos)),
view.state.field(entriesField).map((e) => new ScriptMarker(e, path, menu, title).range(e.pos)),
true,
)
: RangeSet.empty,
+1
Переглянути файл
@@ -30,6 +30,7 @@ export const runConfigsRunAnything: RunAnythingProvider = {
group: "Run Configurations",
order: 10,
items: (query) => matchingConfigs(useRun.getState().configs, query).map(item),
accepts: (line) => useRun.getState().configs.some((c) => c.name === line.trim()),
execute(line) {
const config = useRun.getState().configs.find((c) => c.name === line.trim());
if (!config) return false;
+6 -2
Переглянути файл
@@ -106,18 +106,22 @@
--border-tab-selected: transparent;
flex: none;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-3);
gap: var(--space-1) var(--space-3);
padding: 8px 14px 4px 20px;
}
.scopeDetail {
flex: 1;
flex: 1 1 200px;
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;
+3 -9
Переглянути файл
@@ -67,6 +67,7 @@ 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,
@@ -82,9 +83,7 @@ import {
resolveFindScope,
setFindPopupCommandHandler,
loadFindPopupSize,
loadFindPopupSplit,
saveFindPopupSize,
saveFindPopupSplit,
setFindPopupNewTab,
setFindPopupPinned,
useFindPopup,
@@ -165,11 +164,6 @@ 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);
@@ -869,8 +863,8 @@ function FindInFilesDialog() {
</div>
<div className={styles.split}>
{rows.length ? (
<SplitGroup orientation="vertical" id="find-popup-split" defaultLayout={split} onLayoutChanged={keepSplit}>
<SplitPanel id="results" minSize={ROW * 3} defaultSize="48%">
<SplitGroup orientation="vertical" id="find-popup-split" storageKey={FIND_POPUP_SPLIT_KEY}>
<SplitPanel id="results" minSize={ROW * 3} defaultSize="33%">
{resultsBox}
</SplitPanel>
<SplitHandle hairline={false} />
+1 -13
Переглянути файл
@@ -98,9 +98,8 @@ export function setFindPopupNewTab(newTab: boolean) {
}
const SIZE_KEY = "openidea.search.findPopupSize.v1";
const SPLIT_KEY = "openidea.search.findPopupSplit.v1";
export const FIND_POPUP_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;
@@ -110,17 +109,6 @@ 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
+7 -7
Переглянути файл
@@ -101,14 +101,12 @@
border: 0;
outline: none;
color: var(--fg-strong);
font-family: var(--font-mono);
font-size: var(--fs-code);
font-family: var(--font-ui);
font-size: var(--fs-ui);
caret-color: var(--accent);
}
.filter::placeholder {
color: var(--fg-faint);
font-family: var(--font-ui);
font-size: var(--fs-ui);
}
.filterStatus {
color: var(--fg-muted);
@@ -125,10 +123,12 @@
}
.popupOptions {
display: flex;
flex-wrap: wrap;
align-content: center;
align-items: center;
gap: var(--space-3);
height: 26px;
padding: 0 12px;
gap: var(--space-1) var(--space-3);
min-height: 32px;
padding: var(--space-1) var(--space-3);
border-bottom: 1px solid var(--border-popup);
font-size: var(--fs-small);
}
+1 -1
Переглянути файл
@@ -471,7 +471,7 @@ function FileStructureDialog() {
<Dialog
open
onClose={close}
width={460}
width={540}
position="top"
transparentBackdrop
aria-label="File Structure"
+13 -3
Переглянути файл
@@ -23,6 +23,7 @@ import {
type TreeReorder,
} from "@/ui";
import {
SERVICES_WINDOW,
useServiceProviders,
useToolWindowShown,
serviceProviders,
@@ -30,6 +31,7 @@ import {
type ServiceTreeItem,
type ServiceItemAction,
} from "@/workbench/contributions";
import { useToolWindowLayout } from "@/workbench/toolwindows/store";
import {
addServiceMenu,
clearProviderRoots,
@@ -88,6 +90,9 @@ export function ServicesTreeView() {
const selectedKey = useServicesTree((s) => s.selectedKey);
const selectedKeys = useServicesTree((s) => s.selectedKeys);
const expanded = useServicesTree((s) => s.expanded);
const anchor = useToolWindowLayout((s) => s.placements[SERVICES_WINDOW]?.anchor ?? "bottom");
const sideDocked = anchor !== "bottom";
const orientation = sideDocked ? "vertical" : "horizontal";
const addRef = useRef<HTMLButtonElement>(null);
const filterRef = useRef<HTMLButtonElement>(null);
@@ -219,8 +224,13 @@ export function ServicesTreeView() {
</button>
</div>
) : (
<SplitGroup orientation="horizontal" className={styles.split} storageKey="openidea.services.detailSplit">
<SplitPanel id="services-items" defaultSize="40%" minSize="160px">
<SplitGroup
key={orientation}
orientation={orientation}
className={styles.split}
storageKey={sideDocked ? "openidea.services.detailSplit.vertical" : "openidea.services.detailSplit"}
>
<SplitPanel id="services-items" defaultSize="30%" minSize={sideDocked ? "80px" : "160px"}>
<div className={styles.tree}>
<Tree<ServiceTreeItem>
key={location}
@@ -274,7 +284,7 @@ export function ServicesTreeView() {
<SplitHandle />
<SplitPanel
id="services-detail"
minSize="200px"
minSize={sideDocked ? "120px" : "200px"}
// The panel library puts `overflow: auto` inline; the detail content
// (a console, a log) owns its scrolling, so the pane must not add a second
// bar. A column flex box lets that content fill the pane.
+12 -3
Переглянути файл
@@ -212,9 +212,18 @@ describe("languages settings", () => {
});
it("leaves the Markdown preview font size unset (editor font) and keeps a set one in 8..72", () => {
expect(validateLanguages({}).markdown).toEqual({ previewFontSize: null });
expect(validateLanguages({ markdown: { previewFontSize: 90 } }).markdown).toEqual({ previewFontSize: 72 });
expect(validateLanguages({ markdown: { previewFontSize: "x" } }).markdown).toEqual({ previewFontSize: null });
expect(validateLanguages({}).markdown.previewFontSize).toBeNull();
expect(validateLanguages({ markdown: { previewFontSize: 90 } }).markdown.previewFontSize).toBe(72);
expect(validateLanguages({ markdown: { previewFontSize: "x" } }).markdown.previewFontSize).toBeNull();
});
it("detects Markdown commands by default and asks for their folder until one is chosen", () => {
expect(validateLanguages({}).markdown).toMatchObject({ runCommands: true, commandDirectory: null });
expect(validateLanguages({ markdown: { runCommands: false, commandDirectory: "file" } }).markdown).toMatchObject({
runCommands: false,
commandDirectory: "file",
});
expect(validateLanguages({ markdown: { commandDirectory: "elsewhere" } }).markdown.commandDirectory).toBeNull();
});
it("keeps the Markdown page global, like IDEA's application-level setting", () => {
+1 -1
Переглянути файл
@@ -321,7 +321,7 @@ export function SettingsLayout() {
return (
<SplitGroup id="settings" orientation="horizontal" storageKey="openidea.settings.layout" className={styles.layout}>
<SplitPanel id="navigation" defaultSize="240px" minSize="160px" maxSize="40%" className={styles.sidebar}>
<SplitPanel id="navigation" defaultSize="22.5%" minSize="160px" maxSize="40%" className={styles.sidebar}>
<SearchField
data-autofocus
className={styles.search}
+42 -18
Переглянути файл
@@ -1,5 +1,5 @@
import { useId } from "react";
import { NumberInput, Row, Section } from "../components/Form";
import { NumberInput, Row, Section, Select, SettingToggle } from "../components/Form";
import { useSetting } from "../components/context";
/** Languages & Frameworks › Markdown, after IDEA's: application-level, preview font size follows the editor font until set. */
@@ -7,24 +7,48 @@ export function MarkdownPage() {
const id = useId();
const [size, setSize] = useSetting<number | null>("languages.markdown.previewFontSize");
const [editorSize] = useSetting<number>("editor.fontSize");
const [runCommands] = useSetting<boolean>("languages.markdown.runCommands");
const [directory, setDirectory] = useSetting<"project" | "file" | null>("languages.markdown.commandDirectory");
return (
<Section title="Preview">
<Row
label="Preview font size"
htmlFor={id}
hint="Also used by Markdown cells in Jupyter notebooks. Defaults to the editor font size, independent of the UI font size."
>
<NumberInput
id={id}
value={size ?? editorSize}
onChange={setSize}
min={8}
max={72}
integer
unit="px"
aria-label="Preview font size"
<>
<Section title="Preview">
<Row
label="Preview font size"
htmlFor={id}
hint="Also used by Markdown cells in Jupyter notebooks. Defaults to the editor font size, independent of the UI font size."
>
<NumberInput
id={id}
value={size ?? editorSize}
onChange={setSize}
min={8}
max={72}
integer
unit="px"
aria-label="Preview font size"
/>
</Row>
</Section>
<Section title="Commands">
<SettingToggle
k="languages.markdown.runCommands"
label="Detect commands that can be run right from Markdown files"
/>
</Row>
</Section>
<Row label="Run commands from" disabled={!runCommands}>
<Select<"project" | "file">
value={directory ?? ("" as "project")}
options={DIRECTORY_OPTIONS}
onChange={setDirectory}
disabled={!runCommands}
aria-label="Run commands from"
/>
</Row>
</Section>
</>
);
}
const DIRECTORY_OPTIONS = [
{ value: "project", label: "Project directory" },
{ value: "file", label: "Markdown file parent directory" },
] as const;
+1 -1
Переглянути файл
@@ -169,7 +169,7 @@ export const LANGUAGE_PAGES: PageSpec[] = [
title: "Markdown",
group: LANGUAGES_GROUP,
order: 400,
keywords: ["markdown", "preview", "font size", "jupyter", "notebook"],
keywords: ["markdown", "preview", "font size", "jupyter", "notebook", "run commands", "code block"],
component: MarkdownPage,
},
{
+19
Переглянути файл
@@ -199,6 +199,25 @@ export function activate(): () => void {
focusActiveSoon();
},
},
{
id: "terminal.runLines",
title: "Run Lines in Terminal",
description: "Opens a shell tab and types `{ lines, name?, cwd? }` into it.",
category: "Terminal",
icon: "terminal",
when: "projectOpen",
hidden: true,
run: async ({ arg }) => {
const a = arg as { lines?: unknown; name?: unknown; cwd?: unknown } | undefined;
const lines = Array.isArray(a?.lines) ? a.lines.filter((x): x is string => typeof x === "string") : [];
const cwd = (typeof a?.cwd === "string" && a.cwd) || projectRoot();
if (!lines.length || !cwd) return;
const rt = await loadTerminalRuntime();
rt.newTabRunning(cwd, typeof a?.name === "string" && a.name ? a.name : undefined, lines);
toolWindowService().show(WINDOW, true);
focusActiveSoon();
},
},
{
id: "terminal.runCommand",
title: "Run Command in Terminal",
+1
Переглянути файл
@@ -6,6 +6,7 @@ export {
closeAll,
detachTab,
newTab,
newTabRunning,
pluginSession,
syncTerminalProject,
tabTitle,
+8
Переглянути файл
@@ -247,6 +247,14 @@ export function newTab(cwd: string, name?: string, command?: SessionOptions["com
return tab;
}
/** Opens a shell tab at `cwd` and types `lines` into it, each followed by Return. */
export function newTabRunning(cwd: string, name: string | undefined, lines: readonly string[]): TerminalTab {
const tab = newTab(cwd, name);
// Sent once the shell's PTY exists (the session buffers input until then).
getSession(tab.session)?.input(lines.map((line) => `${line}\r`).join(""));
return tab;
}
export function newTabAt(dir: string): TerminalTab {
return newTab(dir, basename(dir) || "Local");
}
+35 -14
Переглянути файл
@@ -1,16 +1,25 @@
.view {
height: 100%;
display: flex;
flex-direction: column;
min-height: 0;
}
.body {
.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 > * {
.body {
flex: 1;
min-height: 0;
}
@@ -37,13 +46,12 @@
display: flex;
align-items: center;
gap: var(--space-1-5);
height: 32px;
padding: 0 8px;
padding: var(--space-1) var(--space-2);
border-bottom: 1px solid var(--border);
}
.scopeSelect {
min-width: 200px;
max-width: 360px;
flex: 0 1 224px;
min-width: 0;
}
.row {
display: flex;
@@ -57,7 +65,17 @@
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 {
@@ -66,28 +84,31 @@
.muted {
flex: none;
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.directory {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-subtle);
}
.count {
flex: none;
color: var(--fg-subtle);
font-size: var(--fs-small);
margin-left: 4px;
}
.position {
flex: none;
font-family: var(--font-mono);
font-size: var(--fs-small);
min-inline-size: 3ch;
text-align: end;
font-variant-numeric: tabular-nums;
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
Переглянути файл
@@ -29,7 +29,7 @@ describe("TodoView", () => {
render(<TodoView />);
expect(screen.getByText("a.ts")).toBeInTheDocument();
expect(screen.getByText("2 items")).toBeInTheDocument();
expect(screen.getByText("(5, 4)")).toBeInTheDocument();
expect(screen.getByText("5")).toHaveAttribute("title", "(5, 4)");
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, 4)");
await screen.findByText("5");
// 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
+32 -18
Переглянути файл
@@ -19,6 +19,7 @@ import {
SplitPanel,
Spinner,
Tabs,
Toolbar,
Tree,
fileIconName,
type MenuItem,
@@ -291,14 +292,16 @@ function ItemText({ item }: { item: TodoItem }) {
const kwLen = item.keyword.length;
const color = colorFor(item.keyword);
return (
<span className={styles.text} style={{ color }}>
<strong className={styles.keyword}>{item.text.slice(0, kwLen)}</strong>
<span className={styles.text}>
<strong className={styles.keyword} style={{ color }}>
{item.text.slice(0, kwLen)}
</strong>
{item.text.slice(kwLen)}
</span>
);
}
export function TodoHeaderActions() {
function TodoToolbar() {
const settings = useTodoSettings();
const hidden = useTodoView((s) => s.hidden);
const toggleKeyword = useTodoView((s) => s.toggleKeyword);
@@ -316,7 +319,7 @@ export function TodoHeaderActions() {
})),
];
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
@@ -335,7 +338,7 @@ export function TodoHeaderActions() {
onClick={() => updateTodoSettings({ caseSensitive: !settings.caseSensitive })}
/>
<IconButton icon="refresh" size="small" title="Refresh" disabled={scanning} onClick={() => void scanProject()} />
</>
</Toolbar>
);
}
@@ -421,11 +424,20 @@ 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={clsx(styles.fileName, state.selected && styles.selectedText)}>{name}</span>
<span className={styles.muted}>{relativeDir(root, n.group.path)}</span>
<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={styles.count}>
{n.group.items.length === 1 ? tx`${n.group.items.length} item` : tx`${n.group.items.length} items`}
</span>
@@ -434,8 +446,8 @@ export function TodoView() {
}
return (
<span className={styles.row} title={n.item.text}>
<span className={styles.position}>
({n.item.line + 1}, {n.item.col + 1})
<span className={styles.position} title={`(${n.item.line + 1}, ${n.item.col + 1})`}>
{n.item.line + 1}
</span>
<ItemText item={n.item} />
</span>
@@ -469,18 +481,20 @@ export function TodoView() {
return (
<div className={styles.view}>
{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}>
<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 />}
<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>
@@ -519,7 +533,7 @@ export function TodoView() {
{showPreview && (
<>
<SplitHandle />
<SplitPanel id="preview" minSize={160} defaultSize="45%" className={styles.panel}>
<SplitPanel id="preview" minSize={160} defaultSize="50%" className={styles.panel}>
<TodoPreview node={lead} />
</SplitPanel>
</>
+1 -2
Переглянути файл
@@ -4,7 +4,7 @@ import { registerEditorContribution } from "@/editor/api";
import { registerToolWindow, toolWindowService } from "@/workbench/contributions";
import { hasIcon } from "@/ui";
import { activateSettingsPages } from "./settingsPages";
import { TodoHeaderActions, TodoTabs, TodoView, useTodoBadge, useTodoHeaderMenu, useTodoView } from "./TodoView";
import { TodoTabs, TodoView, useTodoBadge, useTodoHeaderMenu, useTodoView } from "./TodoView";
import { todoEditorExtension } from "./highlight";
import { installTodoIndex, scanProject, syncTodoSettingsFromStorage } from "./store";
@@ -21,7 +21,6 @@ export function activate(): () => void {
order: 40,
component: TodoView,
headerContent: TodoTabs,
headerActions: TodoHeaderActions,
headerMenu: useTodoHeaderMenu,
useBadge: useTodoBadge,
}),
+22 -5
Переглянути файл
@@ -25,7 +25,7 @@ import {
T,
} from "@/ui";
import type { PopupAnchor } from "@/ui/Popup";
import { buildBranchRows, withExpanded, type BranchRow, type PopupAction } from "./branches";
import { buildBranchRows, preferredBranchRow, withExpanded, type BranchRow, type PopupAction } from "./branches";
import { branchPresentation, extensionPopupActions, useBranchWidgetExtensions } from "./branchWidgetExtensions";
import { branchMenu, commonBranchMenu, inRepo, tagMenu } from "./branchMenu";
import { loadFavoriteBranches, recentBranches, toggleFavoriteBranch, useFavoriteBranches } from "./branchOps";
@@ -33,6 +33,7 @@ import { inProgress, operationTitle, type InProgress } from "./operations";
import {
buildMultiRepoRows,
currentRepoFor,
preferredRepoRow,
repoHeadLabel,
widgetShowsRepo,
type RepoEntry,
@@ -45,6 +46,22 @@ import type { SyncDirection } from "./syncCommits";
import styles from "./BranchWidget.module.css";
import { tx } from "@/platform/i18n";
/** `active` until the user moves: a new filter selects the row IDEA prefers for it. */
const PREFERRED = -1;
function pickActive<R>(
rows: readonly R[],
active: number,
isSection: (r: R) => boolean,
preferred: () => number,
): number {
if (active === PREFERRED) {
const i = preferred();
if (i >= 0) return i;
} else if (rows[active] && !isSection(rows[active]!)) return active;
return firstSelectable(rows, isSection);
}
export const useBranchesPopup = create<{ open: boolean }>(() => ({ open: false }));
export const showBranchesPopup = () => useBranchesPopup.setState({ open: true });
@@ -446,7 +463,7 @@ function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack }
[branches, recent, query, actions, favorites, tags, options, expanded],
);
const isSection = (r: BranchRow) => r.type === "section";
const activeIndex = rows[active] && !isSection(rows[active]!) ? active : firstSelectable(rows, isSection);
const activeIndex = pickActive(rows, active, isSection, () => preferredBranchRow(rows, query));
const scoped = (items: MenuItem[]) => (root ? inRepo(root, items) : items);
const closeAll = () => {
@@ -528,7 +545,7 @@ function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack }
value={query}
onChange={(v) => {
setQuery(v);
setActive(0);
setActive(PREFERRED);
}}
placeholder={label}
aria-label={label}
@@ -683,7 +700,7 @@ function MultiRepoPanel({ onClose, actions: popupActions }: { onClose: () => voi
[repos, all, query, actions, expanded, favorites, current, recent, tags, options],
);
const isSection = (r: RepoRow) => r.type === "section";
const activeIndex = rows[active] && !isSection(rows[active]!) ? active : firstSelectable(rows, isSection);
const activeIndex = pickActive(rows, active, isSection, () => preferredRepoRow(rows, query));
const closeAll = () => {
setMenuFor(null);
@@ -778,7 +795,7 @@ function MultiRepoPanel({ onClose, actions: popupActions }: { onClose: () => voi
value={query}
onChange={(v) => {
setQuery(v);
setActive(0);
setActive(PREFERRED);
}}
placeholder="Search for branches, actions, repositories"
aria-label="Search for branches, actions, repositories"
+25 -10
Переглянути файл
@@ -26,6 +26,20 @@
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;
@@ -106,13 +120,12 @@
}
.commitBar {
flex: none;
height: 32px;
min-height: 32px;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1);
padding: 0 6px 0 12px;
white-space: nowrap;
overflow: hidden;
gap: var(--space-0-5) var(--space-1);
padding: var(--space-0-5) 6px var(--space-0-5) 12px;
}
.grow {
flex: 1;
@@ -121,6 +134,7 @@
color: var(--fg-faint);
font-family: var(--font-mono);
font-size: var(--fs-tiny);
white-space: nowrap;
}
.lineLenWarn {
color: var(--warning);
@@ -136,8 +150,6 @@
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;
@@ -164,7 +176,6 @@
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;
@@ -175,10 +186,14 @@
.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 {
overflow: hidden;
text-overflow: ellipsis;
white-space: normal;
overflow-wrap: anywhere;
}
.stashList {
flex: 1;
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff. Show more