diff --git a/docs/en/contribute/guidelines/code-style.mdx b/docs/en/contribute/guidelines/code-style.mdx index afacb6246..1ec5bd1b5 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/en/guide/themes.mdx b/docs/en/guide/themes.mdx index 5e57627e7..4172563c1 100644 --- a/docs/en/guide/themes.mdx +++ b/docs/en/guide/themes.mdx @@ -26,7 +26,7 @@ The same page also has: - **Different tool window background**: set tool windows apart from the editor. - **Background Image**: an image shown through the project window, with its **Opacity**, **Fill** (scale, original size or tile) and **Anchor**. - **Accessibility**: **Use contrast scrollbars** and **Adjust colors for red-green vision deficiency** (for protanopia and deuteranopia). -- **Compact mode** under **UI Options**. +- **Compact mode** under **UI Options**, also in **View › Appearance**. As in IntelliJ IDEA, it uses shorter tree and list rows, a smaller main toolbar, tool window stripes and status bar, 16px toolbar and stripe icons, and 1px smaller text in the toolbar, status bar, editor tabs and tool window headers. ## Editor color scheme diff --git a/docs/zh/contribute/guidelines/code-style.mdx b/docs/zh/contribute/guidelines/code-style.mdx index 478688faa..b38345092 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/docs/zh/guide/themes.mdx b/docs/zh/guide/themes.mdx index 2ec7e51a2..9e65ba18e 100644 --- a/docs/zh/guide/themes.mdx +++ b/docs/zh/guide/themes.mdx @@ -26,7 +26,7 @@ description: "选择界面主题和编辑器配色方案,导入 IntelliJ 主 - **不同的工具窗口背景**:让工具窗口与编辑器区分开。 - **背景图像**:透过项目窗口显示的图像,可设置 **不透明度**、**填充**(缩放、原始大小或平铺)和 **位置**。 - **辅助功能**:**使用对比度滚动条** 和 **针对红绿色觉缺陷调整颜色**(适用于红色盲和绿色盲)。 -- **UI 选项** 下的 **紧凑模式**。 +- **UI 选项** 下的 **紧凑模式**,也可在 **视图 › 外观** 中切换。与 IntelliJ IDEA 一致:树和列表的行更矮,主工具栏、工具窗口栏和状态栏更紧凑,工具栏和工具窗口栏图标为 16px,工具栏、状态栏、编辑器标签页和工具窗口标题的文字小 1px。 ## 编辑器配色方案 diff --git a/e2e/agentFocusInput.spec.ts b/e2e/agentFocusInput.spec.ts index a932ca055..0a56d8cdf 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 8f3199083..cd09673a4 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 b6c99b6ba..e3e241946 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 61c969367..af1cb2ac4 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 74ee676b5..9aa1eaf7e 100644 --- a/e2e/codeInsight.spec.ts +++ b/e2e/codeInsight.spec.ts @@ -559,7 +559,82 @@ test("indexed single-file rename previews all anchors and applies only after con } await expect.poll(() => ipcCalls(page, "apply_workspace_edit")).toHaveLength(1); const [apply] = await ipcCalls(page, "apply_workspace_edit"); - expect(apply.edit).toMatchObject({ preconditions: [{ path: FILE, hash: "indexed-snapshot" }] }); + expect(apply?.edit).toMatchObject({ preconditions: [{ path: FILE, hash: "indexed-snapshot" }] }); +}); + +test("rename keeps the typed name, uses the editor font and shows long preview names in a narrow dialog", async ({ + workbench: page, +}) => { + const editor = await openSample(page); + await page.evaluate( + async ({ file, prepared }) => { + const projectModule = "/src/platform/project.ts"; + const schemaModule = "/src/features/settings/model/schema.ts"; + const [{ useProject }, { DEFAULT_SETTINGS }] = await Promise.all([ + import(/* @vite-ignore */ projectModule), + import(/* @vite-ignore */ schemaModule), + ]); + const base = useProject.getState().settings ?? DEFAULT_SETTINGS; + useProject.setState({ settings: { ...base, editor: { ...base.editor, fontSize: 17 } } }); + window.__ipc.handlers.lsp_prepare_rename = () => prepared; + window.__ipc.handlers.lsp_rename = (args) => ({ + preview: true, + incomplete: null, + edit: { + files: [ + { + kind: "edit", + path: file, + edits: [{ range: prepared, new_text: args.newName }], + }, + ], + }, + }); + window.__ipc.handlers.apply_workspace_edit = () => null; + }, + { file: FILE, prepared: range(20, 12, 17) }, + ); + + await caretAt(editor, page, "val order: Order", "order"); + await page.keyboard.press("Shift+F6"); + await expect(page.getByText(/Press ⇧F6 to show dialog/)).toBeVisible(); + const name = "checkoutOrderWithDeliveryInstructionsAndInventoryReservation"; + await page.keyboard.insertText(name); + await page.keyboard.press("Shift+F6"); + await page.setViewportSize({ width: 440, height: 520 }); + const dialog = page.getByRole("dialog", { name: "Rename 'order'", exact: true }); + const input = dialog.getByRole("textbox", { name: "New name" }); + await expect(input).toBeFocused(); + await expect(input).toHaveValue(name); + await expect(input).toHaveCSS("font-size", "17px"); + const [label, field] = await Promise.all([ + dialog.getByText("New name", { exact: true }).boundingBox(), + input.boundingBox(), + ]); + expect(label!.x + label!.width).toBeLessThan(field!.x); + const rename = dialog.getByRole("button", { name: "Rename", exact: true }); + + await input.fill(""); + await expect(rename).toBeDisabled(); + await input.press("Enter"); + await expect(dialog).toBeVisible(); + expect(await ipcCalls(page, "lsp_rename")).toHaveLength(0); + await input.fill(name); + await input.press("Enter"); + + const summary = `Rename 'order' to '${name}'`; + const preview = page.getByRole("dialog", { name: summary, exact: true }); + const context = preview.getByText(summary, { exact: true }); + await expect(context).toBeVisible(); + const geometry = await context.evaluate((element) => ({ + client: element.clientWidth, + content: element.scrollWidth, + })); + expect(geometry.content).toBeLessThanOrEqual(geometry.client + 1); + await expect(preview.getByText("1 occurrence in 1 file")).toBeVisible(); + expect(await ipcCalls(page, "apply_workspace_edit")).toHaveLength(0); + await preview.getByRole("button", { name: "Do Refactor" }).click(); + await expect.poll(() => ipcCalls(page, "apply_workspace_edit")).toHaveLength(1); }); test("intention previews fit narrow windows and wrap long code lines", async ({ workbench: page }) => { diff --git a/e2e/compactMode.spec.ts b/e2e/compactMode.spec.ts new file mode 100644 index 000000000..33ebe2bea --- /dev/null +++ b/e2e/compactMode.spec.ts @@ -0,0 +1,48 @@ +import { expect, test } from "./fixtures"; + +/** Heights IDEA's Islands theme uses in compact mode (`*.compact` keys), against the defaults. */ +const SIZES = { + normal: { titleBar: 40, treeRow: 24, stripeIcon: 20, statusBar: 34, runButton: 30 }, + compact: { titleBar: 32, treeRow: 22, stripeIcon: 16, statusBar: 24, runButton: 26 }, +}; + +async function measure(page: import("@playwright/test").Page) { + return page.evaluate(() => { + const height = (selector: string) => document.querySelector(selector)?.getBoundingClientRect().height ?? null; + return { + titleBar: height("header"), + treeRow: height('[role="tree"][aria-label="Project"] [role="treeitem"]'), + stripeIcon: height("[data-stripe-button] svg"), + statusBar: height('footer[aria-label="Status bar"]'), + runButton: height("[data-run-chooser] + * button"), + }; + }); +} + +test("Compact Mode shrinks rows, toolbars, stripes and the status bar like IDEA", async ({ workbench: page }, info) => { + // Plain-browser mode has no settings backend: set what the toggle action would store. + const setCompact = (compactMode: boolean) => + page.evaluate(async (compactMode) => { + const projectPath = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ projectPath); + const settings = useProject.getState().settings; + useProject.setState({ + settings: { + ...settings, + appearance: { ...settings?.appearance, theme: "dark", syncWithOs: false, compactMode }, + }, + }); + }, compactMode); + + await setCompact(false); + await expect.poll(() => measure(page)).toEqual(SIZES.normal); + await info.attach("normal", { body: await page.screenshot({ animations: "disabled" }), contentType: "image/png" }); + + await setCompact(true); + await expect(page.locator("html")).toHaveAttribute("data-compact", ""); + await expect.poll(() => measure(page)).toEqual(SIZES.compact); + await info.attach("compact", { body: await page.screenshot({ animations: "disabled" }), contentType: "image/png" }); + + await setCompact(false); + await expect.poll(() => measure(page)).toEqual(SIZES.normal); +}); diff --git a/e2e/compactSettingsControls.spec.ts b/e2e/compactSettingsControls.spec.ts index 11405a241..6d5614026 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 613b30c4e..f40075b22 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 643f617e0..b5d7ace54 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 29f75ddeb..da9d3de6c 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 1af77663b..3f909588d 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/editor.spec.ts b/e2e/editor.spec.ts index 1eb7ad204..27db94514 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 568db9312..9d38f3a9e 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 beab21166..843a08a12 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 58c306679..3e38a4108 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 f84f36378..94da49c41 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 d79f9ac09..89dc74248 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 977ecb3eb..c6db0e7f4 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/pushTargetBranch.spec.ts b/e2e/pushTargetBranch.spec.ts index 5be112f10..42f328798 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 0d6edf708..b2fd1ff95 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/runAnything.spec.ts b/e2e/runAnything.spec.ts new file mode 100644 index 000000000..862859696 --- /dev/null +++ b/e2e/runAnything.spec.ts @@ -0,0 +1,79 @@ +import { expect, test } from "./fixtures"; + +test("Run Anything keeps its command field and shortcuts visible as its results scroll", async ({ + workbench: page, +}) => { + await page.setViewportSize({ width: 1080, height: 740 }); + await page.evaluate(async () => { + const projectModule = "/src/platform/project.ts"; + const contributionsModule = "/src/workbench/contributions.ts"; + const historyModule = "/src/features/run-anything/model.ts"; + const [{ useProject }, { registerRunAnythingProvider }, { pushHistory }] = await Promise.all([ + import(/* @vite-ignore */ projectModule), + import(/* @vite-ignore */ contributionsModule), + import(/* @vite-ignore */ historyModule), + ]); + const root = useProject.getState().project.root; + for (const command of ["git status", "git diff --stat", "pnpm lint", "pnpm test"]) pushHistory(root, command); + const tasks = Array.from({ length: 8 }, (_, i) => { + const command = `npm run verify-${i + 1}`; + return { + key: command, + label: `Verify checkout configuration ${i + 1}`, + detail: "checkout-service / workspace verification", + completion: command, + run: () => { + document.body.dataset.runAnythingCommand = command; + }, + }; + }); + registerRunAnythingProvider({ + id: "test-verify", + order: -100, + group: "Run Configurations", + items: (line: string) => tasks.filter((task) => task.completion.includes(line)), + }); + }); + await page.keyboard.press("Control"); + await page.keyboard.press("Control"); + + const popup = page.getByRole("dialog", { name: "Run Anything", exact: true }); + const field = popup.getByLabel("Command line", { exact: true }); + const results = popup.getByRole("listbox", { name: "Run Anything entries" }); + const hint = popup.getByText(/Enter to run, Tab to complete|Tab to complete, Enter to run/); + await expect(field).toBeFocused(); + await page.setViewportSize({ width: 560, height: 340 }); + await expect + .poll(async () => { + const [shell, footer] = await Promise.all([popup.boundingBox(), hint.boundingBox()]); + return ( + !!shell && + !!footer && + Math.abs(shell.x - (560 - shell.width) / 2) < 2 && + shell.x >= 14 && + footer.y + footer.height <= shell.y + shell.height + 1 + ); + }) + .toBe(true); + await expect.poll(() => results.evaluate((el) => el.scrollHeight > el.clientHeight)).toBe(true); + + await field.fill("verify"); + await field.press("ArrowDown"); + await expect(field).toHaveValue("npm run verify-1"); + const selected = results.getByRole("option", { selected: true }); + await expect(selected).toContainText("Verify checkout configuration 1"); + await expect(field).toHaveAttribute("aria-activedescendant", (await selected.getAttribute("id"))!); + await field.press("Tab"); + await expect(field).toHaveValue("npm run verify-1"); + await expect(field).toBeFocused(); + await field.press("Shift+Tab"); + const history = popup.getByRole("button", { name: "Clear History" }); + await expect(history).toBeFocused(); + await history.press("Enter"); + await expect(history).toBeHidden(); + await expect(field).toBeFocused(); + await field.press("ArrowDown"); + await field.press("Enter"); + await expect(popup).toBeHidden(); + await expect(page.locator("body")).toHaveAttribute("data-run-anything-command", "npm run verify-1"); +}); diff --git a/e2e/search.spec.ts b/e2e/search.spec.ts index 567b6c380..3ceea0418 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 81c196c06..3ca17f20c 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 189722f8b..46e2852c9 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 09e36a630..048c8cb6c 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 ad7e5db9f..78a3c09a1 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 fd1510e7c..b3333e5e3 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/view/EditorArea.module.css b/src/editor/core/view/EditorArea.module.css index e491b6ae3..c813c5257 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 f419e138d..1b4a89b6b 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/Popups.module.css b/src/editor/lsp/Popups.module.css index a3215c0bf..5fa6997c8 100644 --- a/src/editor/lsp/Popups.module.css +++ b/src/editor/lsp/Popups.module.css @@ -261,6 +261,34 @@ font-size: var(--fs-tiny); color: var(--fg-faint); } +.symbolRename { + display: grid; + grid-template-columns: auto minmax(0, 1fr); + align-items: center; + gap: var(--space-2) var(--space-3); + padding: var(--space-3); + font-family: var(--font-ui); + font-size: var(--fs-ui); +} +.renameContext, +.symbolRenameNote { + grid-column: 1 / -1; + min-width: 0; + overflow-wrap: anywhere; +} +.renameContext { + color: var(--fg-emphasis); +} +.symbolRename .renameField { + width: 100%; + height: max(var(--h-field), calc(var(--openidea-editor-font-size, var(--fs-code)) + var(--space-2))); + font-family: var(--openidea-editor-font, var(--font-mono)); + font-size: var(--openidea-editor-font-size, var(--fs-code)); +} +.symbolRenameNote { + color: var(--fg-muted); + font-size: var(--fs-small); +} /* Fits its content up to a cap; resized (`data-resized`), it keeps that size and the body scrolls. */ .docPopup { @@ -398,6 +426,36 @@ flex-direction: column; overflow: hidden; } +.renamePreview [data-dialog-body] { + display: block; + overflow: auto; +} +.previewContext { + padding: var(--space-2) 14px 0; + overflow-wrap: anywhere; + color: var(--fg-emphasis); + font-size: var(--fs-ui); +} +.renamePreview .previewList { + overflow: visible; +} +.renamePreview .previewName { + min-width: 0; + max-width: 55%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.renamePreview .previewOp { + flex: 0 1 auto; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.renamePreview .previewWarning { + overflow-wrap: anywhere; +} .previewSummary { flex: none; padding: 10px 14px 6px; @@ -469,6 +527,18 @@ font-size: var(--fs-small); color: var(--fg-editor); } +.renamePreview .previewOccurrences .previewRow { + min-height: var(--h-row); + height: auto; + align-items: baseline; + padding-block: var(--space-1); +} +.renamePreview .previewCode { + font-family: var(--openidea-editor-font, var(--font-mono)); + font-size: var(--openidea-editor-font-size, var(--fs-code)); + white-space: pre-wrap; + overflow-wrap: anywhere; +} .previewMatch { background: var(--bg-search-match); color: var(--fg-search-match, inherit); diff --git a/src/editor/lsp/Popups.tsx b/src/editor/lsp/Popups.tsx index 2fe99609d..551543628 100644 --- a/src/editor/lsp/Popups.tsx +++ b/src/editor/lsp/Popups.tsx @@ -1,5 +1,5 @@ /** React popups for LSP editor features, rendered as a workbench overlay. */ -import { useEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent } from "react"; +import { useEffect, useId, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent } from "react"; import clsx from "clsx"; import { Checkbox, @@ -392,6 +392,54 @@ function RenamePopup({ popup }: { popup: Extract } ); } +function SymbolRenameDialog({ popup }: { popup: Extract }) { + const [value, setValue] = useState(popup.initial); + const field = useId(); + const name = value.trim(); + return ( + { + closePopup(); + popup.onSubmit(name); + }, + }, + { label: "Cancel", role: "cancel" }, + ]} + > +
+
+
{popup.title}
+ + setValue(e.target.value)} + invalid={!name} + /> + {popup.note &&
{popup.note}
} +
+
+
+ ); +} + function DocPopup({ popup }: { popup: Extract }) { const focusSeq = useLspPopup((s) => s.focusSeq); const scope = useRef(null); @@ -536,6 +584,7 @@ function savePreviewSize(size: { w: number; h: number }) { } function PreviewDialog({ popup }: { popup: Extract }) { + const rename = popup.renameThemeClasses !== undefined; const root = useProject((s) => s.project?.root ?? ""); const { summary } = popup; const [initialSize] = useState(loadPreviewSize); @@ -543,8 +592,9 @@ function PreviewDialog({ popup }: { popup: Extract + {rename &&
{popup.title}
} {popup.warnings?.map((w) => (
@@ -573,7 +624,10 @@ function PreviewDialog({ popup }: { popup: Extract{describeSummary(summary)}
{popup.occurrences ? ( -
    +
      {popup.occurrences.map((o, i) => { const lead = o.text.length - o.text.trimStart().length; const text = o.text.trim(); @@ -596,7 +650,9 @@ function PreviewDialog({ popup }: { popup: Extract (
    • - {basename(e.path)} + + {basename(e.path)} + {relativePath(root, e.path)} @@ -742,6 +798,8 @@ export function LspPopups() { return ; case "rename": return ; + case "symbolRename": + return ; case "doc": return ; case "definition": diff --git a/src/editor/lsp/popupStore.ts b/src/editor/lsp/popupStore.ts index 2402517c0..2b4a1a8a9 100644 --- a/src/editor/lsp/popupStore.ts +++ b/src/editor/lsp/popupStore.ts @@ -130,6 +130,14 @@ export type LspPopup = hint?: string; onSubmit: (name: string) => void; } + | { + kind: "symbolRename"; + title: string; + initial: string; + note?: string; + themeClasses: string; + onSubmit: (name: string) => void; + } | { kind: "preview"; title: string; @@ -140,6 +148,8 @@ export type LspPopup = warnings?: string[]; /** Individual occurrences with line previews (single-file syntax-based renames). */ occurrences?: PreviewOccurrence[]; + /** The editor theme for a symbol rename and its occurrence snippets. */ + renameThemeClasses?: string; }; export interface PreviewOccurrence { diff --git a/src/editor/lsp/rename.ts b/src/editor/lsp/rename.ts index e71ff0da8..0a59c6d4a 100644 --- a/src/editor/lsp/rename.ts +++ b/src/editor/lsp/rename.ts @@ -27,9 +27,9 @@ import { executeAction } from "@/platform/actions"; import { whenAllSynced, whenSynced, type EditorDocContext } from "@/editor/api"; import { structure } from "@/editor/structure"; import { docOf, incompleteNote, isUnavailable, lspRequest, reportLspError } from "./lsp"; -import { comparePos, offsetToPos, rangeToOffsets } from "./positions"; +import { offsetToPos, rangeToOffsets } from "./positions"; import { showHint } from "./hint"; -import { caretAnchor, openPopup, type PreviewOccurrence } from "./popupStore"; +import { openPopup, type PreviewOccurrence } from "./popupStore"; import { needsPreview, summarizeWorkspaceEdit } from "./workspaceEdit"; import { endInplaceRename, inplaceSession, startInplaceRename, type Span } from "./inplaceRename"; import { shortcutLabel } from "@/platform/keymap"; @@ -127,10 +127,10 @@ export async function startRename(view: EditorView) { const oldName = view.state.sliceDoc(from, to); const dialog = (initial: string) => openPopup({ - kind: "rename", - anchor: caretAnchor(view, from), + kind: "symbolRename", title: tx`Rename '${oldName}'`, initial, + themeClasses: view.themeClasses, onSubmit: (newName) => void finishRename(view, doc, pos, oldName, newName), }); if (from === to) { @@ -304,6 +304,7 @@ async function finishRename(view: EditorView, doc: EditorDocContext, pos: Pos, o kind: "preview", title: tx`Rename '${oldName}' to '${newName}'`, summary, + renameThemeClasses: view.themeClasses, ...(note ? { warnings: [note] } : {}), confirmLabel: note ? "Rename Anyway" : "Do Refactor", onConfirm: () => void applyEdit(view, edit), @@ -350,13 +351,12 @@ async function startSyntaxRename( return true; } const { plan } = result; - const at = plan.occurrences.find((o) => comparePos(o.range.start, pos) <= 0 && comparePos(pos, o.range.end) <= 0); openPopup({ - kind: "rename", - anchor: caretAnchor(view, rangeToOffsets(view.state.doc, (at ?? plan.occurrences[0]!).range).from), + kind: "symbolRename", title: tx`Rename '${plan.symbol.name}'`, initial: plan.symbol.name, note: `${SYNTAX_NOTE}: local occurrences only`, + themeClasses: view.themeClasses, onSubmit: (newName) => void commitSyntaxRename(view, doc, plan, newName), }); return true; @@ -418,6 +418,7 @@ export async function commitSyntaxRename( }, warnings: [...risks, `${SYNTAX_NOTE}. Only the occurrences below will be renamed.`], occurrences, + renameThemeClasses: view.themeClasses, confirmLabel: "Rename Anyway", onConfirm: apply, }); diff --git a/src/editor/lsp/syntaxFallback.test.ts b/src/editor/lsp/syntaxFallback.test.ts index 733192129..e22799d7f 100644 --- a/src/editor/lsp/syntaxFallback.test.ts +++ b/src/editor/lsp/syntaxFallback.test.ts @@ -646,8 +646,8 @@ describe("rename wiring", () => { const view = editor("const x = 1;\nf({ x });", "typescript", 6); await startRename(view); const popup = useLspPopup.getState().popup; - expect(popup?.kind).toBe("rename"); - if (popup?.kind !== "rename") return; + expect(popup?.kind).toBe("symbolRename"); + if (popup?.kind !== "symbolRename") return; expect(popup.note).toContain("Based on syntax"); popup.onSubmit("y"); await vi.waitFor(() => expect(view.state.doc.toString()).toBe("const y = 1;\nf({ x: y });")); @@ -661,7 +661,7 @@ describe("rename wiring", () => { const view = editor("const x = 1;\nx;\nvar x;", "typescript", 6); await startRename(view); const popup = useLspPopup.getState().popup; - if (popup?.kind !== "rename") throw new Error("no rename popup"); + if (popup?.kind !== "symbolRename") throw new Error("no rename dialog"); popup.onSubmit("y"); await vi.waitFor(() => expect(useLspPopup.getState().popup?.kind).toBe("preview")); const preview = useLspPopup.getState().popup; @@ -860,12 +860,12 @@ describe("rename wiring", () => { await startRename(view); expect(inplaceSession(view.state)?.oldName).toBe("x"); await startRename(view); - expect(useLspPopup.getState().popup?.kind).toBe("rename"); + expect(useLspPopup.getState().popup?.kind).toBe("symbolRename"); if (finish === "cancel") closePopup(); release({ status: "ok", data: r(0, 6, 7) }); await older; expect(inplaceSession(view.state)).toBeNull(); - expect(useLspPopup.getState().popup?.kind ?? null).toBe(finish === "dialog" ? "rename" : null); + expect(useLspPopup.getState().popup?.kind ?? null).toBe(finish === "dialog" ? "symbolRename" : null); }); it.each(["text", "document"])("drops pending preparation when the editor %s changes", async (change) => { @@ -938,7 +938,7 @@ describe("rename wiring", () => { ); cmd.syntaxLocals.mockReturnValueOnce(ok(local({ references: [] }))); await startRename(view); - expect(useLspPopup.getState().popup?.kind).toBe("rename"); + expect(useLspPopup.getState().popup?.kind).toBe("symbolRename"); }); }); diff --git a/src/features/agents/ImportSessionsDialog.tsx b/src/features/agents/ImportSessionsDialog.tsx index 20ff9d9b0..74b77d34e 100644 --- a/src/features/agents/ImportSessionsDialog.tsx +++ b/src/features/agents/ImportSessionsDialog.tsx @@ -1,6 +1,7 @@ /** Import Sessions from Other Apps: pick sessions a scan found now, and import them as tasks. */ import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type MouseEvent } from "react"; import { Button, Dialog, Icon, List, SearchField, Spinner, T, listNavigate, rowSelectionMode, selectRow } from "@/ui"; +import { useRowHeight } from "@/ui/density"; import { hasPrimaryModifier } from "@/platform/keymap"; import { relativePath, useProject } from "@/platform/project"; import { useTx } from "@/platform/i18n"; @@ -41,6 +42,7 @@ function folderOf(cwd: string | null, root: string | undefined): string { function ImportSessionsDialog() { const tx = useTx(); + const rowHeight = useRowHeight(ROW); const listId = useId(); const root = useProject((s) => s.project?.root); const external = useAgents((s) => s.external); @@ -216,7 +218,7 @@ function ImportSessionsDialog() { activeIndex={lead} onSelect={select} isSelected={(r) => !!sel.keys?.has(r.key)} - rowHeight={ROW} + rowHeight={rowHeight} aria-label={tx("Sessions from other apps")} empty={
      diff --git a/src/features/build-tools/ExecutePopup.tsx b/src/features/build-tools/ExecutePopup.tsx index fbac2b5cd..f4ce3716e 100644 --- a/src/features/build-tools/ExecutePopup.tsx +++ b/src/features/build-tools/ExecutePopup.tsx @@ -176,7 +176,6 @@ function ExecutePopup({ tool }: { tool: BuildTool }) { }} focusable={false} hoverSelects={false} - rowHeight={24} sectionHeight={28} className={styles.completions} aria-label="Completions" diff --git a/src/features/code-insight/UsagesPopup.tsx b/src/features/code-insight/UsagesPopup.tsx index 3a5fee831..cf1ec02b7 100644 --- a/src/features/code-insight/UsagesPopup.tsx +++ b/src/features/code-insight/UsagesPopup.tsx @@ -12,6 +12,7 @@ import { codePreviewExtensions } from "@/editor/api"; import { basename } from "@/platform/project"; import { shortcutLabel } from "@/platform/keymap"; import { Icon, IconButton, List, Popup, Select, Spinner, fileIconName, listNavigate } from "@/ui"; +import { useRowHeight } from "@/ui/density"; import { openLocation, readFileLines } from "./ipc"; import { dismissUsagesPopup, @@ -83,6 +84,7 @@ const ROW = 24; function UsagesPopupInner() { const { anchor, symbol, groups, note, loading, scope } = useUsagesPopup(); const preview = useUsagesPopupPreview((s) => s.preview); + const rowHeight = useRowHeight(ROW); const all = useMemo(() => groups.flatMap((g) => g.usages), [groups]); const [filter, setFilter] = useState(""); const accessOptions = useUsageAccessOptions(); @@ -210,7 +212,7 @@ function UsagesPopupInner() { )}
      void; onClose: () => void; }) { + const rowHeight = useRowHeight(22); const [query, setQuery] = useState(""); const [active, setActive] = useState(0); const shown = filterColumns(props.columns, query); @@ -72,7 +74,7 @@ export function ColumnsPopup(props: { onActivate={(_, i) => pick(i)} focusable={false} hoverSelects - rowHeight={22} + rowHeight={rowHeight} aria-label={tx("Columns")} className={styles.columnsList} empty={{tx("No matching columns")}} diff --git a/src/features/database/Database.module.css b/src/features/database/Database.module.css index 0fc9d749d..773eb21ea 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/Grid.test.tsx b/src/features/database/Grid.test.tsx index 3615906f3..50585a2ba 100644 --- a/src/features/database/Grid.test.tsx +++ b/src/features/database/Grid.test.tsx @@ -30,6 +30,7 @@ vi.mock("@tanstack/react-virtual", () => ({ getTotalSize: () => count * 24, getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 24, key: index })), scrollToIndex: () => {}, + measure: () => {}, }), })); diff --git a/src/features/database/ResultsView.tsx b/src/features/database/ResultsView.tsx index 7389066bf..bd09faeec 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"; @@ -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 +165,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 +200,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 +264,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 +308,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`. */ diff --git a/src/features/database/inEditorResults.test.tsx b/src/features/database/inEditorResults.test.tsx index a882ae55e..dd2c68436 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 f1212adab..2419dc64d 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/requestLifecycle.test.ts b/src/features/database/requestLifecycle.test.ts index 74bddfecf..1a8db190b 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/resultView.ts b/src/features/database/resultView.ts index 56b16052c..6c779c6e8 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 050173e80..cc8c33045 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 }] }), @@ -809,3 +811,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/store.ts b/src/features/database/store.ts index 212917e72..b1e386dd1 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/heap/HeapClasses.tsx b/src/features/debugger/heap/HeapClasses.tsx index d99cf385c..046d9e951 100644 --- a/src/features/debugger/heap/HeapClasses.tsx +++ b/src/features/debugger/heap/HeapClasses.tsx @@ -14,6 +14,7 @@ import { type ClassSort, } from "./editor/classRows"; import styles from "./HeapSnapshotEditor.module.css"; +import { useRowHeight } from "@/ui/density"; const COLUMNS: ReadonlyArray<{ key: ClassSort; label: string; numeric: boolean; diff?: boolean }> = [ { key: "name", label: "Class", numeric: false }, @@ -66,6 +67,7 @@ export function HeapClasses({ selected: number | null; onSelect: (row: HeapClassRow | null) => void; }) { + const rowHeight = useRowHeight(22); const tx = useTx(); const [query, setQuery] = useState(DEFAULT_CLASS_QUERY); const compared = changes !== null; @@ -124,7 +126,7 @@ export function HeapClasses({ renderItem={(r) => } activeIndex={selected === null ? -1 : rows.findIndex((r) => r.classIndex === selected)} onActiveChange={(i) => onSelect(rows[i] ?? null)} - rowHeight={22} + rowHeight={rowHeight} tableBody={{ headerRows: 1 }} empty={{tx("No matches")}} /> diff --git a/src/features/debugger/heap/editor/BiggestObjects.tsx b/src/features/debugger/heap/editor/BiggestObjects.tsx index 7c92362b5..6f1a0dcbd 100644 --- a/src/features/debugger/heap/editor/BiggestObjects.tsx +++ b/src/features/debugger/heap/editor/BiggestObjects.tsx @@ -6,6 +6,7 @@ import { formatBytes } from "../../memory/rows"; import { useHeapQuery } from "./heapQuery"; import { ObjectText } from "./ObjectText"; import styles from "../HeapSnapshotEditor.module.css"; +import { useRowHeight } from "@/ui/density"; const LIMIT = 100; @@ -21,6 +22,7 @@ export function BiggestObjects({ selected: number | null; onSelect: (object: HeapObjectRow) => void; }) { + const rowHeight = useRowHeight(22); const tx = useTx(); const page = useHeapQuery(`${snapshot}:${cls.classIndex}`, () => call(commands.debugHeapDominators(snapshot, null, cls.classIndex, 0, LIMIT)), @@ -70,7 +72,7 @@ export function BiggestObjects({ )} activeIndex={selected === null ? -1 : rows.findIndex((o) => o.object === selected)} onActiveChange={(i) => rows[i] && onSelect(rows[i])} - rowHeight={22} + rowHeight={rowHeight} tableBody={{ headerRows: 1 }} />
      diff --git a/src/features/debugger/memory/MemoryView.tsx b/src/features/debugger/memory/MemoryView.tsx index 62ae0238f..5a15421a2 100644 --- a/src/features/debugger/memory/MemoryView.tsx +++ b/src/features/debugger/memory/MemoryView.tsx @@ -24,6 +24,7 @@ import { keepKeysOnButton } from "./rowButtonKeys"; import { columnsOf, formatBytes, formatCount, formatDelta, queryFor, visibleRows, type SortKey } from "./rows"; import { unavailableText } from "./unavailableText"; import styles from "./MemoryView.module.css"; +import { useRowHeight } from "@/ui/density"; const COLUMNS: ReadonlyArray<{ key: SortKey; label: string; numeric: boolean }> = [ { key: "name", label: "Class", numeric: false }, @@ -105,6 +106,7 @@ function ClassRow({ } export function MemoryView({ session }: { session: DebugSession }) { + const rowHeight = useRowHeight(22); // Also re-renders the reason text, which reads the catalog when called. const tx = useTx(); const id = session.id; @@ -248,7 +250,7 @@ export function MemoryView({ session }: { session: DebugSession }) { onActivate={(r, _i, e) => { if (e.type === "keydown" && listsInstances && paused) showInstancesOf(r.name); }} - rowHeight={22} + rowHeight={rowHeight} tableBody={{ headerRows: 1 }} empty={{tx("No matches")}} /> diff --git a/src/features/debugger/ui/Overlays.module.css b/src/features/debugger/ui/Overlays.module.css index 88aef79ab..cae3559e5 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 8408d899a..eef942f23 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={