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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 2234ac7941 Merge remote-tracking branch 'origin/main' into fix/debugger-breakpoints-dialog-layout 2026-11-20 06:05:33 +08:00
l0ng-ai 60d335eec0 fix(refactor): keep the Change Signature parameter table readable (#4602)
The Change Signature dialog's parameter table had fixed column widths and a one-line preview, so in narrow windows types and names were clipped and long signatures ran off the preview. The table columns now share the width with truncation, the preview puts each parameter on its own line as IDEA's does, and the dialog's sections keep their controls visible.
2026-11-20 06:05:24 +08:00
Hafiz Faizan ul hassanтаfaizanalhassan a679e8086f feat(database): pick data source, then database and schema in the query console (#4614)
The query console's Data source dropdown mixed databases into the source list, and SQL Server's second dropdown listed databases. As in DataGrip, the dropdown now lists data sources only, and a database.schema switcher next to it opens a searchable database -> schema tree that loads a database's schemas on expand and moves the console to the picked database; one-level drivers keep a flat schema list and SQLite has none. SQL Server's console schema is now a real schema (SCHEMA_NAME()) that scopes resolution and completion, since a session's default schema can't be changed, while the pooled connection still returns to its database. Tree speed search also opens with Cmd/Ctrl+F, as in IDEA.

Closes #4577

Co-authored-by: faizanalhassan <[email protected]>
2026-11-20 06:04:34 +08:00
Mr0Bread 4c20aa5c8d test(editor): cover missing-file and malformed session restore (#4615)
Adds regression tests for editor session recovery: a deleted selected file is dropped quietly and the remaining tab restores with its caret, a permission-denied tab stays open with its error inline, and truncated session JSON loads as null without writing storage until a valid session replaces it. No production changes.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 06:00:56 +08:00
l0ng-ai d19d74120b fix(debugger): keep values visible in narrow variables panes (#4600)
In narrow Variables panes the name and type kept their full width, so values were cut to nothing and the Show button could be pushed out. Names and types now truncate within caps, the value and its Show button share a group that keeps a minimum width, overflow is measured against that group, and full names and types are in tooltips.
2026-11-20 06:00:12 +08:00
Mr0Bread 4e1cec5233 refactor(ipc): enforce typed error-kind comparisons (#4612)
IPC error kinds were compared as untyped strings (`(e as { kind?: string }).kind === "notFound"`), so a misspelt kind compiled and silently never matched. A typed `isErrorKind(error, kind)` helper, taking a kind from the generated `IdeError["kind"]`, now handles wrapped and raw IPC errors in document sync, editor session restore, Spring service identity, plugin commands and recent projects.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 05:41:29 +08:00
l0ng-ai 150eacc3de fix(editor): keep parameter info readable in narrow panes (#4599)
Parameter Info had a fixed 640px cap and a 12-signature window, so in narrow panes it overflowed the editor and long signatures were clipped. The popup now fits the editor's tooltip bounds and height, uses the editor's current font size, wraps long signatures with a hanging indent, scrolls when needed and keeps the current parameter in view.
2026-11-20 05:40:20 +08:00
l0ng-ai d1cc3cf68a fix(vcs): make merge panes resizable and keep actions visible (#4597)
The merge editor's three panes had fixed widths with decorative dividers, so in narrow windows they could not be resized and the toolbar actions overflowed. The panes are now a SplitGroup whose two handles carry the connector bands, each pane has its own title (branch and side), and the toolbar status is announced.
2026-11-20 05:25:12 +08:00
Mr0Bread 7c00ce4fa1 test(e2e): enforce TypeScript contract checking (#4610)
The e2e TypeScript project was never type checked: its tsconfig didn't inherit the app's settings, so @/ imports didn't resolve and hundreds of diagnostics went unnoticed. e2e/tsconfig.json now extends the root config (plus Node/Vite types and ES2024), pnpm typecheck runs tsrs -p e2e, and the remaining real type errors in the specs and fixtures are fixed; the code-style docs list the new project.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 05:19:07 +08:00
l0ng-ai 6539a95cb8 fix(vcs): keep push review readable in narrow windows (#4594)
The Push dialog's commits, changed files and diff panes had pixel minimums and fixed options rows, so narrow or short windows clipped the review and the target controls. The commits and changes now stack vertically below 640px with their own remembered split, the changed files come before the commit details, panes use relative minimums, and the target bar, options and tag options wrap.
2026-11-20 05:07:24 +08:00
l0ng-ai 08613ca800 fix(debugger): keep evaluation results readable in short dialogs (#4592)
The Evaluate dialog's result had a 220px minimum height, so in short windows the dialog overflowed and the result and buttons were cut off. The dialog now caps its height to the window, the expression field scrolls within half of it, imports wrap, and the result takes the remaining space; the expression uses the editor font and its label is tied to the field.
2026-11-20 04:49:29 +08:00
l0ng-ai 1ad8b06a1a fix(markdown): keep the Project view clickable in Preview only (#4604)
In Preview only the editor panel stays mounted but hidden, with no separator. react-resizable-panels adds an implicit resize region between two enabled panels without a separator; with the hidden panel's rect at zero it spanned everything left of the preview, showing a resize cursor and swallowing clicks in the Project view. The hidden editor panel is now disabled, leaving the group a single resizable panel.

Fixes #4589
2026-11-20 04:35:55 +08:00
l0ng-ai 2ca0e195e5 fix(editor): keep inline find controls inside narrow panes (#4588)
The inline find/replace bar used a fixed grid with a 220px minimum field, so in narrow editor panes the counter, option buttons and Close spilled outside the pane. The bar is now a container-query layout: fields shrink, the action groups wrap, and below 500px (and again below 224px) the actions and replace field move to their own rows while Show Replace and Close stay reachable.
2026-11-20 04:33:34 +08:00
l0ng-ai 32de3d0bf8 test(debugger): select breakpoint rows by accessible name 2026-11-20 04:32:23 +08:00
l0ng-ai 380de4ecd5 fix(debugger): keep breakpoint details usable in narrow windows 2026-11-20 04:26:39 +08:00
Mr0Bread 750d35dd6e fix(vcs): discard stale status after project switch (#4598)
The VCS store reset on project switch, but replies to refreshes started for the previous project still wrote to it, restoring its branch, changed files and decorations and firing conflict notifications. A project generation, bumped on every switch (also when reopening the same folder), now gates full and incremental refresh results, errors and discovered roots; queued paths are dropped on switch, and the refresh queue still drains for the active project.

Closes #4596

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 04:10:23 +08:00
l0ng-ai f0273690b9 fix(run): keep test results readable in narrow panes (#4586)
The test tree's header held the counts, duration and every toolbar action in one 28px row, so narrow Run panes clipped the counts and buttons. As in IDEA's new layout, the status (icon, counts, total duration) now sits above the console, Expand All, Collapse All and Export Test Results move into a More Actions menu, and the tree and console stack vertically below 560px with their own remembered split.
2026-11-20 04:07:52 +08:00
l0ng-ai 04611c0388 fix(database): show a running SQL statement in the editor and results (#4601)
The console tracked the running request only for Run and Cancel; statement marks and result tabs arrived after it ended, and the Results view said "No results" meanwhile. While a request runs, the submitted statements are highlighted with a gutter spinner and a ticking elapsed time, and the Results view opens with an executing bar above the previous result. Edits during the run move the marks and the outcomes land on their statements; cancel or an error clears the indication and keeps the previous result.

Fixes #4565
2026-11-20 04:06:41 +08:00
l0ng-ai 1cfc71ae58 fix(editor): make symbol rename and its preview readable in narrow windows (#4583)
The symbol rename prompt was a caret-anchored popup that could be clipped in narrow windows, and its preview truncated long names. When in-place rename isn't available, Rename now opens a dialog with the symbol context, a New name field in the editor font, and an optional note; the refactoring preview keeps the context, wraps occurrence snippets in the editor font and theme, and truncates long file names with the full path in the tooltip.
2026-11-20 03:56:29 +08:00
l0ng-ai 8daaef38d9 fix(run): keep Run Anything controls visible on short windows (#4581)
Run Anything had a fixed 620px popup with a 360px list cap and a footer that could fall off short windows. The popup now fits the viewport as a column whose list shrinks, uses the shared search field with combobox semantics, shows the completion of the selected entry in the field, pages by the visible row count (compact-aware), and keeps a wrapping footer with the navigation hints.
2026-11-20 03:39:37 +08:00
Chris Schofield efd4e454ee feat(appearance): make Compact Mode match IntelliJ's compact density (#4593)
Compact Mode only lowered the title bar and narrowed the stripes: row heights, toolbar widgets and icons were fixed in code, and nothing in JS (where virtualised list row heights are set) could tell whether the mode was on. A small density store now mirrors the setting for JS, and Compact Mode uses IntelliJ's *.compact theme values: tree/list rows 22 (VCS log 24), toolbar widgets 26, toolbar and stripe icons 16, status bar 24, island gap 4, and chrome text 1px smaller.

Co-authored-by: ChildishForces <[email protected]>
2026-11-20 03:26:32 +08:00
l0ng-ai 0379c37a49 fix(usages): keep results and previews readable in narrow windows (#4580)
The Show Usages popup and the Find usages view used fixed header heights, a flexible spacer and a fixed preview height, so in narrow windows the title, file names and line numbers were clipped and the preview pushed results off screen. Headers now wrap their actions, rows use a file / line / text grid with truncation, and the preview shrinks with the viewport.
2026-11-20 03:21:33 +08:00
l0ng-ai 98da80b2b3 fix(editor): keep the current breadcrumb visible (#4579)
Long breadcrumb trails hid the current file or symbol when the editor or status bar ran out of room. Both trails now scroll to the current location (with edge fades) and keep earlier entries reachable by wheel, trackpad or keyboard. The status bar reserves a minimum width for the path and moves lower-priority widgets into its overflow menu. Code breadcrumbs use the editor font and highlight the symbol at the caret.
2026-11-20 03:05:31 +08:00
l0ng-ai 5c2e7ff92a fix(editor): fit intention previews beside or below the list (#4578)
The intention preview had a fixed 420px width beside the list, which pushed the action list away from the caret or got clipped in narrow windows. The preview now opens to the right when there is room, to the left when that keeps the list by the caret, and below the list in narrow windows. Preview code follows the editor's font settings and theme and wraps long lines.
2026-11-20 02:54:44 +08:00
l0ng-ai e86a853048 fix(run): keep configuration names visible in narrow sidebars (#4573)
A long run target could take the whole row in the Run/Debug Configurations sidebar, leaving the configuration name at zero width and forcing horizontal scrolling. Target labels now truncate in wide panes, narrow panes (container query) hide the muted target and scope, and the row tooltip carries the full name, target, scope and command. Type headings are semibold.
2026-11-20 02:53:44 +08:00
l0ng-ai fd8f0eb99c fix(editor): make quick documentation fit narrow windows (#4568)
Quick Documentation used a fixed 600px cap and kept its caret anchor after the window shrank, so short documents looked cramped and the actions could end up off screen. The popup now sizes to a 300-500px content width, keeps its actions together in the lower-right corner while the document scrolls, and clamps the anchor to the current viewport.
2026-11-20 02:52:46 +08:00
l0ng-ai 121e1fa535 fix(completion): fit the lookup to the editor and its font (#4566)
The lookup reserved a fixed 420px row, so long names pushed the signature and type past the editor edge, and the body-level tooltip ignored temporary editor zoom. It now sizes to its content within the editor's tooltip bounds, truncates each field, applies the label alignment through CodeMirror's own offset so the viewport clamp accounts for it, and follows the editor's current font size.
2026-11-20 02:51:47 +08:00
176 змінених файлів з 4951 додано та 1422 видалено

No files matched your search

+2 -1
Переглянути файл
@@ -217,7 +217,8 @@ impl ManageConnection for MssqlConnectionManager {
let row = client.simple_query("SELECT DB_NAME()").await?.into_row().await?;
let default = row
.and_then(|r| r.get::<&str, _>(0).map(str::to_owned))
.and_then(|db| crate::sql::use_schema(DbDriver::SqlServer, &db));
// Statements that `USE` another database must not move the pooled connection for good.
.map(|db| format!("USE {}", crate::sql::quote_ident(DbDriver::SqlServer, &db)));
Ok(MssqlConnection(Some(client), Context::new(default)))
}
+8 -6
Переглянути файл
@@ -442,7 +442,8 @@ pub fn current_schema(driver: DbDriver) -> Option<&'static str> {
DbDriver::Sqlite | DbDriver::Jdbc => None,
DbDriver::Postgres => Some("SELECT current_schema()"),
DbDriver::Mysql => Some("SELECT DATABASE()"),
DbDriver::SqlServer => Some("SELECT DB_NAME()"),
// The login's default schema; the database is the console's target (IDEA's `database.schema`).
DbDriver::SqlServer => Some("SELECT SCHEMA_NAME()"),
DbDriver::Oracle => Some("SELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') FROM DUAL"),
DbDriver::Snowflake => Some("SELECT CURRENT_SCHEMA()"),
}
@@ -450,12 +451,13 @@ pub fn current_schema(driver: DbDriver) -> Option<&'static str> {
/// The statement that makes unqualified names resolve in `schema` on the
/// connection that runs it (a query console's active schema; `None`: the driver
/// has no schema to switch — SQLite's `main`, ClickHouse's `USE` differs).
/// has no schema to switch — SQLite's `main`, ClickHouse's `USE` differs, and SQL Server
/// cannot change a session's default schema, so its console schema only scopes resolution).
pub fn use_schema(driver: DbDriver, schema: &str) -> Option<String> {
match driver {
DbDriver::Sqlite | DbDriver::Clickhouse | DbDriver::Jdbc => None,
DbDriver::Sqlite | DbDriver::Clickhouse | DbDriver::Jdbc | DbDriver::SqlServer => None,
DbDriver::Postgres => Some(format!("SET search_path TO {}", quote_ident(driver, schema))),
DbDriver::Mysql | DbDriver::SqlServer => Some(format!("USE {}", quote_ident(driver, schema))),
DbDriver::Mysql => Some(format!("USE {}", quote_ident(driver, schema))),
DbDriver::Oracle => Some(format!("ALTER SESSION SET CURRENT_SCHEMA = {}", quote_ident(driver, schema))),
DbDriver::Snowflake => Some(format!("USE SCHEMA {}", quote_ident(driver, schema))),
}
@@ -1030,7 +1032,7 @@ mod tests {
assert_eq!(quote_ident(DbDriver::SqlServer, "a]b"), "[a]]b]");
assert_eq!(qualified(DbDriver::SqlServer, "dbo", "t"), "[dbo].[t]");
assert_eq!(qualified(DbDriver::SqlServer, "", "t"), "[t]");
assert_eq!(current_schema(DbDriver::SqlServer), Some("SELECT DB_NAME()"));
assert_eq!(current_schema(DbDriver::SqlServer), Some("SELECT SCHEMA_NAME()"));
assert_eq!(crate::conn::begin_statement(DbDriver::SqlServer), "BEGIN TRAN");
assert_eq!(
schemas(DbDriver::SqlServer, true),
@@ -1149,7 +1151,7 @@ mod tests {
fn schema_switch_statement_per_dialect() {
assert_eq!(use_schema(DbDriver::Postgres, "app data"), Some("SET search_path TO \"app data\"".into()));
assert_eq!(use_schema(DbDriver::Mysql, "a`b"), Some("USE `a``b`".into()));
assert_eq!(use_schema(DbDriver::SqlServer, "app] data"), Some("USE [app]] data]".into()));
assert_eq!(use_schema(DbDriver::SqlServer, "dbo"), None);
assert_eq!(use_schema(DbDriver::Postgres, "a\"b"), Some("SET search_path TO \"a\"\"b\"".into()));
assert_eq!(use_schema(DbDriver::Oracle, "a\"b"), Some("ALTER SESSION SET CURRENT_SCHEMA = \"a\"\"b\"".into()));
assert!(sqlserver_databases().contains("state = 0 AND HAS_DBACCESS(name) = 1"));
+1 -1
Переглянути файл
@@ -29,7 +29,7 @@ Conventions:
| ---------- | --------------------------------------- | --------------------------------------------------------------------------------------- |
| oxfmt | `pnpm format` (CI: `pnpm format:check`) | `.oxfmtrc.json`: print width 120, double quotes, semicolons, trailing commas everywhere |
| oxlint | `pnpm lint` | `.oxlintrc.json`: TypeScript and React plugins |
| Type check | `pnpm typecheck` | `tsconfig.json` and the configs of `perf/`, `scripts/`, `smoke/` |
| Type check | `pnpm typecheck` | `tsconfig.json` and the configs of `e2e/`, `evals/`, `perf/`, `scripts/`, `smoke/` |
| knip | `pnpm knip` | `knip.ts`: unused files, exports and dependencies |
`pnpm knip` fails on an export nobody imports, a file nobody reaches or a dependency nobody uses. Delete dead code rather than suppressing it; exports used only inside their own file are allowed.
+1 -1
Переглянути файл
@@ -26,7 +26,7 @@ The same page also has:
- **Different tool window background**: set tool windows apart from the editor.
- **Background Image**: an image shown through the project window, with its **Opacity**, **Fill** (scale, original size or tile) and **Anchor**.
- **Accessibility**: **Use contrast scrollbars** and **Adjust colors for red-green vision deficiency** (for protanopia and deuteranopia).
- **Compact mode** under **UI Options**.
- **Compact mode** under **UI Options**, also in **View › Appearance**. As in IntelliJ IDEA, it uses shorter tree and list rows, a smaller main toolbar, tool window stripes and status bar, 16px toolbar and stripe icons, and 1px smaller text in the toolbar, status bar, editor tabs and tool window headers.
## Editor color scheme
+6 -6
Переглянути файл
@@ -25,12 +25,12 @@ description: "Rust 与 TypeScript 的格式化、lint 和死代码检查,以
## TypeScript 与 React
| 工具 | 命令 | 配置 |
| -------- | ---------------------------------------- | --------------------------------------------------------- |
| oxfmt | `pnpm format`(CI:`pnpm format:check`) | `.oxfmtrc.json`:行宽 120、双引号、分号、处处尾逗号 |
| oxlint | `pnpm lint` | `.oxlintrc.json`:TypeScript 和 React 插件 |
| 类型检查 | `pnpm typecheck` | `tsconfig.json` 以及 `perf/`、`scripts/`、`smoke/` 的配置 |
| knip | `pnpm knip` | `knip.ts`:未使用的文件、导出和依赖 |
| 工具 | 命令 | 配置 |
| -------- | ---------------------------------------- | --------------------------------------------------------------------------- |
| oxfmt | `pnpm format`(CI:`pnpm format:check`) | `.oxfmtrc.json`:行宽 120、双引号、处处尾逗号 |
| oxlint | `pnpm lint` | `.oxlintrc.json`:TypeScript 和 React 插件 |
| 类型检查 | `pnpm typecheck` | `tsconfig.json` 以及 `e2e/`、`evals/`、`perf/`、`scripts/`、`smoke/` 的配置 |
| knip | `pnpm knip` | `knip.ts`:未使用的文件、导出和依赖 |
`pnpm knip` 发现没人 import 的导出、没人引用的文件或没人用的依赖时会失败。请删掉死代码,而不是屏蔽检查;只在本文件内使用的导出是允许的。
+1 -1
Переглянути файл
@@ -26,7 +26,7 @@ description: "选择界面主题和编辑器配色方案,导入 IntelliJ 主
- **不同的工具窗口背景**:让工具窗口与编辑器区分开。
- **背景图像**:透过项目窗口显示的图像,可设置 **不透明度**、**填充**(缩放、原始大小或平铺)和 **位置**。
- **辅助功能**:**使用对比度滚动条** 和 **针对红绿色觉缺陷调整颜色**(适用于红色盲和绿色盲)。
- **UI 选项** 下的 **紧凑模式**。
- **UI 选项** 下的 **紧凑模式**,也可在 **视图 › 外观** 中切换。与 IntelliJ IDEA 一致:树和列表的行更矮,主工具栏、工具窗口栏和状态栏更紧凑,工具栏和工具窗口栏图标为 16px,工具栏、状态栏、编辑器标签页和工具窗口标题的文字小 1px。
## 编辑器配色方案
+1 -1
Переглянути файл
@@ -26,7 +26,7 @@ const firstTask: AgentTask = {
const secondTask: AgentTask = { ...firstTask, id: "focus-second", title: "Second focus task" };
const draft = "draft keep this unsent";
const reboundShortcut = "Control+Meta+Shift+J";
const subagent: AgentEntry = {
const subagent: Extract<AgentEntry, { type: "subagent" }> = {
type: "subagent",
id: "focus-child",
title: "Inspect focus behavior",
+1 -1
Переглянути файл
@@ -149,7 +149,7 @@ test("opens slash-prefixed Windows Markdown links with preview content and hover
for (const [label, path, heading] of [
["Specification", spec, "Windows specification"],
["Work skill", skill, "Work specification skill"],
]) {
] as const) {
const link = reply.getByRole("link", { name: label, exact: true });
await link.hover();
await expect(link).toHaveAttribute("title", path);
+7 -7
Переглянути файл
@@ -1,5 +1,7 @@
import { expect, test } from "./fixtures";
import type { AgentQuestion, AgentTask } from "../src/bindings";
import type * as AgentStore from "../src/features/agents/store";
import type * as Ipc from "../src/platform/ipc";
const task: AgentTask = {
id: "questions",
@@ -49,14 +51,12 @@ for (const status of ["running", "ready"] as const) {
const key = JSON.stringify(["request_user_input_async", "call-1", 0]);
await page.evaluate(
async ({ task, status, key }) => {
// Keep the workbench imports in the browser's Vite realm.
const storePath = "/src/features/agents/store.ts";
const ipcPath = "/src/platform/ipc.ts";
const store = await import(storePath);
(await import(ipcPath)).commands.agentAnswerQuestion = async (
id: string,
question: string,
answer: string | null,
) => {
const store: typeof AgentStore = await import(storePath);
const { commands }: typeof Ipc = await import(ipcPath);
commands.agentAnswerQuestion = async (id, question, answer) => {
document.documentElement.dataset.asyncAnswer = JSON.stringify({ id, question, answer });
const entries = store.useAgents.getState().entries.get(id)!;
store.useAgents.setState({
@@ -111,7 +111,7 @@ for (const status of ["running", "ready"] as const) {
if (status === "running") {
await page.evaluate(async (id) => {
const storePath = "/src/features/agents/store.ts";
const { useAgents } = await import(storePath);
const { useAgents }: typeof AgentStore = await import(storePath);
useAgents.setState((s) => ({ tasks: new Map(s.tasks).set(id, { ...s.tasks.get(id)!, status: "ready" }) }));
}, task.id);
await expect(card.getByRole("radio", { name: /^Read latest content/ })).toBeChecked();
+7 -4
Переглянути файл
@@ -1,3 +1,4 @@
import type * as ProjectStore from "../src/platform/project";
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
test.use({ video: "on" });
@@ -114,9 +115,11 @@ test("restricting an attached folder leaves the current project untouched", asyn
test("restricted attachments can be trusted individually from the banner", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
const m = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ m);
// Load the running workbench's store in the browser.
const projectPath = "/src/platform/project.ts";
const { useProject }: typeof ProjectStore = await import(/* @vite-ignore */ projectPath);
const primary = useProject.getState().project;
if (!primary) throw new Error("Expected the sample project to be open");
let current = {
...primary,
trusted: false,
@@ -126,11 +129,11 @@ test("restricted attachments can be trusted individually from the banner", async
const trusted = new Set([primary.root]);
window.__ipc.handlers.project_trust_status = ({ path }) => ({
root: path,
trusted: trusted.has(path),
trusted: typeof path === "string" && trusted.has(path),
decided: true,
});
window.__ipc.handlers.project_trust_set = ({ path, trusted: allow }) => {
if (allow) trusted.add(path);
if (allow && typeof path === "string") trusted.add(path);
current = { ...current, trusted: current.workspace.projects.every((path) => trusted.has(path)) };
};
window.__ipc.handlers.project_current = () => current;
+50
Переглянути файл
@@ -0,0 +1,50 @@
import { expect, test } from "./fixtures";
test("keeps breakpoint details editable when the dialog gets narrow", async ({ workbench: page }) => {
await page.setViewportSize({ width: 500, height: 480 });
await page.evaluate(async () => {
const actionsModule = "/src/platform/actions.ts";
const storeModule = "/src/features/debugger/breakpoints/store.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
const { addBreakpoint } = await import(/* @vite-ignore */ storeModule);
addBreakpoint("/dev/acme-api/CheckInternationalSettlementBeforeDispatch.java", 7, {
condition: "amount > 100",
});
addBreakpoint("/dev/acme-api/Receipt.java", 4);
await executeAction("debug.viewBreakpoints");
});
const dialog = page.getByRole("dialog", { name: "Breakpoints" });
const list = dialog.getByRole("listbox", { name: "All breakpoints" });
const condition = dialog.locator('input[aria-label="Condition"]');
await expect(condition).toHaveValue("amount > 100");
await expect.poll(async () => (await condition.boundingBox())?.width ?? 0).toBeGreaterThanOrEqual(240);
await expect(dialog.getByRole("button", { name: "Done", exact: true })).toBeInViewport({ ratio: 1 });
await condition.fill("amount > 250");
await dialog.getByRole("checkbox", { name: "Evaluate and log", exact: true }).check();
await dialog.getByRole("textbox", { name: "Evaluate and log", exact: true }).fill("total: {amount}");
const first = list.getByRole("option", { name: /CheckInternationalSettlementBeforeDispatch\.java:8/ });
await expect(first.getByText(":8", { exact: true })).toBeInViewport({ ratio: 1 });
await list.getByRole("option", { name: /Receipt\.java:5/ }).click();
await expect(condition).toHaveValue("");
await first.click();
await expect(condition).toHaveValue("amount > 250");
await expect(dialog.getByRole("textbox", { name: "Evaluate and log", exact: true })).toHaveValue("total: {amount}");
await page.setViewportSize({ width: 1080, height: 760 });
const divider = dialog.locator('[data-separator][aria-orientation="vertical"]');
await expect(divider).toBeInViewport();
const oldWidth = (await list.boundingBox())!.width;
const handle = (await divider.boundingBox())!;
await page.mouse.move(handle.x + handle.width / 2, handle.y + handle.height / 2);
await page.mouse.down();
await page.mouse.move(handle.x + 60, handle.y + handle.height / 2, { steps: 4 });
await page.mouse.up();
await expect.poll(async () => (await list.boundingBox())?.width ?? 0).toBeGreaterThan(oldWidth + 20);
await expect(condition).toHaveValue("amount > 250");
const request = dialog.getByRole("textbox", { name: "Part of a request URL" });
await request.scrollIntoViewIfNeeded();
await expect(request).toBeInViewport({ ratio: 1 });
await dialog.getByRole("button", { name: "Done", exact: true }).click();
await expect(dialog).toBeHidden();
});
+75
Переглянути файл
@@ -0,0 +1,75 @@
import type { MethodSignature } from "../src/bindings";
import { expect, stubDesktop, test } from "./fixtures";
const signature: MethodSignature = {
methodIdentifier: "invoice",
modifier: "",
returnType: "Invoice",
methodName: "prepareInvoiceForInternationalSettlement",
parameters: [
["Order", "order"],
["String", "billingCurrency"],
["BigDecimal", "amountBeforeDiscount"],
["Map<String, BigDecimal>", "taxRatesByJurisdiction"],
["List<Adjustment>", "settlementAdjustments"],
["RoundingMode", "roundingMode"],
["LocalDate", "scheduledSettlementDate"],
["boolean", "includeTaxBreakdown"],
].map(([type, name], originalIndex) => ({ type: type!, name: name!, originalIndex, defaultValue: "" })),
exceptions: [],
};
test("keeps parameter rows and a long signature preview usable in a short dialog", async ({ workbench: page }) => {
await page.setViewportSize({ width: 490, height: 520 });
await page.evaluate(async () => {
const workbench = "/src/workbench/contributions.ts";
const { editorService } = await import(/* @vite-ignore */ workbench);
await editorService().openFile("/dev/acme-api/InvoiceService.java");
});
const editor = page.locator(".cm-editor .cm-content");
await expect(editor).toBeVisible();
await stubDesktop(page);
const fontSize = await editor.evaluate(async (content, signature) => {
window.__ipc.handlers.lsp_signature_info = () => signature;
const viewModule = "/node_modules/.vite/deps/@codemirror_view.js";
const prefsModule = "/src/editor/core/cm/prefs.ts";
const { EditorView } = await import(/* @vite-ignore */ viewModule);
const { stepFontZoom } = await import(/* @vite-ignore */ prefsModule);
const base = Number.parseFloat(getComputedStyle(content).fontSize);
const view = EditorView.findFromDOM(content as HTMLElement)!;
stepFontZoom(view, 4);
view.focus();
return `${base + 4}px`;
}, signature);
await expect(editor).toHaveCSS("font-size", fontSize);
await page.keyboard.press("Meta+F6");
const dialog = page.getByRole("dialog", { name: "Change Signature" });
const table = dialog.getByRole("table", { name: "Parameters" });
const names = table.getByRole("textbox", { name: "Name", exact: true });
await expect(names.first()).toBeInViewport({ ratio: 1 });
const defaults = table.getByRole("columnheader", { name: "Default value", exact: true });
await expect(defaults).toHaveCount(0);
const preview = dialog.locator("pre");
await expect(preview).toBeInViewport({ ratio: 1 });
await expect(preview).toHaveCSS("font-size", fontSize);
await expect(names.first()).toHaveCSS("font-size", fontSize);
expect(
await preview.evaluate((el) => el.scrollHeight > el.clientHeight && el.scrollWidth <= el.clientWidth + 1),
).toBe(true);
await expect(dialog.getByRole("button", { name: "Cancel" })).toBeInViewport({ ratio: 1 });
await dialog.getByRole("button", { name: "Add", exact: true }).click();
await expect(defaults).toBeInViewport({ ratio: 1 });
const addedType = table.getByRole("textbox", { name: "Type", exact: true }).last();
await expect(addedType).toBeInViewport({ ratio: 1 });
await addedType.fill("boolean");
await names.last().fill("attachReceipt");
await table.getByRole("textbox", { name: "Default value", exact: true }).last().fill("false");
await dialog.getByRole("button", { name: "Move Up", exact: true }).click();
await expect(names.nth(7)).toHaveValue("attachReceipt");
await expect(preview).toContainText("boolean attachReceipt");
await expect(dialog.getByRole("button", { name: "Preview", exact: true })).toBeEnabled();
await page.keyboard.press("Escape");
await expect(dialog).toBeHidden();
});
+219 -1
Переглянути файл
@@ -427,6 +427,70 @@ test("Find Usages from the editor context menu lists every usage by file and ope
).toHaveAttribute("aria-selected", "true");
});
test("usage locations and preview stay readable as the available space changes", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1040, height: 760 });
const editor = await openSample(page);
await page.evaluate(
({ file, other }) => {
const locations = [
{ path: file, range: { start: { line: 16, col: 8 }, end: { line: 16, col: 15 } } },
{ path: file, range: { start: { line: 20, col: 27 }, end: { line: 20, col: 34 } } },
{ path: other, range: { start: { line: 0, col: 0 }, end: { line: 0, col: 7 } } },
];
window.__ipc.handlers.lsp_references = () => ({
locations,
classified: [{ location: locations[2], kind: "code", text: "service.submit(order)" }],
incomplete: null,
librariesSkipped: true,
});
},
{ file: FILE, other: `${ROOT}/domain/checkout/processing/calculations/PaymentProcessingService.kt` },
);
await caretAt(editor, page, "val order: Order", "service");
await page.keyboard.press("Meta+Alt+F7");
const popup = page.getByRole("dialog", { name: "Usages" });
const scope = popup.getByRole("button", { name: "Scope" });
const openWindow = popup.getByRole("button", { name: /^Open in Find Window/ });
await expect(popup.getByTestId("usage-row")).toHaveCount(3);
await popup.getByRole("button", { name: "Show Preview" }).click();
const code = popup.getByRole("region", { name: "Preview" });
await expect(code.locator(".cm-content")).toContainText("service.find(status");
await page.setViewportSize({ width: 480, height: 470 });
const within = async (child: Locator, parent: Locator) => {
const [c, p] = await Promise.all([child.boundingBox(), parent.boundingBox()]);
return (
!!c &&
!!p &&
c.x >= p.x - 1 &&
c.y >= p.y - 1 &&
c.x + c.width <= p.x + p.width + 1 &&
c.y + c.height <= p.y + p.height + 1
);
};
await expect.poll(() => within(scope, popup)).toBe(true);
await expect.poll(() => within(openWindow, popup)).toBe(true);
await expect.poll(() => within(code, popup)).toBe(true);
const results = popup.getByRole("listbox", { name: "Usages" });
await expect.poll(() => within(popup.getByTestId("usage-row").last(), results)).toBe(true);
const firstRow = popup.getByTestId("usage-row").first();
const file = firstRow.getByText("build.gradle.kts", { exact: true });
await expect(file).toBeVisible();
const [filename, snippet] = await Promise.all([file.boundingBox(), firstRow.locator("mark").boundingBox()]);
expect(filename!.x + filename!.width).toBeLessThan(snippet!.x);
await openWindow.click();
const tree = page.getByRole("tree", { name: "Usages" });
const target = tree.getByRole("treeitem", { name: /^17 service\.find\(status/ });
await target.click();
const preview = page.getByRole("region", { name: "Preview" });
await expect(preview).toContainText("service.find(status");
await expect.poll(async () => (await preview.boundingBox())!.y > (await tree.boundingBox())!.y).toBe(true);
await page.setViewportSize({ width: 1040, height: 760 });
await expect.poll(async () => (await preview.boundingBox())!.x > (await tree.boundingBox())!.x).toBe(true);
await expect(preview).toContainText("service.find(status");
});
test("⇧F6 renames in place and sends the server's edit to be applied", async ({ workbench: page }) => {
const editor = await openSample(page);
await page.evaluate(
@@ -495,7 +559,161 @@ test("indexed single-file rename previews all anchors and applies only after con
}
await expect.poll(() => ipcCalls(page, "apply_workspace_edit")).toHaveLength(1);
const [apply] = await ipcCalls(page, "apply_workspace_edit");
expect(apply.edit).toMatchObject({ preconditions: [{ path: FILE, hash: "indexed-snapshot" }] });
expect(apply?.edit).toMatchObject({ preconditions: [{ path: FILE, hash: "indexed-snapshot" }] });
});
test("rename keeps the typed name, uses the editor font and shows long preview names in a narrow dialog", async ({
workbench: page,
}) => {
const editor = await openSample(page);
await page.evaluate(
async ({ file, prepared }) => {
const projectModule = "/src/platform/project.ts";
const schemaModule = "/src/features/settings/model/schema.ts";
const [{ useProject }, { DEFAULT_SETTINGS }] = await Promise.all([
import(/* @vite-ignore */ projectModule),
import(/* @vite-ignore */ schemaModule),
]);
const base = useProject.getState().settings ?? DEFAULT_SETTINGS;
useProject.setState({ settings: { ...base, editor: { ...base.editor, fontSize: 17 } } });
window.__ipc.handlers.lsp_prepare_rename = () => prepared;
window.__ipc.handlers.lsp_rename = (args) => ({
preview: true,
incomplete: null,
edit: {
files: [
{
kind: "edit",
path: file,
edits: [{ range: prepared, new_text: args.newName }],
},
],
},
});
window.__ipc.handlers.apply_workspace_edit = () => null;
},
{ file: FILE, prepared: range(20, 12, 17) },
);
await caretAt(editor, page, "val order: Order", "order");
await page.keyboard.press("Shift+F6");
await expect(page.getByText(/Press ⇧F6 to show dialog/)).toBeVisible();
const name = "checkoutOrderWithDeliveryInstructionsAndInventoryReservation";
await page.keyboard.insertText(name);
await page.keyboard.press("Shift+F6");
await page.setViewportSize({ width: 440, height: 520 });
const dialog = page.getByRole("dialog", { name: "Rename 'order'", exact: true });
const input = dialog.getByRole("textbox", { name: "New name" });
await expect(input).toBeFocused();
await expect(input).toHaveValue(name);
await expect(input).toHaveCSS("font-size", "17px");
const [label, field] = await Promise.all([
dialog.getByText("New name", { exact: true }).boundingBox(),
input.boundingBox(),
]);
expect(label!.x + label!.width).toBeLessThan(field!.x);
const rename = dialog.getByRole("button", { name: "Rename", exact: true });
await input.fill("");
await expect(rename).toBeDisabled();
await input.press("Enter");
await expect(dialog).toBeVisible();
expect(await ipcCalls(page, "lsp_rename")).toHaveLength(0);
await input.fill(name);
await input.press("Enter");
const summary = `Rename 'order' to '${name}'`;
const preview = page.getByRole("dialog", { name: summary, exact: true });
const context = preview.getByText(summary, { exact: true });
await expect(context).toBeVisible();
const geometry = await context.evaluate((element) => ({
client: element.clientWidth,
content: element.scrollWidth,
}));
expect(geometry.content).toBeLessThanOrEqual(geometry.client + 1);
await expect(preview.getByText("1 occurrence in 1 file")).toBeVisible();
expect(await ipcCalls(page, "apply_workspace_edit")).toHaveLength(0);
await preview.getByRole("button", { name: "Do Refactor" }).click();
await expect.poll(() => ipcCalls(page, "apply_workspace_edit")).toHaveLength(1);
});
test("intention previews fit narrow windows and wrap long code lines", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1600, height: 900 });
const editor = await openSample(page);
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, editor: { ...settings?.editor, fontSize: 16 } } });
});
await expect(editor.locator(".cm-content")).toHaveCSS("font-size", "16px");
const replacement = "com.acme.orders." + "SharedDevelopmentOrderModel".repeat(6);
await page.evaluate(
({ file, replacement, edit }) => {
window.__ipc.handlers.lsp_code_actions = () => [
{
title: "Replace Order with the fully qualified shared development order model",
kind: "quickfix",
isPreferred: true,
disabledReason: null,
edit: { files: [{ kind: "edit", path: file, edits: [{ range: edit, new_text: replacement }] }] },
command: null,
data: null,
server: 1,
},
...Array.from({ length: 11 }, (_, i) => ({
title: `Create alternative Order model ${i + 1}`,
kind: "quickfix",
isPreferred: false,
disabledReason: null,
edit: null,
command: null,
data: null,
server: 1,
})),
];
window.__ipc.handlers.lsp_execute_code_action = () => [];
},
{ file: FILE, replacement, edit: range(20, 19, 24) },
);
await caretAt(editor, page, "val order: Order", "Order ");
await page.keyboard.press("Alt+Enter");
const popup = page.getByRole("dialog", { name: "Intentions", exact: true });
const options = popup.getByRole("listbox", { name: "Intentions" });
const preview = popup.locator('[aria-label="Preview"]');
await expect(preview.locator("pre")).toContainText(replacement);
const wide = (await options.boundingBox())!;
const widePreview = (await preview.boundingBox())!;
expect(widePreview.x).toBeGreaterThanOrEqual(wide.x + wide.width - 1);
await page.setViewportSize({ width: 1050, height: 900 });
await expect
.poll(async () => {
const list = (await options.boundingBox())!;
const code = (await preview.boundingBox())!;
return code.x + code.width - list.x;
})
.toBeLessThanOrEqual(1);
await page.setViewportSize({ width: 520, height: 540 });
await expect
.poll(async () => {
const menu = (await popup.boundingBox())!;
const list = (await options.boundingBox())!;
const code = (await preview.boundingBox())!;
return {
popupFits: menu.x >= 0 && menu.y >= 0 && menu.x + menu.width <= 521 && menu.y + menu.height <= 541,
previewBelow: code.y >= list.y + list.height - 1,
previewFits: code.x >= menu.x && code.x + code.width <= menu.x + menu.width + 1,
};
})
.toEqual({ popupFits: true, previewBelow: true, previewFits: true });
expect(await preview.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(preview.locator("pre")).toHaveCSS("font-size", "16px");
await expect(options).toBeFocused();
await page.keyboard.press("Enter");
await expect(popup).toBeHidden();
await expect.poll(() => ipcCalls(page, "lsp_execute_code_action")).toHaveLength(1);
});
test("diagnostics underline the range and ⌥⏎ applies the preferred quick fix", async ({ workbench: page }) => {
+48
Переглянути файл
@@ -0,0 +1,48 @@
import { expect, test } from "./fixtures";
/** Heights IDEA's Islands theme uses in compact mode (`*.compact` keys), against the defaults. */
const SIZES = {
normal: { titleBar: 40, treeRow: 24, stripeIcon: 20, statusBar: 34, runButton: 30 },
compact: { titleBar: 32, treeRow: 22, stripeIcon: 16, statusBar: 24, runButton: 26 },
};
async function measure(page: import("@playwright/test").Page) {
return page.evaluate(() => {
const height = (selector: string) => document.querySelector(selector)?.getBoundingClientRect().height ?? null;
return {
titleBar: height("header"),
treeRow: height('[role="tree"][aria-label="Project"] [role="treeitem"]'),
stripeIcon: height("[data-stripe-button] svg"),
statusBar: height('footer[aria-label="Status bar"]'),
runButton: height("[data-run-chooser] + * button"),
};
});
}
test("Compact Mode shrinks rows, toolbars, stripes and the status bar like IDEA", async ({ workbench: page }, info) => {
// Plain-browser mode has no settings backend: set what the toggle action would store.
const setCompact = (compactMode: boolean) =>
page.evaluate(async (compactMode) => {
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectPath);
const settings = useProject.getState().settings;
useProject.setState({
settings: {
...settings,
appearance: { ...settings?.appearance, theme: "dark", syncWithOs: false, compactMode },
},
});
}, compactMode);
await setCompact(false);
await expect.poll(() => measure(page)).toEqual(SIZES.normal);
await info.attach("normal", { body: await page.screenshot({ animations: "disabled" }), contentType: "image/png" });
await setCompact(true);
await expect(page.locator("html")).toHaveAttribute("data-compact", "");
await expect.poll(() => measure(page)).toEqual(SIZES.compact);
await info.attach("compact", { body: await page.screenshot({ animations: "disabled" }), contentType: "image/png" });
await setCompact(false);
await expect.poll(() => measure(page)).toEqual(SIZES.normal);
});
+2 -2
Переглянути файл
@@ -6,7 +6,7 @@ for (const [id, selector] of [
["keymap", "[class*='presetLabel']"],
["editor.inspections", "[class*='profileRow'] > span:first-child"],
["vcs.issueNavigation", "[class*='pageBody'] button:not([aria-label])"],
]) {
] as const) {
test(`${id} keeps compact labels inside their controls`, async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog");
@@ -41,7 +41,7 @@ for (const [id, selector] of [
for (const [id, selector] of [
["general", "[class*='fontRow'] > label"],
["build.console", "[class*='inlineRow'] > label"],
]) {
] as const) {
test(`${id} keeps a readable width for inline text`, async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
await expect(page.getByRole("dialog", { name: "Settings", exact: true })).toBeVisible();
+1 -1
Переглянути файл
@@ -49,7 +49,7 @@ commands.lspHover = async () => {
};
commands.lspDocumentLinks = async () => ({ status: "ok", data: [] });
commands.lspDocumentHighlights = async () => ({ status: "ok", data: [] });
commands.cancelRequest = async () => ({ status: "ok", data: null });
commands.cancelRequest = async () => {};
const java = new EditorView({
parent: javaHost,
state: EditorState.create({
+1 -1
Переглянути файл
@@ -10,7 +10,7 @@ test("data source tabs share a stable layout and scroll within a short window",
const dialog = page.getByRole("dialog", { name: "New Data Source" });
const panel = dialog.getByRole("tabpanel");
const dialogSize = () => dialog.evaluate((element) => [element.offsetWidth, element.offsetHeight]);
const dialogSize = () => dialog.evaluate((element: HTMLElement) => [element.offsetWidth, element.offsetHeight]);
await expect(panel.getByRole("textbox", { name: "Host:" })).toBeVisible();
const size = await dialogSize();
await dialog.getByRole("tab", { name: "SSH/SSL" }).click();
+1 -1
Переглянути файл
@@ -187,7 +187,7 @@ test("result context menu fits the viewport, responds to hover and keyboard, and
for (const [theme, label] of [
["solarized-light", "Solarized Light"],
["solarized-dark", "Solarized Dark"],
]) {
] as const) {
test(`${label}: retains the inactive context-menu target's hover until dismissal without selecting it`, async ({
workbench: page,
}, info) => {
+57
Переглянути файл
@@ -113,3 +113,60 @@ test("stops at a breakpoint, shows frames and variables, steps and resumes", asy
await expect.poll(() => ipcCalls(page, "debug_resume")).toHaveLength(1);
await expect(debug.getByText("CreateOrderRequest(sku='A-1', qty=2)")).toBeHidden();
});
test("Evaluate keeps a multiline expression and its result visible in a short dialog", async ({ workbench: page }) => {
await page.setViewportSize({ width: 580, height: 420 });
await stubDesktop(page);
await page.evaluate(async (session) => {
const handlers = window.__ipc.handlers;
handlers.debug_capabilities = () => ({});
handlers.debug_completions = () => [];
handlers.debug_evaluate_in = () => ({
name: "orderSummary",
typeName: "OrderSummary",
value: "total = 36",
variablesReference: 210,
evaluateName: null,
});
handlers.debug_variables = () => [
{ name: "tax", value: "4", typeName: "int", variablesReference: 0, evaluateName: null },
];
const stateModule = "/src/features/debugger/state.ts";
const { adoptSession } = await import(/* @vite-ignore */ stateModule);
adoptSession(session, { name: "Checkout", adapter: "debugpy", status: "paused", selectedFrame: 11 });
}, SESSION);
await page.keyboard.press("Alt+F8");
const dialog = page.getByRole("dialog", { name: "Evaluate expression" });
const field = dialog.getByRole("textbox", { name: "Expression" });
const expression = ["orderSummary(", ...Array.from({ length: 12 }, (_, i) => ` item${i},`), ")"].join("\n");
await field.fill(expression);
await field.press("Enter");
const result = dialog.getByRole("tree", { name: "Evaluation result" });
const row = result.getByRole("treeitem").first();
await expect(row).toContainText("total = 36");
await expect
.poll(() =>
dialog.locator("[data-dialog-body]").evaluate((body) => {
const area = body.querySelector("textarea")!;
const resultRow = body.querySelector('[role="treeitem"]')!.getBoundingClientRect();
const bounds = body.getBoundingClientRect();
return (
body.scrollHeight <= body.clientHeight + 1 &&
area.scrollHeight > area.clientHeight &&
resultRow.top >= bounds.top &&
resultRow.bottom <= bounds.bottom
);
}),
)
.toBe(true);
await row.click();
await row.press("ArrowRight");
await expect(result.getByText("tax", { exact: true })).toBeVisible();
await field.fill("otherExpression");
await dialog.getByRole("button", { name: "History", exact: true }).click();
await page.getByRole("menuitem", { name: /orderSummary/ }).click();
await expect(field).toHaveValue(expression);
await expect(field).toBeFocused();
});
+63
Переглянути файл
@@ -0,0 +1,63 @@
import { expect, stubDesktop, test } from "./fixtures";
const amountName = "regionalSettlementAmountFromExternalProcessorBeforeRounding";
const routingName = "settlementRoutingReferenceForCrossBorderReconciliation";
const routingValue = "'APR-2026 / eu-west / batch-701 / settlement complete'";
test("keeps values and their full-value action readable in a narrow debugger", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1220, height: 760 });
await stubDesktop(page);
await page.evaluate(
async ({ amountName, routingName, routingValue }) => {
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);
const h = window.__ipc.handlers;
h.debug_scopes = () => [{ name: "Locals", variablesReference: 100, expensive: false }];
h.debug_variables = () => [
{ name: amountName, value: "47.74", typeName: "float", variablesReference: 0, evaluateName: amountName },
{ name: routingName, value: routingValue, typeName: "str", variablesReference: 0, evaluateName: routingName },
];
adoptSession(91, {
name: "Checkout",
adapter: "debugpy",
status: "paused",
selectedFrame: 11,
frames: [{ id: 11, name: "checkout", path: null, line: 0, column: 0, presentationHint: null }],
});
moveToolWindow("debug", "right");
setToolWindowSize("right", 390);
toolWindowService().show("debug", true);
},
{ amountName, routingName, routingValue },
);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click();
const amount = debug.getByText("47.74", { exact: true });
await expect
.poll(() => amount.evaluate((el) => el.clientWidth > 0 && el.scrollWidth <= el.clientWidth + 1))
.toBe(true);
const routing = debug.getByRole("treeitem").filter({ hasText: routingName });
const show = routing.getByTitle("Show", { exact: true });
await expect(show).toBeInViewport({ ratio: 1 });
await show.click();
const dialog = page.getByRole("dialog", { name: `Value of ${routingName}` });
await expect(dialog.getByText(routingValue, { exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await expect(dialog).toBeHidden();
await page.setViewportSize({ width: 1640, height: 760 });
await page.evaluate(async () => {
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { moveToolWindow } = await import(/* @vite-ignore */ layoutModule);
moveToolWindow("debug", "bottom");
});
await expect(show).toBeHidden();
await expect
.poll(() => routing.getByText(routingValue, { exact: true }).evaluate((el) => el.scrollWidth <= el.clientWidth + 1))
.toBe(true);
});
+112
Переглянути файл
@@ -133,6 +133,64 @@ test("breadcrumbs follow the caret into the symbol under it", async ({ workbench
await expect(bar).toBeHidden();
});
test("narrow breadcrumb bars keep the current symbol visible and allow opening earlier crumbs", async ({
workbench: page,
}) => {
const editor = await openFromTree(page, "build.gradle.kts");
const path = page.getByRole("navigation", { name: "Breadcrumbs", exact: true });
const code = page.getByRole("navigation", { name: "Code breadcrumbs" });
await editor.locator(".cm-line", { hasText: "service.find(status" }).click();
await expect(code).toContainText("list()");
await page.evaluate(async () => {
const documentModule = "/src/editor/core/model/document.ts";
const editorModule = "/src/editor/core/controller.ts";
const projectModule = "/src/platform/project.ts";
const schemaModule = "/src/features/settings/model/schema.ts";
const [{ useOutline }, { useEditorStatus }, { useProject }, { DEFAULT_SETTINGS }] = await Promise.all([
import(/* @vite-ignore */ documentModule),
import(/* @vite-ignore */ editorModule),
import(/* @vite-ignore */ projectModule),
import(/* @vite-ignore */ schemaModule),
]);
const base = useProject.getState().settings ?? DEFAULT_SETTINGS;
useProject.setState({ settings: { ...base, editor: { ...base.editor, fontSize: 17 } } });
const activePath = useEditorStatus.getState().status.path;
let outline = useOutline.getState()[activePath];
for (const name of ["OrderProcessingStrategies", "SalesApplicationRouting", "CheckoutWorkspaceConfiguration"]) {
outline = [{ ...outline[0], name, detail: null, children: outline }];
}
useOutline.setState({ [activePath]: outline });
});
await page.setViewportSize({ width: 620, height: 620 });
const fullyInBar = (bar: typeof path, label: string) =>
bar.evaluate((nav, text) => {
const crumb = [...nav.querySelectorAll("button")].find((button) => button.textContent === text);
if (!crumb) return false;
const { left, right } = nav.getBoundingClientRect();
const rect = crumb.getBoundingClientRect();
return rect.width > 0 && rect.left >= left - 1 && rect.right <= right + 1;
}, label);
for (const bar of [path, code]) {
await expect.poll(() => fullyInBar(bar, "list()")).toBe(true);
await expect(bar.locator('[aria-current="location"]')).toHaveText("list()");
}
await expect(code.locator('[aria-current="location"]')).toHaveCSS("font-size", "17px");
await code.hover();
await page.mouse.wheel(0, -1200);
await expect.poll(() => fullyInBar(code, "CheckoutWorkspaceConfiguration")).toBe(true);
const current = path.locator('[aria-current="location"]');
await current.focus();
await current.press("Home");
const project = path.getByRole("button", { name: /acme-api/ }).first();
await expect(project).toBeFocused();
await expect.poll(() => fullyInBar(path, "acme-api")).toBe(true);
await project.press("ArrowDown");
await expect(page.getByRole("listbox", { name: "acme-api" })).toBeVisible();
});
/** What the in-memory backend has saved for `path`. */
const saved = (page: Page, path: string) =>
page.evaluate(async (path) => {
@@ -174,6 +232,48 @@ test("⌘R replaces every match in the file", async ({ workbench: page }) => {
await expect(editor.locator(".cm-line", { hasText: "OrderDto" })).toHaveCount(2);
});
test("the inline find and replace controls stay inside a narrow editor pane", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 760 });
const editor = await openFromTree(page, "build.gradle.kts");
await editor.locator(".cm-content").click();
await page.keyboard.press("Meta+r");
const bar = page.getByRole("search", { name: "Replace in file" });
const find = bar.getByRole("textbox", { name: "Find" });
const replace = bar.getByRole("textbox", { name: "Replace" });
const next = bar.getByRole("button", { name: /Next Occurrence/ });
await find.fill("OrderDto");
await find.press("Tab");
await expect(replace).toBeFocused();
await replace.fill("OrderView");
const navigationIsBelowFind = async () => {
const [input, button] = await Promise.all([find.boundingBox(), next.boundingBox()]);
return !!input && !!button && button.y >= input.y + input.height;
};
const controlsFit = () =>
bar.evaluate((panel) => {
const bounds = panel.getBoundingClientRect();
return [...panel.querySelectorAll("button, textarea")].every((element) => {
const control = element.getBoundingClientRect();
return control.width > 0 && control.left >= bounds.left && control.right <= bounds.right;
});
});
await expect.poll(navigationIsBelowFind).toBe(false);
await page.setViewportSize({ width: 590, height: 760 });
await expect.poll(controlsFit).toBe(true);
await expect.poll(navigationIsBelowFind).toBe(true);
await page.setViewportSize({ width: 495, height: 760 });
await expect.poll(controlsFit).toBe(true);
await expect(find).toHaveValue("OrderDto");
await expect(replace).toHaveValue("OrderView");
await next.click();
await expect(bar.getByText(/^[12]\/2$/)).toBeVisible();
await bar.getByRole("button", { name: "Replace All" }).click();
await expect(editor.locator(".cm-line", { hasText: "OrderView" })).toHaveCount(2);
await bar.getByRole("button", { name: "Close", exact: true }).click();
await expect(bar).toBeHidden();
});
test("Markdown preview highlights ⌘F matches, selected words and scales diagrams with font zoom", async ({
workbench: page,
}) => {
@@ -538,3 +638,15 @@ test("dragging the Markdown split divider resizes and reflows editor and preview
.poll(async () => Math.round((await reopenedEditor.boundingBox())!.width))
.toBe(Math.round(initialEditor));
});
test("Markdown Preview only leaves the Project view clickable", async ({ workbench: page }) => {
await openFromTree(page, "README.md");
await page.getByRole("button", { name: "Preview Only" }).click();
await expect(page.getByRole("document", { name: "Markdown preview" })).toBeVisible();
const row = page.getByRole("treeitem", { name: "build.gradle.kts", exact: true });
// A hidden editor panel used to leave an implicit resize region over everything left of the preview,
// which swallowed the click.
await row.click();
await expect(row).toHaveAttribute("aria-selected", "true");
});
+3 -4
Переглянути файл
@@ -45,11 +45,10 @@ POST https://example.test/messages
const json = document.createElement("div");
json.id = "json";
document.body.append(json);
const jsonSupport = await loadSupport(findLanguageDescription("JSON", "body.json")!);
if (!jsonSupport) throw new Error("Failed to load JSON support for the highlighting fixture");
new EditorView({
parent: json,
doc: '{"name": "World", "count": 12, "enabled": true, "ready": false, "empty": null, "items": [1]}',
extensions: [
await loadSupport(findLanguageDescription("JSON", "body.json")!),
syntaxHighlighting(openideaHighlightStyle),
],
extensions: [jsonSupport, syntaxHighlighting(openideaHighlightStyle)],
});
+7 -4
Переглянути файл
@@ -1,4 +1,5 @@
import { readFileSync } from "node:fs";
import type * as EditorBackend from "../src/editor/core/backend";
import { expect, test } from "./fixtures";
const xml = readFileSync(
@@ -10,13 +11,14 @@ test("imported PHP colours stay separate from Java and preserve regular text on
workbench: page,
}, info) => {
await page.evaluate(async (xml) => {
// Load the workbench modules in the browser's Vite realm.
const iclsPath = "/src/platform/icls.ts";
const projectPath = "/src/platform/project.ts";
const backendPath = "/src/editor/core/backend.ts";
const contributionsPath = "/src/workbench/contributions.ts";
const { parseIcls } = await import(iclsPath);
const { useProject } = await import(projectPath);
const { docBackend } = await import(backendPath);
const { docBackend }: typeof EditorBackend = await import(backendPath);
const { editorService } = await import(contributionsPath);
const previous = useProject.getState().settings ?? {};
useProject.setState({
@@ -31,10 +33,11 @@ test("imported PHP colours stay separate from Java and preserve regular text on
},
});
const backend = docBackend();
if (!("files" in backend) || !(backend.files instanceof Map)) throw new Error("Expected the in-memory backend");
const open = backend.open.bind(backend);
backend.open = async (...args: Parameters<typeof open>) => {
const result = await open(...args);
return args[0].endsWith(".php") ? { ...result, language: "php", uiMode: "PHP" } : result;
backend.open = async (path) => {
const result = await open(path);
return path.endsWith(".php") ? { ...result, language: "php", uiMode: "PHP" } : result;
};
backend.files.set(
"/dev/acme-api/palette.php",
+2 -1
Переглянути файл
@@ -1,5 +1,6 @@
import { EditorView } from "@codemirror/view";
import { commands, type InlayHint, type Range } from "../src/platform/ipc";
import type { InlayHint, Range } from "../src/bindings";
import { commands } from "../src/platform/ipc";
import { setInvokeRoute } from "../src/platform/tauriCore";
import { lspDoc } from "../src/editor/lsp/lsp";
import { inlayExtension } from "../src/editor/lsp/inlay";
+16 -11
Переглянути файл
@@ -1,3 +1,4 @@
import type { DataSource_Deserialize, DbJdbcDriver } from "../src/bindings";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("configures a local JDBC profile and a source through mocked IPC", async ({ workbench: page }, info) => {
@@ -102,21 +103,25 @@ test("configures a local JDBC profile and a source through mocked IPC", async ({
await source.getByLabel("Property value", { exact: true }).fill("true");
await test.click();
await expect(source.getByRole("status")).toHaveText("Succeeded: Mock JDBC database");
const [{ source: tested, password }] = await ipcCalls(page, "db_test");
expect(password).toBe("mock secret");
const [tested] = await ipcCalls(page, "db_test");
expect(tested).toMatchObject({
driver: "jdbc",
url,
user: "example-user",
readOnly: true,
properties: [{ name: "ssl", value: "true" }],
password: "mock secret",
source: {
driver: "jdbc",
url,
user: "example-user",
readOnly: true,
properties: [{ name: "ssl", value: "true" }],
},
});
await source.getByRole("button", { name: "OK", exact: true }).click();
await expect(source).not.toBeVisible();
const [{ sources }] = await ipcCalls(page, "db_save_sources");
const [saved] = sources as Record<string, unknown>[];
const [{ driver }] = await ipcCalls(page, "db_save_jdbc_driver");
const [save] = await ipcCalls(page, "db_save_sources");
const saved = (save?.sources as DataSource_Deserialize[] | undefined)?.[0];
const [profile] = await ipcCalls(page, "db_save_jdbc_driver");
const driver = profile?.driver as DbJdbcDriver | undefined;
if (!saved || !driver) throw new Error("Expected the JDBC source and driver to be saved");
expect(saved.readOnly).toBe(true);
expect(saved.jdbcDriver).toBe((driver as Record<string, unknown>).id);
expect(saved.jdbcDriver).toBe(driver.id);
for (const key of ["jars", "className", "classpath", "exec", "password"]) expect(saved).not.toHaveProperty(key);
});
+3 -3
Переглянути файл
@@ -1,5 +1,5 @@
/** Linked Gradle builds use isolated native stubs; no real builds or files are touched. */
import type { GradleModel, RunConfig } from "../src/platform/ipc";
import type { GradleModel, RunConfig_Deserialize } from "../src/bindings";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const build = (dir: string): GradleModel => ({
@@ -46,7 +46,7 @@ test("links independent Gradle roots, runs identical task paths in their own bui
};
h["plugin:dialog|open"] = () => ["/dev/acme-api/second/settings.gradle"];
h.run_start = (args) => {
const config = args.config as RunConfig;
const config = args.config as RunConfig_Deserialize;
const id = ++runId;
setTimeout(() => window.__ipc.emit({ type: "runExited", run: id, code: 0 }), 50);
return { id, configId: config.id, name: config.name, pid: 4242 + id, running: true, pty: false };
@@ -89,7 +89,7 @@ test("links independent Gradle roots, runs identical task paths in their own bui
await expect.poll(async () => (await ipcCalls(page, "run_start")).length).toBe(1);
await tasks.nth(1).dblclick();
await expect.poll(async () => (await ipcCalls(page, "run_start")).length).toBe(2);
const runs = (await ipcCalls(page, "run_start")).map((args) => args.config as RunConfig);
const runs = (await ipcCalls(page, "run_start")).map((args) => args.config as RunConfig_Deserialize);
expect(runs[0]!.id).not.toBe(runs[1]!.id);
for (const [index, dir] of ["first", "second"].entries()) {
expect(runs[index]).toMatchObject({
+38
Переглянути файл
@@ -63,6 +63,44 @@ const result = (page: Page) => page.getByRole("region", { name: "Result" });
const text = async (pane: Locator) => (await pane.locator(".cm-content").innerText()).replace(/​/g, "");
const status = (page: Page) => page.locator("#merge-host [class*=status]").first();
test("merge controls and pane titles fit while resizing the result", async ({ page }) => {
await page.setViewportSize({ width: 400, height: 600 });
await mountMerge(page);
const host = page.locator("#merge-host");
for (const name of ["Accept Yours", "Accept Theirs", "Cancel", "Apply"])
await expect(host.getByRole("button", { name, exact: true })).toBeInViewport({ ratio: 1 });
await expect(status(page)).toHaveText("3 changes left, 2 conflicts");
await expect(status(page)).toBeInViewport({ ratio: 1 });
const ours = page.getByRole("region", { name: "Your version" });
await expect(ours.getByText("Your version", { exact: true })).toBeVisible();
await expect(
page.getByRole("region", { name: "Their version" }).getByText("Their version", { exact: true }),
).toBeVisible();
await ours.locator(".cm-merge-accept").nth(1).focus();
await page.keyboard.press("Enter");
await expect.poll(() => text(result(page))).toContain("\nmine\n");
await page.setViewportSize({ width: 980, height: 660 });
const resultWidth = async () => (await result(page).boundingBox())!.width;
const initial = await resultWidth();
const left = host.getByRole("separator", { name: "Resize left merge pane" });
await left.press("ArrowLeft");
await expect.poll(resultWidth).toBeGreaterThan(initial + 1);
const right = host.getByRole("separator", { name: "Resize right merge pane" });
const grip = (await right.boundingBox())!;
const withLeftResized = await resultWidth();
await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2);
await page.mouse.down();
await page.mouse.move(grip.x + grip.width / 2 + 36, grip.y + grip.height / 2, { steps: 4 });
await page.mouse.up();
await expect.poll(resultWidth).toBeGreaterThan(withLeftResized + 20);
await expect(result(page).getByText("Result", { exact: true })).toBeVisible();
await expect(ours.getByText("Changes from main", { exact: true })).toBeVisible();
await expect.poll(() => text(result(page))).toContain("\nmine\n");
});
/** Capture the save boundary, keeping real editor state, dialogs and Apply behavior. */
async function captureWrites(page: Page) {
await page.evaluate(async () => {
+76
Переглянути файл
@@ -0,0 +1,76 @@
import type { Page } from "@playwright/test";
import type { SignatureHelp } from "../src/bindings";
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
function signature(name: string, parameters: string[]) {
let offset = name.length + 1;
const ranges: [number, number][] = parameters.map((parameter) => {
const range: [number, number] = [offset, offset + parameter.length];
offset = range[1] + 2;
return range;
});
return { label: `${name}(${parameters.join(", ")}): Invoice`, parameters: ranges, documentation: null };
}
async function openParameterInfo(page: Page, help: SignatureHelp) {
const editor = await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate((help) => {
window.__ipc.handlers.lsp_signature_help = () => help;
}, help);
await editor.locator(".cm-line", { hasText: "return order.toDto()" }).click();
await page.keyboard.press("End");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("Meta+p");
const popup = page.locator(".cm-lsp-signature");
await expect(popup).toBeVisible();
return { editor, popup };
}
test("parameter info wraps long parameters and follows the editor width", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 700 });
const parameter = "roundingPolicyForThirdPartyPaymentsWithMultipleSettlementCurrencies: RoundingPolicy";
const { editor, popup } = await openParameterInfo(page, {
signatures: [signature("formatInvoice", ["order: Cart", parameter, "currency: string"])],
activeSignature: 0,
activeParameter: 1,
});
await page.setViewportSize({ width: 560, height: 650 });
await expect
.poll(async () => {
const [pane, hint] = await Promise.all([editor.boundingBox(), popup.boundingBox()]);
return !!pane && !!hint && hint.x >= pane.x - 1 && hint.x + hint.width <= pane.x + pane.width + 1;
})
.toBe(true);
await expect.poll(() => popup.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(popup.locator("b")).toHaveText(parameter);
const fontSize = await editor.locator(".cm-content").evaluate((el) => getComputedStyle(el).fontSize);
await expect(popup).toHaveCSS("font-size", fontSize);
await page.keyboard.press("Escape");
await expect(popup).toBeHidden();
});
test("parameter info keeps the active overload visible and scrolls to the others", async ({ workbench: page }) => {
const signatures = Array.from({ length: 20 }, (_, i) =>
signature("formatInvoice", [`order: Cart${i}`, "currency: string"]),
);
const { popup } = await openParameterInfo(page, { signatures, activeSignature: 16, activeParameter: 1 });
await expect(popup.locator(".cm-lsp-signature-row")).toHaveCount(signatures.length);
const active = popup.locator(".cm-lsp-signature-active b");
await expect(active).toHaveText("currency: string");
await expect
.poll(async () => {
const [frame, parameter] = await Promise.all([popup.boundingBox(), active.boundingBox()]);
return (
!!frame && !!parameter && parameter.y >= frame.y && parameter.y + parameter.height <= frame.y + frame.height
);
})
.toBe(true);
expect(await popup.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
await popup.hover();
await page.mouse.wheel(0, -1200);
await expect.poll(() => popup.evaluate((el) => el.scrollTop)).toBe(0);
await expect(
popup.getByText("formatInvoice(order: Cart0, currency: string): Invoice", { exact: true }),
).toBeInViewport();
});
+120 -42
Переглянути файл
@@ -9,50 +9,75 @@ import { expect, stubDesktop, test } from "./fixtures";
const ROOT = "/dev/acme-api";
const HUGE = `feature/wrap-${"x".repeat(140)}`;
async function openPushDialog(page: Page) {
const OUTGOING = "Apply order-level discounts before calculating checkout taxes";
async function openPushDialog(page: Page, { outgoing = false, multi = false } = {}) {
await stubDesktop(page);
await page.evaluate(async (root) => {
const h = window.__ipc.handlers;
h.vcs_roots = () => [{ root, operation: null, head: "main", headCommit: "1111111" }];
h.vcs_branch_info = () => ({
head: "main",
headCommit: "1111111",
upstream: "origin/main",
ahead: 0,
behind: 0,
operation: null,
});
h.vcs_status = () => [];
h.vcs_log = () => [];
h.vcs_remotes = () => [{ name: "origin", url: "[email protected]:acme/api.git" }];
const branch = (name: string, remote: boolean, upstream: string | null = null) => ({
name,
remote,
current: !remote,
upstream,
ahead: 0,
behind: 0,
lastCommitMs: 0,
});
h.vcs_branches = () => [
branch("main", false, "origin/main"),
branch("feature/login", false),
branch("origin/main", true),
branch("origin/feature/login", true),
branch("origin/fix/error-auth", true),
branch("origin/feature/PLATFORM-12345-order-history-export", true),
branch(`origin/feature/wrap-${"x".repeat(140)}`, true),
];
const vcsModule = "/src/features/vcs/store.ts";
const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsModule);
useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false });
await refreshNow();
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
void executeAction("vcs.push");
}, ROOT);
await page.evaluate(
async ({ root, outgoing, multi, subject }) => {
const h = window.__ipc.handlers;
const head = multi ? "feature/refine-checkout-pricing-and-order-summary-for-regional-release" : "main";
const roots = multi ? [root, `${root}/billing-and-refunds`] : [root];
h.vcs_roots = () => roots.map((root) => ({ root, operation: null, head, headCommit: "1111111" }));
h.vcs_branch_info = () => ({
head,
headCommit: "1111111",
upstream: `origin/${head}`,
ahead: outgoing ? 1 : 0,
behind: 0,
operation: null,
});
h.vcs_status = () => [];
h.vcs_log = () =>
outgoing
? [
{
id: "2222222",
shortId: "2222222",
parents: ["1111111"],
summary: subject,
message: subject + "\n\nKeep the new totals consistent with receipts.",
author: "Sam Rivera",
email: "[email protected]",
timeMs: 1795100000000,
},
]
: [];
h.vcs_commit_files = () => [{ path: "checkout.ts", oldPath: null, kind: "modified" }];
h.vcs_has_hook = () => false;
h.vcs_remotes = () => [{ name: "origin", url: "[email protected]:acme/api.git" }];
const branch = (name: string, remote: boolean, upstream: string | null = null) => ({
name,
remote,
current: !remote,
upstream,
ahead: 0,
behind: 0,
lastCommitMs: 0,
});
h.vcs_branches = () => [
branch("main", false, "origin/main"),
branch("feature/login", false),
branch("origin/main", true),
branch("origin/feature/login", true),
branch("origin/fix/error-auth", true),
branch("origin/feature/PLATFORM-12345-order-history-export", true),
branch(`origin/feature/wrap-${"x".repeat(140)}`, true),
];
const vcsModule = "/src/features/vcs/store.ts";
const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsModule);
useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false });
await refreshNow();
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
void executeAction("vcs.push");
},
{ root: ROOT, outgoing, multi, subject: OUTGOING },
);
const dialog = page.getByRole("dialog", { name: /Push/ });
const input = dialog.getByRole("combobox", { name: "Target branch" });
const input = multi
? dialog.getByRole("textbox", { name: "Target branch of acme-api" })
: dialog.getByRole("combobox", { name: "Target branch" });
await expect(input).toBeVisible();
return { dialog, input };
}
@@ -127,3 +152,56 @@ test("Escape closes the list but keeps the dialog", async ({ workbench: page })
await expect(page.getByRole("listbox", { name: "Remote branches" })).toHaveCount(0);
await expect(dialog).toBeVisible();
});
test("Push keeps commit subjects and changed files readable in a narrow window", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1140, height: 760 });
const { dialog, input } = await openPushDialog(page, { outgoing: true });
const outgoing = dialog.getByRole("listbox", { name: "Outgoing commits" });
const files = dialog.getByRole("tree", { name: "Changed files" });
const commit = outgoing.getByRole("option", { name: new RegExp(OUTGOING) });
await commit.click();
await expect(files.getByText("checkout.ts")).toBeVisible();
const filesBelowCommits = async () => {
const [list, tree] = await Promise.all([outgoing.boundingBox(), files.boundingBox()]);
return !!list && !!tree && tree.y >= list.y + list.height;
};
await expect.poll(filesBelowCommits).toBe(false);
await page.setViewportSize({ width: 540, height: 630 });
await expect.poll(filesBelowCommits).toBe(true);
await expect(commit).toHaveAttribute("aria-selected", "true");
const subject = commit.getByText(OUTGOING, { exact: true });
await expect(subject).toHaveAttribute("title", /Sam Rivera/);
await expect.poll(() => subject.evaluate((el) => el.scrollWidth <= el.clientWidth)).toBe(true);
await expect(input).toHaveValue("main");
await expect(dialog.getByRole("button", { name: "Push", exact: true })).toBeInViewport();
const details = dialog.getByRole("region", { name: "Commit details" });
await expect(details).toContainText("Keep the new totals consistent with receipts.");
await expect
.poll(async () => {
const [tree, message] = await Promise.all([files.boundingBox(), details.boundingBox()]);
return !!tree && !!message && message.y >= tree.y + tree.height;
})
.toBe(true);
});
test("Push keeps per-repository targets editable with long source branches", async ({ workbench: page }) => {
await page.setViewportSize({ width: 475, height: 620 });
const { dialog, input } = await openPushDialog(page, { outgoing: true, multi: true });
const other = dialog.getByRole("textbox", { name: "Target branch of billing-and-refunds" });
for (const field of [input, other]) {
await expect
.poll(() =>
field.evaluate((target) => {
const row = target.closest('[role="treeitem"]')!.getBoundingClientRect();
const bounds = target.getBoundingClientRect();
return bounds.width >= 42 && bounds.left >= row.left && bounds.right <= row.right;
}),
)
.toBe(true);
}
await input.fill("release/checkout");
await expect(input).toHaveValue("release/checkout");
await expect(other).toHaveValue(/^feature\//);
await expect(dialog.getByRole("checkbox", { name: "acme-api" })).toBeChecked();
});
+73
Переглянути файл
@@ -0,0 +1,73 @@
import type { Page } from "@playwright/test";
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
async function quickDocumentation(page: Page, markdown: string) {
const editor = await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate((value) => {
window.__ipc.handlers.lsp_hover = () => ({ contents: { kind: "markdown", value }, range: null });
}, markdown);
const line = editor.locator(".cm-line", { hasText: "return order.toDto()" });
await line.click();
await page.keyboard.press("End");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("F1");
const popup = page.getByRole("dialog", { name: "Documentation", exact: true });
await expect(popup.locator(".cm-lsp-markdown")).toBeVisible();
return popup;
}
test("short quick documentation uses a readable width and a compact corner of actions", async ({ workbench: page }) => {
const popup = await quickDocumentation(page, "Returns the total.");
const back = popup.getByRole("button", { name: "Back", exact: true });
const dock = popup.getByRole("button", { name: "Show in Documentation Tool Window" });
await expect(dock).toBeVisible();
const bounds = (await popup.boundingBox())!;
expect(bounds.width).toBeGreaterThanOrEqual(298);
expect(bounds.width).toBeLessThan(320);
const backBounds = (await back.boundingBox())!;
const dockBounds = (await dock.boundingBox())!;
expect(backBounds.x).toBeGreaterThan(bounds.x + bounds.width / 2);
expect(bounds.x + bounds.width - dockBounds.x - dockBounds.width).toBeLessThan(16);
await expect(popup.locator(".cm-lsp-markdown")).toHaveCSS("font-size", "13px");
await page.keyboard.press("Escape");
await expect(popup).toBeHidden();
});
test("long quick documentation scrolls with its actions in view", async ({ workbench: page }) => {
const signature = "fun calculateTotal(order: Order, options: ExtendedPricingOptions): CalculationResult";
const markdown = [
`\`\`\`kotlin\n${signature}\n\`\`\``,
...Array.from({ length: 22 }, (_, i) => {
return `Section ${i + 1}. Explains the applicable pricing rules, shipping restrictions and currency options.`;
}),
"End of pricing documentation.",
].join("\n\n");
const popup = await quickDocumentation(page, markdown);
const dock = popup.getByRole("button", { name: "Show in Documentation Tool Window" });
await expect(dock).toBeVisible();
expect((await popup.boundingBox())!.width).toBeLessThan(508);
await page.setViewportSize({ width: 430, height: 500 });
await expect
.poll(async () => {
const box = (await popup.boundingBox())!;
return Math.max(-box.x, -box.y, box.x + box.width - 430, box.y + box.height - 500);
})
.toBeLessThanOrEqual(1);
const body = popup.locator(".cm-lsp-markdown").locator("..");
const last = popup.getByText("End of pricing documentation.");
const dockBefore = (await dock.boundingBox())!;
await expect(body.locator("pre")).toContainText(signature);
const scroll = await body.evaluate((node) => {
node.scrollTop = node.scrollHeight;
return { top: node.scrollTop, horizontalOverflow: node.scrollWidth - node.clientWidth };
});
expect(scroll.top).toBeGreaterThan(0);
expect(scroll.horizontalOverflow).toBeLessThanOrEqual(1);
const lastBounds = (await last.boundingBox())!;
expect(lastBounds.y + lastBounds.height).toBeLessThanOrEqual(dockBefore.y + 1);
expect(await dock.boundingBox()).toEqual(dockBefore);
await expect(dock).toBeInViewport();
});
+76 -3
Переглянути файл
@@ -3,15 +3,21 @@
* the process. Processes are stubbed at the IPC layer; `crates/ide-run` covers spawning them.
*/
import type { Page } from "@playwright/test";
import type { RunConfig } from "../src/bindings";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const RUN_ID = 7;
/** One saved `npm run dev` configuration; `run_start` prints `output` and exits with `exit` unless null. */
async function stubRun(page: Page, output: { kind: string; text: string }[], exit: number | null) {
async function stubRun(
page: Page,
output: { kind: string; text: string }[],
exit: number | null,
overrides: Partial<RunConfig> = {},
) {
await stubDesktop(page);
await page.evaluate(
async ({ output, exit, runId }) => {
async ({ output, exit, runId, overrides }) => {
const config = {
id: "npm:dev",
name: "dev",
@@ -23,6 +29,7 @@ async function stubRun(page: Page, output: { kind: string; text: string }[], exi
detected: false,
isTest: false,
debugAdapter: null,
...overrides,
};
const h = window.__ipc.handlers;
h.run_configs = () => [config];
@@ -43,7 +50,7 @@ async function stubRun(page: Page, output: { kind: string; text: string }[], exi
await loadConfigs();
selectConfig(config.id);
},
{ output, exit, runId: RUN_ID },
{ output, exit, runId: RUN_ID, overrides },
);
}
@@ -177,6 +184,72 @@ test("Go reruns keep each package's exact failures and the original configuratio
]);
});
test("test results keep counts, actions and selected output visible as the pane narrows", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1060, height: 740 });
const goPackage = "example.com/checkout";
const name = "TestCheckoutTotalsWithDiscountsAndPendingInventoryReservations";
const message = "expected subtotal 42, got 37";
const records = [
{ Action: "run", Test: name },
{ Action: "output", Test: name, Output: message + "\n" },
{ Action: "fail", Test: name, Elapsed: 0.125 },
{ Action: "pass", Test: "TestPayment", Elapsed: 0.02 },
{ Action: "skip", Test: "TestDelayedShipping" },
{ Action: "fail", Elapsed: 0.17 },
];
await stubRun(
page,
records.map((record) => ({ kind: "stdout", text: JSON.stringify({ Package: goPackage, ...record }) + "\n" })),
1,
{
id: "go:checkout-tests",
name: "Checkout tests",
kind: "go",
command: "go",
args: ["test", "-json"],
isTest: true,
},
);
await page.keyboard.press("Control+r");
const run = page.getByRole("region", { name: "Run", exact: true });
const tree = run.getByRole("tree", { name: "Test results" });
const row = tree.getByRole("treeitem", { name: new RegExp(name) });
await row.click();
const output = run.getByRole("log");
await expect(output).toContainText(message);
await expect.poll(async () => (await output.boundingBox())!.x > (await tree.boundingBox())!.x).toBe(true);
await page.setViewportSize({ width: 540, height: 740 });
await expect
.poll(async () => {
const [list, console] = await Promise.all([tree.boundingBox(), output.boundingBox()]);
return !!list && !!console && console.y >= list.y + list.height - 1;
})
.toBe(true);
const summary = run.getByRole("status").filter({ hasText: "1 failing" });
for (const count of ["1 failing", "1 passed", "1 ignored"]) await expect(summary.getByText(count)).toBeVisible();
await expect(row).toHaveAttribute("aria-selected", "true");
await expect(row.getByText("125 ms")).toBeVisible();
await expect(output).toContainText(message);
const toolbar = run.getByRole("toolbar", { name: "Test results" });
await toolbar.getByRole("button", { name: "More Actions" }).click();
await expect(page.getByRole("menuitem", { name: "Collapse All" })).toBeVisible();
await expect(page.getByRole("menuitem", { name: "Export Test Results…" })).toBeVisible();
await page.keyboard.press("Escape");
const divider = run.getByRole("separator");
const treeHeight = async () => (await tree.boundingBox())!.height;
const beforeResize = await treeHeight();
await divider.press("ArrowDown");
await expect.poll(treeHeight).toBeGreaterThan(beforeResize + 1);
const customizedHeight = await treeHeight();
await page.setViewportSize({ width: 1060, height: 740 });
await expect.poll(async () => (await output.boundingBox())!.x > (await tree.boundingBox())!.x).toBe(true);
await page.setViewportSize({ width: 540, height: 740 });
await expect.poll(async () => Math.abs((await treeHeight()) - customizedHeight)).toBeLessThan(2);
await expect(output).toContainText(message);
});
test("CMake builds the selected target in Build before starting only the application in Run", async ({
workbench: page,
}) => {
+79
Переглянути файл
@@ -0,0 +1,79 @@
import { expect, test } from "./fixtures";
test("Run Anything keeps its command field and shortcuts visible as its results scroll", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1080, height: 740 });
await page.evaluate(async () => {
const projectModule = "/src/platform/project.ts";
const contributionsModule = "/src/workbench/contributions.ts";
const historyModule = "/src/features/run-anything/model.ts";
const [{ useProject }, { registerRunAnythingProvider }, { pushHistory }] = await Promise.all([
import(/* @vite-ignore */ projectModule),
import(/* @vite-ignore */ contributionsModule),
import(/* @vite-ignore */ historyModule),
]);
const root = useProject.getState().project.root;
for (const command of ["git status", "git diff --stat", "pnpm lint", "pnpm test"]) pushHistory(root, command);
const tasks = Array.from({ length: 8 }, (_, i) => {
const command = `npm run verify-${i + 1}`;
return {
key: command,
label: `Verify checkout configuration ${i + 1}`,
detail: "checkout-service / workspace verification",
completion: command,
run: () => {
document.body.dataset.runAnythingCommand = command;
},
};
});
registerRunAnythingProvider({
id: "test-verify",
order: -100,
group: "Run Configurations",
items: (line: string) => tasks.filter((task) => task.completion.includes(line)),
});
});
await page.keyboard.press("Control");
await page.keyboard.press("Control");
const popup = page.getByRole("dialog", { name: "Run Anything", exact: true });
const field = popup.getByLabel("Command line", { exact: true });
const results = popup.getByRole("listbox", { name: "Run Anything entries" });
const hint = popup.getByText(/Enter to run, Tab to complete|Tab to complete, Enter to run/);
await expect(field).toBeFocused();
await page.setViewportSize({ width: 560, height: 340 });
await expect
.poll(async () => {
const [shell, footer] = await Promise.all([popup.boundingBox(), hint.boundingBox()]);
return (
!!shell &&
!!footer &&
Math.abs(shell.x - (560 - shell.width) / 2) < 2 &&
shell.x >= 14 &&
footer.y + footer.height <= shell.y + shell.height + 1
);
})
.toBe(true);
await expect.poll(() => results.evaluate((el) => el.scrollHeight > el.clientHeight)).toBe(true);
await field.fill("verify");
await field.press("ArrowDown");
await expect(field).toHaveValue("npm run verify-1");
const selected = results.getByRole("option", { selected: true });
await expect(selected).toContainText("Verify checkout configuration 1");
await expect(field).toHaveAttribute("aria-activedescendant", (await selected.getAttribute("id"))!);
await field.press("Tab");
await expect(field).toHaveValue("npm run verify-1");
await expect(field).toBeFocused();
await field.press("Shift+Tab");
const history = popup.getByRole("button", { name: "Clear History" });
await expect(history).toBeFocused();
await history.press("Enter");
await expect(history).toBeHidden();
await expect(field).toBeFocused();
await field.press("ArrowDown");
await field.press("Enter");
await expect(popup).toBeHidden();
await expect(page.locator("body")).toHaveAttribute("data-run-anything-command", "npm run verify-1");
});
+25 -3
Переглянути файл
@@ -1,8 +1,8 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function openConfigurations(page: Page) {
await page.evaluate(async () => {
async function openConfigurations(page: Page, target?: string) {
await page.evaluate(async (target) => {
const path = "/src/features/run/store.ts";
const { useRun } = await import(/* @vite-ignore */ path);
const base = {
@@ -21,6 +21,7 @@ async function openConfigurations(page: Page) {
...base,
id: "layout:app",
name: "Payments development server",
target,
beforeLaunch: [{ kind: "run", target: "layout:prepare" }],
},
{ ...base, id: "layout:prepare", name: "Prepare generated sources for the payments development server" },
@@ -29,10 +30,31 @@ async function openConfigurations(page: Page) {
loaded: true,
editorOpen: true,
});
});
}, target);
await expect(page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true })).toBeVisible();
}
test("long run target names leave room for configuration names in the sidebar", async ({ workbench: page }) => {
const target = "payments-development-shared-staging-runner-west";
await openConfigurations(page, target);
const dialog = page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true });
const tree = dialog.getByRole("tree", { name: "Run configurations", exact: true });
const row = tree.getByRole("treeitem", { name: /^Payments development server/ });
const name = row.getByText("Payments development server", { exact: true });
const badge = row.getByText(`@ ${target}`, { exact: true });
await expect(badge).toBeVisible();
for (const width of [1100, 520]) {
await page.setViewportSize({ width, height: 820 });
await expect.poll(async () => (await name.boundingBox())!.width).toBeGreaterThan(width === 1100 ? 80 : 50);
await expect.poll(() => tree.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
}
await expect(badge).toBeHidden();
await expect(row).toHaveAttribute("title", new RegExp(`Payments development server @ ${target}`));
await expect(dialog.getByRole("textbox", { name: "Name", exact: true })).toHaveValue("Payments development server");
});
test("run configuration sidebar resizes with mouse and keyboard and remembers the layout", async ({
workbench: page,
}) => {
+8 -4
Переглянути файл
@@ -1,3 +1,4 @@
import type { SearchQuery } from "../src/bindings";
import { doubleShift, expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
test("double Shift opens Search Everywhere with its tabs; Escape closes it", async ({ workbench: page }) => {
@@ -100,11 +101,14 @@ test("Find in Files streams matches by file and opens the chosen one at its line
await expect
.poll(
async () =>
(await ipcCalls(page, "search_start")).filter((c) => !/\bTODO\b/.test(c.query?.pattern ?? "")).at(-1)?.query,
(await ipcCalls(page, "search_start"))
.filter(({ query }) => {
const pattern = query && typeof query === "object" && "pattern" in query ? query.pattern : undefined;
return typeof pattern !== "string" || !/\bTODO\b/.test(pattern);
})
.at(-1)?.query,
)
.toMatchObject({
pattern: "OrderService",
});
.toMatchObject({ pattern: "OrderService" } satisfies Pick<SearchQuery, "pattern">);
const preview = dialog.getByRole("region", { name: "Preview", exact: true }).locator(".cm-content");
await expect(preview).toHaveAttribute("contenteditable", "true");
// Matches take the editor scheme's search result background (IDEA's SEARCH_RESULT_ATTRIBUTES) and keep the syntax colours.
+1 -1
Переглянути файл
@@ -79,7 +79,7 @@ test.describe("search popups at the minimum window width", () => {
[400, 500],
[600, 700],
[1120, 750],
]) {
] as const) {
await page.setViewportSize({ width, height });
await expectControlsFit(page);
// Room enough for the title and the reporter's count: shown whole, on one line.
+2 -2
Переглянути файл
@@ -9,9 +9,9 @@ test("semantic roles honor all Color Scheme attributes and keep modifier styles"
[".cm-sem-function:not(.cm-sem-static)", "rgb(102, 136, 170)"],
[".cm-sem-parameter", "rgb(119, 153, 187)"],
[".cm-sem-constant", "rgb(136, 170, 204)"],
]) {
] as const) {
const role = page.locator(selector);
await expect(role).toHaveCSS("color", color!);
await expect(role).toHaveCSS("color", color);
await expect(role).toHaveCSS("background-color", "rgb(221, 238, 255)");
}
await expect(page.locator(".cm-sem-namespace")).toHaveCSS("font-style", "italic");
+1 -1
Переглянути файл
@@ -6,7 +6,7 @@ for (const [id, selector] of [
["languages.servers", "[class*='body'] > [class*='language'][aria-label]"],
["plugins", "[class*='body'] > [class*='details']"],
["agents.list", "section[aria-label='Codex']"],
]) {
] as const) {
test(`${id} keeps its details usable beside the list`, async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
+4 -8
Переглянути файл
@@ -1,12 +1,8 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"types": ["node"]
"lib": ["ES2024", "DOM", "DOM.Iterable"],
"types": ["node", "vite/client"]
},
"include": ["./**/*.ts", "../playwright.config.ts"]
"include": [".", "../playwright.config.ts", "../src/**/*.d.ts"]
}
+1 -1
Переглянути файл
@@ -17,7 +17,7 @@
"format": "oxfmt",
"format:check": "oxfmt --check",
"knip": "knip",
"typecheck": "tsrs --noEmit && tsrs -p tsconfig.node.json --noEmit && tsrs -p perf --noEmit && tsrs -p evals --noEmit && tsrs -p scripts --noEmit && tsrs -p smoke --noEmit",
"typecheck": "tsrs --noEmit && tsrs -p tsconfig.node.json --noEmit && tsrs -p perf --noEmit && tsrs -p evals --noEmit && tsrs -p scripts --noEmit && tsrs -p smoke --noEmit && tsrs -p e2e --noEmit",
"gen:bindings": "cargo test -p openidea --test export_bindings",
"gen:windows-icons": "node scripts/gen-windows-icons.ts",
"gen:angular-grammar": "lezer-generator src/editor/core/cm/angular/angular.grammar --typeScript -o src/editor/core/cm/angular/parser.ts",
+73 -1
Переглянути файл
@@ -1,9 +1,11 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { EditorController, openFilePaths, useEditorStatus, useTabs } from "./controller";
import { EditorController, openFilePaths, useEditorStatus, useTabErrors, useTabs } from "./controller";
import { createMemoryBackend } from "./backend";
import { initialTabsState } from "./model/tabs";
import { useDocMeta } from "./model/document";
import { storeSession } from "./model/session";
import { resetDistractionFree, setDistractionFree } from "@/workbench/distractionFree";
import * as contributions from "@/workbench/contributions";
import {
registerEditorKind,
registerTextEditorWrapper,
@@ -11,6 +13,7 @@ import {
useProjectViewLead,
} from "@/workbench/contributions";
import { registerActions } from "@/platform/actions";
import { IpcError, type ErrorKind } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useRemote } from "@/platform/remote";
import { hideContextMenu, resolveMenuItems, useContextMenuStore } from "@/ui";
@@ -29,6 +32,75 @@ afterEach(() => {
useEditorStatus.setState({ status: null });
});
describe("restoring an editor session", () => {
const root = "/session-restore";
const existing = `${root}/existing.txt`;
const unavailable = `${root}/unavailable.txt`;
const text = "first\nsecond";
let controller: EditorController | undefined;
afterEach(() => {
controller?.stop();
controller = undefined;
storeSession(root, null);
useTabErrors.setState({}, true);
vi.restoreAllMocks();
});
async function restoreWithOpenError(kind: ErrorKind, message: string) {
storeSession(root, {
version: 1,
layout: { kind: "pane", tabs: [{ path: existing }, { path: unavailable }], active: 1 },
activePane: 0,
files: { [existing]: { anchor: 6, head: 6 } },
});
const backend = createMemoryBackend({ [existing]: text });
// For an absent path the memory backend serves sample text, not a disk error.
const open = backend.open.bind(backend);
vi.spyOn(backend, "open").mockImplementation(async (path) => {
if (path === unavailable) throw new IpcError({ kind, message });
return open(path);
});
const editor = (controller = new EditorController(backend));
editor.start();
const restoring = editor.restoreSession(root);
const state = useTabs.getState();
const selected = state.panes[state.activePane]!.active!;
// Restore opens the selected tab in the background. Join the same slot request.
await Promise.all([restoring, editor.ensureSlot(selected)]);
return { editor, selected };
}
it("silently drops a deleted selected file and restores the remaining tab", async () => {
const notify = vi.fn();
vi.spyOn(contributions, "notifications").mockReturnValue({ notify });
const { editor, selected } = await restoreWithOpenError("notFound", `No such file: ${unavailable}`);
expect(notify).not.toHaveBeenCalled();
expect(useTabErrors.getState()).toEqual({});
expect(openFilePaths(useTabs.getState())).toEqual([existing]);
expect(editor.slotFor(selected)).toBeNull();
expect(editor.activeInput()?.path).toBe(existing);
// In the app the visible tab's editor host requests this slot after selection changes.
const state = useTabs.getState();
const slot = await editor.ensureSlot(state.panes[state.activePane]!.active!);
expect(slot?.model.path).toBe(existing);
expect(slot?.state.doc.toString()).toBe(text);
expect(slot?.caret()).toMatchObject({ line: 1, col: 0 });
});
it("keeps a tab and reports its open error when access is denied", async () => {
const message = `Permission denied: ${unavailable}`;
const { editor, selected } = await restoreWithOpenError("permissionDenied", message);
expect(openFilePaths(useTabs.getState())).toEqual([existing, unavailable]);
expect(editor.activeInput()?.path).toBe(unavailable);
expect(useTabErrors.getState()).toEqual({ [selected]: message });
});
});
describe("EditorController", () => {
it("returns navigation context to the editor when activating a non-text tab", async () => {
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "one\n" }));
+2 -2
Переглянути файл
@@ -47,7 +47,7 @@ import { useDistractionFree } from "@/workbench/distractionFree";
import { restoreMaximizedToolWindow } from "@/workbench/toolwindows/store";
import { ask, confirm } from "@/workbench/messages";
import { t, tx } from "@/platform/i18n";
import { call, commands, isTauri } from "@/platform/ipc";
import { call, commands, isErrorKind, isTauri } from "@/platform/ipc";
import { openLightweightEditor } from "./openLightweightEditor";
import { windowBackgroundHex } from "@/workbench/theme";
import { hoverActionsAt } from "@/platform/hoverActions";
@@ -736,7 +736,7 @@ export class EditorController implements SlotHost {
return this.slots.get(tabId) ?? this.createSlot(tabId, m, init);
})
.catch((e: unknown) => {
if (this.restoredTabs.has(tabId) && (e as { kind?: string } | null)?.kind === "notFound") {
if (this.restoredTabs.has(tabId) && isErrorKind(e, "notFound")) {
// A file from the saved session no longer exists: drop its tab quietly.
this.restoredTabs.delete(tabId);
this.restoredViews.delete(path);
+48 -2
Переглянути файл
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
initialTabsState,
moveTabToNewSplit,
@@ -9,7 +9,15 @@ import {
togglePin,
type TabsState,
} from "./tabs";
import { loadSession, parseSession, restoreTabsState, serializeSession, slashPath } from "./session";
import {
loadSession,
parseSession,
restoreTabsState,
serializeSession,
slashPath,
storeSession,
type EditorSession,
} from "./session";
const file = (path: string) => ({ kind: "file", key: `file:${path}`, path });
const fileKey = (p: string) => `file:${p}`;
@@ -103,6 +111,44 @@ describe("editor session", () => {
});
});
describe("loading a session with malformed JSON", () => {
const root = "/malformed-session";
const key = `openidea.editorSession.v1:${root}`;
const malformed = '{"version":1,"layout":{"kind":"pane","tabs":[';
beforeEach(() => localStorage.setItem(key, malformed));
afterEach(() => {
vi.restoreAllMocks();
localStorage.removeItem(key);
});
it("returns null without writing to storage or changing the saved bytes", () => {
const before = localStorage.getItem(key);
expect(before).toBe(malformed);
const setItem = vi.spyOn(Storage.prototype, "setItem");
expect(loadSession(root)).toBeNull();
expect(localStorage.getItem(key)).toBe(before);
expect(setItem).not.toHaveBeenCalled();
});
it("loads a valid session after an explicit save replaces malformed JSON", () => {
expect(loadSession(root)).toBeNull();
const path = `${root}/recovered.ts`;
const recovered: EditorSession = {
version: 1,
layout: { kind: "pane", tabs: [{ path }], active: 0 },
activePane: 0,
files: { [path]: { anchor: 1, head: 2 } },
};
storeSession(root, recovered);
expect(JSON.parse(localStorage.getItem(key)!)).toEqual(recovered);
expect(loadSession(root)).toEqual(recovered);
});
});
describe("moveTabToNewSplit", () => {
it("moves a tab into a new pane on the given edge", () => {
let s = initialTabsState();
+2 -2
Переглянути файл
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { ChangeSet, Text } from "@codemirror/state";
import type { TextChange } from "@/platform/ipc";
import type { IdeError, TextChange } from "@/platform/ipc";
import { DocSync, toTextChanges } from "./DocSync";
import { minimalChanges } from "./diff";
@@ -19,7 +19,7 @@ function numberedLines(count: number) {
}
class OutOfSync extends Error {
kind = "outOfSync";
readonly kind: IdeError["kind"] = "outOfSync";
}
/** Backend double: requests are queued and processed explicitly, in order. */
+2 -6
Переглянути файл
@@ -25,7 +25,7 @@
* the snapshot, selections mapped).
*/
import { ChangeSet, Text } from "@codemirror/state";
import type { TextChange } from "@/platform/ipc";
import { isErrorKind, type TextChange } from "@/platform/ipc";
import { minimalChanges } from "./diff";
export interface SyncTransport {
@@ -64,10 +64,6 @@ export const frameScheduler: Scheduler = (fn) => {
setTimeout(once, 50);
};
function isOutOfSync(e: unknown): boolean {
return typeof e === "object" && e !== null && (e as { kind?: string }).kind === "outOfSync";
}
export function toTextChanges(cs: ChangeSet): TextChange[] {
const out: TextChange[] = [];
cs.iterChanges((fromA, toA, _fromB, _toB, inserted) => {
@@ -210,7 +206,7 @@ export class DocSync {
}
private onReject(error: unknown) {
if (!isOutOfSync(error)) {
if (!isErrorKind(error, "outOfSync")) {
this.host.onError?.(error);
this.hardResync(error);
return;
+149 -37
Переглянути файл
@@ -151,52 +151,126 @@
}
/* Find / replace bar */
.find {
.findContainer {
flex: none;
display: grid;
grid-template-columns: minmax(220px, 420px) auto 1fr;
align-items: center;
column-gap: var(--space-1-5);
row-gap: var(--space-1-5);
padding: 6px 8px 6px 10px;
min-width: 0;
container: editor-find / inline-size;
background: var(--bg-editor-inline, var(--bg-elev));
border-bottom: 1px solid var(--border-editor-tabs, var(--border));
}
.findExpandable {
grid-template-columns: auto minmax(220px, 420px) auto 1fr;
.find {
display: grid;
grid-template-columns: [mode] auto [field] minmax(0, 420px) [actions] fit-content(50%) [close] minmax(
min-content,
1fr
);
align-items: start;
row-gap: var(--space-1);
padding: var(--space-1-5) var(--space-2);
}
.findExpand {
grid-column: 1;
grid-row: 1;
}
.findExpandable .findField {
grid-column: 2;
grid-area: 1 / mode;
margin-inline-end: var(--space-1);
}
.findField {
grid-area: 1 / field;
}
.replaceField {
grid-area: 2 / field;
}
.findField,
.replaceField {
min-width: 0;
}
.findButtons {
.findClose {
grid-area: 1 / close;
justify-self: end;
margin-inline-start: var(--space-1);
}
.findExpand,
.findClose {
margin-block-start: var(--space-1);
}
.findButtons,
.replaceButtons {
display: flex;
flex-wrap: wrap;
align-items: center;
min-width: 0;
min-height: var(--h-field);
margin-inline-start: var(--space-1-5);
}
.findButtons {
grid-area: 1 / actions;
gap: var(--space-0-5);
}
.replaceButtons {
grid-area: 2 / actions;
gap: var(--space-1);
}
.findCount {
font-size: var(--fs-ui);
min-inline-size: 5ch;
padding-inline: var(--space-1);
font-size: var(--fs-small);
font-variant-numeric: tabular-nums;
color: var(--fg-subtle);
padding: 0 8px 0 4px;
min-width: 56px;
white-space: nowrap;
}
.findCountNone {
color: var(--danger);
}
.findClose {
justify-self: end;
@container editor-find (width < 500px) {
.find {
grid-template-columns: [mode] auto [field] minmax(0, 1fr) [close] auto;
}
.findButtons,
.replaceButtons {
grid-column: field / -1;
min-height: 0;
margin-inline-start: 0;
}
.findButtons {
grid-row: 2;
}
.replaceField {
grid-row: 3;
}
.replaceButtons {
grid-row: 4;
}
.replaceButtons > button {
max-width: 100%;
height: auto;
min-height: var(--h-control);
white-space: normal;
overflow-wrap: anywhere;
}
}
.replaceButtons {
display: flex;
align-items: center;
gap: var(--space-1-5);
@container editor-find (width < 224px) {
.findField,
.replaceField,
.replaceButtons {
grid-column: mode / -1;
}
.findExpand,
.findClose {
grid-row: 2;
margin-block-start: 0;
}
.findButtons {
grid-column: field;
}
.findInput {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(20px, 1fr));
height: auto;
padding-block: var(--space-1);
}
.findInput textarea {
grid-column: 2 / -1;
}
}
/* Go to line */
@@ -218,15 +292,44 @@
min-width: 0;
overflow: hidden;
}
.crumbButton {
flex: none;
max-width: 240px;
gap: 5px;
color: var(--fg);
}
.crumbButton:last-child {
flex: 0 1 auto;
.crumbStrip {
display: flex;
align-items: center;
min-width: 0;
overflow-x: auto;
overflow-y: hidden;
scrollbar-width: none;
}
.crumbStrip::-webkit-scrollbar {
display: none;
}
.crumbStrip:is([data-crumbs-before], [data-crumbs-after]) {
--crumb-mask: linear-gradient(
to right,
var(--crumb-start, black),
black var(--space-3),
black calc(100% - var(--space-3)),
var(--crumb-end, black)
);
-webkit-mask-image: var(--crumb-mask);
mask-image: var(--crumb-mask);
}
.crumbStrip[data-crumbs-before] {
--crumb-start: transparent;
}
.crumbStrip[data-crumbs-after] {
--crumb-end: transparent;
}
.crumbStrip .crumbButton {
flex: none;
max-width: min(240px, 100%);
margin: 0;
padding: 0 var(--space-1);
font: inherit;
color: inherit;
}
.crumbStrip .crumbButton[aria-current="location"] {
color: var(--fg);
}
.crumbIcon {
flex: none;
@@ -240,7 +343,6 @@
.statusSep {
flex: none;
color: var(--fg-faint);
margin: 0 2px;
}
.lock {
display: inline-flex;
@@ -339,13 +441,23 @@
flex: none;
display: flex;
align-items: center;
gap: var(--space-0-5);
height: 26px;
padding: 0 8px;
height: max(24px, calc(1em + var(--space-2)));
padding: 0 var(--space-2);
overflow: hidden;
background: var(--bg-editor, var(--bg-island));
color: var(--fg-muted);
font-size: var(--fs-small);
font-family: var(--font-mono);
font-size: var(--fs-code);
}
.codeCrumbs .crumbStrip {
gap: var(--space-0-5);
}
.codeCrumbs .crumbButton {
height: max(20px, calc(1em + var(--space-1)));
max-width: 100%;
}
.codeCrumbs .crumbButton[aria-current="location"] {
background: var(--bg-tree-selected-inactive);
}
.codeCrumbsTop {
border-bottom: 1px solid var(--border-editor-tabs, var(--border));
+176 -173
Переглянути файл
@@ -608,182 +608,185 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
const canReplace = !!opts.search && !invalid;
return (
<div
ref={panelRef}
onFocusCapture={() => {
focusedTarget = target;
setContext("findBarFocus", true);
setContext(
"findBarHasResults",
!!target.results && !!opts.search && (!opts.regexp || regexValid(opts.search)) && !!count?.total,
);
}}
onBlurCapture={(e) => {
if (!panelRef.current?.contains(e.relatedTarget as Node | null)) setContext("findBarFocus", false);
}}
className={clsx(styles.find, onReplaceShown && styles.findExpandable)}
role="search"
aria-label={replace ? "Replace in file" : "Find in file"}
>
{onReplaceShown && (
<IconButton
icon={replace ? "chevron-down" : "chevron-right"}
title={replace ? "Hide Replace" : "Show Replace"}
size="small"
className={styles.findExpand}
aria-expanded={replace}
onMouseDown={(e) => e.preventDefault()}
onClick={() => {
if (replaceBoxRef.current?.contains(document.activeElement)) inputRef.current?.focus();
onReplaceShown(!replace);
}}
<div className={styles.findContainer}>
<div
ref={panelRef}
onFocusCapture={() => {
focusedTarget = target;
setContext("findBarFocus", true);
setContext(
"findBarHasResults",
!!target.results && !!opts.search && (!opts.regexp || regexValid(opts.search)) && !!count?.total,
);
}}
onBlurCapture={(e) => {
if (!panelRef.current?.contains(e.relatedTarget as Node | null)) setContext("findBarFocus", false);
}}
className={styles.find}
role="search"
aria-label={replace ? "Replace in file" : "Find in file"}
>
{onReplaceShown && (
<IconButton
icon={replace ? "chevron-down" : "chevron-right"}
title={replace ? "Hide Replace" : "Show Replace"}
size="small"
className={styles.findExpand}
aria-expanded={replace}
onMouseDown={(e) => e.preventDefault()}
onClick={() => {
if (replaceBoxRef.current?.contains(document.activeElement)) inputRef.current?.focus();
onReplaceShown(!replace);
}}
/>
)}
<div ref={findBoxRef} className={styles.findField}>
<SearchField
ref={inputRef}
value={opts.search}
onChange={(search) => setOpts({ search })}
placeholder="Find"
aria-label="Find"
invalid={invalid || none}
multiline
onHistory={() => setHistoryMenu("find")}
onKeyDown={(e) => onKeyDown(e, "find")}
className={styles.findInput}
toggles={[
{
id: "case",
icon: "case",
title: "Match Case",
shortcut: formatBinding("Alt+C"),
pressed: opts.caseSensitive,
onToggle: () => toggle("caseSensitive"),
},
{
id: "word",
icon: "word",
title: "Words",
shortcut: formatBinding("Alt+W"),
pressed: opts.wholeWord,
onToggle: () => toggle("wholeWord"),
},
{
id: "regex",
icon: "regex",
title: "Regex",
shortcut: formatBinding("Alt+X"),
pressed: opts.regexp,
onToggle: () => toggle("regexp"),
},
]}
/>
</div>
<div className={styles.findButtons}>
<span className={clsx(styles.findCount, (none || invalid) && styles.findCountNone)} aria-live="polite">
{counter}
</span>
<IconButton
icon="arrow-up"
title="Previous Occurrence"
shortcut={formatBinding("Shift+Enter")}
size="small"
onClick={() => run(findPrevious)}
/>
<IconButton
icon="arrow-down"
title="Next Occurrence"
shortcut={formatBinding("Enter")}
size="small"
onClick={() => run(findNext)}
/>
<IconButton
ref={filterRef}
icon="filter"
title="Filter Search Results"
size="small"
pressed={scoped || inChanges || opts.context !== "any"}
onClick={() => setFilterMenu(true)}
/>
<IconButton ref={moreRef} icon="more" title="More" size="small" onClick={() => setMoreMenu(true)} />
</div>
<IconButton icon="close" title="Close" shortcut="⎋" size="small" className={styles.findClose} onClick={close} />
{replace && (
<>
<div ref={replaceBoxRef} className={styles.replaceField}>
<SearchField
ref={replaceRef}
value={opts.replace}
onChange={(value) => setOpts({ replace: value })}
placeholder="Replace"
aria-label="Replace"
multiline
onHistory={() => setHistoryMenu("replace")}
onKeyDown={(e) => onKeyDown(e, "replace")}
toggles={[
{
id: "preserveCase",
icon: "preserve-case",
title: "Preserve Case",
pressed: opts.preserveCase,
onToggle: () => toggle("preserveCase"),
},
]}
/>
</div>
<div className={styles.replaceButtons}>
<Button
size="small"
title={tx`Replace (${formatBinding("Alt+P")})`}
onClick={doReplace}
disabled={!canReplace}
>
<T>Replace</T>
</Button>
<Button
size="small"
title={tx`Replace All (${formatBinding("Alt+A")})`}
onClick={doReplaceAll}
disabled={!canReplace}
>
<T>Replace All</T>
</Button>
<Button
size="small"
title={
count?.excluded ? tx`Include (${formatBinding("Alt+L")})` : tx`Exclude (${formatBinding("Alt+L")})`
}
onClick={() => run(excludeCurrent)}
disabled={!canReplace || (!count?.total && !count?.excluded)}
>
{count?.excluded ? <T>Include</T> : <T>Exclude</T>}
</Button>
</div>
</>
)}
<Menu
open={historyMenu !== null}
anchor={historyMenu === "replace" ? replaceBoxRef : findBoxRef}
items={historyMenu ? historyItems(historyMenu) : []}
placement="bottom-start"
aria-label="Recent searches"
onClose={() => setHistoryMenu(null)}
/>
)}
<div ref={findBoxRef} className={styles.findField}>
<SearchField
ref={inputRef}
value={opts.search}
onChange={(search) => setOpts({ search })}
placeholder="Find"
aria-label="Find"
invalid={invalid || none}
multiline
onHistory={() => setHistoryMenu("find")}
onKeyDown={(e) => onKeyDown(e, "find")}
toggles={[
{
id: "case",
icon: "case",
title: "Match Case",
shortcut: formatBinding("Alt+C"),
pressed: opts.caseSensitive,
onToggle: () => toggle("caseSensitive"),
},
{
id: "word",
icon: "word",
title: "Words",
shortcut: formatBinding("Alt+W"),
pressed: opts.wholeWord,
onToggle: () => toggle("wholeWord"),
},
{
id: "regex",
icon: "regex",
title: "Regex",
shortcut: formatBinding("Alt+X"),
pressed: opts.regexp,
onToggle: () => toggle("regexp"),
},
]}
<Menu
open={moreMenu}
anchor={moreRef}
items={moreItems}
placement="bottom-end"
aria-label="Find options"
onClose={() => setMoreMenu(false)}
/>
<Menu
open={filterMenu}
anchor={filterRef}
items={filterItems}
placement="bottom-end"
aria-label="Filter search results"
onClose={() => setFilterMenu(false)}
/>
</div>
<div className={styles.findButtons}>
<span className={clsx(styles.findCount, (none || invalid) && styles.findCountNone)} aria-live="polite">
{counter}
</span>
<IconButton
icon="arrow-up"
title="Previous Occurrence"
shortcut={formatBinding("Shift+Enter")}
size="small"
onClick={() => run(findPrevious)}
/>
<IconButton
icon="arrow-down"
title="Next Occurrence"
shortcut={formatBinding("Enter")}
size="small"
onClick={() => run(findNext)}
/>
<IconButton
ref={filterRef}
icon="filter"
title="Filter Search Results"
size="small"
pressed={scoped || inChanges || opts.context !== "any"}
onClick={() => setFilterMenu(true)}
/>
<IconButton ref={moreRef} icon="more" title="More" size="small" onClick={() => setMoreMenu(true)} />
</div>
<IconButton icon="close" title="Close" shortcut="⎋" size="small" className={styles.findClose} onClick={close} />
{replace && (
<>
<div ref={replaceBoxRef} className={styles.findField}>
<SearchField
ref={replaceRef}
value={opts.replace}
onChange={(value) => setOpts({ replace: value })}
placeholder="Replace"
aria-label="Replace"
multiline
onHistory={() => setHistoryMenu("replace")}
onKeyDown={(e) => onKeyDown(e, "replace")}
toggles={[
{
id: "preserveCase",
icon: "preserve-case",
title: "Preserve Case",
pressed: opts.preserveCase,
onToggle: () => toggle("preserveCase"),
},
]}
/>
</div>
<div className={styles.replaceButtons}>
<Button
size="small"
title={tx`Replace (${formatBinding("Alt+P")})`}
onClick={doReplace}
disabled={!canReplace}
>
<T>Replace</T>
</Button>
<Button
size="small"
title={tx`Replace All (${formatBinding("Alt+A")})`}
onClick={doReplaceAll}
disabled={!canReplace}
>
<T>Replace All</T>
</Button>
<Button
size="small"
title={
count?.excluded ? tx`Include (${formatBinding("Alt+L")})` : tx`Exclude (${formatBinding("Alt+L")})`
}
onClick={() => run(excludeCurrent)}
disabled={!canReplace || (!count?.total && !count?.excluded)}
>
{count?.excluded ? <T>Include</T> : <T>Exclude</T>}
</Button>
</div>
</>
)}
<Menu
open={historyMenu !== null}
anchor={historyMenu === "replace" ? replaceBoxRef : findBoxRef}
items={historyMenu ? historyItems(historyMenu) : []}
placement="bottom-start"
aria-label="Recent searches"
onClose={() => setHistoryMenu(null)}
/>
<Menu
open={moreMenu}
anchor={moreRef}
items={moreItems}
placement="bottom-end"
aria-label="Find options"
onClose={() => setMoreMenu(false)}
/>
<Menu
open={filterMenu}
anchor={filterRef}
items={filterItems}
placement="bottom-end"
aria-label="Filter search results"
onClose={() => setFilterMenu(false)}
/>
</div>
);
}
+114 -48
Переглянути файл
@@ -1,15 +1,16 @@
/** Status bar widgets of the active text editor (design footer). */
import { Fragment, useRef, useState } from "react";
import { Fragment, useLayoutEffect, useRef, useState, type ComponentPropsWithoutRef } from "react";
import clsx from "clsx";
import { useShallow } from "zustand/react/shallow";
import { executeAction } from "@/platform/actions";
import { shortcutLabel } from "@/platform/keymap";
import { basename, dirname, projectFolder, relativePath, useProject } from "@/platform/project";
import type { LineEnding, OutlineItem } from "@/platform/ipc";
import { BarButton, Icon, Menu, badgeKind, fileIconName } from "@/ui";
import { BarButton, Icon, Menu, badgeKind, fileIconName, revealHorizontally } from "@/ui";
import { notifications, useProjectViewLead } from "@/workbench/contributions";
import { useDistractionFree } from "@/workbench/distractionFree";
import { ENCODING_CHOICES, useEditorPrefs } from "@/platform/editorSettings";
import { BUNDLED_MONO_FAMILY, monoFontFamily } from "@/platform/fonts";
import {
gitRevisionOf,
isUntitledUri,
@@ -145,15 +146,39 @@ function pathCrumbs(project: { root: string; name: string } | null, path: string
return segments;
}
/** A row of crumbs; a segment with `nav` opens a popup of its children. */
function CrumbNav({ segments, className, ariaLabel }: { segments: Crumb[]; className?: string; ariaLabel?: string }) {
const [popup, setPopup] = useState<{ nav: NavSegment; anchor: HTMLElement } | null>(null);
function updateBreadcrumbEdges(row: HTMLDivElement) {
row.toggleAttribute("data-crumbs-before", row.scrollLeft > 1);
row.toggleAttribute("data-crumbs-after", row.scrollLeft + row.clientWidth < row.scrollWidth - 1);
}
function BreadcrumbStrip({
trail,
activateOnDown = false,
children,
...props
}: ComponentPropsWithoutRef<"nav"> & { trail: string; activateOnDown?: boolean }) {
const strip = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const row = strip.current;
if (!row) return;
const revealCurrent = () => {
const focused = document.activeElement;
if (focused instanceof HTMLElement && row.contains(focused)) revealHorizontally(row, focused);
else row.scrollLeft = row.scrollWidth;
updateBreadcrumbEdges(row);
};
revealCurrent();
if (typeof ResizeObserver === "undefined") return;
const resize = new ResizeObserver(revealCurrent);
resize.observe(row);
return () => resize.disconnect();
}, [trail]);
return (
<nav
className={className}
aria-label={ariaLabel}
{...props}
onKeyDown={(e) => {
const buttons = [...e.currentTarget.querySelectorAll<HTMLButtonElement>("button")];
if (e.altKey || e.ctrlKey || e.metaKey) return;
const buttons = [...(strip.current?.querySelectorAll("button") ?? [])];
const index = buttons.indexOf(e.target as HTMLButtonElement);
if (index < 0) return;
let next: number;
@@ -161,7 +186,7 @@ function CrumbNav({ segments, className, ariaLabel }: { segments: Crumb[]; class
else if (e.key === "ArrowRight") next = Math.min(buttons.length - 1, index + 1);
else if (e.key === "Home") next = 0;
else if (e.key === "End") next = buttons.length - 1;
else if (e.key === "ArrowDown") {
else if (e.key === "ArrowDown" && activateOnDown) {
e.preventDefault();
e.stopPropagation();
buttons[index]?.click();
@@ -172,30 +197,64 @@ function CrumbNav({ segments, className, ariaLabel }: { segments: Crumb[]; class
buttons[next]?.focus();
}}
>
{segments.map((s, i) => (
<Fragment key={i}>
{i > 0 && <Icon name="chevron-right" size={12} className={styles.statusSep} />}
<BarButton
className={styles.crumbButton}
tooltip={s.title}
aria-haspopup={s.nav ? "listbox" : undefined}
onClick={(e) => {
const nav = s.nav;
const anchor = e.currentTarget;
if (nav) setPopup((p) => (p?.anchor === anchor ? null : { nav, anchor }));
else s.run?.();
}}
>
{s.icon && <Icon name={s.icon} size={16} className={styles.crumbIcon} />}
<span className={styles.crumbLabel}>{s.label}</span>
</BarButton>
</Fragment>
))}
{popup && <NavChildrenPopup segment={popup.nav} anchor={popup.anchor} onClose={() => setPopup(null)} />}
<div
ref={strip}
className={styles.crumbStrip}
onScroll={(e) => updateBreadcrumbEdges(e.currentTarget)}
onWheel={(e) => {
if (e.shiftKey || e.ctrlKey || e.deltaX) return;
const row = e.currentTarget;
const scale = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? row.clientWidth : 1;
row.scrollLeft += e.deltaY * scale;
}}
>
{children}
</div>
</nav>
);
}
/** A row of crumbs; a segment with `nav` opens a popup of its children. */
function CrumbNav({ segments, className }: { segments: Crumb[]; className?: string }) {
const [popup, setPopup] = useState<{ nav: NavSegment; anchor: HTMLElement } | null>(null);
return (
<BreadcrumbStrip
trail={segments.map((s) => s.title).join("\n")}
activateOnDown
className={className}
aria-label={tx("Breadcrumbs")}
>
{segments.map((s, i) => {
const current = i === segments.length - 1;
const icon = s.nav?.kind === "dir" && !s.nav.root && !current ? undefined : s.icon;
return (
<Fragment key={i}>
{i > 0 && <Icon name="chevron-right" size={12} className={styles.statusSep} />}
<BarButton
className={styles.crumbButton}
tooltip={s.title}
aria-current={current ? "location" : undefined}
aria-haspopup={s.nav ? "listbox" : undefined}
onClick={(e) => {
const nav = s.nav;
const anchor = e.currentTarget;
if (nav) setPopup((p) => (p?.anchor === anchor ? null : { nav, anchor }));
else s.run?.();
}}
>
{icon && (
<Icon name={icon} size={s.nav?.kind === "dir" && s.nav.root ? 12 : 16} className={styles.crumbIcon} />
)}
<span className={styles.crumbLabel}>{s.label}</span>
</BarButton>
</Fragment>
);
})}
{popup && <NavChildrenPopup segment={popup.nav} anchor={popup.anchor} onClose={() => setPopup(null)} />}
</BreadcrumbStrip>
);
}
/**
* IDEA new UI navigation bar (the top of the workbench, or the status bar
* footer via `inStatusBar`): project › dirs › file › symbols, with icons;
@@ -241,7 +300,7 @@ export function Breadcrumbs({ className, inStatusBar = false }: { className?: st
segments.push(projectCrumb(project ?? currentProject));
}
if (!segments.length) return null;
return <CrumbNav segments={segments} className={className ?? styles.status} ariaLabel={tx("Breadcrumbs")} />;
return <CrumbNav segments={segments} className={className ?? styles.status} />;
}
/** The status bar instance of the navigation bar; renders only for `statusBar`. */
@@ -262,7 +321,8 @@ export function CodeBreadcrumbs({
tabId: string;
position: "top" | "bottom";
}) {
const prefs = useEditorPrefs().breadcrumbs;
const { breadcrumbs: prefs, fallbackFont } = useEditorPrefs();
const editorSettings = useProject((s) => s.settings?.editor);
const language = useDocMeta((s) => s[path]?.language);
const outline = useOutline((s) => s[path]);
let chain = useCaretSymbols(path, outline);
@@ -278,29 +338,35 @@ export function CodeBreadcrumbs({
!chain.length
)
return null;
const family = editorSettings?.fontFamily;
const fontFamily =
(family && family !== BUNDLED_MONO_FAMILY) || fallbackFont.trim()
? monoFontFamily(family, fallbackFont, "var(--font-mono)")
: undefined;
const fontSize = editorSettings?.fontSize ?? undefined;
return (
<nav
<BreadcrumbStrip
trail={JSON.stringify([path, fontFamily, fontSize, ...chain.map((item) => item.name)])}
style={{ fontFamily, fontSize }}
className={clsx(styles.codeCrumbs, position === "top" ? styles.codeCrumbsTop : styles.codeCrumbsBottom)}
aria-label={tx("Code breadcrumbs")}
>
{chain.map((item, i) => (
<Fragment key={i}>
{i > 0 && <Icon name="chevron-right" size={12} className={styles.statusSep} />}
<BarButton
className={styles.crumbButton}
tooltip={item.detail ?? item.name}
onClick={() =>
void editorController().openFile(path, {
selection: { line: item.selection_range.start.line, col: item.selection_range.start.col },
})
}
>
<Icon name={`symbol-${badgeKind(item.kind)}`} size={14} className={styles.crumbIcon} />
<span className={styles.crumbLabel}>{item.name}</span>
</BarButton>
</Fragment>
<BarButton
key={i}
className={styles.crumbButton}
tooltip={item.detail ?? item.name}
aria-current={i === chain.length - 1 ? "location" : undefined}
onClick={() =>
void editorController().openFile(path, {
selection: { line: item.selection_range.start.line, col: item.selection_range.start.col },
})
}
>
<span className={styles.crumbLabel}>{item.name}</span>
</BarButton>
))}
</nav>
</BreadcrumbStrip>
);
}
+124 -9
Переглянути файл
@@ -30,8 +30,7 @@
}
.withPreview {
flex-direction: row;
width: auto;
max-width: min(1160px, 94vw);
min-width: 0;
}
.listMain {
display: flex;
@@ -39,6 +38,11 @@
min-width: 0;
flex: none;
}
.withPreview .listMain {
flex: 1 1 320px;
min-width: 300px;
min-height: 0;
}
.mnemonic {
width: 10px;
flex: none;
@@ -48,14 +52,39 @@
text-align: right;
}
.previewPanel {
width: 420px;
flex: none;
flex: 0 1 var(--list-preview-width);
min-width: 300px;
min-height: 60px;
max-height: 340px;
max-height: 300px;
overflow: auto;
border-left: 1px solid var(--border-popup);
background: var(--bg-popup-inline, var(--bg-elev));
}
.previewLeft {
flex-direction: row-reverse;
}
.previewLeft .previewPanel {
border-left: 0;
border-right: 1px solid var(--border-popup);
}
.previewBelow {
flex-direction: column;
}
.previewBelow .listMain {
flex: 0 1 auto;
min-width: 0;
}
.previewBelow .previewPanel {
flex: 0 1 auto;
min-width: 0;
min-height: 0;
max-height: min(300px, 40vh);
border-left: 0;
border-top: 1px solid var(--border-popup);
}
.previewBelow .previewPanel[aria-busy] {
height: 60px;
}
.previewText {
padding: 8px 10px;
font-size: var(--fs-small);
@@ -66,12 +95,13 @@
padding: 6px 0;
font-family: var(--openidea-editor-font, var(--font-mono));
font-weight: var(--fw-code);
font-size: var(--fs-small);
font-size: var(--openidea-editor-font-size, var(--fs-code));
color: var(--fg-editor);
}
.diffLine {
padding: 0 10px;
white-space: pre;
white-space: pre-wrap;
overflow-wrap: anywhere;
min-height: 1.4em;
}
.diff-added {
@@ -231,6 +261,34 @@
font-size: var(--fs-tiny);
color: var(--fg-faint);
}
.symbolRename {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
align-items: center;
gap: var(--space-2) var(--space-3);
padding: var(--space-3);
font-family: var(--font-ui);
font-size: var(--fs-ui);
}
.renameContext,
.symbolRenameNote {
grid-column: 1 / -1;
min-width: 0;
overflow-wrap: anywhere;
}
.renameContext {
color: var(--fg-emphasis);
}
.symbolRename .renameField {
width: 100%;
height: max(var(--h-field), calc(var(--openidea-editor-font-size, var(--fs-code)) + var(--space-2)));
font-family: var(--openidea-editor-font, var(--font-mono));
font-size: var(--openidea-editor-font-size, var(--fs-code));
}
.symbolRenameNote {
color: var(--fg-muted);
font-size: var(--fs-small);
}
/* Fits its content up to a cap; resized (`data-resized`), it keeps that size and the body scrolls. */
.docPopup {
@@ -238,6 +296,10 @@
flex-direction: column;
overflow: hidden;
}
.docPopup:not([data-resized]) {
width: max-content;
min-width: min(300px, 90vw);
}
.docScope {
display: contents;
}
@@ -246,21 +308,32 @@
}
.docPopup .docFrame {
flex: 1 1 auto;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
}
.docPopup:not([data-resized]) .docFrame {
max-width: min(600px, 90vw);
max-height: 420px;
max-width: min(500px, 90vw);
max-height: 500px;
}
.docPopup .docBody {
flex: 1 1 auto;
min-height: 0;
overflow: auto;
overscroll-behavior: contain;
padding: var(--space-2) var(--space-4) var(--space-1);
}
.docPopup .docToolbar {
position: static;
flex: none;
align-self: flex-end;
margin: 0 var(--space-2) var(--space-1);
padding: 0;
border: 0;
}
.docPopup .docToolbar .spacer {
display: none;
}
.docWindowFrame {
height: 100%;
@@ -353,6 +426,36 @@
flex-direction: column;
overflow: hidden;
}
.renamePreview [data-dialog-body] {
display: block;
overflow: auto;
}
.previewContext {
padding: var(--space-2) 14px 0;
overflow-wrap: anywhere;
color: var(--fg-emphasis);
font-size: var(--fs-ui);
}
.renamePreview .previewList {
overflow: visible;
}
.renamePreview .previewName {
min-width: 0;
max-width: 55%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.renamePreview .previewOp {
flex: 0 1 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.renamePreview .previewWarning {
overflow-wrap: anywhere;
}
.previewSummary {
flex: none;
padding: 10px 14px 6px;
@@ -424,6 +527,18 @@
font-size: var(--fs-small);
color: var(--fg-editor);
}
.renamePreview .previewOccurrences .previewRow {
min-height: var(--h-row);
height: auto;
align-items: baseline;
padding-block: var(--space-1);
}
.renamePreview .previewCode {
font-family: var(--openidea-editor-font, var(--font-mono));
font-size: var(--openidea-editor-font-size, var(--fs-code));
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.previewMatch {
background: var(--bg-search-match);
color: var(--fg-search-match, inherit);
+129 -18
Переглянути файл
@@ -1,5 +1,5 @@
/** React popups for LSP editor features, rendered as a workbench overlay. */
import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import { useEffect, useId, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent } from "react";
import clsx from "clsx";
import {
Checkbox,
@@ -49,11 +49,17 @@ function ItemIcon({ item }: { item: ListPopupItem }) {
return <span className={styles.iconSpacer} />;
}
function ListPreviewPanel({ preview }: { preview: ListPreview | null | "loading" }) {
function ListPreviewPanel({
preview,
themeClasses,
}: {
preview: ListPreview | null | "loading";
themeClasses?: string;
}) {
if (preview === "loading") return <div className={styles.previewPanel} aria-busy="true" />;
if (!preview) return null;
return (
<div className={styles.previewPanel} aria-label={tx("Preview")}>
<div className={clsx(styles.previewPanel, themeClasses)} role="region" aria-label={tx("Preview")}>
{preview.kind === "text" ? (
<div className={styles.previewText}>{preview.text}</div>
) : (
@@ -70,6 +76,9 @@ function ListPreviewPanel({ preview }: { preview: ListPreview | null | "loading"
);
}
const LIST_PREVIEW_WIDTH = 420;
const MIN_SIDE_BY_SIDE_WIDTH = 660;
function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
const [query, setQuery] = useState("");
const filtered = useMemo(() => {
@@ -91,6 +100,13 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
const [preview, setPreview] = useState<{ id: string; data: ListPreview | null } | null>(null);
const fetchPreview = popup.preview;
const [viewportWidth, setViewportWidth] = useState(() => window.innerWidth);
useEffect(() => {
if (!fetchPreview) return;
const resize = () => setViewportWidth(window.innerWidth);
window.addEventListener("resize", resize);
return () => window.removeEventListener("resize", resize);
}, [fetchPreview]);
useEffect(() => {
if (!fetchPreview || !activeItem || activeItem.disabled) return;
const ctrl = new AbortController();
@@ -164,22 +180,46 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
? ("loading" as const)
: null
: null;
const hasPreview = shownPreview !== null;
const previewBelow = hasPreview && viewportWidth <= MIN_SIDE_BY_SIDE_WIDTH;
const previewLeft =
hasPreview &&
!previewBelow &&
popup.anchor.x + width + LIST_PREVIEW_WIDTH > viewportWidth - 6 &&
popup.anchor.x >= LIST_PREVIEW_WIDTH + 6;
const anchor = useMemo(() => {
if (!fetchPreview) return popup.anchor;
const x = popup.anchor.x - (previewLeft ? LIST_PREVIEW_WIDTH : 0);
return {
getBoundingClientRect: () =>
new DOMRect(
Math.max(0, Math.min(x, window.innerWidth)),
Math.max(0, Math.min(popup.anchor.y, window.innerHeight)),
0,
0,
),
};
}, [fetchPreview, popup.anchor, previewLeft]);
const popupSize = {
width: hasPreview ? width + LIST_PREVIEW_WIDTH : width,
"--list-preview-width": `${LIST_PREVIEW_WIDTH}px`,
} as CSSProperties;
const indexOf = (item: ListPopupItem) => popup.items.indexOf(item);
return (
<Popup
open
anchor={popup.anchor}
anchor={anchor}
onClose={closePopup}
aria-label={popup.title}
className={clsx(styles.listPopup, popup.preview && styles.withPreview)}
style={popup.preview ? undefined : { width }}
className={clsx(
styles.listPopup,
hasPreview && styles.withPreview,
previewBelow && styles.previewBelow,
previewLeft && styles.previewLeft,
)}
style={popupSize}
>
<div
className={styles.listMain}
style={popup.preview ? { width } : undefined}
data-testid="list-popup"
aria-busy={popup.busy || undefined}
>
<div className={styles.listMain} data-testid="list-popup" aria-busy={popup.busy || undefined}>
<div className={styles.listHeader}>
<span className={styles.listTitle}>{popup.title}</span>
{popup.busy && <Spinner size={12} />}
@@ -260,7 +300,7 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
/>
</div>
</div>
{popup.preview && <ListPreviewPanel preview={shownPreview} />}
{popup.preview && <ListPreviewPanel preview={shownPreview} themeClasses={popup.themeClasses} />}
{sub?.item.submenu && (
<Popup
open
@@ -352,10 +392,71 @@ function RenamePopup({ popup }: { popup: Extract<LspPopup, { kind: "rename" }> }
);
}
function SymbolRenameDialog({ popup }: { popup: Extract<LspPopup, { kind: "symbolRename" }> }) {
const [value, setValue] = useState(popup.initial);
const field = useId();
const name = value.trim();
return (
<Dialog
open
title="Rename"
aria-label={popup.title}
onClose={closePopup}
blockWorkbenchShortcuts
width={440}
buttons={[
{
label: "Rename",
role: "default",
disabled: !name,
onClick: () => {
closePopup();
popup.onSubmit(name);
},
},
{ label: "Cancel", role: "cancel" },
]}
>
<div className={popup.themeClasses}>
<div className={styles.symbolRename}>
<div className={styles.renameContext}>{popup.title}</div>
<label htmlFor={field}>
<T>New name</T>
</label>
<Input
id={field}
className={styles.renameField}
mono
data-autofocus
autoSelect
value={value}
onChange={(e) => setValue(e.target.value)}
invalid={!name}
/>
{popup.note && <div className={styles.symbolRenameNote}>{popup.note}</div>}
</div>
</div>
</Dialog>
);
}
function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
const focusSeq = useLspPopup((s) => s.focusSeq);
const scope = useRef<HTMLDivElement>(null);
const opened = useRef(focusSeq);
// The captured caret can end up outside the viewport while the popup is open.
const anchor = useMemo(
() => ({
getBoundingClientRect: () =>
new DOMRect(
Math.max(0, Math.min(popup.anchor.x, window.innerWidth)),
Math.max(0, Math.min(popup.anchor.y, window.innerHeight)),
0,
0,
),
}),
[popup.anchor],
);
useEffect(() => {
if (focusSeq !== opened.current)
scope.current?.querySelector<HTMLElement>("[data-lsp-doc]")?.focus({ preventScroll: true });
@@ -364,7 +465,7 @@ function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
return (
<Popup
open
anchor={popup.anchor}
anchor={anchor}
onClose={closePopup}
aria-label="Documentation"
className={styles.docPopup}
@@ -483,6 +584,7 @@ function savePreviewSize(size: { w: number; h: number }) {
}
function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }> }) {
const rename = popup.renameThemeClasses !== undefined;
const root = useProject((s) => s.project?.root ?? "");
const { summary } = popup;
const [initialSize] = useState(loadPreviewSize);
@@ -490,8 +592,9 @@ function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }
<Dialog
open
onClose={closePopup}
title={popup.title}
className={styles.previewDialog}
title={rename ? "Rename" : popup.title}
aria-label={popup.title}
className={clsx(styles.previewDialog, rename && styles.renamePreview)}
width={560}
minWidth={400}
minHeight={220}
@@ -512,6 +615,7 @@ function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }
{ label: "Cancel", role: "cancel" },
]}
>
{rename && <div className={styles.previewContext}>{popup.title}</div>}
{popup.warnings?.map((w) => (
<div key={w} className={styles.previewWarning} role="note">
<Icon name="warning" size={14} />
@@ -520,7 +624,10 @@ function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }
))}
<div className={styles.previewSummary}>{describeSummary(summary)}</div>
{popup.occurrences ? (
<ul className={styles.previewList} aria-label={tx("Occurrences")}>
<ul
className={clsx(styles.previewList, styles.previewOccurrences, popup.renameThemeClasses)}
aria-label={tx("Occurrences")}
>
{popup.occurrences.map((o, i) => {
const lead = o.text.length - o.text.trimStart().length;
const text = o.text.trim();
@@ -543,7 +650,9 @@ function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }
{summary.entries.map((e) => (
<li key={e.path} className={styles.previewRow}>
<Icon name={fileIconName(basename(e.path), e.path)} size={14} className={styles.itemIcon} />
<span className={styles.previewName}>{basename(e.path)}</span>
<span className={styles.previewName} title={relativePath(root, e.path)}>
{basename(e.path)}
</span>
<span className={styles.previewPath} title={relativePath(root, e.path)}>
{relativePath(root, e.path)}
</span>
@@ -689,6 +798,8 @@ export function LspPopups() {
return <ListPopup key={seq} popup={popup} />;
case "rename":
return <RenamePopup key={seq} popup={popup} />;
case "symbolRename":
return <SymbolRenameDialog key={seq} popup={popup} />;
case "doc":
return <DocPopup key={seq} popup={popup} />;
case "definition":
+1
Переглянути файл
@@ -552,6 +552,7 @@ export async function showIntentions(view: EditorView) {
items,
busy,
preview,
themeClasses: view.themeClasses,
onClose: () => {
dismissed = true;
},
+11
Переглянути файл
@@ -104,6 +104,7 @@ export type LspPopup =
pin?: { label: string; run: () => void };
/** Side panel for the selected row, fetched lazily; `signal` aborts when the selection moves. */
preview?: (item: ListPopupItem, signal: AbortSignal) => Promise<ListPreview | null>;
themeClasses?: string;
/** Runs when the popup goes away (closed, replaced or a row ran). */
onClose?: () => void;
}
@@ -129,6 +130,14 @@ export type LspPopup =
hint?: string;
onSubmit: (name: string) => void;
}
| {
kind: "symbolRename";
title: string;
initial: string;
note?: string;
themeClasses: string;
onSubmit: (name: string) => void;
}
| {
kind: "preview";
title: string;
@@ -139,6 +148,8 @@ export type LspPopup =
warnings?: string[];
/** Individual occurrences with line previews (single-file syntax-based renames). */
occurrences?: PreviewOccurrence[];
/** The editor theme for a symbol rename and its occurrence snippets. */
renameThemeClasses?: string;
};
export interface PreviewOccurrence {
+8 -7
Переглянути файл
@@ -27,9 +27,9 @@ import { executeAction } from "@/platform/actions";
import { whenAllSynced, whenSynced, type EditorDocContext } from "@/editor/api";
import { structure } from "@/editor/structure";
import { docOf, incompleteNote, isUnavailable, lspRequest, reportLspError } from "./lsp";
import { comparePos, offsetToPos, rangeToOffsets } from "./positions";
import { offsetToPos, rangeToOffsets } from "./positions";
import { showHint } from "./hint";
import { caretAnchor, openPopup, type PreviewOccurrence } from "./popupStore";
import { openPopup, type PreviewOccurrence } from "./popupStore";
import { needsPreview, summarizeWorkspaceEdit } from "./workspaceEdit";
import { endInplaceRename, inplaceSession, startInplaceRename, type Span } from "./inplaceRename";
import { shortcutLabel } from "@/platform/keymap";
@@ -127,10 +127,10 @@ export async function startRename(view: EditorView) {
const oldName = view.state.sliceDoc(from, to);
const dialog = (initial: string) =>
openPopup({
kind: "rename",
anchor: caretAnchor(view, from),
kind: "symbolRename",
title: tx`Rename '${oldName}'`,
initial,
themeClasses: view.themeClasses,
onSubmit: (newName) => void finishRename(view, doc, pos, oldName, newName),
});
if (from === to) {
@@ -304,6 +304,7 @@ async function finishRename(view: EditorView, doc: EditorDocContext, pos: Pos, o
kind: "preview",
title: tx`Rename '${oldName}' to '${newName}'`,
summary,
renameThemeClasses: view.themeClasses,
...(note ? { warnings: [note] } : {}),
confirmLabel: note ? "Rename Anyway" : "Do Refactor",
onConfirm: () => void applyEdit(view, edit),
@@ -350,13 +351,12 @@ async function startSyntaxRename(
return true;
}
const { plan } = result;
const at = plan.occurrences.find((o) => comparePos(o.range.start, pos) <= 0 && comparePos(pos, o.range.end) <= 0);
openPopup({
kind: "rename",
anchor: caretAnchor(view, rangeToOffsets(view.state.doc, (at ?? plan.occurrences[0]!).range).from),
kind: "symbolRename",
title: tx`Rename '${plan.symbol.name}'`,
initial: plan.symbol.name,
note: `${SYNTAX_NOTE}: local occurrences only`,
themeClasses: view.themeClasses,
onSubmit: (newName) => void commitSyntaxRename(view, doc, plan, newName),
});
return true;
@@ -418,6 +418,7 @@ export async function commitSyntaxRename(
},
warnings: [...risks, `${SYNTAX_NOTE}. Only the occurrences below will be renamed.`],
occurrences,
renameThemeClasses: view.themeClasses,
confirmLabel: "Rename Anyway",
onConfirm: apply,
});
+51 -10
Переглянути файл
@@ -6,8 +6,17 @@
*/
import { EditorSelection, Prec, StateEffect, StateField, type Extension } from "@codemirror/state";
import { completionStatus, hasNextSnippetField, hasPrevSnippetField } from "@codemirror/autocomplete";
import { EditorView, ViewPlugin, keymap, showTooltip, type Tooltip, type ViewUpdate } from "@codemirror/view";
import {
EditorView,
ViewPlugin,
keymap,
repositionTooltips,
showTooltip,
type Tooltip,
type ViewUpdate,
} from "@codemirror/view";
import { commands, type SignatureHelp } from "@/platform/ipc";
import { tooltipBounds } from "@/editor/core/cm/setup";
import { docOf, lspRequest, reportLspError, debounce } from "./lsp";
import { offsetToPos } from "./positions";
import { showHint } from "./hint";
@@ -40,8 +49,6 @@ export function splitSignature(label: string, params: ReadonlyArray<[number, num
return { before: label.slice(0, s), param: label.slice(s, e), after: label.slice(e) };
}
const MAX_ROWS = 12;
/** Whether an overload can take an argument at `index` (varargs take any number). */
export function acceptsParameter(sig: { label: string; parameters: ReadonlyArray<[number, number]> }, index: number) {
if (index < sig.parameters.length) return true;
@@ -54,23 +61,27 @@ function signatureTooltip(s: SigState): Tooltip {
pos: s.pos,
above: true,
strictSide: false,
create: () => {
create: (view) => {
const dom = document.createElement("div");
dom.className = "cm-lsp-signature";
dom.setAttribute("role", "tooltip");
const { signatures, activeSignature, activeParameter } = s.help;
const start = Math.max(0, Math.min(activeSignature - 6, signatures.length - MAX_ROWS));
signatures.slice(start, start + MAX_ROWS).forEach((sig, j) => {
const i = start + j;
let active: HTMLElement | null = null;
signatures.forEach((sig, i) => {
const row = document.createElement("div");
row.className = "cm-lsp-signature-row";
if (i === activeSignature) row.classList.add("cm-lsp-signature-active");
else if (!acceptsParameter(sig, activeParameter)) row.classList.add("cm-lsp-signature-disabled");
if (i === activeSignature) {
row.classList.add("cm-lsp-signature-active");
row.setAttribute("aria-current", "true");
active = row;
} else if (!acceptsParameter(sig, activeParameter)) row.classList.add("cm-lsp-signature-disabled");
const parts = splitSignature(sig.label, sig.parameters, activeParameter);
row.append(parts.before);
if (parts.param) {
const b = document.createElement("b");
b.textContent = parts.param;
row.appendChild(b);
if (i === activeSignature) active = b;
}
row.append(parts.after);
dom.appendChild(row);
@@ -81,7 +92,37 @@ function signatureTooltip(s: SigState): Tooltip {
d.classList.add("cm-lsp-signature-doc");
dom.appendChild(d);
}
return { dom };
const fit = ({ left, right }: { left: number; right: number }) => {
const width = `${Math.max(0, Math.floor(right - left))}px`;
const fontSize = getComputedStyle(view.contentDOM).fontSize;
const changed = dom.style.getPropertyValue("--cm-signature-width") !== width || dom.style.fontSize !== fontSize;
if (changed) {
dom.style.setProperty("--cm-signature-width", width);
dom.style.fontSize = fontSize;
}
return changed;
};
// Reveal the current parameter after wrapping or a vertical clamp. Leave manual scrolling alone.
let fittedWidth = 0;
let fittedHeight = 0;
return {
dom,
mount: () => void fit(tooltipBounds(view)),
positioned: (space) => {
if (fit(space)) {
repositionTooltips(view);
return;
}
if (!active || (fittedWidth === dom.clientWidth && fittedHeight === dom.clientHeight)) return;
fittedWidth = dom.clientWidth;
fittedHeight = dom.clientHeight;
const top = dom.getBoundingClientRect().top + dom.clientTop;
const parameter = active.getBoundingClientRect();
const below = parameter.bottom - (top + fittedHeight);
if (parameter.top < top || parameter.height >= fittedHeight) dom.scrollTop += parameter.top - top;
else if (below > 0) dom.scrollTop += below;
},
};
},
};
}
+6 -6
Переглянути файл
@@ -646,8 +646,8 @@ describe("rename wiring", () => {
const view = editor("const x = 1;\nf({ x });", "typescript", 6);
await startRename(view);
const popup = useLspPopup.getState().popup;
expect(popup?.kind).toBe("rename");
if (popup?.kind !== "rename") return;
expect(popup?.kind).toBe("symbolRename");
if (popup?.kind !== "symbolRename") return;
expect(popup.note).toContain("Based on syntax");
popup.onSubmit("y");
await vi.waitFor(() => expect(view.state.doc.toString()).toBe("const y = 1;\nf({ x: y });"));
@@ -661,7 +661,7 @@ describe("rename wiring", () => {
const view = editor("const x = 1;\nx;\nvar x;", "typescript", 6);
await startRename(view);
const popup = useLspPopup.getState().popup;
if (popup?.kind !== "rename") throw new Error("no rename popup");
if (popup?.kind !== "symbolRename") throw new Error("no rename dialog");
popup.onSubmit("y");
await vi.waitFor(() => expect(useLspPopup.getState().popup?.kind).toBe("preview"));
const preview = useLspPopup.getState().popup;
@@ -860,12 +860,12 @@ describe("rename wiring", () => {
await startRename(view);
expect(inplaceSession(view.state)?.oldName).toBe("x");
await startRename(view);
expect(useLspPopup.getState().popup?.kind).toBe("rename");
expect(useLspPopup.getState().popup?.kind).toBe("symbolRename");
if (finish === "cancel") closePopup();
release({ status: "ok", data: r(0, 6, 7) });
await older;
expect(inplaceSession(view.state)).toBeNull();
expect(useLspPopup.getState().popup?.kind ?? null).toBe(finish === "dialog" ? "rename" : null);
expect(useLspPopup.getState().popup?.kind ?? null).toBe(finish === "dialog" ? "symbolRename" : null);
});
it.each(["text", "document"])("drops pending preparation when the editor %s changes", async (change) => {
@@ -938,7 +938,7 @@ describe("rename wiring", () => {
);
cmd.syntaxLocals.mockReturnValueOnce(ok(local({ references: [] })));
await startRename(view);
expect(useLspPopup.getState().popup?.kind).toBe("rename");
expect(useLspPopup.getState().popup?.kind).toBe("symbolRename");
});
});
+17 -10
Переглянути файл
@@ -270,28 +270,35 @@ export const lspTheme = EditorView.theme({
cursor: "pointer",
},
".cm-lsp-link-button:hover": { color: "var(--link-hover)", textDecoration: "underline" },
".cm-lsp-signature": {
".cm-tooltip.cm-lsp-signature": {
fontFamily: "var(--openidea-editor-font, var(--font-mono))",
fontWeight: "var(--fw-code, 400)",
fontSize: "var(--openidea-editor-font-size, var(--fs-code))",
padding: "6px 10px",
maxWidth: "640px",
maxWidth: "min(640px, var(--cm-signature-width, 100%))",
maxHeight: "min(380px, 65vh)",
paddingBlock: "var(--space-0-5)",
overflow: "auto",
overscrollBehavior: "contain",
},
".cm-lsp-signature-row": {
color: "var(--fg-secondary)",
whiteSpace: "pre-wrap",
overflowWrap: "anywhere",
lineHeight: "1.5",
padding: "var(--space-0-5) var(--space-2)",
paddingInlineStart: "calc(var(--space-2) + 2ch)",
textIndent: "-2ch",
},
".cm-lsp-signature-row": { color: "var(--fg-subtle)", whiteSpace: "pre-wrap", lineHeight: "max(20px, 1.5em)" },
".cm-lsp-signature-active": {
color: "var(--fg-strong)",
backgroundColor: "var(--bg-identifier-under-caret, color-mix(in srgb, var(--accent) 14%, transparent))",
margin: "0 -10px",
padding: "0 10px",
},
".cm-lsp-signature-disabled": { opacity: "0.55" },
".cm-lsp-signature b": { fontWeight: "var(--fw-code-bold, 700)", color: "var(--fg-strong)" },
".cm-lsp-signature-doc": {
borderTop: "1px solid var(--border-popup)",
marginTop: "6px",
paddingTop: "6px",
maxHeight: "160px",
overflow: "auto",
marginTop: "var(--space-1)",
padding: "var(--space-2)",
},
".cm-tooltip:has(> .cm-lsp-hint)": { background: "none", border: "none", boxShadow: "none" },
".cm-lsp-hint": {
+67 -35
Переглянути файл
@@ -1,7 +1,6 @@
.dialog [data-dialog-body] {
display: flex;
flex-direction: column;
overflow: hidden;
}
.body {
@@ -9,8 +8,8 @@
min-height: 0;
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: 14px;
gap: var(--space-2);
padding: var(--space-3);
font-size: var(--fs-ui);
color: var(--fg);
}
@@ -18,54 +17,34 @@
.header {
flex: none;
display: grid;
grid-template-columns: 150px 1fr 1fr;
gap: var(--space-3);
grid-template-columns: minmax(0, 0.75fr) minmax(0, 1fr) minmax(0, 1.25fr);
align-items: end;
gap: var(--space-2);
}
.field {
flex: none;
display: flex;
flex-direction: column;
gap: var(--space-1-5);
gap: var(--space-1);
min-width: 0;
}
.parameters {
flex: 1 1 auto;
min-height: 0;
min-height: calc(var(--h-list-row) * 5);
display: flex;
flex-direction: column;
border: 1px solid var(--border);
border-radius: 4px;
border-radius: var(--radius-control);
overflow: hidden;
}
.toolbar {
flex: none;
display: flex;
gap: var(--space-1);
padding: 2px 4px;
border-bottom: 1px solid var(--border);
}
.table {
flex: 1 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
}
.head,
.row {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
align-items: center;
gap: var(--space-2);
padding: 0 8px;
min-height: var(--h-list-row);
}
.head {
color: var(--fg-muted);
padding: var(--space-0-5) var(--space-1);
border-bottom: 1px solid var(--border);
}
@@ -73,6 +52,57 @@
flex: 1 1 auto;
min-height: 0;
overflow: auto;
scroll-padding-block-start: var(--h-list-row);
}
.table {
width: 100%;
table-layout: fixed;
border-spacing: 0;
}
.table :is(th, td) {
padding: 0 var(--space-2);
}
.table th {
position: sticky;
top: 0;
z-index: 1;
height: var(--h-list-row);
border-bottom: 1px solid var(--border);
background: var(--bg-dialog, var(--bg-elev));
color: var(--fg-muted);
text-align: start;
font-weight: 400;
}
.table th:first-child {
width: 42%;
}
.table th:first-child:nth-last-child(3) {
width: 36%;
}
.table th:nth-child(3) {
width: 28%;
}
.body .code,
.preview {
font-family: var(--signature-font-family, var(--font-mono));
font-size: var(--signature-font-size, var(--fs-code));
font-weight: var(--signature-font-weight, var(--fw-code));
}
.body .code {
width: 100%;
height: max(var(--h-field), calc(var(--signature-font-size, var(--fs-code)) + var(--space-2)));
}
.row .code:focus-visible {
box-shadow: inset 0 -1px var(--focus-ring);
}
.row:hover {
@@ -84,14 +114,16 @@
}
.preview {
height: clamp(56px, 18vh, 128px);
margin: 0;
padding: 6px 8px;
padding: var(--space-1-5) var(--space-2);
border: 1px solid var(--border);
border-radius: 4px;
font-family: var(--font-mono);
font-size: var(--fs-code);
border-radius: var(--radius-control);
overflow: auto;
white-space: pre-wrap;
overflow-wrap: anywhere;
line-height: 1.5;
user-select: text;
color: var(--fg);
background: var(--bg-input);
}
+100 -54
Переглянути файл
@@ -1,5 +1,5 @@
/** IDEA's Change Signature dialog for Java methods (`signature.ts`). */
import { useEffect, useRef, useState } from "react";
import { useEffect, useId, useLayoutEffect, useRef, useState, type CSSProperties } from "react";
import type { MethodSignature } from "@/bindings";
import { Checkbox, Dialog, IconButton, Input, Select, Spinner, T, Toolbar } from "@/ui";
import { useTx } from "@/platform/i18n";
@@ -34,6 +34,16 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
const [delegate, setDelegate] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const previewLabel = useId();
const selectedRow = useRef<HTMLTableRowElement>(null);
const [codeStyle] = useState(() => {
const { fontFamily, fontSize, fontWeight } = getComputedStyle(request.view.contentDOM);
return {
"--signature-font-family": fontFamily,
"--signature-font-size": fontSize,
"--signature-font-weight": fontWeight,
} as CSSProperties;
});
const signature: MethodSignature = {
...info,
@@ -45,6 +55,10 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
const problem = signatureProblem(signature);
const ready = !busy && !problem && signatureChanged(info, signature);
const current = Math.min(selected, rows.length - 1);
const hasNewParameters = rows.some((row) => row.originalIndex < 0);
useLayoutEffect(() => {
selectedRow.current?.scrollIntoView({ block: "nearest", inline: "nearest" });
}, [current, rows.length]);
// Closing the dialog cancels a refactoring still being checked: it applies nothing.
const running = useRef<AbortController | null>(null);
@@ -93,7 +107,8 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
title="Change Signature"
className={styles.dialog}
width={640}
minHeight={380}
minWidth={360}
minHeight={360}
maxHeight={640}
resizable="both"
buttons={[
@@ -110,7 +125,7 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
) : undefined
}
>
<div className={styles.body}>
<div className={styles.body} style={codeStyle}>
<div className={styles.header}>
<label className={styles.field}>
<T>Visibility:</T>
@@ -123,11 +138,18 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
</label>
<label className={styles.field}>
<T>Return type:</T>
<Input mono value={returnType} onChange={(e) => setReturnType(e.target.value)} />
<Input className={styles.code} mono value={returnType} onChange={(e) => setReturnType(e.target.value)} />
</label>
<label className={styles.field}>
<T>Name:</T>
<Input mono autoFocus autoSelect value={methodName} onChange={(e) => setMethodName(e.target.value)} />
<Input
className={styles.code}
mono
data-autofocus
autoSelect
value={methodName}
onChange={(e) => setMethodName(e.target.value)}
/>
</label>
</div>
<div className={styles.parameters}>
@@ -142,59 +164,83 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
onClick={() => move(1)}
/>
</Toolbar>
<div className={styles.table} role="table" aria-label={tx("Parameters")}>
<div className={styles.head} role="row">
<span role="columnheader">
<T>Type</T>
</span>
<span role="columnheader">
<T>Name</T>
</span>
<span role="columnheader">
<T>Default value</T>
</span>
</div>
<div className={styles.rows}>
{rows.map((row, i) => (
<div
key={row.key}
className={styles.row}
role="row"
aria-selected={i === current}
onFocusCapture={() => setSelected(i)}
>
<Input
mono
variant="bare"
aria-label={tx("Type")}
value={row.type}
autoFocus={row.originalIndex < 0 && !row.type}
onChange={(e) => update(row.key, { type: e.target.value })}
/>
<Input
mono
variant="bare"
aria-label={tx("Name")}
value={row.name}
onChange={(e) => update(row.key, { name: e.target.value })}
/>
<Input
mono
variant="bare"
aria-label={tx("Default value")}
value={row.originalIndex < 0 ? row.defaultValue : ""}
disabled={row.originalIndex >= 0}
onChange={(e) => update(row.key, { defaultValue: e.target.value })}
/>
</div>
))}
</div>
<div className={styles.rows}>
<table className={styles.table} aria-label={tx("Parameters")}>
<thead>
<tr>
<th scope="col">
<T>Type</T>
</th>
<th scope="col">
<T>Name</T>
</th>
{hasNewParameters && (
<th scope="col">
<T>Default value</T>
</th>
)}
</tr>
</thead>
<tbody>
{rows.map((row, i) => (
<tr
key={row.key}
ref={i === current ? selectedRow : undefined}
className={styles.row}
aria-selected={i === current}
onFocusCapture={() => setSelected(i)}
>
<td>
<Input
className={styles.code}
mono
variant="bare"
aria-label={tx("Type")}
value={row.type}
title={row.type}
autoFocus={row.originalIndex < 0 && !row.type}
onChange={(e) => update(row.key, { type: e.target.value })}
/>
</td>
<td>
<Input
className={styles.code}
mono
variant="bare"
aria-label={tx("Name")}
value={row.name}
title={row.name}
onChange={(e) => update(row.key, { name: e.target.value })}
/>
</td>
{hasNewParameters && (
<td>
{row.originalIndex < 0 && (
<Input
className={styles.code}
mono
variant="bare"
aria-label={tx("Default value")}
value={row.defaultValue}
onChange={(e) => update(row.key, { defaultValue: e.target.value })}
/>
)}
</td>
)}
</tr>
))}
</tbody>
</table>
</div>
</div>
<Checkbox checked={delegate} onChange={setDelegate} label={<T>Delegate via overloading method</T>} />
<div className={styles.field}>
<T>Signature Preview</T>
<pre className={styles.preview}>{signatureText(signature)}</pre>
<span id={previewLabel}>
<T>Signature Preview</T>
</span>
<pre className={styles.preview} role="region" aria-labelledby={previewLabel} tabIndex={0}>
{signatureText(signature)}
</pre>
</div>
{(error ?? (signatureChanged(info, signature) ? problem : null)) && (
<span className={styles.error} role="alert">
+1 -1
Переглянути файл
@@ -16,7 +16,7 @@ const info: MethodSignature = {
describe("change signature", () => {
it("previews the signature like the declaration", () => {
expect(signatureText(info)).toBe("public int sum(int a, int b) throws java.io.IOException");
expect(signatureText(info)).toBe("public int sum(\n int a,\n int b\n) throws java.io.IOException");
expect(signatureText({ ...info, modifier: "", parameters: [], exceptions: [] })).toBe("int sum()");
});
+4 -3
Переглянути файл
@@ -36,7 +36,7 @@ export const parameterRow = (p: SignatureParameter): ParameterRow => ({ ...p, ke
export const newParameter = (): ParameterRow =>
parameterRow({ type: "", name: "", defaultValue: "", originalIndex: -1 });
/** `public int sum(int a, int b) throws IOException`, as the dialog's preview shows it. */
/** Formats the declaration for the dialog's preview. */
export function signatureText(sig: {
modifier: string;
returnType: string;
@@ -44,8 +44,9 @@ export function signatureText(sig: {
parameters: readonly SignatureParameter[];
exceptions?: readonly { type: string }[];
}): string {
const params = sig.parameters.map((p) => `${p.type} ${p.name}`.trim()).join(", ");
const head = [sig.modifier, sig.returnType, `${sig.methodName}(${params})`].filter(Boolean).join(" ");
const params = sig.parameters.map((p) => `${p.type} ${p.name}`.trim());
const args = params.length > 1 ? `\n ${params.join(",\n ")}\n` : (params[0] ?? "");
const head = [sig.modifier, sig.returnType, `${sig.methodName}(${args})`].filter(Boolean).join(" ");
const throws = sig.exceptions?.length ? ` throws ${sig.exceptions.map((e) => e.type).join(", ")}` : "";
return head + throws;
}
+3 -1
Переглянути файл
@@ -1,6 +1,7 @@
/** Import Sessions from Other Apps: pick sessions a scan found now, and import them as tasks. */
import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent } from "react";
import { Button, Dialog, Icon, List, SearchField, Spinner, T, listNavigate, rowSelectionMode, selectRow } from "@/ui";
import { useRowHeight } from "@/ui/density";
import { hasPrimaryModifier } from "@/platform/keymap";
import { relativePath, useProject } from "@/platform/project";
import { useTx } from "@/platform/i18n";
@@ -41,6 +42,7 @@ function folderOf(cwd: string | null, root: string | undefined): string {
function ImportSessionsDialog() {
const tx = useTx();
const rowHeight = useRowHeight(ROW);
const listId = useId();
const root = useProject((s) => s.project?.root);
const external = useAgents((s) => s.external);
@@ -216,7 +218,7 @@ function ImportSessionsDialog() {
activeIndex={lead}
onSelect={select}
isSelected={(r) => !!sel.keys?.has(r.key)}
rowHeight={ROW}
rowHeight={rowHeight}
aria-label={tx("Sessions from other apps")}
empty={
<div className={styles.empty}>
-1
Переглянути файл
@@ -176,7 +176,6 @@ function ExecutePopup({ tool }: { tool: BuildTool }) {
}}
focusable={false}
hoverSelects={false}
rowHeight={24}
sectionHeight={28}
className={styles.completions}
aria-label="Completions"
+54 -17
Переглянути файл
@@ -5,18 +5,27 @@
overflow: hidden;
}
.header {
height: 26px;
flex: none;
display: flex;
align-items: center;
gap: var(--space-2);
padding: 0 10px;
flex-wrap: wrap;
min-height: var(--h-field);
gap: var(--space-0-5) var(--space-2);
padding: var(--space-0-5) 10px;
border-bottom: 1px solid var(--border-popup);
font-size: var(--fs-small);
font-size: var(--fs-ui);
color: var(--fg-muted);
}
.actions {
display: flex;
align-items: center;
flex-wrap: wrap;
min-width: 0;
gap: var(--space-0-5) var(--space-2);
font-size: var(--fs-small);
}
.scope {
flex: none;
max-width: min(100%, 18em);
}
.searching {
@@ -26,23 +35,32 @@
}
.title {
flex: 1;
flex: 1 1 160px;
display: flex;
align-items: baseline;
gap: var(--space-1);
min-width: 0;
color: var(--fg-emphasis);
}
.titleLabel {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--fg-emphasis);
}
.count {
flex: none;
white-space: nowrap;
font-size: var(--fs-small);
color: var(--fg-subtle);
}
.link {
flex: none;
max-width: 100%;
border: none;
background: none;
padding: 0;
font: inherit;
color: var(--link);
text-align: left;
cursor: pointer;
}
.link:hover {
@@ -52,7 +70,6 @@
.body {
display: flex;
flex-direction: column;
min-height: 24px;
padding: 2px 0;
box-sizing: content-box;
}
@@ -60,21 +77,31 @@
flex: 1;
}
.row {
display: flex;
display: grid;
grid-template-columns: min(34%, 176px) 5ch minmax(0, 1fr);
align-items: center;
gap: var(--space-2);
min-width: 0;
width: 100%;
}
.file {
display: flex;
align-items: center;
gap: var(--space-1);
min-width: 0;
}
.icon {
flex: none;
color: var(--fg-muted);
}
.spacer {
flex: 1;
.fileName {
overflow: hidden;
text-overflow: ellipsis;
}
.where {
flex: none;
.line {
overflow: hidden;
text-align: right;
font-variant-numeric: tabular-nums;
font-size: var(--fs-small);
color: var(--fg-subtle);
}
@@ -95,12 +122,15 @@
outline: none;
}
.filter {
flex: none;
max-width: 12ch;
font-family: var(--font-mono);
color: var(--fg-strong);
background: var(--accent-soft);
border-radius: var(--radius-small);
padding: 0 4px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.noMatch {
color: var(--danger);
@@ -111,8 +141,9 @@
font-size: var(--fs-small);
}
.preview {
flex: none;
height: 200px;
flex: 0 1 auto;
height: min(164px, 32vh);
min-height: min(64px, 18vh);
border-top: 1px solid var(--border-popup);
overflow: hidden;
}
@@ -131,3 +162,9 @@
.previewMatch {
background: var(--bg-text-search-result);
}
@media (max-width: 600px) {
.title {
flex-basis: 100%;
}
}
+52 -42
Переглянути файл
@@ -12,6 +12,7 @@ import { codePreviewExtensions } from "@/editor/api";
import { basename } from "@/platform/project";
import { shortcutLabel } from "@/platform/keymap";
import { Icon, IconButton, List, Popup, Select, Spinner, fileIconName, listNavigate } from "@/ui";
import { useRowHeight } from "@/ui/density";
import { openLocation, readFileLines } from "./ipc";
import {
dismissUsagesPopup,
@@ -83,6 +84,7 @@ const ROW = 24;
function UsagesPopupInner() {
const { anchor, symbol, groups, note, loading, scope } = useUsagesPopup();
const preview = useUsagesPopupPreview((s) => s.preview);
const rowHeight = useRowHeight(ROW);
const all = useMemo<Usage[]>(() => groups.flatMap((g) => g.usages), [groups]);
const [filter, setFilter] = useState("");
const accessOptions = useUsageAccessOptions();
@@ -93,6 +95,7 @@ function UsagesPopupInner() {
const [active, setActive] = useState(0);
const current = Math.min(active, items.length - 1);
const total = usageCount(groups);
const rowCount = Math.max(1, Math.min(14, items.length));
const pick = (u: Usage | undefined) => {
if (!u) return;
close();
@@ -158,46 +161,48 @@ function UsagesPopupInner() {
>
<div className={styles.header}>
<span className={styles.title}>
{symbol ? tx`Usages of ${symbol}` : tx("Usages")}{" "}
<span className={styles.titleLabel}>{symbol ? tx`Usages of ${symbol}` : tx("Usages")}</span>{" "}
<span className={styles.count}>
{filter || items.length !== total ? tx`${items.length} of ${total} found` : tx`${total} found`}
</span>
</span>
{scope && (
<Select<UsageScope>
variant="ghost"
aria-label={tx("Scope")}
className={styles.scope}
value={scope}
options={[
{ value: "project", label: tx("Project Files") },
{ value: "libraries", label: tx("Project and Libraries") },
]}
onChange={setUsagesPopupScope}
<div className={styles.actions}>
{scope && (
<Select<UsageScope>
variant="ghost"
aria-label={tx("Scope")}
className={styles.scope}
value={scope}
options={[
{ value: "project", label: tx("Project Files") },
{ value: "libraries", label: tx("Project and Libraries") },
]}
onChange={setUsagesPopupScope}
/>
)}
{loading && (
<span className={styles.searching} role="status" aria-label={tx("Searching for more usages")}>
<Spinner size={16} variant="spokes" />
</span>
)}
{filter && (
<span className={clsx(styles.filter, !items.length && styles.noMatch)} role="status">
{filter}
</span>
)}
<IconButton
icon="preview-details"
size="small"
title="Show Preview"
pressed={preview}
onMouseDown={(e) => e.preventDefault()}
onClick={() => setUsagesPopupPreview(!preview)}
/>
)}
{loading && (
<span className={styles.searching} role="status" aria-label={tx("Searching for more usages")}>
<Spinner size={16} variant="spokes" />
</span>
)}
{filter && (
<span className={clsx(styles.filter, !items.length && styles.noMatch)} role="status">
{filter}
</span>
)}
<IconButton
icon="preview-details"
size="small"
title="Show Preview"
pressed={preview}
onMouseDown={(e) => e.preventDefault()}
onClick={() => setUsagesPopupPreview(!preview)}
/>
<button type="button" className={styles.link} onClick={openInFindWindow}>
{tx("Open in Find Window")}
{keys ? ` ${keys}` : ""}
</button>
<button type="button" className={styles.link} onClick={openInFindWindow}>
{tx("Open in Find Window")}
{keys ? ` ${keys}` : ""}
</button>
</div>
</div>
<UsageAccessFilter items={all} />
{note && (
@@ -205,7 +210,10 @@ function UsagesPopupInner() {
{note}
</div>
)}
<div className={styles.body} style={{ height: Math.max(1, Math.min(14, items.length)) * ROW }}>
<div
className={styles.body}
style={{ height: rowCount * rowHeight, minHeight: `min(${Math.min(rowCount, 3) * rowHeight}px, 18vh)` }}
>
<List
items={items}
getKey={(u) =>
@@ -215,7 +223,7 @@ function UsagesPopupInner() {
onActiveChange={setActive}
focusable={false}
hoverSelects
rowHeight={ROW}
rowHeight={rowHeight}
aria-label="Usages"
onActivate={pick}
empty={
@@ -225,12 +233,14 @@ function UsagesPopupInner() {
}
renderItem={(u) => (
<div className={styles.row} data-testid="usage-row" data-path={u.path} data-line={u.line}>
<Icon name={fileIconName(basename(u.path), u.path)} size={16} className={styles.icon} />
<UsagePreview usage={u} />
<span className={styles.spacer} />
<span className={styles.where}>
{basename(u.path)}:{u.line + 1}
<span className={styles.file}>
<Icon name={fileIconName(basename(u.path), u.path)} size={16} className={styles.icon} />
<span className={styles.fileName} title={u.path}>
{basename(u.path)}
</span>
</span>
<span className={styles.line}>{u.line + 1}</span>
<UsagePreview usage={u} />
</div>
)}
/>
+32 -7
Переглянути файл
@@ -25,15 +25,15 @@
background: var(--border);
}
.summary {
height: 26px;
min-height: 26px;
flex: none;
display: flex;
align-items: center;
gap: var(--space-1-5);
padding: 0 10px;
flex-wrap: wrap;
gap: var(--space-0-5) var(--space-1-5);
padding: var(--space-0-5) 10px;
font-size: var(--fs-ui);
color: var(--fg-subtle);
white-space: nowrap;
}
.groupLabel {
color: var(--fg);
@@ -42,12 +42,13 @@
color: var(--danger);
}
.link {
flex: none;
max-width: 100%;
border: none;
background: none;
padding: 0;
font: inherit;
color: var(--link);
text-align: left;
cursor: pointer;
}
.link:hover {
@@ -81,9 +82,18 @@
flex: none;
}
.file {
flex: none;
max-width: 56%;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg);
}
.muted,
.directory {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-subtle);
}
.count {
flex: none;
color: var(--fg-subtle);
@@ -101,7 +111,7 @@
overflow: hidden;
text-overflow: ellipsis;
font-family: var(--font-mono);
font-size: var(--fs-ui);
font-size: var(--fs-code);
color: var(--fg);
}
.match {
@@ -135,3 +145,18 @@
flex: 1;
min-height: 0;
}
.splitFrame {
display: flex;
min-width: 0;
}
.sourcePreview {
display: flex;
flex-direction: column;
font-family: var(--font-mono);
font-size: var(--fs-code);
line-height: 1.45;
}
.sourcePreview .sourceText[role="region"] {
font: inherit;
font-weight: var(--fw-code);
}
+53 -19
Переглянути файл
@@ -2,11 +2,13 @@
* "usages" tool window: Find Usages results grouped by file with line
* previews, one tab per search (pinnable, as the Find tool window's tabs).
*/
import { useCallback, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { useCallback, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import clsx from "clsx";
import { create } from "zustand";
import { previewColors, tokenSpans, useLineTokens } from "@/editor/lineTokens";
import { formatMessage, useTx } from "@/platform/i18n";
import { useEditorPrefs } from "@/platform/editorSettings";
import { BUNDLED_MONO_FAMILY, monoFontFamily } from "@/platform/fonts";
import { shortcutLabel } from "@/platform/keymap";
import { basename, relativeDir, useProject } from "@/platform/project";
import { maybeEditorService, useOccurrenceNavigator } from "@/workbench/contributions";
@@ -245,8 +247,12 @@ export function UsagesView() {
return (
<span className={clsx(styles.row, isExcluded(n) && styles.excluded)}>
<Icon name={fileIconName(basename(path), path)} size={16} className={styles.icon} />
<span className={styles.file}>{basename(path)}</span>
<span className={styles.muted}>{relativeDir(root, path)}</span>
<span className={styles.file} title={path}>
{basename(path)}
</span>
<span className={styles.directory} title={path}>
{relativeDir(root, path)}
</span>
<span className={styles.count}>
{n.group.usages.length} {tx(n.group.usages.length === 1 ? "usage" : "usages")}
</span>
@@ -401,34 +407,62 @@ export function useUsagesHeaderMenu(): MenuItem[] {
function UsagesSplit({ preview, children }: { preview: ReactNode; children: ReactNode }) {
const show = useUsagesOptions((s) => s.preview);
const frame = useRef<HTMLDivElement>(null);
const [stacked, setStacked] = useState(false);
useLayoutEffect(() => {
const el = frame.current;
if (!show || !el) return;
const measure = () => setStacked(el.clientWidth < 580);
measure();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(measure);
observer.observe(el);
return () => observer.disconnect();
}, [show]);
if (!show) return children;
return (
<SplitGroup orientation="horizontal" id="usages-preview-split" storageKey="openidea.usages.previewSplit">
<SplitPanel id="usages" minSize={160} className={styles.panel}>
{children}
</SplitPanel>
<SplitHandle />
<SplitPanel id="preview" minSize={160} defaultSize="45%" className={styles.panel}>
{preview}
</SplitPanel>
</SplitGroup>
<div ref={frame} className={styles.splitFrame}>
<SplitGroup
orientation={stacked ? "vertical" : "horizontal"}
id="usages-preview-split"
storageKey={stacked ? "openidea.usages.previewSplit.vertical" : "openidea.usages.previewSplit"}
>
<SplitPanel id="usages" minSize={stacked ? "30%" : 160} className={styles.panel}>
{children}
</SplitPanel>
<SplitHandle />
<SplitPanel id="preview" minSize={stacked ? "30%" : 160} defaultSize="45%" className={styles.panel}>
{preview}
</SplitPanel>
</SplitGroup>
</div>
);
}
function UsagesPreview({ node }: { node: Node | null }) {
const usage = node?.kind === "usage" ? node.usage : node?.kind === "file" ? (node.group.usages[0] ?? null) : null;
const search = useUsages(activeUsageSearch);
const settings = useProject((s) => s.settings?.editor);
const { fallbackFont } = useEditorPrefs();
const family = settings?.fontFamily;
const fontFamily =
(family && family !== BUNDLED_MONO_FAMILY) || fallbackFont.trim()
? monoFontFamily(family, fallbackFont, "var(--font-mono)")
: undefined;
const highlights = useMemo(() => {
const group = usage && search?.groups.find((g) => g.path === usage.path);
return (group?.usages ?? []).map((u) => ({ line: u.line, ranges: [[u.col, u.endCol] as const] }));
}, [usage, search?.groups]);
return (
<SourcePreview
path={usage?.path ?? null}
line={usage?.line ?? 0}
highlights={highlights}
load={previewText}
colorize={previewColors}
/>
<div className={styles.sourcePreview} style={{ fontFamily, fontSize: settings?.fontSize ?? undefined }}>
<SourcePreview
path={usage?.path ?? null}
line={usage?.line ?? 0}
highlights={highlights}
load={previewText}
colorize={previewColors}
className={styles.sourceText}
/>
</div>
);
}
+3 -1
Переглянути файл
@@ -7,6 +7,7 @@ import { Icon, Input, List, Popup, listNavigate } from "@/ui";
import { tx } from "@/platform/i18n";
import type { GridColumn } from "./Grid";
import styles from "./Database.module.css";
import { useRowHeight } from "@/ui/density";
export function filterColumns(columns: readonly GridColumn[], query: string): number[] {
const q = query.trim().toLowerCase();
@@ -24,6 +25,7 @@ export function ColumnsPopup(props: {
onPick: (col: number) => void;
onClose: () => void;
}) {
const rowHeight = useRowHeight(22);
const [query, setQuery] = useState("");
const [active, setActive] = useState(0);
const shown = filterColumns(props.columns, query);
@@ -72,7 +74,7 @@ export function ColumnsPopup(props: {
onActivate={(_, i) => pick(i)}
focusable={false}
hoverSelects
rowHeight={22}
rowHeight={rowHeight}
aria-label={tx("Columns")}
className={styles.columnsList}
empty={<span>{tx("No matching columns")}</span>}
+28
Переглянути файл
@@ -154,6 +154,28 @@
flex: 1;
min-height: 0;
}
/* A console's request in flight; the previous result stays below it. */
.executing {
flex: none;
display: flex;
align-items: center;
gap: var(--space-2);
min-width: 0;
padding: var(--space-1) var(--space-3);
border-bottom: 1px solid var(--border);
color: var(--fg-muted);
font-size: var(--fs-small);
}
.executingText {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.executingTime {
flex: none;
font-variant-numeric: tabular-nums;
}
/* Gives way before the name does. */
.treeDetail {
color: var(--fg-muted);
@@ -657,6 +679,12 @@
}
/* Console run feedback: timing after a statement, gutter check / error, error banner. */
:global(.cm-openidea-db-executing) {
background: var(--accent-soft);
}
:global(.cm-openidea-db-elapsed) {
font-variant-numeric: tabular-nums;
}
:global(.cm-openidea-db-timing) {
margin-left: 1.5em;
color: var(--fg-muted);
+1
Переглянути файл
@@ -30,6 +30,7 @@ vi.mock("@tanstack/react-virtual", () => ({
getTotalSize: () => count * 24,
getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 24, key: index })),
scrollToIndex: () => {},
measure: () => {},
}),
}));
+41 -3
Переглянути файл
@@ -16,6 +16,8 @@ import {
type MouseEvent,
} from "react";
import clsx from "clsx";
import { useShallow } from "zustand/react/shallow";
import { basename } from "@/platform/project";
import { call, commands, type DbPlanNode, type DbQueryResult } from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
import { setContext } from "@/platform/context";
@@ -35,7 +37,7 @@ import {
resolveTarget,
type EditBlockReason,
} from "./resultEditing";
import { pageWindow } from "./resultView";
import { formatElapsed, pageWindow } from "./resultView";
import { resultTabMenu } from "./resultTabActions";
import { analyze } from "./sql/analyze";
import { nameMatcher } from "./sql/dialect";
@@ -55,6 +57,7 @@ import {
rerunResult,
useDatabase,
withConnection,
type ConsoleExecution,
type OutputLine,
type ResultTab,
} from "./store";
@@ -271,8 +274,8 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
const editability = useMemo(() => resultEditability(text, driver), [text, driver]);
const model = useDatabase((s) => s.completion[tab.sourceId]) ?? null;
const target = useMemo(
() => (editability.kind === "editable" ? resolveTarget(editability, model, tab.schema, driver) : null),
[editability, model, tab.schema, driver],
() => (editability.kind === "editable" ? resolveTarget(editability, model, tab.schema) : null),
[editability, model, tab.schema],
);
const detailsId = target ? detailsKey(tab.sourceId, target.schema ?? "", target.table) : null;
const details = useDatabase((s) => (detailsId ? s.details[detailsId] : undefined));
@@ -744,8 +747,40 @@ function PinButton({ tab }: { tab: ResultTab }) {
);
}
/** The most recently started console request, while it runs. */
function useLatestExecution(): [string, ConsoleExecution] | undefined {
return useDatabase(
useShallow((s) => {
let latest: [string, ConsoleExecution] | undefined;
for (const entry of Object.entries(s.executions))
if (!latest || entry[1].startedAt > latest[1].startedAt) latest = entry;
return latest;
}),
);
}
function ExecutingBar({ path, execution }: { path: string; execution: ConsoleExecution }) {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const timer = setInterval(() => setNow(Date.now()), 100);
return () => clearInterval(timer);
}, [execution.startedAt]);
const name = basename(path);
const count = execution.statements;
return (
<div className={styles.executing} role="status">
<Spinner size={12} label={tx("Executing")} />
<span className={styles.executingText} title={path}>
{count > 1 ? tx`Executing ${count} statements in ${name}…` : tx`Executing in ${name}…`}
</span>
<span className={styles.executingTime}>{formatElapsed(Math.max(0, now - execution.startedAt))}</span>
</div>
);
}
export function ResultsView() {
const results = useDatabase((s) => s.results);
const execution = useLatestExecution();
const active = useDatabase((s) => s.activeResult);
const hasOutput = useDatabase((s) => s.output.length > 0);
const root = useRef<HTMLDivElement>(null);
@@ -772,6 +807,8 @@ export function ResultsView() {
owner: e.currentTarget,
});
};
const executing = execution && <ExecutingBar path={execution[0]} execution={execution[1]} />;
if (!results.length && !hasOutput && executing) return <div className={styles.view}>{executing}</div>;
if (!results.length && !hasOutput)
return (
<EmptyState title="No results">
@@ -825,6 +862,7 @@ export function ResultsView() {
]}
/>
</ToolWindowContentTabs>
{executing}
<div
ref={panel}
className={styles.fill}
+255 -64
Переглянути файл
@@ -23,6 +23,7 @@ import {
Facet,
Prec,
RangeSet,
type Range,
StateEffect,
StateField,
type Extension,
@@ -42,12 +43,29 @@ import {
import { useEffect, useMemo, useRef, useState, type PointerEvent } from "react";
import { createRoot } from "react-dom/client";
import type { EditorDocContext } from "@/editor/api";
import { iconNode } from "@/ui/iconNode";
import { call, commands, type DbDriver, type DbSessionContext, type DbStatementOutcome } from "@/platform/ipc";
import { iconNode, spinnerNode } from "@/ui/iconNode";
import {
call,
commands,
type DbDriver,
type DbSessionContext,
type DbStatementOutcome,
type SqlStatement,
} from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
import { Icon, IconButton, Select, Toolbar, lazyComponent } from "@/ui";
import { useProject } from "@/platform/project";
import { activeSchema, schemaSwitchable, sourceIcon, sourceLabel, splitTarget, targetOf } from "./model";
import {
activeSchema,
parseSchemaTreeValue,
schemaSwitchable,
schemaTreeRows,
schemaTreeValue,
sourceIcon,
sourceLabel,
splitTarget,
targetOf,
} from "./model";
import { loadSavedCatalog, offerIntrospection } from "./introspection";
import { analyze, templateContexts, valuesSlot } from "./sql/analyze";
import {
@@ -82,7 +100,6 @@ import {
setConsoleSchema,
setManualCommit,
sourceById,
targetLabel,
useDatabase,
} from "./store";
import styles from "./Database.module.css";
@@ -93,6 +110,7 @@ import type { ResultTab } from "./store";
/** `templates` feature's language-data key for finer template contexts. */
const TEMPLATE_CONTEXT_KEY = "openideaTemplateContexts";
import { formatElapsed } from "./resultView";
import { SQL_LANGUAGE } from "./sqlLanguage";
export { SQL_LANGUAGE };
const ROW_LIMITS = ["100", "500", "1000", "5000", "50000"];
@@ -107,19 +125,40 @@ interface RunMark {
ms: number | null;
}
/** The statements a running request submitted (a batch: all of them, in order). */
interface Executing {
/** Tells this run from a later one on the same console. */
token: number;
/** The statements' offsets in the text sent. */
sent: readonly { from: number; to: number }[];
/** Where they are now. */
spans: readonly { from: number; to: number }[];
/** Where the elapsed time shows: after the last statement's `;`. */
at: number;
startedAt: number;
}
interface RunState {
marks: readonly RunMark[];
/** Message of the bottom error banner (`null`: hidden). */
banner: string | null;
executing: Executing | null;
}
const setRun = StateEffect.define<RunState>();
const runField = StateField.define<RunState>({
create: () => ({ marks: [], banner: null }),
create: () => ({ marks: [], banner: null, executing: null }),
update(value, tr) {
for (const e of tr.effects) if (e.is(setRun)) return e.value;
if (!tr.docChanged) return value;
// The request runs the text it was sent; edits only move where that shows.
const ex = value.executing;
const executing = ex && {
...ex,
spans: ex.spans.map((r) => ({ from: tr.changes.mapPos(r.from, 1), to: tr.changes.mapPos(r.to, -1) })),
at: tr.changes.mapPos(ex.at),
};
// Editing a statement drops its mark.
const marks: RunMark[] = [];
for (const m of value.marks) {
@@ -135,12 +174,18 @@ const runField = StateField.define<RunState>({
timingAt: tr.changes.mapPos(m.timingAt),
});
}
return { ...value, marks };
return { ...value, marks, executing };
},
provide: (f) => [
EditorView.decorations.from(f, (st) => {
const ranges = [];
const ex = st.executing;
for (const r of ex?.spans ?? [])
if (r.from < r.to) ranges.push(Decoration.mark({ class: "cm-openidea-db-executing" }).range(r.from, r.to));
if (ex) ranges.push(Decoration.widget({ widget: new ElapsedWidget(ex.startedAt), side: 1 }).range(ex.at));
for (const m of st.marks) {
// The new run takes the place of a statement's last outcome.
if (ex?.spans.some((r) => r.from <= m.to && m.from <= r.to)) continue;
if (m.error)
ranges.push(
Decoration.mark({ class: "cm-openidea-db-error", attributes: { title: m.error } }).range(m.from, m.to),
@@ -164,11 +209,47 @@ class TimingWidget extends WidgetType {
toDOM() {
const span = document.createElement("span");
span.className = "cm-openidea-db-timing";
span.textContent = this.ms < 1000 ? `${Math.round(this.ms)} ms` : `${(this.ms / 1000).toFixed(1)} s`;
span.textContent = formatElapsed(this.ms);
return span;
}
}
/** The running time of the request, ticking until it ends. */
class ElapsedWidget extends WidgetType {
private timer: ReturnType<typeof setInterval> | undefined;
constructor(readonly startedAt: number) {
super();
}
eq(other: ElapsedWidget) {
return other.startedAt === this.startedAt;
}
toDOM() {
const span = document.createElement("span");
span.className = "cm-openidea-db-timing cm-openidea-db-elapsed";
const tick = () => {
const elapsed = formatElapsed(Date.now() - this.startedAt);
span.textContent = tx`Executing… ${elapsed}`;
};
tick();
this.timer = setInterval(tick, 100);
return span;
}
destroy() {
clearInterval(this.timer);
}
}
class ExecutingMarker extends GutterMarker {
eq(other: GutterMarker) {
return other instanceof ExecutingMarker;
}
toDOM() {
const el = spinnerNode(12, "cm-openidea-db-run-executing");
el.title = tx("Executing");
return el;
}
}
class RunMarker extends GutterMarker {
constructor(readonly error: string | null) {
super();
@@ -192,9 +273,12 @@ const runGutter = gutter({
markers: (view) => {
const st = view.state.field(runField);
const doc = view.state.doc;
const ranges = st.marks
.filter((m) => m.from <= doc.length)
const ex = st.executing;
const ranges: Range<GutterMarker>[] = st.marks
.filter((m) => m.from <= doc.length && !ex?.spans.some((r) => r.from <= m.to && m.from <= r.to))
.map((m) => new RunMarker(m.error).range(doc.lineAt(m.from).from));
const first = ex?.spans[0];
if (first && first.from <= doc.length) ranges.push(new ExecutingMarker().range(doc.lineAt(first.from).from));
return RangeSet.of(ranges, true);
},
});
@@ -233,20 +317,59 @@ export function markOutcomes(view: EditorView, outcomes: readonly DbStatementOut
}));
const failed = outcomes.find((o) => o.error);
const name = failed ? (sourceById(consoleSource(view.state.facet(consolePath)))?.name ?? "") : "";
view.dispatch({ effects: setRun.of({ marks, banner: failed ? `[${name}] ${failed.error}` : null }) });
view.dispatch({
effects: setRun.of({ ...view.state.field(runField), marks, banner: failed ? `[${name}] ${failed.error}` : null }),
});
}
let nextExecution = 0;
/** `outcomes` at where their statements are now, when the text was edited while they ran. */
function placed(
executing: Executing | null,
token: number,
outcomes: readonly DbStatementOutcome[],
): readonly DbStatementOutcome[] {
if (executing?.token !== token) return outcomes;
return outcomes.map((o) => {
const i = executing.sent.findIndex((r) => r.from === o.statement.from && r.to === o.statement.to);
const now = executing.spans[i];
return now ? { ...o, statement: { ...o.statement, from: now.from, to: now.to } } : o;
});
}
/** Runs `from`–`to` of `view`, showing the submitted statements as executing until the request ends. */
async function executeRange(view: EditorView, path: string, from: number, to: number) {
const token = ++nextExecution;
const sent = view.state.doc;
const start = (statements: readonly SqlStatement[]) => {
// The offsets are into the text sent; an edit since (while asking for parameters) leaves them unplaced.
if (view.state.doc !== sent) return;
const spans = statements.map((st) => ({ from: st.from, to: st.to }));
const last = spans.at(-1);
if (!last) return;
const at = view.state.sliceDoc(last.to, last.to + 1) === ";" ? last.to + 1 : last.to;
const executing = { token, sent: spans, spans, at, startedAt: Date.now() };
view.dispatch({ effects: setRun.of({ ...view.state.field(runField), executing }) });
};
try {
const outcomes = await executeConsole(path, sent.toString(), from, to, start);
if (outcomes.length) markOutcomes(view, placed(view.state.field(runField).executing, token, outcomes));
} finally {
const st = view.state.field(runField, false);
if (st?.executing?.token === token) view.dispatch({ effects: setRun.of({ ...st, executing: null }) });
}
}
/** Runs the statement at the caret (or the selected ones) of `view`. */
export async function executeInView(view: EditorView, path: string) {
const sel = view.state.selection.main;
const outcomes = await executeConsole(path, view.state.doc.toString(), sel.from, sel.to);
if (outcomes.length) markOutcomes(view, outcomes);
await executeRange(view, path, sel.from, sel.to);
}
/** Runs every statement of `view`, in order (stops at the first that fails). */
export async function executeScriptInView(view: EditorView, path: string) {
const outcomes = await executeConsole(path, view.state.doc.toString(), 0, view.state.doc.length);
if (outcomes.length) markOutcomes(view, outcomes);
await executeRange(view, path, 0, view.state.doc.length);
}
/** Explain Plan of the statement at the caret (or the first selected one) of `view`. */
@@ -472,7 +595,6 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
const maxRows = useDatabase((s) => s.maxRows);
const manual = useDatabase((s) => !!bound && s.manualCommit.has(bound));
const pending = useDatabase((s) => !!bound && s.pendingTx.has(bound));
const databases = useDatabase((s) => s.databases);
const inEditor = useProject((s) => inEditorResults(s.settings));
// SQL resolution scopes in the settings can move the console to another data source.
useProject((s) => s.settings);
@@ -480,7 +602,6 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
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]);
@@ -488,49 +609,35 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
const schemaList = useDatabase((s) => (bound ? s.schemas[bound] : undefined));
const schema = activeSchema(pickedSchema, defaultSchema);
useEffect(() => {
if (boundId && (sqlServer || listsDatabases(sourceById(boundId))) && !useDatabase.getState().databases[boundId])
if (boundId && listsDatabases(sourceById(boundId)) && !useDatabase.getState().databases[boundId])
void loadDatabases(boundId);
}, [boundId, sqlServer]);
}, [boundId]);
// Loads the list again after a refresh drops it.
const schemasMissing = !schemaList;
useEffect(() => {
if (bound && switchable && !sqlServer && !useDatabase.getState().schemas[bound]) void loadSchemas(bound);
}, [bound, switchable, sqlServer]);
if (bound && switchable && schemasMissing) void loadSchemas(bound);
}, [bound, switchable, schemasMissing]);
const schemaOptions = useMemo(() => {
if (!switchable) return [];
const databaseList = boundId ? databases[boundId] : undefined;
const names = sqlServer
? databaseList?.status === "ok"
? databaseList.value.names
: []
: schemaList?.status === "ok"
? schemaList.value
: [];
const names = schemaList?.status === "ok" ? schemaList.value : [];
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, icon: "db-schema" });
return out;
}, [switchable, schemaList, defaultSchema, sqlServer, boundId, databases]);
const targets = useMemo(() => {
const out: Array<{ value: string; label: string; detail?: string; icon: string }> = [];
for (const s of sources) {
const id = s.id ?? "";
const dbs = databases[id];
const host = sourceLabel(s).slice((s.name ?? "").length + 1);
if (listsDatabases(s) && dbs?.status === "ok") {
for (const name of dbs.value.names)
out.push({
value: targetOf(id, name, dbs.value.current),
label: `${s.name ?? ""}: ${name}`,
detail: host,
icon: sourceIcon(s),
});
} 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))
out.push({ value: bound, label: targetLabel(bound), icon: "database" });
return out;
}, [sources, databases, bound]);
}, [switchable, schemaList, defaultSchema]);
// IDEA's order: pick the data source, then a database and a schema in it.
const sourceOptions = useMemo(
() =>
sources.map((s) => ({
value: s.id ?? "",
label: s.name ?? "",
verbatim: true,
detail: sourceLabel(s).slice((s.name ?? "").length + 1),
icon: sourceIcon(s),
})),
[sources],
);
useEffect(() => {
if (!loaded) void loadSources();
}, [loaded]);
@@ -617,23 +724,28 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
<Select
variant="ghost"
aria-label="Data source"
value={bound ?? null}
value={boundId}
placeholder={sources.length ? "<data source>" : "None configured"}
options={targets}
onChange={(id) => bindConsole(path, id)}
options={sourceOptions}
searchable
onChange={(id) => id !== boundId && bindConsole(path, id)}
disabled={!sources.length}
/>
{switchable && (
<Select
variant="ghost"
aria-label={sqlServer ? "Database" : "Schema"}
value={schema || null}
placeholder="<schema>"
options={schemaOptions}
searchable={schemaOptions.length > 10}
onChange={(v) => setConsoleSchema(path, v)}
disabled={!bound}
/>
{bound && boundId && switchable && listsDatabases(sourceById(boundId)) ? (
<DatabaseSchemaSwitcher path={path} bound={bound} sourceId={boundId} schema={schema} />
) : (
switchable && (
<Select
variant="ghost"
aria-label="Schema"
value={schema || null}
placeholder="<schema>"
options={schemaOptions}
searchable
onChange={(v) => setConsoleSchema(path, v)}
disabled={!bound}
/>
)
)}
{driver === "sqlite" && (
<span className={styles.consoleSchema} title={tx("Schema")}>
@@ -645,6 +757,85 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
);
}
/**
* The `database.schema` switcher of a data source that shows several databases (IDEA's): a tree of
* its databases, expanding to their schemas. Choosing a schema in another database moves the console there.
*/
function DatabaseSchemaSwitcher({
path,
bound,
sourceId,
schema,
}: {
path: string;
bound: string;
sourceId: string;
schema: string;
}) {
const listed = useDatabase((s) => s.databases[sourceId]);
const schemas = useDatabase((s) => s.schemas);
const read = useDatabase((s) => s.catalogs[sourceId]?.databases);
const current = listed?.status === "ok" ? listed.value.current : null;
const database = splitTarget(bound).database ?? current;
// The console's database starts expanded, again whenever the console moves to another one.
const [opened, setOpened] = useState<{ at: string | null; open: ReadonlySet<string> } | null>(null);
const expanded = useMemo(
() => (opened && opened.at === database ? opened.open : new Set(database ? [database] : [])),
[opened, database],
);
const targetFor = (name: string) => (name === database ? bound : targetOf(sourceId, name, current));
// Schemas of expanded databases that are not read yet, or were dropped by a refresh.
const missing = [...expanded]
.filter((name) => !read?.[name] && !schemas[targetFor(name)])
.map(targetFor)
.join("\n");
useEffect(() => {
for (const target of missing ? missing.split("\n") : []) void loadSchemas(target);
}, [missing]);
const rows = useMemo(() => {
const names = listed?.status === "ok" ? [...listed.value.names] : [];
// The console's database is offered even before the list loads.
if (database && !names.includes(database)) names.unshift(database);
return schemaTreeRows(names, expanded, (name) => {
const target = name === database ? bound : targetOf(sourceId, name, current);
const list = schemas[target];
if (list?.status === "ok") return list.value;
if (read?.[name]) return read[name].map((s) => s.name);
return list?.status === "error" ? { error: list.message } : undefined;
});
}, [listed, database, expanded, schemas, read, bound, sourceId, current]);
const value = database && schema ? schemaTreeValue(database, schema) : null;
return (
<Select
variant="ghost"
aria-label="Database and schema"
value={value}
placeholder="<schema>"
options={rows}
searchable
renderValue={() => (database ? (schema ? `${database}.${schema}` : database) : tx("<schema>"))}
keepOpen={(v) => parseSchemaTreeValue(v).schema === null}
onChange={(v) => {
const pick = parseSchemaTreeValue(v);
if (pick.schema === null) {
const next = new Set(expanded);
if (!next.delete(pick.database)) {
next.add(pick.database);
// Expanding again retries a database whose schemas could not be read.
const target = targetFor(pick.database);
if (useDatabase.getState().schemas[target]?.status === "error") void loadSchemas(target);
}
setOpened({ at: database, open: next });
return;
}
const target = targetFor(pick.database);
if (target !== bound) bindConsole(path, target);
setConsoleSchema(path, pick.schema);
}}
/>
);
}
const quoted = (name: string) => `"${name.replace(/"/g, '""')}"`;
/**
+59 -1
Переглянути файл
@@ -3,9 +3,10 @@ import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useProject } from "@/platform/project";
import { consoleExtension } from "./console";
import { consoleExtension, executeScriptInView } from "./console";
import { SQL_LANGUAGE } from "./sqlLanguage";
import { executeConsole, rerunResult, useDatabase } from "./store";
import { provideToolWindowService } from "@/workbench/contributions";
const backend = vi.hoisted(() => ({ execute: vi.fn(), statements: vi.fn() }));
@@ -30,6 +31,7 @@ const initial = useDatabase.getState();
let runs = 0;
beforeEach(() => {
provideToolWindowService({ show: () => {} } as never);
runs = 0;
useProject.setState({
project: { name: "p", root: "/p", trusted: true } as never,
@@ -134,3 +136,59 @@ describe("In-Editor Results", () => {
view.destroy();
});
});
describe("statements in flight", () => {
it("marks what was submitted with its running time, then the outcome", async () => {
const parent = document.createElement("div");
document.body.append(parent);
const doc = "SELECT 1;\nSELECT 2;\n";
const view = new EditorView({
parent,
state: EditorState.create({
doc,
extensions: consoleExtension({ language: SQL_LANGUAGE, path: PATH } as never),
}),
});
let finish!: () => void;
const gate = new Promise<void>((resolve) => {
finish = resolve;
});
const execute = backend.execute.getMockImplementation()!;
backend.execute.mockImplementationOnce(async (...args: unknown[]) => {
await gate;
return execute(...(args as Parameters<typeof execute>));
});
const executing = () => [...view.dom.querySelectorAll(".cm-openidea-db-executing")].map((e) => e.textContent);
const elapsed = () => view.dom.querySelector(".cm-openidea-db-elapsed")?.textContent;
let pending!: Promise<void>;
await act(async () => {
pending = executeScriptInView(view, PATH);
await vi.waitFor(() => expect(backend.execute).toHaveBeenCalled());
});
expect(executing()).toEqual(["SELECT 1", "SELECT 2"]);
expect(elapsed()).toMatch(/^Executing… \d+ ms$/);
expect(view.dom.querySelector(".cm-openidea-db-run-executing")).not.toBeNull();
// Typing above moves the marks with their text.
act(() => view.dispatch({ changes: { from: 0, insert: "-- a longer note above\n" } }));
expect(executing()).toEqual(["SELECT 1", "SELECT 2"]);
await act(async () => {
finish();
await pending;
});
expect(executing()).toEqual([]);
expect(elapsed()).toBeUndefined();
// The outcomes land on the statements, not on where they were when sent.
const lines = [...view.dom.querySelectorAll(".cm-openidea-db-gutter .cm-gutterElement")]
.filter((e) => e.querySelector(".cm-openidea-db-run-ok"))
.map((e) => e.getBoundingClientRect().top);
expect(lines).toHaveLength(2);
expect(view.dom.querySelectorAll(".cm-openidea-db-timing")).toHaveLength(2);
expect(view.state.doc.lineAt(view.posAtDOM(view.dom.querySelector(".cm-openidea-db-timing")!)).text).toBe(
"SELECT 1;",
);
view.destroy();
});
});
+1
Переглянути файл
@@ -157,6 +157,7 @@ export function activate(): () => void {
manualCommit: new Set(),
pendingTx: new Set(),
running: {},
executions: {},
dialog: null,
newMenuOpen: false,
});
+70
Переглянути файл
@@ -484,3 +484,73 @@ export function parseSourceUrl(raw: string): { source: Partial<DataSource>; pass
if (properties.length) source.properties = properties;
return { source, password };
}
/** A row of the console's database › schema switcher. */
export interface SchemaTreeRow {
value: string;
label: string;
verbatim?: boolean;
icon?: string;
disabled?: boolean;
/** Searching a database's name keeps its schemas visible. */
keywords?: string;
tree: { depth: number; expanded?: boolean };
}
const TREE_SEP = "\u0000";
/** The switcher value of database `database`, or of its schema `schema`. */
export function schemaTreeValue(database: string, schema?: string): string {
return schema === undefined ? `d${TREE_SEP}${database}` : `s${TREE_SEP}${database}${TREE_SEP}${schema}`;
}
/** The database (and schema, for a schema row) a switcher value names. */
export function parseSchemaTreeValue(value: string): { database: string; schema: string | null } {
const [kind, database = "", schema = ""] = value.split(TREE_SEP);
return { database, schema: kind === "s" ? schema : null };
}
/**
* Rows of the switcher (IDEA's `database.schema` popup): every database, each expanded one followed
* by its schemas, a "Loading…" row while `schemasOf` has none for it yet, or the error reading them.
*/
export function schemaTreeRows(
databases: readonly string[],
expanded: ReadonlySet<string>,
schemasOf: (database: string) => readonly string[] | { error: string } | undefined,
): SchemaTreeRow[] {
const out: SchemaTreeRow[] = [];
for (const database of databases) {
const open = expanded.has(database);
out.push({
value: schemaTreeValue(database),
label: database,
verbatim: true,
icon: "database",
tree: { depth: 0, expanded: open },
});
if (!open) continue;
const schemas = schemasOf(database);
if (!schemas || "error" in schemas) {
out.push({
value: `l${TREE_SEP}${database}`,
label: schemas ? schemas.error : "Loading…",
verbatim: !!schemas,
disabled: true,
keywords: database,
tree: { depth: 1 },
});
continue;
}
for (const schema of schemas)
out.push({
value: schemaTreeValue(database, schema),
label: schema,
verbatim: true,
icon: "db-schema",
keywords: database,
tree: { depth: 1 },
});
}
return out;
}
+3
Переглянути файл
@@ -67,6 +67,7 @@ import {
useDatabase,
withConnection,
} from "./store";
import { provideToolWindowService } from "@/workbench/contributions";
const initial = useDatabase.getState();
const initialProject = useProject.getState();
@@ -129,6 +130,8 @@ function switchProject(project: ProjectInfo) {
}
beforeEach(() => {
// `showServiceView` reaches the real service, not the mocked accessor above.
provideToolWindowService({ show: ui.show } as never);
vi.resetAllMocks();
useProject.setState({ project: projectA });
savedSources = [pg, other];
+3 -5
Переглянути файл
@@ -205,12 +205,10 @@ describe("resolveTarget", () => {
expect(resolveTarget(e, model)).toEqual({ schema: "nope", table: "missing", alias: null });
});
it("refuses unresolved defaults and SQL Server database/schema ambiguity", () => {
it("refuses an unresolved default and keeps an explicit schema over the console's", () => {
expect(resolveTarget(editable("SELECT * FROM users"), model, "")).toBeNull();
expect(resolveTarget(editable("SELECT * FROM users"), model, "public", "sqlServer")).toBeNull();
const explicit = editable("SELECT * FROM dbo.users");
expect(resolveTarget(explicit, model, "other_database", "sqlServer")).toBeNull();
expect(resolveTarget(explicit, model, "public", "sqlServer")).toEqual({
expect(resolveTarget(editable("SELECT * FROM users"), model, "sales")?.schema).toBe("sales");
expect(resolveTarget(editable("SELECT * FROM dbo.users"), model, "sales")).toEqual({
schema: "dbo",
table: "users",
alias: null,
-3
Переглянути файл
@@ -227,10 +227,7 @@ export function resolveTarget(
e: Extract<ResultEditability, { kind: "editable" }>,
model: DbCompletion | null,
schema?: string,
driver: DbDriver = "postgres",
): { schema: string | null; table: string; alias: string | null } | null {
// SQL Server switches databases, but table details and edits take a table schema.
if (driver === "sqlServer" && (e.schema === null || (schema && schema !== model?.defaultSchema))) return null;
if (e.schema === null && schema === "") return null;
return { schema: e.schema ?? (schema || model?.defaultSchema || null), table: e.table, alias: e.alias };
}
+6 -1
Переглянути файл
@@ -1,7 +1,7 @@
/**
* Pure helpers of the result views: IDEA's local filter and client-side sort
* of loaded rows, search in the grid, paging of console results, the
* Aggregates of a selection, and the series of the chart.
* Aggregates of a selection, the series of the chart, and how long a statement took.
*/
import type { Cell } from "./model";
@@ -462,3 +462,8 @@ export function pageWindow({ page, pageSize, rows, hasMore, total }: PageState):
export function pageFetch(page: number, pageSize: number): { maxRows: number; skip: number } {
return { maxRows: pageSize, skip: page * pageSize };
}
/** A statement's run time as IDEA shows it: `840 ms`, `3.2 s`. */
export function formatElapsed(ms: number): string {
return ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`;
}
+65 -6
Переглянути файл
@@ -9,6 +9,7 @@ import { ResultsView } from "./ResultsView";
import { executeConsole, explainConsole, pinResult, rerunResult, useDatabase, type ResultTab } from "./store";
import { registerResultTabActions } from "./resultTabActions";
import { activeTableEditor, installTableEditorFocus } from "./tableEditorFocus";
import { provideToolWindowService } from "@/workbench/contributions";
const backend = vi.hoisted(() => ({
driver: "postgres" as DbDriver,
@@ -95,6 +96,7 @@ function show(text: string, columns: Array<{ name: string }>, rows: (string | nu
}
beforeEach(() => {
provideToolWindowService({ show: () => {} } as never);
vi.clearAllMocks();
backend.statements.mockImplementation((_id: unknown, text: string) =>
Promise.resolve({ status: "ok", data: [{ from: 0, to: text.length, text }] }),
@@ -483,15 +485,11 @@ describe("read-only results with a reason", () => {
expect(backend.applyEdits).not.toHaveBeenCalled();
});
it("keeps an unresolved SQL Server table schema read-only", async () => {
it("resolves an unqualified SQL Server table in the console's schema", async () => {
backend.driver = "sqlServer";
show("SELECT * FROM users", [{ name: "id" }, { name: "name" }], [["1", "Ann"]]);
await act(async () => render(<ResultsView />));
expect(await screen.findByRole("note")).toHaveTextContent(
"Read-only: the table schema could not be identified in the result database.",
);
expect(screen.queryByRole("button", { name: "Submit" })).toBeNull();
expect(backend.details).not.toHaveBeenCalled();
expect(backend.details).toHaveBeenCalledWith("pg", "public", "users");
});
it.each(["postgres", "sqlServer"] as const)("matches case-sensitive key columns exactly for %s", async (driver) => {
@@ -809,3 +807,64 @@ describe("result tab reuse (IDEA: new results replace the console's unpinned tab
expect(useDatabase.getState().activeResult).toBe(fresh);
});
});
describe("a console request in flight", () => {
const hold = () => {
let finish!: () => void;
const gate = new Promise<void>((resolve) => {
finish = resolve;
});
const execute = backend.execute.getMockImplementation()!;
backend.execute.mockImplementationOnce(async (...args: unknown[]) => {
await gate;
return execute(...(args as Parameters<typeof execute>));
});
return () => finish();
};
it("shows that it is executing instead of No results on a first run", async () => {
show("SELECT 1", [{ name: "id" }], [["1"]]);
useDatabase.setState({ results: [], activeResult: null, consoles: { "console.sql": "pg" } });
const finish = hold();
await act(async () => render(<ResultsView />));
let pending!: Promise<unknown>;
await act(async () => {
pending = executeConsole("console.sql", "SELECT pg_sleep(5)", 0, 0);
await vi.waitFor(() => expect(backend.execute).toHaveBeenCalled());
});
expect(screen.queryByText("No results")).toBeNull();
expect(screen.getByText("Executing in console.sql…").parentElement).toHaveTextContent(/\d+ ms$/);
await act(async () => {
finish();
await pending;
});
expect(screen.queryByText(/Executing in/)).toBeNull();
expect(useDatabase.getState().executions).toEqual({});
});
it("keeps the previous result visible while the next run executes", async () => {
show("SELECT * FROM users", [{ name: "id" }, { name: "name" }], [["1", "Ann"]]);
useDatabase.setState({ consoles: { "console.sql": "pg" } });
backend.statements.mockResolvedValueOnce({
status: "ok",
data: [
{ from: 0, to: 8, text: "SELECT 1" },
{ from: 10, to: 18, text: "SELECT 2" },
],
});
const finish = hold();
await act(async () => render(<ResultsView />));
let pending!: Promise<unknown>;
await act(async () => {
pending = executeConsole("console.sql", "SELECT 1; SELECT 2", 0, 18);
await vi.waitFor(() => expect(backend.execute).toHaveBeenCalled());
});
expect(screen.getByText("Executing 2 statements in console.sql…")).toBeTruthy();
expect(screen.getByText("Ann")).toBeTruthy();
await act(async () => {
finish();
await pending;
});
expect(screen.queryByText(/Executing/)).toBeNull();
});
});
+37
Переглянути файл
@@ -0,0 +1,37 @@
import { describe, expect, it } from "vitest";
import { parseSchemaTreeValue, schemaTreeRows, schemaTreeValue } from "./model";
describe("console database › schema switcher", () => {
it("round-trips database and schema values", () => {
expect(parseSchemaTreeValue(schemaTreeValue("shop"))).toEqual({ database: "shop", schema: null });
expect(parseSchemaTreeValue(schemaTreeValue("shop", "public"))).toEqual({ database: "shop", schema: "public" });
expect(parseSchemaTreeValue(schemaTreeValue("a.b", "c:d"))).toEqual({ database: "a.b", schema: "c:d" });
});
it("lists schemas under expanded databases only", () => {
const schemas: Record<string, string[]> = { shop: ["public", "audit"], crm: ["public"] };
const rows = schemaTreeRows(["shop", "crm"], new Set(["shop"]), (d) => schemas[d]);
expect(rows.map((r) => [r.label, r.tree])).toEqual([
["shop", { depth: 0, expanded: true }],
["public", { depth: 1 }],
["audit", { depth: 1 }],
["crm", { depth: 0, expanded: false }],
]);
expect(rows[1]!.value).toBe(schemaTreeValue("shop", "public"));
});
it("shows a disabled loading row while an expanded database's schemas load", () => {
const rows = schemaTreeRows(["shop"], new Set(["shop"]), () => undefined);
expect(rows[1]).toMatchObject({ label: "Loading…", disabled: true, tree: { depth: 1 } });
});
it("shows the error when an expanded database's schemas cannot be read", () => {
const rows = schemaTreeRows(["shop"], new Set(["shop"]), () => ({ error: "timed out" }));
expect(rows[1]).toMatchObject({ label: "timed out", verbatim: true, disabled: true });
});
it("lets a search for the database name keep its schemas", () => {
const rows = schemaTreeRows(["shop"], new Set(["shop"]), () => ["public"]);
expect(rows[1]).toMatchObject({ label: "public", keywords: "shop" });
});
});
+21 -2
Переглянути файл
@@ -174,6 +174,12 @@ export interface SourceCatalog {
databases: Record<string, DbCatalogSchema[]>;
}
export interface ConsoleExecution {
startedAt: number;
/** Statements submitted (a batch runs them in order; the backend doesn't say which one is current). */
statements: number;
}
interface DatabaseState {
sources: DataSource[];
loaded: boolean;
@@ -205,6 +211,8 @@ interface DatabaseState {
output: OutputLine[];
/** Console path → running request. */
running: Record<string, RequestId>;
/** Console path → what its running request submitted, and since when (ms since the epoch). */
executions: Record<string, ConsoleExecution>;
maxRows: number;
dialog: DialogState | null;
/** Target of the tree's lead node. */
@@ -271,6 +279,7 @@ export const useDatabase = create<DatabaseState>(() => ({
activeResult: null,
output: [],
running: {},
executions: {},
maxRows: 500,
dialog: null,
selectedSource: null,
@@ -1233,6 +1242,8 @@ export async function executeConsole(
text: string,
from: number,
to: number,
/** Called once the statements are submitted, with what was submitted. */
onStart?: (statements: readonly SqlStatement[]) => void,
): Promise<DbStatementOutcome[]> {
const id = consoleSource(path);
if (!id) {
@@ -1252,8 +1263,14 @@ export async function executeConsole(
const prev = useDatabase.getState().running[path];
if (prev) void commands.cancelRequest(prev);
const request = nextRequestId();
useDatabase.setState((s) => ({ running: { ...s.running, [path]: request } }));
useDatabase.setState((s) => ({
running: { ...s.running, [path]: request },
executions: { ...s.executions, [path]: { startedAt: Date.now(), statements: statements.length } },
}));
onStart?.(statements);
try {
// IDEA brings the results up as the run starts, showing it executing.
if (!inEditorResults()) showServiceView(RESULTS_VIEW, false);
const pageSize = useDatabase.getState().maxRows;
const schema = consoleSchema(path) || (await loadCompletion(id))?.defaultSchema || "";
if (!current()) return [];
@@ -1296,7 +1313,9 @@ export async function executeConsole(
if (s.running[path] !== request) return s;
const running = { ...s.running };
delete running[path];
return { running };
const executions = { ...s.executions };
delete executions[path];
return { running, executions };
});
}
}
+6 -3
Переглянути файл
@@ -24,7 +24,10 @@ describe("the Breakpoints dialog", () => {
});
const dialog = () => screen.getByRole("dialog", { name: "Breakpoints" });
const row = (name: string) => within(within(dialog()).getByLabelText("All breakpoints")).getByText(name);
const row = (location: string) =>
within(within(dialog()).getByRole("listbox", { name: "All breakpoints" })).getByRole("option", {
name: (name) => name.includes(`Enable breakpoint at ${location}`),
});
const condition = () => within(dialog()).getByLabelText("Condition") as HTMLInputElement;
/** A row's mouse click as the list sees it: mousedown selects, click (with its count) activates. */
const clickRow = (name: string, detail: number) => {
@@ -37,8 +40,8 @@ describe("the Breakpoints dialog", () => {
render(<DebuggerOverlays />);
clickRow("main.py:7", 1);
expect(openFile).not.toHaveBeenCalled();
// Its details show beside the list.
expect(within(dialog()).getAllByText("main.py:7")).toHaveLength(2);
expect(row("main.py:7").getAttribute("aria-selected")).toBe("true");
expect(condition().value).toBe("");
clickRow("main.py:3", 2);
expect(openFile).toHaveBeenCalledWith(path, { selection: { line: 2, col: 0 } });
});
+3 -1
Переглянути файл
@@ -14,6 +14,7 @@ import {
type ClassSort,
} from "./editor/classRows";
import styles from "./HeapSnapshotEditor.module.css";
import { useRowHeight } from "@/ui/density";
const COLUMNS: ReadonlyArray<{ key: ClassSort; label: string; numeric: boolean; diff?: boolean }> = [
{ key: "name", label: "Class", numeric: false },
@@ -66,6 +67,7 @@ export function HeapClasses({
selected: number | null;
onSelect: (row: HeapClassRow | null) => void;
}) {
const rowHeight = useRowHeight(22);
const tx = useTx();
const [query, setQuery] = useState<ClassQuery>(DEFAULT_CLASS_QUERY);
const compared = changes !== null;
@@ -124,7 +126,7 @@ export function HeapClasses({
renderItem={(r) => <ClassRow row={r} changes={changes} />}
activeIndex={selected === null ? -1 : rows.findIndex((r) => r.classIndex === selected)}
onActiveChange={(i) => onSelect(rows[i] ?? null)}
rowHeight={22}
rowHeight={rowHeight}
tableBody={{ headerRows: 1 }}
empty={<span className={styles.note}>{tx("No matches")}</span>}
/>
+3 -1
Переглянути файл
@@ -6,6 +6,7 @@ import { formatBytes } from "../../memory/rows";
import { useHeapQuery } from "./heapQuery";
import { ObjectText } from "./ObjectText";
import styles from "../HeapSnapshotEditor.module.css";
import { useRowHeight } from "@/ui/density";
const LIMIT = 100;
@@ -21,6 +22,7 @@ export function BiggestObjects({
selected: number | null;
onSelect: (object: HeapObjectRow) => void;
}) {
const rowHeight = useRowHeight(22);
const tx = useTx();
const page = useHeapQuery(`${snapshot}:${cls.classIndex}`, () =>
call(commands.debugHeapDominators(snapshot, null, cls.classIndex, 0, LIMIT)),
@@ -70,7 +72,7 @@ export function BiggestObjects({
)}
activeIndex={selected === null ? -1 : rows.findIndex((o) => o.object === selected)}
onActiveChange={(i) => rows[i] && onSelect(rows[i])}
rowHeight={22}
rowHeight={rowHeight}
tableBody={{ headerRows: 1 }}
/>
</div>
-3
Переглянути файл
@@ -1,7 +1,4 @@
.section {
flex: none;
max-height: 40%;
overflow: auto;
border-top: 1px solid var(--border-popup);
padding: 6px 12px 8px;
display: flex;
+3 -1
Переглянути файл
@@ -24,6 +24,7 @@ import { keepKeysOnButton } from "./rowButtonKeys";
import { columnsOf, formatBytes, formatCount, formatDelta, queryFor, visibleRows, type SortKey } from "./rows";
import { unavailableText } from "./unavailableText";
import styles from "./MemoryView.module.css";
import { useRowHeight } from "@/ui/density";
const COLUMNS: ReadonlyArray<{ key: SortKey; label: string; numeric: boolean }> = [
{ key: "name", label: "Class", numeric: false },
@@ -105,6 +106,7 @@ function ClassRow({
}
export function MemoryView({ session }: { session: DebugSession }) {
const rowHeight = useRowHeight(22);
// Also re-renders the reason text, which reads the catalog when called.
const tx = useTx();
const id = session.id;
@@ -248,7 +250,7 @@ export function MemoryView({ session }: { session: DebugSession }) {
onActivate={(r, _i, e) => {
if (e.type === "keydown" && listsInstances && paused) showInstancesOf(r.name);
}}
rowHeight={22}
rowHeight={rowHeight}
tableBody={{ headerRows: 1 }}
empty={<span className={styles.note}>{tx("No matches")}</span>}
/>
+137 -44
Переглянути файл
@@ -88,36 +88,46 @@
}
/* breakpoints dialog */
.bpDialog {
display: flex;
height: 420px;
min-height: 0;
}
.bpListPane {
width: 360px;
flex: none;
.bpWindow [data-dialog-body] {
display: flex;
flex-direction: column;
border-right: 1px solid var(--border-popup);
min-height: 0;
overflow: hidden;
}
.bpDialog {
flex: 1 1 420px;
}
.bpListHeader {
height: var(--h-header);
min-height: var(--h-header);
flex: none;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: var(--space-1-5);
padding: 0 8px 0 12px;
padding: var(--space-0-5) var(--space-2);
border-bottom: 1px solid var(--border-popup);
}
.bpListActions {
display: flex;
gap: var(--space-1);
margin-inline-start: auto;
}
.bpList {
flex: 1;
flex: 1 0 calc(2 * var(--h-list-row));
min-height: 0;
}
.bpAuxiliary {
flex: 0 1 auto;
max-height: 42%;
min-height: 0;
overflow: auto;
}
.bpRow,
.chooserRow {
display: flex;
@@ -135,6 +145,31 @@
color: var(--fg-emphasis);
}
.bpLocation {
display: inline-flex;
min-width: 0;
align-items: baseline;
}
.bpRow .bpName,
.bpLocation .bpName {
flex: 0 1 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
font-family: var(--font-ui);
}
.bpLine {
flex: none;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.bpRow > svg {
flex: none;
}
.bpDir {
flex: 1;
min-width: 0;
@@ -156,14 +191,29 @@
.bpDetail {
flex: 1;
min-width: 0;
min-height: 0;
overflow: auto;
}
.detail {
padding: 12px 14px;
padding: var(--space-3);
display: flex;
flex-direction: column;
gap: 10px;
gap: var(--space-2);
}
.detail .bpTitle {
flex-wrap: wrap;
gap: var(--space-1) var(--space-2);
}
.detail :is(.bpFile, .bpLocation) {
flex: 1 1 12ch;
font-family: var(--font-ui);
}
.detail .label {
font-size: var(--fs-ui);
}
.statusLine {
@@ -172,31 +222,72 @@
}
/* evaluate dialog */
.evalDialog {
height: min(440px, 100%);
}
.evalBody {
height: 100%;
box-sizing: border-box;
padding: 12px 14px;
padding: var(--space-2) var(--space-3) 0;
display: flex;
flex-direction: column;
gap: 10px;
gap: var(--space-2);
}
.evalExpression,
.evalResult {
display: flex;
flex-direction: column;
min-height: 0;
gap: var(--space-1);
}
/* Long fragments scroll inside the field so the result keeps its own space. */
.evalExpression {
max-height: 50%;
}
.evalImport {
flex: none;
max-height: 40%;
overflow: auto;
padding: var(--space-1);
display: flex;
flex-wrap: wrap;
align-items: center;
align-content: start;
gap: var(--space-1) var(--space-2);
border-bottom: 1px solid var(--border);
}
.evalImport > button {
max-width: 100%;
height: auto;
min-height: var(--h-control);
white-space: normal;
overflow-wrap: anywhere;
}
/* Grows with the dialog when it is resized. */
.evalResult {
flex: 1;
min-height: 220px;
}
.evalResultContent {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
border: 1px solid var(--border-popup);
border-radius: var(--radius-small);
padding: 4px 6px;
padding: var(--space-0-5) var(--space-1);
overflow: hidden;
}
.evalHint {
padding: var(--space-2);
color: var(--fg-muted);
font-size: var(--fs-small);
overflow: auto;
}
.chooser {
@@ -204,9 +295,6 @@
}
.exceptions {
flex: none;
max-height: 40%;
overflow: auto;
border-top: 1px solid var(--border-popup);
padding: 6px 12px 8px;
display: flex;
@@ -259,33 +347,38 @@
/* Evaluate: a field that grows with ⇧Enter, like IDEA's expression editor. */
.evalInputRow {
display: flex;
align-items: flex-start;
gap: var(--space-1);
}
.evalInput {
flex: 1;
min-width: 0;
min-height: var(--h-field, 28px);
padding: 5px 8px;
resize: none;
appearance: none;
border: 0;
min-height: 0;
border-radius: var(--radius-control, 4px);
background: var(--bg-field, var(--bg-button));
box-shadow: inset 0 0 0 1px var(--border-button);
color: var(--fg-strong);
font-family: var(--font-mono);
font-size: var(--fs-ui);
line-height: 18px;
outline: none;
-webkit-user-select: text;
user-select: text;
}
.evalInput:focus {
.evalInputRow:focus-within {
box-shadow:
inset 0 0 0 1px var(--focus-ring),
0 0 0 1px var(--focus-ring);
}
.evalInput {
flex: 1;
min-width: 0;
min-height: 0;
padding: var(--space-1) var(--space-2);
resize: none;
appearance: none;
border: 0;
background: none;
color: var(--fg-strong);
font-family: var(--font-mono);
font-size: var(--fs-code);
font-weight: var(--fw-code);
line-height: var(--lh-code);
outline: none;
-webkit-user-select: text;
user-select: text;
}
.evalInput::placeholder {
color: var(--fg-faint);
}
.evalHistory {
align-self: flex-start;
margin: var(--space-1);
}
+142 -78
Переглянути файл
@@ -3,6 +3,7 @@ import {
Fragment,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
@@ -13,7 +14,23 @@ import { basename, relativePath, useProject } from "@/platform/project";
import { executeAction, getAction } from "@/platform/actions";
import { call, commands, type AttachableProcess, type RunConfig, type Variable } from "@/platform/ipc";
import { maybeEditorService, notifications } from "@/workbench/contributions";
import { Button, Checkbox, Dialog, Icon, IconButton, Input, Kbd, List, Menu, Popup, Toggle, T } from "@/ui";
import {
Button,
Checkbox,
Dialog,
Icon,
IconButton,
Input,
Kbd,
List,
Menu,
Popup,
SplitGroup,
SplitHandle,
SplitPanel,
Toggle,
T,
} from "@/ui";
import { isConditional, suspends, type BreakpointEntry } from "../breakpoints/model";
import {
removeAllBreakpoints,
@@ -373,6 +390,15 @@ type DialogRow =
| ({ type: "line"; key: string } & BpRow)
| { type: "special"; key: string; bp: SpecialBreakpoint };
function BreakpointLocation({ path, line }: { path: string; line: number }) {
return (
<span className={styles.bpLocation} title={`${path}:${line + 1}`}>
<span className={styles.bpName}>{basename(path)}</span>
<span className={styles.bpLine}>:{line + 1}</span>
</span>
);
}
function BreakpointsDialog() {
const state = useOverlays((s) => s.breakpoints);
const byFile = useBreakpoints((s) => s.byFile);
@@ -407,6 +433,18 @@ function BreakpointsDialog() {
// Enter on Done and a click on a row don't blur them.
const commitRef = useRef<(() => void) | null>(null);
const open = !!state;
const layout = useRef<HTMLDivElement>(null);
const [stacked, setStacked] = useState(false);
useLayoutEffect(() => {
const el = layout.current;
if (!open || !el) return;
const update = () => setStacked(el.clientWidth > 0 && el.clientWidth < 560);
update();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(update);
observer.observe(el);
return () => observer.disconnect();
}, [open]);
const current = items.find((r) => r.key === (selected ?? state?.id)) ?? items[0];
const close = () => {
commitRef.current?.();
@@ -430,28 +468,38 @@ function BreakpointsDialog() {
open={open}
onClose={close}
title="Breakpoints"
className={styles.bpWindow}
width={760}
minWidth={400}
minHeight={340}
resizable="both"
aria-label="Breakpoints"
buttons={[{ label: "Done", role: "default", onClick: close }]}
>
<div className={styles.bpDialog}>
<div className={styles.bpListPane}>
<SplitGroup
elementRef={layout}
orientation={stacked ? "vertical" : "horizontal"}
storageKey={stacked ? "openidea.debug.breakpoints.stacked" : "openidea.debug.breakpoints.split"}
className={styles.bpDialog}
>
<SplitPanel id="breakpoint-list" defaultSize={stacked ? "42%" : "35%"} minSize={stacked ? "34%" : "216px"}>
<div className={styles.bpListHeader}>
<Toggle checked={muted} onChange={setMuted} label="Mute breakpoints" />
<div className={styles.spacer} />
<IconButton
icon="plus"
title="Add Method Breakpoint"
size="small"
onClick={() => setSelected(addMethodBreakpoint("").id)}
/>
<IconButton
icon="trash"
title="Remove All Breakpoints"
size="small"
disabled={!items.length}
onClick={removeAll}
/>
<div className={styles.bpListActions}>
<IconButton
icon="plus"
title="Add Method Breakpoint"
size="small"
onClick={() => setSelected(addMethodBreakpoint("").id)}
/>
<IconButton
icon="trash"
title="Remove All Breakpoints"
size="small"
disabled={!items.length}
onClick={removeAll}
/>
</div>
</div>
<List
items={rows}
@@ -486,7 +534,9 @@ function BreakpointsDialog() {
aria-label={tx`Enable ${specialTitle(r.bp)}`}
/>
<Icon name={r.bp.kind === "method" ? "breakpoint-method" : "breakpoint-field"} size={14} />
<span className={styles.bpName}>{specialTitle(r.bp)}</span>
<span className={styles.bpName} title={specialTitle(r.bp)}>
{specialTitle(r.bp)}
</span>
{r.bp.path && (
<span className={styles.bpDir}>
{basename(r.bp.path)}
@@ -520,9 +570,7 @@ function BreakpointsDialog() {
}
aria-hidden
/>
<span className={styles.bpName}>
{basename(r.path)}:{r.bp.line + 1}
</span>
<BreakpointLocation path={r.path} line={r.bp.line} />
<span className={styles.bpDir}>{relativePath(root, r.path)}</span>
{isConditional(r.bp) && <span className={styles.bpCond}>{suspends(r.bp) ? "if" : "log"}</span>}
{r.bp.temporary && (
@@ -534,17 +582,22 @@ function BreakpointsDialog() {
);
}}
/>
<ExceptionBreakpoints open={open} />
<EventBreakpointsSection />
</div>
<div className={styles.bpDetail}>
{current?.type === "line" ? (
<BreakpointDetail key={current.key} row={current} onGo={() => goTo(current)} commitRef={commitRef} />
) : current?.type === "special" ? (
<SpecialDetail key={current.key} bp={current.bp} onGo={() => goTo(current)} commitRef={commitRef} />
) : null}
</div>
</div>
<div className={styles.bpAuxiliary}>
<ExceptionBreakpoints open={open} />
<EventBreakpointsSection />
</div>
</SplitPanel>
<SplitHandle />
<SplitPanel id="breakpoint-detail" minSize={stacked ? "42%" : "284px"}>
<div className={styles.bpDetail}>
{current?.type === "line" ? (
<BreakpointDetail key={current.key} row={current} onGo={() => goTo(current)} commitRef={commitRef} />
) : current?.type === "special" ? (
<SpecialDetail key={current.key} bp={current.bp} onGo={() => goTo(current)} commitRef={commitRef} />
) : null}
</div>
</SplitPanel>
</SplitGroup>
</Dialog>
);
}
@@ -610,10 +663,7 @@ function BreakpointDetail({
return (
<div className={styles.detail}>
<div className={styles.bpTitle}>
<span className={styles.bpFile}>
{basename(path)}:{bp.line + 1}
</span>
<div className={styles.spacer} />
<BreakpointLocation path={path} line={bp.line} />
<Button size="small" variant="ghost" onClick={onGo}>
<T>Go to Source</T>
</Button>
@@ -664,8 +714,9 @@ function SpecialDetail({
<div className={styles.detail}>
<div className={styles.bpTitle}>
<Icon name={bp.kind === "method" ? "breakpoint-method" : "breakpoint-field"} size={14} />
<span className={styles.bpFile}>{specialTitle(bp)}</span>
<div className={styles.spacer} />
<span className={styles.bpFile} title={specialTitle(bp)}>
{specialTitle(bp)}
</span>
{bp.path && (
<Button size="small" variant="ghost" onClick={onGo}>
<T>Go to Source</T>
@@ -764,8 +815,9 @@ function EvaluateDialogInner({ initial }: { initial: string }) {
const [history, setHistory] = useState(() => readHistory("evaluate"));
const [historyMenu, setHistoryMenu] = useState(false);
const historyPos = useRef(-1);
const historyButton = useRef<HTMLSpanElement>(null);
const historyButton = useRef<HTMLButtonElement>(null);
const field = useRef<HTMLTextAreaElement>(null);
const expressionId = useId();
const session = useDebug((s) => (s.active != null ? s.sessions[s.active] : undefined));
const paused = session?.status === "paused";
const close = () => useOverlays.setState({ evaluate: null });
@@ -824,7 +876,10 @@ function EvaluateDialogInner({ initial }: { initial: string }) {
onClose={close}
title="Evaluate"
width={620}
minWidth={340}
minHeight={240}
resizable="both"
className={styles.evalDialog}
aria-label="Evaluate expression"
footerStart={
<Button
@@ -844,13 +899,14 @@ function EvaluateDialogInner({ initial }: { initial: string }) {
]}
>
<div className={styles.evalBody}>
<div className={styles.field}>
<span className={styles.label}>
<div className={styles.evalExpression}>
<label className={styles.label} htmlFor={expressionId}>
<T>Expression</T>
</span>
</label>
<div className={styles.evalInputRow}>
<textarea
ref={field}
id={expressionId}
className={styles.evalInput}
rows={lines}
value={expression}
@@ -866,19 +922,22 @@ function EvaluateDialogInner({ initial }: { initial: string }) {
spellCheck={false}
autoComplete="off"
data-autofocus=""
aria-label={tx("Expression")}
placeholder={paused ? "Expression to evaluate in the selected frame" : "Pause the program to evaluate"}
placeholder={tx(
paused ? "Expression to evaluate in the selected frame" : "Pause the program to evaluate",
)}
/>
{completion.popup}
<span ref={historyButton}>
<IconButton
icon="history"
title="History"
size="small"
disabled={!history.length}
onClick={() => setHistoryMenu(true)}
/>
</span>
<IconButton
ref={historyButton}
className={styles.evalHistory}
icon="history"
title="History"
size="small"
aria-haspopup="menu"
aria-expanded={historyMenu}
disabled={!history.length}
onClick={() => setHistoryMenu(true)}
/>
</div>
<Menu
open={historyMenu}
@@ -891,32 +950,37 @@ function EvaluateDialogInner({ initial }: { initial: string }) {
.map((h) => ({ label: h.replace(/\s+/g, " "), verbatim: true, run: () => recall(h) }))}
/>
</div>
{ambiguous && (
<div className={styles.evalImport} role="group" aria-label={tx("Class to import")}>
<span className={styles.label}>{tx`Choose the class to import for ${className}:`}</span>
{ambiguous.candidates.map((c) => (
<Button
key={c}
variant="ghost"
size="small"
onClick={() => {
if (session) rememberImport(session.id, c);
void run();
}}
>
{c}
</Button>
))}
</div>
)}
<div className={styles.evalResult}>
{result ? (
<VariablesView roots={[result]} session={session?.id ?? null} aria-label="Evaluation result" />
) : (
<div className={styles.empty}>
{paused ? tx("Press Enter to evaluate") : tx("Evaluation is available while the program is suspended")}
</div>
)}
<span className={styles.label}>
<T>Result</T>
</span>
<div className={styles.evalResultContent}>
{ambiguous && (
<div className={styles.evalImport} role="group" aria-label={tx("Class to import")}>
<span className={styles.label}>{tx`Choose the class to import for ${className}:`}</span>
{ambiguous.candidates.map((c) => (
<Button
key={c}
variant="ghost"
size="small"
onClick={() => {
if (session) rememberImport(session.id, c);
void run();
}}
>
{c}
</Button>
))}
</div>
)}
{result ? (
<VariablesView roots={[result]} session={session?.id ?? null} aria-label="Evaluation result" />
) : (
<div className={styles.evalHint}>
{paused ? tx("Press Enter to evaluate") : tx("Evaluation is available while the program is suspended")}
</div>
)}
</div>
</div>
</div>
</Dialog>
+30 -6
Переглянути файл
@@ -10,12 +10,12 @@
.row {
display: flex;
align-items: center;
gap: 5px;
gap: var(--space-1);
min-width: 0;
width: 100%;
max-width: 100%;
box-sizing: border-box;
font-family: var(--font-mono);
font-family: var(--font-ui);
font-size: var(--fs-ui);
white-space: pre;
color: var(--fg);
@@ -23,17 +23,27 @@
}
.name {
flex: none;
min-width: 0;
max-width: 45%;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg);
}
.evalName {
flex: 0 1 auto;
max-width: 45%;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.varName {
color: var(--debug-name, var(--syn-property));
}
.nodeIcon {
flex: none;
margin-right: 1px;
}
.eq {
@@ -41,15 +51,28 @@
color: var(--fg-subtle);
}
.valueGroup {
display: flex;
align-items: center;
gap: var(--space-1);
min-width: min(8ch, 45%);
flex: 1 1 0;
}
.value {
min-width: 0;
flex: 1 1 0;
overflow: hidden;
text-overflow: ellipsis;
font-family: var(--font-mono);
}
.showValue {
flex: none;
flex: 0 0 auto;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding: 0;
border: 0;
background: none;
@@ -104,6 +127,7 @@
.type {
min-width: 0;
max-width: 25%;
flex: 0 1 auto;
overflow: hidden;
text-overflow: ellipsis;
@@ -128,7 +152,7 @@
.editInput {
flex: 1;
min-width: 80px;
min-width: min(80px, 40%);
height: 18px;
padding: 0 4px;
font: inherit;
+45 -25
Переглянути файл
@@ -415,7 +415,9 @@ function VarEditRow({
useEffect(() => acquirePopup(), []);
return (
<span className={styles.row}>
<span className={styles.name}>{node.name}</span>
<span className={styles.name} title={node.name}>
{node.name}
</span>
<span className={styles.eq}>=</span>
<input
className={clsx(styles.editInput, error && styles.editInvalid)}
@@ -465,18 +467,21 @@ function VarRow({
const valueRef = useRef<HTMLSpanElement>(null);
const [overflow, setOverflow] = useState(false);
useLayoutEffect(() => {
const el = valueRef.current;
if (!el) {
const text = valueRef.current;
const group = text?.parentElement;
if (!text || !group) {
setOverflow(false);
return;
}
const update = () => setOverflow(el.scrollWidth > el.clientWidth + 1);
// The group measures the space available before the Show button takes any of it.
const update = () => setOverflow(text.scrollWidth > group.clientWidth + 1);
update();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(update);
observer.observe(el);
observer.observe(group);
observer.observe(text);
return () => observer.disconnect();
}, [node.value]);
}, [node.value, node.typeName, node.error]);
if (node.kind === "message") return <span className={styles.message}>{node.name}</span>;
if (node.kind === "scope")
return (
@@ -487,13 +492,22 @@ function VarRow({
);
const kind = node.error ? null : classifyValue(node.value, node.typeName);
const shown = shownValue(node.value, node.typeName);
const evaluation = node.kind === "eval";
return (
<span className={styles.row}>
<span className={styles.row} title={node.name}>
<Icon name={nodeIcon(node)} size={16} className={styles.nodeIcon} />
{!shown.entry && (
<>
<span className={clsx(styles.name, node.kind === "var" && styles.varName, changed && styles.changed)}>
{node.name}
<span
className={clsx(
styles.name,
evaluation && styles.evalName,
node.kind === "var" && styles.varName,
changed && styles.changed,
)}
title={evaluation ? node.name : undefined}
>
{evaluation ? oneLine(node.name) : node.name}
</span>
<span className={styles.eq}>=</span>
</>
@@ -502,23 +516,29 @@ function VarRow({
<span className={styles.error}>{oneLine(node.error)}</span>
) : (
<>
{shown.label && <span className={styles.type}>{shown.label}</span>}
<span ref={valueRef} className={clsx(styles.value, kind && styles[kind])} title={node.value}>
{oneLine(shown.text)}
</span>
{overflow && (
<button
type="button"
className={styles.showValue}
title={tx("Show")}
onClick={(e) => {
e.stopPropagation();
onShowValue(node);
}}
>
…{tx("Show")}
</button>
{shown.label && (
<span className={styles.type} title={shown.label}>
{shown.label}
</span>
)}
<span className={styles.valueGroup}>
<span ref={valueRef} className={clsx(styles.value, kind && styles[kind])} title={node.value}>
{oneLine(shown.text)}
</span>
{overflow && (
<button
type="button"
className={styles.showValue}
title={tx("Show")}
onClick={(e) => {
e.stopPropagation();
onShowValue(node);
}}
>
…{tx("Show")}
</button>
)}
</span>
</>
)}
</span>
+3 -1
Переглянути файл
@@ -18,6 +18,7 @@ import {
import type { CloneSourceProps } from "@/workbench/contributions";
import { openInBrowser } from "../data/local";
import styles from "./GitHubCloneSource.module.css";
import { useRowHeight } from "@/ui/density";
type Row = { repo: GhAccountRepo; indices: number[] | null };
@@ -32,6 +33,7 @@ export function matchRepos(repos: readonly GhAccountRepo[], query: string): Row[
}
export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSourceProps) {
const rowHeight = useRowHeight(26);
const [state, setState] = useState<GhAccountRepos | null>(null);
const [query, setQuery] = useState("");
const [attempt, setAttempt] = useState(0);
@@ -140,7 +142,7 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource
activeIndex={active}
onActiveChange={pick}
focusable={false}
rowHeight={26}
rowHeight={rowHeight}
empty={
<span className={styles.muted}>
<T>{state.repos.length ? "No matching repositories" : "No repositories"}</T>
+3 -1
Переглянути файл
@@ -16,6 +16,7 @@ import { prettyDate } from "../ui/prettyDate";
import { commitDescription } from "./model";
import { selectCommit, useCreatePr, type CreateChange } from "./store";
import styles from "./Create.module.css";
import { useRowHeight } from "@/ui/density";
function Centered({ children, error }: { children: ReactNode; error?: boolean }) {
return <div className={error ? `${styles.centered} ${styles.errorText}` : styles.centered}>{children}</div>;
@@ -170,6 +171,7 @@ function showDiff(all: readonly CreateChange[], first: CreateChange) {
}
function ChangesTree() {
const rowHeight = useRowHeight(22);
const changes = useCreatePr((s) => s.changes);
const files = changes?.state === "ok" ? changes.value : null;
const roots = useMemo(() => (files ? buildFileTree(files, (f) => f.path) : []), [files]);
@@ -219,7 +221,7 @@ function ChangesTree() {
selected={selection}
onSelectionChange={setSelection}
multiSelect
rowHeight={22}
rowHeight={rowHeight}
aria-label="Changes"
speedSearch
onActivate={(n) => n.file && showDiff(ordered, n.file)}
-1
Переглянути файл
@@ -178,7 +178,6 @@ function HeadPopup(props: { anchor: HTMLElement; initialRepo: GHRemote; onClose:
onActivate={(r) => choose(r)}
focusable={false}
hoverSelects
rowHeight={24}
className={styles.headList}
aria-label="Branches"
empty={<div className={styles.hint}>{tx("Nothing to show")}</div>}
-1
Переглянути файл
@@ -78,7 +78,6 @@ export function BranchWidget({
getKey={(a) => a}
onActivate={(a) => run(a)}
hoverSelects
rowHeight={24}
aria-label={tx("Branches")}
renderItem={(a, state) => (
<div className={styles.popupRow} data-active={state.active || undefined}>
+2 -2
Переглянути файл
@@ -1,5 +1,5 @@
/** Bounded local configuration evidence, never an effective runtime identity. */
import type { FileEntry } from "@/platform/ipc";
import { isErrorKind, type FileEntry } from "@/platform/ipc";
import { ipcPath } from "@/platform/paths";
export interface ServiceReader {
@@ -90,7 +90,7 @@ export async function loadServiceName(module: string, reader: ServiceReader): Pr
try {
entries = await reader.directory(directory);
} catch (error) {
if ((error as { kind?: string }).kind === "notFound") continue;
if (isErrorKind(error, "notFound")) continue;
return null;
}
for (const file of entries) {
-1
Переглянути файл
@@ -86,7 +86,6 @@ function EditMacrosDialog({ onClose }: { onClose: () => void }) {
getKey={(m) => m.name}
activeIndex={Math.min(active, saved.length - 1)}
onActiveChange={setActive}
rowHeight={24}
className={styles.list}
aria-label="Macros"
empty={
+2 -1
Переглянути файл
@@ -1,6 +1,7 @@
/** Installed plugins, their UI contributions, the selected plugin theme, and the operations on them. */
import { create } from "zustand";
import { tx } from "@/platform/i18n";
import { isErrorKind } from "@/platform/ipc";
import type {
ActiveTheme,
CapabilityInfo,
@@ -412,7 +413,7 @@ export async function runPluginCommand(
const status = usePlugins.getState().plugins.find((p) => p.id === pluginId)?.status;
// A trap disables the plugin and the backend already announced why; a
// consent request opens its own dialog.
const permission = (e as { kind?: string }).kind === "permissionDenied";
const permission = isErrorKind(e, "permissionDenied");
if (status !== "failed" && !permission)
notifications().notify({ group: "plugins", level: "error", title: `${title} failed`, body: errorText(e) });
return null;
-1
Переглянути файл
@@ -79,7 +79,6 @@ function NewPopup({ at, items }: { at: { x: number; y: number }; items: MenuItem
onActivate={(r) => pick(r)}
focusable={false}
hoverSelects
rowHeight={24}
className={styles.list}
aria-label="File types"
empty={
+45 -27
Переглянути файл
@@ -1,61 +1,67 @@
.popup {
width: 620px;
max-width: calc(100vw - 32px);
display: flex;
flex-direction: column;
width: min(670px, calc(100vw - 32px));
overflow: hidden;
}
.body {
flex: 1 1 auto;
display: flex;
flex-direction: column;
min-height: 0;
font-family: var(--font-ui);
}
.header {
flex: none;
display: flex;
align-items: center;
gap: var(--space-2);
height: var(--h-row);
padding: 4px 10px 0;
font-size: var(--fs-small);
color: var(--fg-subtle);
min-height: var(--h-field);
padding: var(--space-0-5) var(--space-3);
border-bottom: 1px solid var(--border-popup);
background: var(--bg-frame, var(--bg-app));
}
.title {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: var(--fs-ui);
font-weight: 600;
color: var(--fg-strong);
}
.link {
flex: none;
max-width: 50%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding: 0;
border: 0;
background: none;
color: var(--link);
font: inherit;
font-size: var(--fs-small);
cursor: pointer;
}
.link:hover {
color: var(--link-hover);
}
.inputRow {
display: flex;
align-items: center;
gap: var(--space-1-5);
padding: 6px 10px;
border-bottom: 1px solid var(--border-popup);
}
.inputIcon {
.query {
flex: none;
color: var(--fg-subtle);
}
.input {
flex: 1;
font-family: var(--font-ui);
padding: var(--space-2);
}
.rows {
max-height: 360px;
height: auto;
flex: 1 1 auto;
min-height: var(--h-row);
max-height: 600px;
overflow-x: hidden;
}
.section {
display: flex;
align-items: center;
width: 100%;
gap: 10px;
gap: var(--space-3);
padding: 0;
font-size: var(--fs-small);
color: var(--fg-subtle);
@@ -93,23 +99,35 @@
.detail {
flex: 0 1 auto;
min-width: 0;
max-width: 45%;
max-width: min(36%, 26ch);
overflow: hidden;
text-overflow: ellipsis;
font-style: italic;
margin-left: auto;
color: var(--fg-subtle);
font-size: var(--fs-small);
white-space: nowrap;
}
.activeRow .detail {
color: var(--fg);
}
.empty {
padding: 6px 10px;
padding: var(--space-1) var(--space-3) var(--space-2);
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.footer {
padding: 6px 10px;
flex: none;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-0-5) var(--space-3);
padding: var(--space-1-5) var(--space-3);
border-top: 1px solid var(--border-popup);
font-size: var(--fs-small);
color: var(--fg-subtle);
}
.navigationHint {
display: inline-flex;
align-items: center;
gap: var(--space-1);
}
+86 -48
Переглянути файл
@@ -4,14 +4,15 @@
* the selected entry, or the line itself: a provider that claims it, else the
* shell in the project directory, its output in the Run tool window.
*/
import { useMemo, useState, type KeyboardEvent } from "react";
import { useId, useMemo, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import { create } from "zustand";
import { executeAction } from "@/platform/actions";
import { usePlatform } from "@/platform/platformInfo";
import { useProject } from "@/platform/project";
import { Icon, Input, List, Popup, T, listNavigate } from "@/ui";
import { Icon, Kbd, List, Popup, SearchField, T, firstSelectable, listNavigate } from "@/ui";
import { runAnythingProviderList } from "@/workbench/contributions";
import { useRowHeight } from "@/ui/density";
import { buildRows, clearHistory, pushHistory, readHistory, shellRunConfig, type Row } from "./model";
import styles from "./RunAnything.module.css";
@@ -44,8 +45,13 @@ export function RunAnythingHost() {
}
const isSection = (r: Row) => r.kind === "section";
const ROW_HEIGHT = 24;
const commandAnchor = { getBoundingClientRect: () => new DOMRect(window.innerWidth / 2, 72, 0, 0) };
function RunAnythingPopup({ root }: { root: string }) {
const field = useRef<HTMLInputElement>(null);
const rowHeight = useRowHeight(ROW_HEIGHT);
const listId = useId();
const [line, setLine] = useState("");
const [active, setActive] = useState(-1);
const [history, setHistory] = useState(() => readHistory(root));
@@ -57,6 +63,10 @@ function RunAnythingPopup({ root }: { root: string }) {
}),
[line, history],
);
const selected = rows[active];
const first = firstSelectable(rows, isSection);
const hasRows = first >= 0;
const command = selected?.kind === "item" ? (selected.item.completion ?? selected.item.label) : line;
const run = (row: Row | undefined) => {
if (!row || row.kind !== "item") return;
@@ -75,21 +85,25 @@ function RunAnythingPopup({ root }: { root: string }) {
setActive(-1);
};
const onKeyDown = (e: KeyboardEvent) => {
const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.nativeEvent.isComposing || e.altKey || e.ctrlKey || e.metaKey) return;
if (["ArrowDown", "ArrowUp", "PageDown", "PageUp"].includes(e.key)) {
const next = listNavigate(e.key, { items: rows, active: Math.max(active, 0), wrap: true, isSection });
if (next !== null) {
const height = e.currentTarget.ownerDocument.getElementById(listId)?.clientHeight ?? rowHeight;
const pageSize = Math.max(1, Math.floor(height / rowHeight) - 1);
const next = listNavigate(e.key, { items: rows, active, wrap: true, isSection, pageSize });
if (next !== null && hasRows) {
e.preventDefault();
setActive(active < 0 && e.key === "ArrowDown" ? rows.findIndex((r) => !isSection(r)) : next);
setActive(next < 0 ? first : next);
}
return;
}
if (e.key === "Tab") {
if (e.key === "Tab" && !e.shiftKey && hasRows) {
e.preventDefault();
complete(rows[active >= 0 ? active : rows.findIndex((r) => !isSection(r))]);
e.stopPropagation();
complete(selected ?? rows[first]);
} else if (e.key === "Enter") {
e.preventDefault();
if (active >= 0) run(rows[active]);
if (selected) run(selected);
else runLine();
}
};
@@ -97,7 +111,7 @@ function RunAnythingPopup({ root }: { root: string }) {
return (
<Popup
open
anchor={{ x: window.innerWidth / 2, y: 72 }}
anchor={commandAnchor}
placement="bottom"
onClose={close}
role="dialog"
@@ -117,59 +131,83 @@ function RunAnythingPopup({ root }: { root: string }) {
onClick={() => {
clearHistory(root);
setHistory([]);
setActive(-1);
field.current?.focus();
}}
>
<T>Clear History</T>
</button>
)}
</div>
<div className={styles.inputRow}>
<Icon name="run-anything" size={16} className={styles.inputIcon} />
<Input
<div className={styles.query}>
<SearchField
ref={field}
data-autofocus
variant="bare"
className={styles.input}
value={line}
leadingIcon="run-anything"
clearable={false}
role="combobox"
aria-autocomplete="list"
aria-expanded={hasRows}
aria-controls={hasRows ? listId : undefined}
aria-activedescendant={selected?.kind === "item" ? `${listId}-${active}` : undefined}
value={command}
placeholder="Run a command, configuration or goal"
aria-label="Command line"
onChange={(e) => {
setLine(e.target.value);
onChange={(value) => {
setLine(value);
setActive(-1);
}}
onKeyDown={onKeyDown}
/>
</div>
<List
items={rows}
getKey={(r) => r.key}
isSection={isSection}
renderSection={(r) => <div className={styles.section}>{r.kind === "section" && <T>{r.label}</T>}</div>}
activeIndex={active}
onActiveChange={setActive}
onActivate={(r) => run(r)}
focusable={false}
hoverSelects={false}
rowHeight={24}
className={styles.rows}
aria-label="Run Anything entries"
empty={
<div className={styles.empty}>
{line.trim() ? <T>Press Enter to run the command in the project directory</T> : <T>Type a command</T>}
{hasRows ? (
<>
<List
id={listId}
items={rows}
getKey={(r) => r.key}
isSection={isSection}
renderSection={(r) => <div className={styles.section}>{r.kind === "section" && <T>{r.label}</T>}</div>}
activeIndex={active}
onActiveChange={setActive}
onActivate={(r) => run(r)}
focusable={false}
hoverSelects={false}
rowHeight={rowHeight}
className={styles.rows}
aria-label="Run Anything entries"
renderItem={(r, state) =>
r.kind === "item" ? (
<div className={clsx(styles.row, state.active && styles.activeRow)}>
<Icon name={r.item.icon ?? "run"} size={16} className={styles.rowIcon} />
<span className={styles.label} title={r.item.label}>
{r.item.label}
</span>
{r.item.detail && (
<span className={styles.detail} title={r.item.detail}>
{r.item.detail}
</span>
)}
</div>
) : null
}
/>
<div className={styles.footer}>
<span className={styles.navigationHint}>
<Kbd>↑</Kbd>
<Kbd>↓</Kbd>
<T>Navigate</T>
</span>
<T>Tab to complete, Enter to run</T>
</div>
}
renderItem={(r, state) =>
r.kind === "item" ? (
<div className={clsx(styles.row, state.active && styles.activeRow)}>
<Icon name={r.item.icon ?? "run"} size={16} className={styles.rowIcon} />
<span className={styles.label}>{r.item.label}</span>
{r.item.detail && <span className={styles.detail}>{r.item.detail}</span>}
</div>
) : null
}
/>
<div className={styles.footer}>
<T>Enter to run, Tab to complete. Other commands run in the project directory.</T>
</div>
</>
) : (
line.trim() && (
<div className={styles.empty}>
<T>Press Enter to run the command in the project directory</T>
</div>
)
)}
</div>
</Popup>
);
+4 -2
Переглянути файл
@@ -1,6 +1,7 @@
import { useMemo, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import { HighlightedText, Icon, List, Popup, SearchField, fuzzyMatch, listNavigate, T, type PopupAnchor } from "@/ui";
import { useRowHeight } from "@/ui/density";
import { useRunConfigTypes, runConfigTypes, type RunConfigTypeContribution } from "@/workbench/contributions";
import styles from "./Run.module.css";
@@ -59,6 +60,7 @@ export function AddConfigPopup({
onClose: () => void;
}) {
const types = useRunConfigTypes((s) => s.types);
const rowHeight = useRowHeight(ROW);
const [query, setQuery] = useState("");
const rows = useMemo(() => typeRows(runConfigTypes(types), query), [types, query]);
const isSection = (r: TypeRow) => r.kind === "group";
@@ -115,7 +117,7 @@ export function AddConfigPopup({
variant="bare"
/>
</div>
<div style={{ height: Math.max(ROW, Math.min(rows.length * ROW, 14 * ROW)) }}>
<div style={{ height: Math.max(rowHeight, Math.min(rows.length * rowHeight, 14 * rowHeight)) }}>
<List<TypeRow>
aria-label="Configuration types"
className={styles.chooserList}
@@ -127,7 +129,7 @@ export function AddConfigPopup({
onActiveChange={setActive}
focusable={false}
hoverSelects
rowHeight={ROW}
rowHeight={rowHeight}
onActivate={(r) => pick(r)}
empty={
<span className={styles.chooserMuted}>
Loaded 100 of 176 files, more files were not shown because too many files have changed in this diff. Show more