diff --git a/crates/ide-db/src/conn.rs b/crates/ide-db/src/conn.rs index 12ab78e0f6..6404797582 100644 --- a/crates/ide-db/src/conn.rs +++ b/crates/ide-db/src/conn.rs @@ -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))) } diff --git a/crates/ide-db/src/sql.rs b/crates/ide-db/src/sql.rs index 8dff30d667..e8872f6483 100644 --- a/crates/ide-db/src/sql.rs +++ b/crates/ide-db/src/sql.rs @@ -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 { 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")); diff --git a/docs/en/contribute/guidelines/code-style.mdx b/docs/en/contribute/guidelines/code-style.mdx index afacb6246b..1ec5bd1b56 100644 --- a/docs/en/contribute/guidelines/code-style.mdx +++ b/docs/en/contribute/guidelines/code-style.mdx @@ -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. diff --git a/docs/zh/contribute/guidelines/code-style.mdx b/docs/zh/contribute/guidelines/code-style.mdx index 478688faad..b38345092d 100644 --- a/docs/zh/contribute/guidelines/code-style.mdx +++ b/docs/zh/contribute/guidelines/code-style.mdx @@ -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 的导出、没人引用的文件或没人用的依赖时会失败。请删掉死代码,而不是屏蔽检查;只在本文件内使用的导出是允许的。 diff --git a/e2e/agentFocusInput.spec.ts b/e2e/agentFocusInput.spec.ts index a932ca0553..0a56d8cdf7 100644 --- a/e2e/agentFocusInput.spec.ts +++ b/e2e/agentFocusInput.spec.ts @@ -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 = { type: "subagent", id: "focus-child", title: "Inspect focus behavior", diff --git a/e2e/agentMarkdown.spec.ts b/e2e/agentMarkdown.spec.ts index 8f31990839..cd09673a45 100644 --- a/e2e/agentMarkdown.spec.ts +++ b/e2e/agentMarkdown.spec.ts @@ -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); diff --git a/e2e/agentQuestions.spec.ts b/e2e/agentQuestions.spec.ts index b6c99b6ba2..e3e2419463 100644 --- a/e2e/agentQuestions.spec.ts +++ b/e2e/agentQuestions.spec.ts @@ -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(); diff --git a/e2e/attachProject.spec.ts b/e2e/attachProject.spec.ts index 61c969367b..af1cb2ac40 100644 --- a/e2e/attachProject.spec.ts +++ b/e2e/attachProject.spec.ts @@ -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; diff --git a/e2e/codeInsight.spec.ts b/e2e/codeInsight.spec.ts index 721c6e632e..9aa1eaf7ef 100644 --- a/e2e/codeInsight.spec.ts +++ b/e2e/codeInsight.spec.ts @@ -559,7 +559,7 @@ 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 ({ diff --git a/e2e/compactSettingsControls.spec.ts b/e2e/compactSettingsControls.spec.ts index 11405a241f..6d56140268 100644 --- a/e2e/compactSettingsControls.spec.ts +++ b/e2e/compactSettingsControls.spec.ts @@ -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(); diff --git a/e2e/configurationNavigation.fixture.ts b/e2e/configurationNavigation.fixture.ts index 613b30c4ef..f40075b222 100644 --- a/e2e/configurationNavigation.fixture.ts +++ b/e2e/configurationNavigation.fixture.ts @@ -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({ diff --git a/e2e/databaseDialogLayout.spec.ts b/e2e/databaseDialogLayout.spec.ts index 643f617e05..b5d7ace545 100644 --- a/e2e/databaseDialogLayout.spec.ts +++ b/e2e/databaseDialogLayout.spec.ts @@ -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(); diff --git a/e2e/databaseResultTabs.spec.ts b/e2e/databaseResultTabs.spec.ts index 29f75ddeb7..da9d3de6c1 100644 --- a/e2e/databaseResultTabs.spec.ts +++ b/e2e/databaseResultTabs.spec.ts @@ -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) => { diff --git a/e2e/debug.spec.ts b/e2e/debug.spec.ts index 1af77663b1..3f909588da 100644 --- a/e2e/debug.spec.ts +++ b/e2e/debug.spec.ts @@ -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(); +}); diff --git a/e2e/debugVariablesLayout.spec.ts b/e2e/debugVariablesLayout.spec.ts new file mode 100644 index 0000000000..c83fcb6c9c --- /dev/null +++ b/e2e/debugVariablesLayout.spec.ts @@ -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); +}); diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts index 1eb7ad2044..27db945149 100644 --- a/e2e/editor.spec.ts +++ b/e2e/editor.spec.ts @@ -232,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, }) => { @@ -596,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"); +}); diff --git a/e2e/httpHighlight.fixture.ts b/e2e/httpHighlight.fixture.ts index 568db93127..9d38f3a9e6 100644 --- a/e2e/httpHighlight.fixture.ts +++ b/e2e/httpHighlight.fixture.ts @@ -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)], }); diff --git a/e2e/icls-php.spec.ts b/e2e/icls-php.spec.ts index beab211665..843a08a124 100644 --- a/e2e/icls-php.spec.ts +++ b/e2e/icls-php.spec.ts @@ -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) => { - 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", diff --git a/e2e/inlayRequests.fixture.ts b/e2e/inlayRequests.fixture.ts index 58c3066792..3e38a4108c 100644 --- a/e2e/inlayRequests.fixture.ts +++ b/e2e/inlayRequests.fixture.ts @@ -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"; diff --git a/e2e/jdbc-source.spec.ts b/e2e/jdbc-source.spec.ts index f84f363787..94da49c41b 100644 --- a/e2e/jdbc-source.spec.ts +++ b/e2e/jdbc-source.spec.ts @@ -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[]; - 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).id); + expect(saved.jdbcDriver).toBe(driver.id); for (const key of ["jars", "className", "classpath", "exec", "password"]) expect(saved).not.toHaveProperty(key); }); diff --git a/e2e/linkedGradle.spec.ts b/e2e/linkedGradle.spec.ts index d79f9ac091..89dc742485 100644 --- a/e2e/linkedGradle.spec.ts +++ b/e2e/linkedGradle.spec.ts @@ -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({ diff --git a/e2e/mergeEditor.spec.ts b/e2e/mergeEditor.spec.ts index 977ecb3eb1..c6db0e7f4c 100644 --- a/e2e/mergeEditor.spec.ts +++ b/e2e/mergeEditor.spec.ts @@ -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 () => { diff --git a/e2e/parameterInfoLayout.spec.ts b/e2e/parameterInfoLayout.spec.ts new file mode 100644 index 0000000000..c4a83cca32 --- /dev/null +++ b/e2e/parameterInfoLayout.spec.ts @@ -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(); +}); diff --git a/e2e/pushTargetBranch.spec.ts b/e2e/pushTargetBranch.spec.ts index 5be112f105..42f328798f 100644 --- a/e2e/pushTargetBranch.spec.ts +++ b/e2e/pushTargetBranch.spec.ts @@ -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: "git@example.com: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: "sam@example.com", + timeMs: 1795100000000, + }, + ] + : []; + h.vcs_commit_files = () => [{ path: "checkout.ts", oldPath: null, kind: "modified" }]; + h.vcs_has_hook = () => false; + h.vcs_remotes = () => [{ name: "origin", url: "git@example.com: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(); +}); diff --git a/e2e/run.spec.ts b/e2e/run.spec.ts index 0d6edf708d..b2fd1ff95c 100644 --- a/e2e/run.spec.ts +++ b/e2e/run.spec.ts @@ -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 = {}, +) { 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, }) => { diff --git a/e2e/search.spec.ts b/e2e/search.spec.ts index 567b6c3803..3ceea04184 100644 --- a/e2e/search.spec.ts +++ b/e2e/search.spec.ts @@ -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); 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. diff --git a/e2e/searchPopupsNarrow.spec.ts b/e2e/searchPopupsNarrow.spec.ts index 81c196c06d..3ca17f20c5 100644 --- a/e2e/searchPopupsNarrow.spec.ts +++ b/e2e/searchPopupsNarrow.spec.ts @@ -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. diff --git a/e2e/semanticStyle.spec.ts b/e2e/semanticStyle.spec.ts index 189722f8ba..46e2852c9b 100644 --- a/e2e/semanticStyle.spec.ts +++ b/e2e/semanticStyle.spec.ts @@ -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"); diff --git a/e2e/settingsPaneLayout.spec.ts b/e2e/settingsPaneLayout.spec.ts index 09e36a6307..048c8cb6cf 100644 --- a/e2e/settingsPaneLayout.spec.ts +++ b/e2e/settingsPaneLayout.spec.ts @@ -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 }); diff --git a/e2e/tsconfig.json b/e2e/tsconfig.json index ad7e5db9f1..78a3c09a1c 100644 --- a/e2e/tsconfig.json +++ b/e2e/tsconfig.json @@ -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"] } diff --git a/package.json b/package.json index fd1510e7cc..b3333e5e35 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/editor/core/controller.test.ts b/src/editor/core/controller.test.ts index 943109c392..cb2e723906 100644 --- a/src/editor/core/controller.test.ts +++ b/src/editor/core/controller.test.ts @@ -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" })); diff --git a/src/editor/core/controller.ts b/src/editor/core/controller.ts index e0c12c95cc..87bde26776 100644 --- a/src/editor/core/controller.ts +++ b/src/editor/core/controller.ts @@ -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); diff --git a/src/editor/core/model/session.test.ts b/src/editor/core/model/session.test.ts index 3b512109f1..3e0be06c5d 100644 --- a/src/editor/core/model/session.test.ts +++ b/src/editor/core/model/session.test.ts @@ -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(); diff --git a/src/editor/core/sync/DocSync.test.ts b/src/editor/core/sync/DocSync.test.ts index c252ecfeff..60fa19fdd1 100644 --- a/src/editor/core/sync/DocSync.test.ts +++ b/src/editor/core/sync/DocSync.test.ts @@ -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. */ diff --git a/src/editor/core/sync/DocSync.ts b/src/editor/core/sync/DocSync.ts index 8bd433fd8f..6aec61e8de 100644 --- a/src/editor/core/sync/DocSync.ts +++ b/src/editor/core/sync/DocSync.ts @@ -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; diff --git a/src/editor/core/view/EditorArea.module.css b/src/editor/core/view/EditorArea.module.css index e491b6ae3f..c813c52573 100644 --- a/src/editor/core/view/EditorArea.module.css +++ b/src/editor/core/view/EditorArea.module.css @@ -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 */ diff --git a/src/editor/core/view/FindBar.tsx b/src/editor/core/view/FindBar.tsx index f419e138db..1b4a89b6b6 100644 --- a/src/editor/core/view/FindBar.tsx +++ b/src/editor/core/view/FindBar.tsx @@ -608,182 +608,185 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo const canReplace = !!opts.search && !invalid; return ( -
{ - 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 && ( - e.preventDefault()} - onClick={() => { - if (replaceBoxRef.current?.contains(document.activeElement)) inputRef.current?.focus(); - onReplaceShown(!replace); - }} +
+
{ + 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 && ( + e.preventDefault()} + onClick={() => { + if (replaceBoxRef.current?.contains(document.activeElement)) inputRef.current?.focus(); + onReplaceShown(!replace); + }} + /> + )} +
+ 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"), + }, + ]} + /> +
+
+ + {counter} + + run(findPrevious)} + /> + run(findNext)} + /> + setFilterMenu(true)} + /> + setMoreMenu(true)} /> +
+ + {replace && ( + <> +
+ 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"), + }, + ]} + /> +
+
+ + + +
+ + )} + setHistoryMenu(null)} /> - )} -
- 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"), - }, - ]} + setMoreMenu(false)} + /> + setFilterMenu(false)} />
-
- - {counter} - - run(findPrevious)} - /> - run(findNext)} - /> - setFilterMenu(true)} - /> - setMoreMenu(true)} /> -
- - {replace && ( - <> -
- 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"), - }, - ]} - /> -
-
- - - -
- - )} - setHistoryMenu(null)} - /> - setMoreMenu(false)} - /> - setFilterMenu(false)} - />
); } diff --git a/src/editor/lsp/signature.ts b/src/editor/lsp/signature.ts index 41e036e13a..ae34dd0293 100644 --- a/src/editor/lsp/signature.ts +++ b/src/editor/lsp/signature.ts @@ -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; + }, + }; }, }; } diff --git a/src/editor/lsp/theme.ts b/src/editor/lsp/theme.ts index 846df3f7ae..24b39da1b1 100644 --- a/src/editor/lsp/theme.ts +++ b/src/editor/lsp/theme.ts @@ -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": { diff --git a/src/features/database/Database.module.css b/src/features/database/Database.module.css index 0fc9d749dd..773eb21ea1 100644 --- a/src/features/database/Database.module.css +++ b/src/features/database/Database.module.css @@ -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); diff --git a/src/features/database/ResultsView.tsx b/src/features/database/ResultsView.tsx index 7389066bff..1250957393 100644 --- a/src/features/database/ResultsView.tsx +++ b/src/features/database/ResultsView.tsx @@ -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 ( +
+ + + {count > 1 ? tx`Executing ${count} statements in ${name}…` : tx`Executing in ${name}…`} + + {formatElapsed(Math.max(0, now - execution.startedAt))} +
+ ); +} + 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(null); @@ -772,6 +807,8 @@ export function ResultsView() { owner: e.currentTarget, }); }; + const executing = execution && ; + if (!results.length && !hasOutput && executing) return
{executing}
; if (!results.length && !hasOutput) return ( @@ -825,6 +862,7 @@ export function ResultsView() { ]} /> + {executing}
(); const runField = StateField.define({ - 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({ 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 | 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[] = 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 }) { 10} - onChange={(v) => setConsoleSchema(path, v)} - disabled={!bound} - /> + {bound && boundId && switchable && listsDatabases(sourceById(boundId)) ? ( + + ) : ( + switchable && ( + (database ? (schema ? `${database}.${schema}` : database) : tx(""))} + 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, '""')}"`; /** diff --git a/src/features/database/inEditorResults.test.tsx b/src/features/database/inEditorResults.test.tsx index a882ae55e6..dd2c68436f 100644 --- a/src/features/database/inEditorResults.test.tsx +++ b/src/features/database/inEditorResults.test.tsx @@ -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((resolve) => { + finish = resolve; + }); + const execute = backend.execute.getMockImplementation()!; + backend.execute.mockImplementationOnce(async (...args: unknown[]) => { + await gate; + return execute(...(args as Parameters)); + }); + 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; + 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(); + }); +}); diff --git a/src/features/database/index.ts b/src/features/database/index.ts index f1212adab5..2419dc64d0 100644 --- a/src/features/database/index.ts +++ b/src/features/database/index.ts @@ -157,6 +157,7 @@ export function activate(): () => void { manualCommit: new Set(), pendingTx: new Set(), running: {}, + executions: {}, dialog: null, newMenuOpen: false, }); diff --git a/src/features/database/model.ts b/src/features/database/model.ts index ce21b72b01..19d754db27 100644 --- a/src/features/database/model.ts +++ b/src/features/database/model.ts @@ -484,3 +484,73 @@ export function parseSourceUrl(raw: string): { source: Partial; 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, + 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; +} diff --git a/src/features/database/requestLifecycle.test.ts b/src/features/database/requestLifecycle.test.ts index 74bddfecff..1a8db190b2 100644 --- a/src/features/database/requestLifecycle.test.ts +++ b/src/features/database/requestLifecycle.test.ts @@ -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]; diff --git a/src/features/database/resultEditing.test.ts b/src/features/database/resultEditing.test.ts index 99065599fe..722157ac7a 100644 --- a/src/features/database/resultEditing.test.ts +++ b/src/features/database/resultEditing.test.ts @@ -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, diff --git a/src/features/database/resultEditing.ts b/src/features/database/resultEditing.ts index b35a64e1e7..7c6084233d 100644 --- a/src/features/database/resultEditing.ts +++ b/src/features/database/resultEditing.ts @@ -227,10 +227,7 @@ export function resolveTarget( e: Extract, 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 }; } diff --git a/src/features/database/resultView.ts b/src/features/database/resultView.ts index 56b16052c4..6c779c6e80 100644 --- a/src/features/database/resultView.ts +++ b/src/features/database/resultView.ts @@ -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`; +} diff --git a/src/features/database/results-view.test.tsx b/src/features/database/results-view.test.tsx index 050173e809..ae4d88adce 100644 --- a/src/features/database/results-view.test.tsx +++ b/src/features/database/results-view.test.tsx @@ -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()); - 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((resolve) => { + finish = resolve; + }); + const execute = backend.execute.getMockImplementation()!; + backend.execute.mockImplementationOnce(async (...args: unknown[]) => { + await gate; + return execute(...(args as Parameters)); + }); + 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()); + let pending!: Promise; + 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()); + let pending!: Promise; + 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(); + }); +}); diff --git a/src/features/database/schemaTree.test.ts b/src/features/database/schemaTree.test.ts new file mode 100644 index 0000000000..c36db09ba5 --- /dev/null +++ b/src/features/database/schemaTree.test.ts @@ -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 = { 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" }); + }); +}); diff --git a/src/features/database/store.ts b/src/features/database/store.ts index 212917e72b..b1e386dd1f 100644 --- a/src/features/database/store.ts +++ b/src/features/database/store.ts @@ -174,6 +174,12 @@ export interface SourceCatalog { databases: Record; } +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; + /** Console path → what its running request submitted, and since when (ms since the epoch). */ + executions: Record; maxRows: number; dialog: DialogState | null; /** Target of the tree's lead node. */ @@ -271,6 +279,7 @@ export const useDatabase = create(() => ({ 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 { 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 }; }); } } diff --git a/src/features/debugger/ui/Overlays.module.css b/src/features/debugger/ui/Overlays.module.css index 88aef79ab9..cae3559e53 100644 --- a/src/features/debugger/ui/Overlays.module.css +++ b/src/features/debugger/ui/Overlays.module.css @@ -172,31 +172,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 { @@ -259,33 +300,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); +} diff --git a/src/features/debugger/ui/Overlays.tsx b/src/features/debugger/ui/Overlays.tsx index 8408d899a0..eef942f235 100644 --- a/src/features/debugger/ui/Overlays.tsx +++ b/src/features/debugger/ui/Overlays.tsx @@ -764,8 +764,9 @@ function EvaluateDialogInner({ initial }: { initial: string }) { const [history, setHistory] = useState(() => readHistory("evaluate")); const [historyMenu, setHistoryMenu] = useState(false); const historyPos = useRef(-1); - const historyButton = useRef(null); + const historyButton = useRef(null); const field = useRef(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 +825,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={