diff --git a/crates/ide-host/tests/maven_external.rs b/crates/ide-host/tests/maven_external.rs index ca28bdc46..a74dc7319 100644 --- a/crates/ide-host/tests/maven_external.rs +++ b/crates/ide-host/tests/maven_external.rs @@ -49,7 +49,7 @@ async fn external_maven_link_persists_reloads_and_unlink_keeps_files() { assert_eq!(b.pom, canonical); assert_eq!(dunce::canonicalize(root.join(&b.dir)).unwrap(), sibling); assert_eq!(host.project("main").unwrap().content_roots(), vec![sibling.clone()]); - assert_eq!(host.project("main").unwrap().lsp.jdtls_import_roots(), vec![sibling.clone()]); + assert_eq!(import_roots(&host, |roots| !roots.is_empty()).await, vec![sibling.clone()]); let reloaded = ops::build::build_model(&host, "main").await.unwrap(); assert_eq!( @@ -63,13 +63,26 @@ async fn external_maven_link_persists_reloads_and_unlink_keeps_files() { let gone = ops::build::build_model(&host, "main").await.unwrap(); assert!(gone.maven.unwrap().projects.iter().all(|p| p.artifact_id != "b")); assert!(host.project("main").unwrap().content_roots().is_empty()); - assert!(host.project("main").unwrap().lsp.jdtls_import_roots().is_empty()); + assert!(import_roots(&host, |roots| roots.is_empty()).await.is_empty()); assert_eq!(saved(), Vec::::new()); assert_eq!(std::fs::read_to_string(root.join("pom.xml")).unwrap(), a_pom); assert_eq!(std::fs::read_to_string(sibling.join("pom.xml")).unwrap(), b_pom); host.shutdown().await; } +/// The language server's Maven import roots once `ready` holds: a settings change refreshes them in +/// the background. +async fn import_roots(host: &Host, ready: impl Fn(&[std::path::PathBuf]) -> bool) -> Vec { + for _ in 0..200 { + let roots = host.project("main").unwrap().lsp.jdtls_import_roots(); + if ready(&roots) { + return roots; + } + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + } + host.project("main").unwrap().lsp.jdtls_import_roots() +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn reactor_module_beside_a_trusted_project_is_a_content_root_until_removed() { let temp = tempfile::tempdir().unwrap(); diff --git a/e2e/breakpointPopoverLayout.spec.ts b/e2e/breakpointPopoverLayout.spec.ts new file mode 100644 index 000000000..f272cc252 --- /dev/null +++ b/e2e/breakpointPopoverLayout.spec.ts @@ -0,0 +1,52 @@ +import type { EditorView } from "@codemirror/view"; +import { expect, stubDesktop, test } from "./fixtures"; + +test("gutter breakpoint keeps its location and buttons visible while editing in a short window", async ({ + workbench: page, +}) => { + await page.setViewportSize({ width: 410, height: 340 }); + await stubDesktop(page); + const name = "RecalculateInternationalPaymentsAcrossMultipleRegionalSettlementCyclesAndVerifyReceiptTotals.ts"; + const path = `/dev/acme-api/${name}`; + await page.evaluate(async (path) => { + const contributionsModule = "/src/workbench/contributions.ts"; + const { editorService } = await import(/* @vite-ignore */ contributionsModule); + await editorService().openFile(path); + }, path); + await page.locator(".cm-content").evaluate(async (editor, path) => { + const view = (editor as HTMLElement & { cmTile: { view: EditorView } }).cmTile.view; + const insert = Array.from({ length: 14 }, (_, i) => `const amount${i + 1} = ${i * 10};`).join("\n"); + view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert } }); + const breakpointsModule = "/src/features/debugger/breakpoints/store.ts"; + const { addBreakpoint } = await import(/* @vite-ignore */ breakpointsModule); + window.__ipc.handlers.debug_set_breakpoints = () => []; + addBreakpoint(path, 7, { condition: "amount8 > 50", hitCondition: ">= 3", logMessage: "amount: {amount8}" }); + }, path); + const marker = page.locator(".cm-lineNumbers .cm-gutterElement").filter({ hasText: /^8$/ }); + const open = () => marker.click({ button: "right" }); + await open(); + + const popup = page.getByRole("dialog", { name: "Breakpoint properties" }); + const done = popup.getByRole("button", { name: "Done", exact: true }); + const condition = popup.getByLabel("Condition", { exact: true }); + await expect(condition).toBeFocused(); + await expect(done).toBeInViewport({ ratio: 1 }); + const location = popup.getByTitle(`${path}:8`, { exact: true }); + await expect(location.getByText(":8", { exact: true })).toBeInViewport({ ratio: 1 }); + await expect(popup.getByText("Condition", { exact: true })).toHaveCSS("font-size", "13px"); + + await condition.fill("amount8 > 60"); + const log = popup.getByRole("textbox", { name: "Evaluate and log", exact: true }); + await log.fill("paid: {amount8}"); + await expect(location).toBeInViewport({ ratio: 1 }); + await expect(done).toBeInViewport({ ratio: 1 }); + await done.click(); + await expect(popup).toBeHidden(); + + await open(); + await expect(condition).toHaveValue("amount8 > 60"); + await expect(log).toHaveValue("paid: {amount8}"); + await popup.getByRole("button", { name: /^More/ }).click(); + const dialog = page.getByRole("dialog", { name: "Breakpoints", exact: true }); + await expect(dialog.getByLabel("Condition", { exact: true })).toHaveValue("amount8 > 60"); +}); diff --git a/e2e/build-output-layout.spec.ts b/e2e/build-output-layout.spec.ts index 0c1ac642f..e294d8e94 100644 --- a/e2e/build-output-layout.spec.ts +++ b/e2e/build-output-layout.spec.ts @@ -1,8 +1,8 @@ import type { Page } from "@playwright/test"; import { expect, test } from "./fixtures"; -async function showBuild(page: Page) { - await page.evaluate(async () => { +async function showBuild(page: Page, diagnosticPath: string | null = null) { + await page.evaluate(async (path) => { const storePath = "/src/features/build/store.ts"; const layoutPath = "/src/workbench/toolwindows/store.ts"; const { useBuildRun } = await import(/* @vite-ignore */ storePath); @@ -17,10 +17,10 @@ async function showBuild(page: Page) { { kind: "out", text: "Compiling TypeScript" }, { kind: "err", text: "Expected a number" }, ], - messages: [{ severity: "error", text: "Expected a number", path: null, range: null, code: null }], + messages: [{ severity: "error", text: "Expected a number", path, range: null, code: null }], }); showToolWindow("build", true); - }); + }, diagnosticPath); const build = page.getByRole("region", { name: "Build", exact: true }); await expect(build.getByRole("log", { name: "Build output" })).toBeVisible(); return build; @@ -35,6 +35,28 @@ test("Build gives about two thirds of the initial split to output", async ({ wor expect(treeWidth / (treeWidth + consoleWidth)).toBeCloseTo(0.33, 2); }); +test("Build reserves room for duration and file counts beside long directory paths", async ({ workbench: page }) => { + await page.setViewportSize({ width: 760, height: 680 }); + const path = "/dev/acme-api/src/services/regional-catalogs/generated/api/development/builders/catalog.ts"; + const build = await showBuild(page, path); + const root = build.getByRole("treeitem", { name: /^Build Project/ }); + const filename = build.getByTitle(path, { exact: true }).getByText("catalog.ts", { exact: true }); + const counts = build.getByTitle(path, { exact: true }).getByText("1 error", { exact: true }); + const errorSummary = root.getByText("1 error", { exact: true }); + const elapsed = root.getByText("1 s 200 ms", { exact: true }); + await expect(elapsed).toHaveCSS("font-size", "12px"); + await expect(counts).toBeInViewport({ ratio: 1 }); + const textFits = (el: Element) => { + const range = document.createRange(); + range.selectNodeContents(el); + return range.getBoundingClientRect().width <= el.getBoundingClientRect().width; + }; + expect(await filename.evaluate(textFits)).toBe(true); + expect(await errorSummary.evaluate(textFits)).toBe(true); + const [duration, row] = await Promise.all([elapsed.boundingBox(), root.boundingBox()]); + expect(row!.x + row!.width - duration!.x - duration!.width).toBeLessThan(12); +}); + test("Build output and diagnostics respond to a console font change", async ({ workbench: page }) => { const build = await showBuild(page); const log = build.getByRole("log", { name: "Build output" }); diff --git a/e2e/codeInsight.spec.ts b/e2e/codeInsight.spec.ts index f27f1c1f9..c5f65fac4 100644 --- a/e2e/codeInsight.spec.ts +++ b/e2e/codeInsight.spec.ts @@ -111,6 +111,7 @@ test("completion lists the server's items and inserts the chosen one", async ({ }); await expect(editor.locator(".cm-content")).toHaveCSS("font-size", zoomedSize); await expect(method.locator(".cm-completionLabel")).toHaveCSS("font-size", zoomedSize); + await page.keyboard.type("toD"); await expect(popup.getByText("total", { exact: true })).toBeHidden(); // Refreshing the results rebuilds the list; the hint bar must stay below it, not jump to the top. @@ -124,6 +125,37 @@ test("completion lists the server's items and inserts the chosen one", async ({ await expect(popup).toBeHidden(); await expect(editor.locator(".cm-activeLine")).toHaveText(/^\s*order\.toDto\(\)$/); expect((await ipcCalls(page, "lsp_completion")).length).toBeGreaterThan(0); + + await page.evaluate(async () => { + const path = "/src/platform/actions.ts"; + await (await import(/* @vite-ignore */ path)).executeAction("editor.splitRight"); + }); + const panes = page.locator("[data-pane-id]"); + await expect(panes).toHaveCount(2); + await page.setViewportSize({ width: 480, height: 760 }); + await panes.last().locator(".cm-content").focus(); + await page.keyboard.press("End"); + await page.keyboard.press("Enter"); + await page.keyboard.type("order."); + await page.keyboard.press("Control+Space"); + const footer = popup.locator(".cm-lsp-completion-footer"); + await expect + .poll(() => + footer.evaluate((el) => { + const tip = el.querySelector("span")!; + const sort = el.querySelector("button")!; + const a = tip.getBoundingClientRect(); + const b = sort.getBoundingClientRect(); + return { + oneRow: Math.abs(a.y + a.height / 2 - b.y - b.height / 2) <= 1, + hintClipped: tip.scrollWidth > tip.clientWidth, + sortFits: sort.scrollWidth <= sort.clientWidth + 1 && b.right <= el.getBoundingClientRect().right, + }; + }), + ) + .toEqual({ oneRow: true, hintClipped: true, sortFits: true }); + await expect(footer.getByTitle("Press ↵ to insert, ⇥ to replace")).toHaveCSS("font-size", "12px"); + await expect(footer.getByRole("button", { name: "Sort by name" })).toBeInViewport({ ratio: 1 }); }); test("long completion signatures fit the editor when the workbench is narrowed", async ({ workbench: page }) => { diff --git a/e2e/colorPickerLayout.spec.ts b/e2e/colorPickerLayout.spec.ts new file mode 100644 index 000000000..f1f5f799f --- /dev/null +++ b/e2e/colorPickerLayout.spec.ts @@ -0,0 +1,62 @@ +import { expect, test } from "./fixtures"; + +test("the editor color picker fits recent colors and keeps its actions visible", async ({ workbench: page }) => { + await page.setViewportSize({ width: 980, height: 720 }); + await page.evaluate(async () => { + const recent = Array.from({ length: 20 }, (_, i) => `#${((i + 1) * 314241).toString(16).padStart(6, "0")}ff`); + localStorage.setItem("openidea.colorPicker.recent.v1", JSON.stringify(recent)); + const contributions = "/src/workbench/contributions.ts"; + const { editorService } = await import(/* @vite-ignore */ contributions); + await editorService().openFile("/dev/acme-api/theme.css"); + }); + const editor = page.locator(".cm-editor").first(); + const contents = editor.locator(".cm-content"); + await contents.click(); + await page.keyboard.press("Meta+a"); + await page.keyboard.insertText(".notice { color: #5a8fbd; }"); + + const swatch = editor.locator(".cm-openidea-gutter-colors").getByTitle("#5a8fbd", { exact: true }); + const picker = page.getByRole("dialog", { name: "Color picker", exact: true }); + const palette = picker.locator(".react-colorful__saturation"); + const hex = picker.getByRole("textbox", { name: "Hexadecimal", exact: true }); + const apply = picker.getByRole("button", { name: "Apply", exact: true }); + const cancel = picker.getByRole("button", { name: "Cancel", exact: true }); + const recent = picker.getByRole("group", { name: "Recent colors", exact: true }).getByRole("button"); + await swatch.click(); + await expect(hex).toHaveValue("5A8FBDFF"); + expect((await picker.boundingBox())!.width).toBeLessThanOrEqual(308); + await expect(palette).toHaveCSS("height", "152px"); + expect(await picker.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0); + await hex.fill("#ff0000"); + expect(await picker.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0); + await page.keyboard.press("Escape"); + await expect(picker).toBeHidden(); + + await page.setViewportSize({ width: 280, height: 315 }); + await swatch.click(); + await expect(recent).toHaveCount(20); + const swatchRows = await recent.evaluateAll((elements) => { + const rows: number[] = []; + for (const element of elements) { + const box = element.getBoundingClientRect(); + if (!rows.includes(box.top)) rows.push(box.top); + const previous = element.previousElementSibling?.getBoundingClientRect(); + if (previous?.top === box.top && previous.right > box.left) throw new Error("Color swatches overlap"); + } + return rows.length; + }); + expect(swatchRows).toBeGreaterThan(2); + expect(await picker.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0); + await expect(apply).toBeInViewport({ ratio: 1 }); + await expect(cancel).toBeInViewport({ ratio: 1 }); + await hex.fill("#d27c54"); + await cancel.click(); + await expect(picker).toBeHidden(); + await expect(contents).toContainText("#5a8fbd"); + + await swatch.click(); + await hex.fill("#d27c54"); + await apply.click(); + await expect(picker).toBeHidden(); + await expect(contents).toContainText("#d27c54"); +}); diff --git a/e2e/commit.spec.ts b/e2e/commit.spec.ts index ca6c3859b..ffbb9df33 100644 --- a/e2e/commit.spec.ts +++ b/e2e/commit.spec.ts @@ -85,6 +85,66 @@ test("⌘K commits the checked changes with the typed message", async ({ workben await expect(changes.getByRole("checkbox", { name: "Include build.gradle.kts in commit" })).toBeHidden(); }); +test("commit options align author fields and keep the date editable in a narrow dialog", async ({ + workbench: page, +}) => { + await stubRepository(page); + await page.setViewportSize({ width: 1040, height: 700 }); + await page.keyboard.press("Meta+k"); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + await panel.getByRole("button", { name: "Commit Options", exact: true }).click(); + const popup = page.getByRole("dialog", { name: "Commit Options", exact: true }); + const author = popup.getByRole("textbox", { name: "Author", exact: true }); + const date = popup.getByLabel("Author date", { exact: true }); + const clear = popup.getByRole("button", { name: "Clear author date", exact: true }); + const name = "Regional Ledger Review "; + const time = "2024-06-04T13:20:21"; + await author.fill(name); + await date.fill(time); + const authorBox = (await author.boundingBox())!; + const dateBox = (await date.boundingBox())!; + const dateLabel = (await popup.getByText("Author date", { exact: true }).boundingBox())!; + const clearBox = (await clear.boundingBox())!; + expect(authorBox.x).toBeCloseTo(dateBox.x, 0); + expect(dateLabel.y).toBeGreaterThanOrEqual(dateBox.y); + expect(dateLabel.y).toBeLessThan(dateBox.y + dateBox.height); + expect(clearBox.x + clearBox.width).toBeCloseTo(authorBox.x + authorBox.width, 0); + await expect(clear).toBeInViewport({ ratio: 1 }); + + await page.keyboard.press("Escape"); + await expect(popup).toBeHidden(); + await page.evaluate(async () => { + const projectModule = "/src/platform/project.ts"; + const { useProject } = await import(/* @vite-ignore */ projectModule); + const { settings } = useProject.getState(); + useProject.setState({ + settings: { ...settings, vcs: { ...settings?.vcs, commit: { ...settings?.vcs?.commit, nonModal: false } } }, + }); + }); + await page.setViewportSize({ width: 650, height: 650 }); + await page.keyboard.press("Meta+k"); + const dialog = page.getByRole("dialog", { name: "Commit Changes", exact: true }); + const options = dialog.getByRole("group", { name: "Commit Options", exact: true }); + const compactAuthor = options.getByRole("textbox", { name: "Author", exact: true }); + const compactDate = options.getByLabel("Author date", { exact: true }); + const compactClear = options.getByRole("button", { name: "Clear author date", exact: true }); + await expect(compactAuthor).toHaveValue(name); + await expect(compactDate).toHaveValue(time); + const labelBox = (await options.getByText("Author:", { exact: true }).boundingBox())!; + const inputBox = (await compactAuthor.boundingBox())!; + expect(inputBox.x).toBeCloseTo(labelBox.x, 0); + expect(inputBox.y).toBeGreaterThanOrEqual(labelBox.y + labelBox.height); + const box = (await compactDate.boundingBox())!; + const buttonBox = (await compactClear.boundingBox())!; + expect(box.width).toBeCloseTo(inputBox.width, 0); + expect(buttonBox.y).toBeGreaterThanOrEqual(box.y + box.height); + expect(await options.evaluate((node) => node.scrollWidth - node.clientWidth)).toBeLessThanOrEqual(1); + await compactClear.click(); + await expect(compactDate).toHaveValue(""); + await expect(compactClear).toBeHidden(); + await expect(compactAuthor).toHaveValue(name); +}); + test("the Commit window gives its message preferred focus", async ({ workbench: page }) => { await stubRepository(page); const stripe = page.locator('[data-stripe-button="commit"]'); @@ -720,6 +780,81 @@ test("Commit Options applies a named TODO filter independently of the TODO windo expect(await ipcCalls(page, "vcs_commit")).toEqual([]); }); +test("commit check text scrolls independently of its status icon and retry action", async ({ workbench: page }) => { + await stubRepository(page); + await page.setViewportSize({ width: 850, height: 650 }); + await page.evaluate(async () => { + const registryPath = "/src/features/vcs/commitCheckRegistry.ts"; + const layoutPath = "/src/workbench/toolwindows/store.ts"; + const { registerCommitCheck } = await import(/* @vite-ignore */ registryPath); + const layout = await import(/* @vite-ignore */ layoutPath); + layout.moveToolWindow("commit", "left"); + layout.setToolWindowSize("left", 238); + for (let index = 0; index < 6; index++) { + registerCommitCheck({ + id: `test.commitLayout.${index}`, + order: index - 1000, + title: `Ledger check ${index + 1}`, + run: () => { + if (index === 0) document.body.dataset.checkRuns = String(Number(document.body.dataset.checkRuns ?? 0) + 1); + return { + severity: "error", + text: "The regional settlement totals differ from the monthly inventory audit and need a second review.", + fix: + index === 5 + ? { + label: "Review final check", + run: () => { + document.body.dataset.commitCheckReviewed = "yes"; + }, + } + : undefined, + }; + }, + }); + } + }); + await page.keyboard.press("Meta+k"); + const commit = page.getByRole("region", { name: "Commit", exact: true }); + await commit.getByRole("textbox", { name: "Commit message" }).fill("Review the settlement totals"); + await commit.getByRole("button", { name: "Commit Options", exact: true }).click(); + const options = page.getByRole("dialog", { name: "Commit Options", exact: true }); + await options.getByRole("button", { name: "Run Commit Checks", exact: true }).click(); + + const feedback = commit.getByRole("alert").filter({ hasText: "Ledger check 1" }); + const first = feedback.getByText("Ledger check 1", { exact: true }); + const second = feedback.getByText("Ledger check 2", { exact: true }); + const results = first.locator("../.."); + const icon = feedback.locator("svg").first(); + const retry = commit.getByRole("button", { name: "Rerun Commit Checks", exact: true }); + const commitAnyway = commit.getByRole("button", { name: "Commit Anyway", exact: true }); + await expect(commitAnyway).toBeInViewport({ ratio: 1 }); + await expect(first).toHaveCSS("font-size", "13px"); + const firstRow = (await first.locator("..").boundingBox())!; + const secondRow = (await second.locator("..").boundingBox())!; + expect(secondRow.y - (firstRow.y + firstRow.height)).toBeCloseTo(4, 0); + expect(await results.evaluate((node) => node.scrollHeight > node.clientHeight)).toBe(true); + const statusTop = (await icon.boundingBox())!.y; + const retryTop = (await retry.boundingBox())!.y; + await results.evaluate((node) => { + node.scrollTop = node.scrollHeight; + }); + expect(await results.evaluate((node) => node.scrollTop)).toBeGreaterThan(0); + expect((await icon.boundingBox())!.y).toBeCloseTo(statusTop, 0); + expect((await retry.boundingBox())!.y).toBeCloseTo(retryTop, 0); + const details = feedback.getByRole("button", { name: "Review final check", exact: true }); + await expect(details).toBeInViewport({ ratio: 1 }); + await expect(icon).toBeInViewport({ ratio: 1 }); + await expect(retry).toBeInViewport({ ratio: 1 }); + await expect(commitAnyway).toBeInViewport({ ratio: 1 }); + await details.click(); + await expect(page.locator("body")).toHaveAttribute("data-commit-check-reviewed", "yes"); + await retry.click(); + await expect(page.locator("body")).toHaveAttribute("data-check-runs", "2"); + await expect(first).toBeVisible(); + expect(await ipcCalls(page, "vcs_commit")).toEqual([]); +}); + test("the TODO check reports unreadable files and can retry after they become available", async ({ workbench: page, }) => { @@ -1024,27 +1159,51 @@ test("the Commit tool window restores the draft and author options for the inclu await expect(message).toHaveValue("Default draft"); }); -test("commit message history opens above the message without an empty icon column", async ({ workbench: page }) => { +test("commit message history shows compact message previews above the editor", async ({ workbench: page }) => { + await page.emulateMedia({ reducedMotion: "reduce" }); await stubRepository(page); await page.keyboard.press("Meta+k"); const message = page.getByRole("textbox", { name: "Commit message" }); await expect(message).toBeVisible(); await page.evaluate((root) => { - localStorage.setItem(`openidea.vcs.commitMessages:${root}`, JSON.stringify(["Previous commit message"])); + localStorage.setItem( + `openidea.vcs.commitMessages:${root}`, + JSON.stringify([ + "Update inventory\n\nReview settlement totals", + "Update inventory\n\nReconcile export records", + ...Array.from({ length: 7 }, (_, index) => `Earlier message ${index + 1}`), + ]), + ); }, ROOT); await message.fill("Draft"); - await page.getByRole("button", { name: "Commit Message History" }).click(); + const history = page.getByRole("button", { name: "Commit Message History" }); + await history.click(); const menu = page.getByRole("menu", { name: "Recent commit messages" }); - const row = menu.getByRole("menuitem", { name: "Previous commit message" }); + const row = menu.getByRole("menuitem", { name: /Update inventory.*Review settlement totals/ }); await expect(row).toBeVisible(); - const messageBox = await message.boundingBox(); - const menuBox = await menu.locator("..").boundingBox(); - expect(messageBox).not.toBeNull(); - expect(menuBox).not.toBeNull(); - expect(menuBox!.y + menuBox!.height).toBeLessThan(messageBox!.y); - expect(Math.abs(menuBox!.x - messageBox!.x)).toBeLessThan(2); + const messageBox = (await message.boundingBox())!; + const menuBox = (await menu.locator("..").boundingBox())!; + const rowBox = (await row.boundingBox())!; + expect(messageBox.y - menuBox.y - menuBox.height).toBeCloseTo(3, 0); + expect(Math.abs(menuBox.x - messageBox.x)).toBeLessThan(2); + expect(menuBox.height).toBeLessThan(rowBox.height * 8); + await expect(row).toHaveCSS("font-family", await message.evaluate((el) => getComputedStyle(el).fontFamily)); + await expect(row).toHaveCSS("font-size", await message.evaluate((el) => getComputedStyle(el).fontSize)); await expect(row.locator("span")).toHaveCount(1); + + await row.press("Escape"); + await expect(menu).toBeHidden(); + await expect(message).toHaveValue("Draft"); + await history.click(); + await row.press("Home"); + await expect(row).toBeFocused(); + await page.keyboard.press("ArrowDown"); + const second = menu.getByRole("menuitem", { name: /Update inventory.*Reconcile export records/ }); + await expect(second).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(message).toHaveValue("Update inventory\n\nReconcile export records"); + await expect(message).toBeFocused(); }); test("Amend shows the original author and warns when the committer differs", async ({ workbench: page }) => { @@ -1155,6 +1314,60 @@ async function stubEarlierAmend(page: Page) { }); } +test("Amend sizes the chooser for long subjects while keeping the last commit action distinct", async ({ + workbench: page, +}) => { + await stubEarlierAmend(page); + const tip = "Record regional settlement adjustments across the quarterly audit and reconciliation reports"; + const earlier = "Expand the warehouse reconciliation report with monthly ledger and inventory audit totals"; + await page.evaluate( + ({ tip, earlier }) => { + const handlers = window.__ipc.handlers; + const log = handlers.vcs_log!; + handlers.vcs_log = (args) => + (log(args) as { id: string; summary: string; message: string }[]).map((commit) => { + const subject = commit.id === "1111111" ? tip : commit.id === "aaaaaaa" ? earlier : commit.summary; + return { ...commit, summary: subject, message: subject }; + }); + }, + { tip, earlier }, + ); + await page.setViewportSize({ width: 1040, height: 700 }); + await page.keyboard.press("Meta+k"); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + const choose = panel.getByRole("button", { name: "Choose Commit to Amend", exact: true }); + await choose.click(); + const list = page.getByRole("listbox", { name: "Choose Commit to Amend", exact: true }); + const popup = list.locator("xpath=ancestor::*[@data-popup]"); + const search = popup.getByRole("textbox", { name: "Search commits", exact: true }); + const last = list.getByRole("option", { name: /^Amend Last Commit/ }); + const previous = list.getByRole("option", { name: earlier, exact: true }); + + await expect(previous).toBeVisible(); + const wide = (await popup.boundingBox())!; + expect(wide.width).toBeGreaterThan(360); + expect(wide.width).toBeLessThanOrEqual(522); + await expect(last.getByText("Amend Last Commit", { exact: true })).toHaveCSS("font-weight", "600"); + await expect(last.getByText(tip, { exact: true })).toHaveAttribute("title", tip); + await expect(previous.getByText(earlier, { exact: true })).toHaveAttribute("title", earlier); + + await page.setViewportSize({ width: 440, height: 520 }); + await expect + .poll(async () => { + const box = (await popup.boundingBox())!; + return box.x >= 0 && box.x + box.width <= 440 && box.width < wide.width; + }) + .toBe(true); + await expect(search).toBeFocused(); + await search.fill("inventory audit"); + await expect(previous).toBeVisible(); + await search.press("Enter"); + await expect(list).toBeHidden(); + await page.setViewportSize({ width: 1040, height: 700 }); + await page.keyboard.press("Meta+k"); + await expect(panel.getByRole("textbox", { name: "Commit message" })).toHaveValue(earlier); +}); + test("Amend can select an earlier commit before protected history", async ({ workbench: page }) => { await stubEarlierAmend(page); await page.keyboard.press("Meta+k"); diff --git a/e2e/fileRenameLayout.spec.ts b/e2e/fileRenameLayout.spec.ts new file mode 100644 index 000000000..0853a5cac --- /dev/null +++ b/e2e/fileRenameLayout.spec.ts @@ -0,0 +1,80 @@ +import { expect, test } from "./fixtures"; + +const root = "/dev/acme-api"; +const stem = "InternationalSettlementRegionalReconciliationAndAuditWarehouseAllocationConfiguration"; +const original = stem + ".txt"; +const renamed = "WarehouseAllocation.txt"; + +test("file rename groups the name and reflows the options without losing validation", async ({ workbench: page }) => { + await page.setViewportSize({ width: 1000, height: 700 }); + await page.evaluate( + async ({ root, original }) => { + const fsModule = "/src/features/project-tree/fs.ts"; + const storeModule = "/src/features/project-tree/store.ts"; + const { projectFs } = await import(/* @vite-ignore */ fsModule); + const { loadDir } = await import(/* @vite-ignore */ storeModule); + await projectFs(root).createFile(root + "/" + original); + await loadDir(root, true); + }, + { root, original }, + ); + const source = page.getByRole("treeitem", { name: original, exact: true }); + await source.click(); + await page.keyboard.press("Shift+F6"); + + const dialog = page.getByRole("dialog", { name: "Rename", exact: true }); + const prompt = dialog.getByText("Rename file '" + original + "' and its usages to:", { exact: true }); + const field = dialog.getByRole("textbox", { name: "New name" }); + const references = dialog.getByRole("checkbox", { name: "Search for references" }); + const comments = dialog.getByRole("checkbox", { name: "Search in comments and strings" }); + const submit = dialog.getByRole("button", { name: "Refactor", exact: true }); + const referencesRow = references.locator("xpath=ancestor::label"); + const commentsRow = comments.locator("xpath=ancestor::label"); + + await expect(field).toBeFocused(); + const selected = await field.evaluate((el: HTMLInputElement) => el.value.slice(el.selectionStart!, el.selectionEnd!)); + expect(selected).toBe(stem); + + await expect + .poll(async () => { + const a = (await prompt.boundingBox())!; + const b = (await field.boundingBox())!; + return b.y - a.y - a.height; + }) + .toBeCloseTo(4, 0); + await expect + .poll(async () => { + const a = (await referencesRow.boundingBox())!; + const b = (await commentsRow.boundingBox())!; + return Math.abs(a.y - b.y) < 1 && b.x >= a.x + a.width; + }) + .toBe(true); + + await field.fill("README.md"); + await expect(dialog.getByRole("alert")).toBeVisible(); + await expect(submit).toBeDisabled(); + await page.setViewportSize({ width: 400, height: 520 }); + await expect + .poll(async () => { + const a = (await referencesRow.boundingBox())!; + const b = (await commentsRow.boundingBox())!; + return b.y >= a.y + a.height; + }) + .toBe(true); + await expect(field).toHaveValue("README.md"); + await expect(prompt).toBeInViewport({ ratio: 1 }); + await expect(submit).toBeInViewport({ ratio: 1 }); + expect( + await dialog.locator("[data-dialog-body]").evaluate((node) => node.scrollWidth - node.clientWidth), + ).toBeLessThanOrEqual(1); + + await field.fill(renamed); + await expect(dialog.getByRole("alert")).toBeHidden(); + await references.uncheck(); + await comments.uncheck(); + await submit.click(); + await expect(dialog).toBeHidden(); + await page.setViewportSize({ width: 1000, height: 700 }); + await expect(page.getByRole("treeitem", { name: renamed, exact: true })).toBeVisible(); + await expect(source).toHaveCount(0); +}); diff --git a/e2e/findHistoryLayout.spec.ts b/e2e/findHistoryLayout.spec.ts new file mode 100644 index 000000000..745c1e496 --- /dev/null +++ b/e2e/findHistoryLayout.spec.ts @@ -0,0 +1,78 @@ +import type { Locator, Page } from "@playwright/test"; +import { expect, openFromTree, test } from "./fixtures"; + +const latest = "regional-order-reconciliation-endpoints-for-sandbox-environments/".repeat(3) + "checkout\nText to find"; + +async function seedHistory(page: Page, kind: "find" | "replace") { + await page.evaluate( + async ({ kind, latest }) => { + const searchModule = "/src/platform/search.ts"; + const { rememberSearch } = await import(/* @vite-ignore */ searchModule); + for (let i = 0; i < 19; i++) rememberSearch(kind, `Order rule ${i}`); + rememberSearch(kind, latest); + }, + { kind, latest }, + ); +} + +async function openHistory(field: Locator, menu: Locator) { + await field.focus(); + await field.press("Alt+ArrowDown"); + await expect(menu).toBeVisible(); +} + +test("editor find history grows with the field and restores the original query", async ({ workbench: page }) => { + await page.setViewportSize({ width: 1040, height: 700 }); + await openFromTree(page, "build.gradle.kts"); + await page.keyboard.press("Meta+f"); + await seedHistory(page, "find"); + + const field = page.getByRole("textbox", { name: "Find", exact: true }); + const menu = page.getByRole("menu", { name: "Recent Searches", exact: true }); + await openHistory(field, menu); + + const newest = menu.getByRole("menuitem").first(); + await expect(newest).toHaveText(latest.replace("\n", " ⏎ ")); + await expect(newest).toHaveAttribute("title", latest); + await expect.poll(async () => (await menu.boundingBox())!.width).toBeGreaterThan(420); + await newest.press("Enter"); + await expect(menu).toBeHidden(); + await expect(field).toHaveValue(latest); + await expect(field).toBeFocused(); +}); + +test("project replacement history stays inside a narrow window and keeps its heading visible", async ({ + workbench: page, +}) => { + await page.setViewportSize({ width: 440, height: 520 }); + await page.keyboard.press("Meta+Shift+r"); + await seedHistory(page, "replace"); + + const field = page.getByRole("textbox", { name: "Replace with" }); + const menu = page.getByRole("menu", { name: "Recent Replacements" }); + await openHistory(field, menu); + + const popup = menu.locator(".."); + const heading = popup.getByText("Recent Replacements", { exact: true }); + const newest = menu.getByRole("menuitem").first(); + await expect(newest).toHaveText(latest.replace("\n", " ⏎ ")); + await expect + .poll(async () => { + const { x, width } = (await popup.boundingBox())!; + return x >= 0 && x + width <= 440; + }) + .toBe(true); + + await newest.press("End"); + const oldest = menu.getByRole("menuitem").last(); + await expect(oldest).toBeFocused(); + await expect.poll(async () => popup.evaluate((node) => node.scrollTop)).toBeGreaterThan(0); + await expect(heading).toBeInViewport(); + + await oldest.press("Home"); + await expect(newest).toBeFocused(); + await newest.press("Enter"); + await expect(menu).toBeHidden(); + await expect(field).toHaveValue(latest); + await expect(field).toBeFocused(); +}); diff --git a/e2e/gitAnnotateLayout.spec.ts b/e2e/gitAnnotateLayout.spec.ts index f0b93ba4f..80cae317e 100644 --- a/e2e/gitAnnotateLayout.spec.ts +++ b/e2e/gitAnnotateLayout.spec.ts @@ -3,11 +3,12 @@ import { expect, openFromTree, stubDesktop, test } from "./fixtures"; test("Git annotations align dates and full author names at UI text size", async ({ workbench: page }) => { const editor = await openFromTree(page, "build.gradle.kts"); await stubDesktop(page); - await page.evaluate(async () => { + const longEmail = `reconciliation+${"regional-settlement-".repeat(5)}review@example.invalid`; + await page.evaluate(async (email) => { const root = "/dev/acme-api"; const file = `${root}/build.gradle.kts`; const handlers = window.__ipc.handlers; - handlers.vcs_blame = () => [ + const lines = [ { commit: "a1234567".padEnd(40, "a"), author: "Lena Park", @@ -21,6 +22,23 @@ test("Git annotations align dates and full author names at UI text size", async summary: "Review totals", }, ]; + handlers.vcs_blame = () => lines; + handlers.vcs_log = ({ query }) => { + const { branch } = query as { branch?: string }; + const line = lines.find(({ commit }) => commit === branch); + if (!line) return []; + return [ + { + ...line, + id: line.commit, + shortId: line.commit.slice(0, 8), + refs: [], + parents: [], + email: line === lines[0] ? "lena@example.invalid" : email, + message: line.summary, + }, + ]; + }; const projectModule = "/src/platform/project.ts"; const { useProject } = await import(/* @vite-ignore */ projectModule); const { settings } = useProject.getState(); @@ -39,7 +57,7 @@ test("Git annotations align dates and full author names at UI text size", async const actionsModule = "/src/platform/actions.ts"; const { executeAction } = await import(/* @vite-ignore */ actionsModule); await executeAction("vcs.annotate", file); - }); + }, longEmail); const gutter = editor.locator(".cm-vcs-blame"); const first = gutter.locator("[data-commit]").filter({ hasText: "3 May 2026" }); @@ -51,6 +69,21 @@ test("Git annotations align dates and full author names at UI text size", async await expect .poll(async () => Math.abs((await firstAuthor.boundingBox())!.x - (await secondAuthor.boundingBox())!.x)) .toBeLessThan(1); + + await first.hover(); + const details = page.getByRole("dialog").filter({ has: page.getByTitle("Show Commit in Git Log") }); + await expect(details).toContainText("lena@example.invalid"); + await expect.poll(async () => (await details.boundingBox())!.width).toBeLessThan(400); + await expect(details.getByTitle("Show Commit in Git Log")).toHaveCSS( + "font-family", + await details.evaluate((el) => getComputedStyle(el).fontFamily), + ); + + await page.setViewportSize({ width: 430, height: 640 }); + await second.hover(); + await expect(details).toContainText(longEmail); + await expect(details).toBeInViewport({ ratio: 1 }); + await expect.poll(() => details.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); const uiSize = await editor.evaluate((el) => getComputedStyle(el).getPropertyValue("--fs-ui").trim()); await expect(firstAuthor).toHaveCSS("font-size", uiSize); diff --git a/e2e/gitLogCommitChooser.spec.ts b/e2e/gitLogCommitChooser.spec.ts new file mode 100644 index 000000000..c531a5205 --- /dev/null +++ b/e2e/gitLogCommitChooser.spec.ts @@ -0,0 +1,104 @@ +import { expect, stubDesktop, test } from "./fixtures"; + +const rootSubject = "Start warehouse reporting"; +const mergeSubject = "Merge reporting changes"; +const firstSubject = "Align regional settlement totals with the warehouse ledger before monthly reconciliation closes"; +const secondSubject = "Keep archived settlement adjustments in the regional audit trail after the ledger is rebuilt"; + +test("Git Log commit choices fit their rows and navigate by keyboard after filtering", async ({ workbench: page }) => { + await page.setViewportSize({ width: 1040, height: 700 }); + await stubDesktop(page); + await page.evaluate( + async ({ mergeSubject, firstSubject, secondSubject, rootSubject }) => { + const root = "/dev/acme-api"; + const changes = [ + [mergeSubject, "Merge Author", [1, 2]], + [firstSubject, "Priya Kapoor", [3]], + [secondSubject, "Morgan Olsen", [3]], + [rootSubject, "Initial Author", []], + ] as const; + const id = (i: number) => String(i + 1).repeat(40); + const commits = changes.map(([summary, author, parents], i) => ({ + id: id(i), + shortId: id(i).slice(0, 8), + parents: parents.map(id), + refs: i === 0 ? ["HEAD", "main"] : [], + author, + email: "author@example.com", + timeMs: Date.UTC(2026, 10, 15 - i, 10 + i, 30), + summary, + message: summary, + })); + const handlers = window.__ipc.handlers; + handlers.vcs_log = ({ query }) => { + const { skip, limit, range } = query as { skip: number; limit: number; range?: string }; + return range ? [] : commits.slice(skip, limit ? skip + limit : undefined); + }; + handlers.vcs_log_refs = () => ({}); + handlers.vcs_log_users = () => []; + handlers.vcs_branches = () => []; + handlers.vcs_branch_info = () => ({ head: "main", headCommit: id(0), ahead: 0, behind: 0 }); + handlers.vcs_config_get = () => null; + handlers.vcs_commit_files = () => []; + handlers.vcs_log_details_batch = ({ revisions }) => + (revisions as string[]).map(() => ({ message: "", containingBranches: [], signature: "N" })); + const vcsModule = "/src/features/vcs/store.ts"; + const contextModule = "/src/platform/context.ts"; + const actionsModule = "/src/platform/actions.ts"; + const { useVcs } = await import(/* @vite-ignore */ vcsModule); + const { setContext } = await import(/* @vite-ignore */ contextModule); + const { executeAction } = await import(/* @vite-ignore */ actionsModule); + useVcs.setState({ available: true, root, repo: root, roots: [root], branchesLoaded: true }); + setContext("vcsAvailable", true); + await executeAction("vcs.showLog"); + }, + { mergeSubject, firstSubject, secondSubject, rootSubject }, + ); + + const log = page.getByRole("listbox", { name: "Commits", exact: true }); + const merge = log.getByRole("option", { name: new RegExp(mergeSubject) }); + await merge.click(); + await log.press("ArrowRight"); + const chooser = page.getByRole("dialog", { name: "Select Parent Commit", exact: true }); + const options = chooser.getByRole("option"); + const filter = chooser.getByRole("combobox", { name: "Search commits" }); + await expect(filter).toBeFocused(); + await expect(options).toHaveCount(2); + const before = (await chooser.boundingBox())!; + expect(before.height).toBeLessThan(200); + const first = options.filter({ hasText: firstSubject }); + const subject = first.getByText(firstSubject, { exact: true }); + const author = first.getByText("Priya Kapoor", { exact: true }); + const hash = first.getByText("22222222", { exact: true }); + await expect(subject).toHaveCSS("font-size", "13px"); + await expect(author).toHaveCSS("font-size", "12px"); + expect((await subject.boundingBox())!.y).toBeLessThan((await hash.boundingBox())!.y); + await expect(subject.locator("..")).toHaveAttribute("title", /Priya Kapoor/); + + await page.setViewportSize({ width: 440, height: 520 }); + const narrow = (await chooser.boundingBox())!; + expect(narrow.x + narrow.width).toBeLessThanOrEqual(440); + expect(await chooser.evaluate((node) => node.scrollWidth - node.clientWidth)).toBeLessThanOrEqual(1); + await filter.fill("No such change"); + await expect(chooser.getByText("No commits", { exact: true })).toBeVisible(); + await filter.press("Enter"); + await expect(chooser).toBeVisible(); + await filter.fill("Morgan Olsen"); + await expect(options).toHaveCount(1); + await expect(options.first()).toContainText(secondSubject); + await filter.fill(""); + await expect(options).toHaveCount(2); + await filter.press("ArrowDown"); + await expect(options.filter({ hasText: secondSubject })).toHaveAttribute("aria-selected", "true"); + await filter.press("Enter"); + await expect(chooser).toBeHidden(); + await expect(log.getByRole("option", { name: new RegExp(secondSubject) })).toHaveAttribute("aria-selected", "true"); + + await log.getByRole("option", { name: new RegExp(rootSubject) }).click(); + await log.press("ArrowLeft"); + const children = page.getByRole("dialog", { name: "Select Child Commit", exact: true }); + await expect(children.getByRole("option")).toHaveCount(2); + await children.getByRole("option", { name: new RegExp(firstSubject) }).click(); + await expect(children).toBeHidden(); + await expect(log.getByRole("option", { name: new RegExp(firstSubject) })).toHaveAttribute("aria-selected", "true"); +}); diff --git a/e2e/imageViewerLayout.spec.ts b/e2e/imageViewerLayout.spec.ts new file mode 100644 index 000000000..b2f069a1e --- /dev/null +++ b/e2e/imageViewerLayout.spec.ts @@ -0,0 +1,48 @@ +import { expect, stubDesktop, test } from "./fixtures"; + +test("image controls and metadata stay readable in a narrow editor", async ({ workbench: page }) => { + await page.setViewportSize({ width: 1080, height: 700 }); + await stubDesktop(page); + await page.evaluate(async () => { + const path = "/dev/acme-api/status.svg"; + const image = + ''; + window.__ipc.handlers.fs_read_image = () => "data:image/svg+xml," + encodeURIComponent(image); + window.__ipc.handlers.fs_probe = () => ({ size: 4096, binary: false, tooLarge: false }); + const contributions = "/src/workbench/contributions.ts"; + const { editorService } = await import(/* @vite-ignore */ contributions); + await editorService().openFile(path); + }); + const toolbars = page.getByRole("toolbar", { name: "Image viewer", exact: true }); + const toolbar = toolbars.last(); + const zoomIn = toolbar.getByRole("button", { name: "Zoom In", exact: true }); + const actualSize = toolbar.getByRole("button", { name: "Actual Size", exact: true }); + const chessboard = toolbar.getByRole("button", { name: "Show Chessboard", exact: true }); + const showText = toolbar.getByRole("button", { name: "Open as Text", exact: true }); + const dimensions = toolbar.getByText(/128\s*×\s*96/); + await expect(page.getByRole("img", { name: "status.svg", exact: true })).toBeVisible(); + await expect(dimensions).toBeVisible(); + const wideHeight = (await toolbar.boundingBox())!.height; + + await page.getByRole("button", { name: "Split Right", exact: true }).click(); + await expect(toolbars).toHaveCount(2); + await page.setViewportSize({ width: 640, height: 570 }); + expect(await dimensions.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0); + expect((await toolbar.boundingBox())!.height).toBeGreaterThan(wideHeight); + expect((await dimensions.boundingBox())!.y).toBeGreaterThan((await zoomIn.boundingBox())!.y); + await expect(dimensions).toHaveCSS("font-size", "13px"); + await expect(showText).toHaveCSS("white-space", "nowrap"); + for (const item of [zoomIn, actualSize, chessboard, showText, dimensions]) { + await expect(item).toBeInViewport({ ratio: 1 }); + } + await expect(toolbar.getByText("4.0 KB", { exact: true })).toBeVisible(); + + await zoomIn.click(); + await expect(toolbar.getByText("125%", { exact: true })).toBeVisible(); + await actualSize.click(); + await expect(toolbar.getByText("100%", { exact: true })).toBeVisible(); + await chessboard.click(); + await expect(chessboard).toHaveAttribute("aria-pressed", "false"); + await showText.click(); + await expect(page.locator(".cm-content")).toBeVisible(); +}); diff --git a/e2e/newBranch.spec.ts b/e2e/newBranch.spec.ts index 6bcfa0ebc..ba70049f9 100644 --- a/e2e/newBranch.spec.ts +++ b/e2e/newBranch.spec.ts @@ -11,7 +11,7 @@ async function openNewBranchDialog( page: Page, from?: string, mergeBase = "1111111", - blocked = false, + blocked: boolean | string = false, withPrefix = false, ) { await stubDesktop(page); @@ -43,7 +43,10 @@ async function openNewBranchDialog( ]; h.vcs_create_branch = ({ options }) => blocked && (options as { mode?: string } | null)?.mode === "normal" - ? { checkout: { kind: "localChanges", files: ["dirty.txt"] }, created: null } + ? { + checkout: { kind: "localChanges", files: [typeof blocked === "string" ? blocked : "dirty.txt"] }, + created: null, + } : { checkout: { kind: "done" }, created: { tip: "2222222", previousTip: null } }; h.vcs_merge_base = () => mergeBase; const vcsModule = "/src/features/vcs/store.ts"; @@ -151,6 +154,36 @@ for (const [button, mode] of [ }); } +test("local changes review keeps file names and checkout choices visible", async ({ workbench: page }) => { + await page.setViewportSize({ width: 1040, height: 740 }); + const folder = "services/international-payments/regional-settlement/weekly-close/adjustments"; + const path = `${folder}/ReceiptPolicy.ts`; + const { dialog, input } = await openNewBranchDialog(page, "2".repeat(40), "1111111", path); + await input.fill("topic"); + await dialog.getByRole("button", { name: "Create", exact: true }).click(); + const review = page.getByRole("dialog", { name: "Git Checkout Problem" }); + const force = review.getByRole("button", { name: "Force Checkout", exact: true }); + const smart = review.getByRole("button", { name: "Smart Checkout", exact: true }); + const cancel = review.getByRole("button", { name: "Don't Checkout", exact: true }); + await expect(force).toBeVisible(); + expect((await force.boundingBox())!.x - (await review.boundingBox())!.x).toBeLessThan(24); + + await page.setViewportSize({ width: 420, height: 480 }); + const tree = review.getByRole("tree", { name: "Changed files" }); + const row = tree.getByRole("treeitem", { name: `ReceiptPolicy.ts ${folder}`, exact: true }); + await expect(row.getByTitle(path, { exact: true })).toBeVisible(); + const file = row.getByText("ReceiptPolicy.ts", { exact: true }); + await expect(file).toBeInViewport({ ratio: 1 }); + expect(await file.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); + await expect(row.getByText(folder, { exact: true })).toHaveCSS("font-size", "12px"); + const restoreHint = review.getByText(/Smart Checkout .* your changes and restores them/); + expect((await restoreHint.boundingBox())!.y).toBeLessThan((await tree.boundingBox())!.y); + for (const button of [force, smart, cancel]) await expect(button).toBeInViewport({ ratio: 1 }); + await cancel.click(); + await expect(review).toBeHidden(); + expect(await ipcCalls(page, "vcs_create_branch")).toHaveLength(1); +}); + test("pasted text has its spaces replaced", async ({ workbench: page }) => { const { dialog, input } = await openNewBranchDialog(page); await input.fill(""); diff --git a/e2e/notificationBalloonLayout.spec.ts b/e2e/notificationBalloonLayout.spec.ts new file mode 100644 index 000000000..b62858080 --- /dev/null +++ b/e2e/notificationBalloonLayout.spec.ts @@ -0,0 +1,34 @@ +import { expect, test } from "./fixtures"; + +test("fits notification body and actions below the dismiss button in a narrow window", async ({ workbench: page }) => { + await page.setViewportSize({ width: 420, height: 540 }); + const title = "Validation failed for the catalog service"; + const body = "The build stopped while checking the catalog response type."; + const action = "recheckCatalogServiceResponsePayloadAfterRegeneratingTypesForDevelopment"; + await page.evaluate( + async ({ title, body, action }) => { + const servicePath = "/src/workbench/contributions.ts"; + const { notifications } = await import(/* @vite-ignore */ servicePath); + notifications().notify({ + level: "error", + title, + body, + actions: [{ label: action, run: () => document.body.setAttribute("data-validation-retried", "true") }], + }); + }, + { title, body, action }, + ); + + const balloon = page.getByRole("alert").filter({ hasText: title }); + const message = balloon.getByText(body, { exact: true }); + const dismiss = balloon.getByRole("button", { name: "Dismiss", exact: true }); + const retry = balloon.getByRole("button", { name: action, exact: true }); + await expect(balloon).toBeInViewport({ ratio: 1 }); + const [messageBox, dismissBox] = await Promise.all([message.boundingBox(), dismiss.boundingBox()]); + expect(messageBox!.y).toBeGreaterThanOrEqual(dismissBox!.y + dismissBox!.height); + expect(messageBox!.x + messageBox!.width).toBeGreaterThanOrEqual(dismissBox!.x + dismissBox!.width - 1); + expect(await retry.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); + await retry.click(); + await expect(page.locator("body")).toHaveAttribute("data-validation-retried", "true"); + await expect(balloon).toBeHidden(); +}); diff --git a/e2e/quickEvaluateLayout.spec.ts b/e2e/quickEvaluateLayout.spec.ts index ec18d0e0a..cc3ad0fb1 100644 --- a/e2e/quickEvaluateLayout.spec.ts +++ b/e2e/quickEvaluateLayout.spec.ts @@ -1,9 +1,7 @@ import type { EditorView } from "@codemirror/view"; import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; -test("Quick Evaluate opens an object tree that fits the editor and returns focus on Escape", async ({ - workbench: page, -}) => { +test("Quick Evaluate and hover keep value previews usable in a narrow editor", async ({ workbench: page }) => { await page.setViewportSize({ width: 445, height: 500 }); await stubDesktop(page); await page.evaluate(async () => { @@ -19,7 +17,9 @@ test("Quick Evaluate opens an object tree that fits the editor and returns focus h.fs_probe = () => ({ size: 48, binary: false, tooLarge: false }); h.fs_read_text = () => "summary = {}\nsubtotal = 42\n"; h.debug_evaluate_in = ({ expression }) => - expression === "summary" ? value("summary", "{...}", "dict", 101) : value("subtotal", "42", "int"); + expression === "summary" + ? value("summary", `{'audit': '${"Regional settlement totals ".repeat(8)}'}`, "dict", 101) + : value("subtotal", "42", "int"); h.debug_variables = ({ reference }) => reference === 101 ? [value("audit", "{...}", "dict", 102), value("total", "47.74", "float")] @@ -81,8 +81,59 @@ test("Quick Evaluate opens an object tree that fits the editor and returns focus await evaluate(2); await expect(hint.getByRole("tree")).toHaveCount(0); await expect(hint).toHaveText(/subtotal\s*=\s*42/); - expect(await ipcCalls(page, "debug_evaluate_in")).toEqual([ + const scalar = hint.locator("[class*='_valueTooltip_']"); + const uiFont = await page.locator("body").evaluate((el) => getComputedStyle(el).fontFamily); + await expect(scalar).toHaveCSS("font-family", uiFont); + await expect(scalar).toHaveCSS("font-size", "13px"); + await expect(scalar).toHaveCSS("font-weight", "700"); + await expect(scalar.locator(".cm-openidea-icon")).toHaveCount(1); + await content.press("Escape"); + await expect(hint).toBeHidden(); + + await page.setViewportSize({ width: 620, height: 480 }); + await page.evaluate(async () => { + const layoutModule = "/src/workbench/toolwindows/store.ts"; + const servicesModule = "/src/workbench/contributions.ts"; + const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule); + const { toolWindowService } = await import(/* @vite-ignore */ servicesModule); + moveToolWindow("project", "left"); + setToolWindowSize("left", 220); + toolWindowService().show("project", false); + }); + await expect.poll(async () => (await editor.boundingBox())!.x).toBeGreaterThan(160); + const position = await content.evaluate((el) => { + const { view } = (el as HTMLElement & { cmTile: { view: EditorView } }).cmTile; + return view.coordsAtPos(view.state.doc.line(1).from + 2); + }); + await page.mouse.move(position!.left, (position!.top + position!.bottom) / 2); + const hover = page.locator(".cm-tooltip-hover").locator("[class*='_valueTooltip_']"); + const expand = hover.getByRole("button", { name: "Expand value" }); + await expect(hover).toContainText("Regional settlement totals"); + await expect(hover).toHaveCSS("font-family", uiFont); + const summary = hover.locator("[class*='_valueText_']"); + const textBox = (await summary.boundingBox())!; + const controlBox = (await expand.boundingBox())!; + const iconBox = (await hover.locator(".cm-openidea-icon").boundingBox())!; + expect(textBox.height).toBeGreaterThan(20); + expect(Math.abs(controlBox.y - iconBox.y)).toBeLessThan(1); + expect(textBox.x).toBeGreaterThanOrEqual(iconBox.x + iconBox.width); + const fitsEditor = async () => { + const tooltip = await hover.boundingBox(); + const pane = (await editor.boundingBox())!; + return !!tooltip && tooltip.x >= pane.x - 1 && tooltip.x + tooltip.width <= pane.x + pane.width + 1; + }; + await expect.poll(fitsEditor).toBe(true); + await page.setViewportSize({ width: 555, height: 480 }); + await expect.poll(fitsEditor).toBe(true); + await expand.click(); + const pinned = hint.getByRole("tree", { name: "summary" }); + await expect(pinned).toBeFocused(); + await pinned.press("Escape"); + await expect(content).toBeFocused(); + const calls = await ipcCalls(page, "debug_evaluate_in"); + expect(calls.filter((call) => call.context === "watch")).toEqual([ { session: 91, frameId: 11, expression: "summary", context: "watch" }, { session: 91, frameId: 11, expression: "subtotal", context: "watch" }, ]); + expect(calls).toContainEqual({ session: 91, frameId: 11, expression: "summary", context: "hover" }); }); diff --git a/e2e/replaceAllConfirmationLayout.spec.ts b/e2e/replaceAllConfirmationLayout.spec.ts new file mode 100644 index 000000000..c5b5c0224 --- /dev/null +++ b/e2e/replaceAllConfirmationLayout.spec.ts @@ -0,0 +1,75 @@ +import type { SearchQuery } from "../src/bindings"; +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; + +test("Replace All keeps both values readable and the actions visible", async ({ workbench: page }) => { + const pattern = `LEGACY_${"MONTH_END_RECONCILIATION_INPUT_".repeat(15)}END`; + const replacement = `ACTIVE_${"MONTH_END_RECONCILIATION_OUTPUT_".repeat(18)}END`; + await page.emulateMedia({ reducedMotion: "reduce" }); + await page.setViewportSize({ width: 1040, height: 700 }); + await stubDesktop(page); + await page.evaluate((pattern) => { + window.__ipc.handlers.search_validate = () => null; + window.__ipc.handlers.search_start = ({ query, onEvent }) => { + if ((query as SearchQuery).pattern !== pattern) return null; + setTimeout(() => { + for (const relPath of ["invoice.txt", "receipt.txt"]) { + window.__ipc.send(onEvent, { + type: "file", + file: { + path: `/dev/acme-api/${relPath}`, + relPath, + matches: [{ line: 0, text: pattern, ranges: [[0, pattern.length]], textOffset: 0 }], + }, + }); + } + window.__ipc.send(onEvent, { + type: "done", + summary: { files: 2, matches: 2, limitHit: false, cancelled: false, elapsedMs: 1 }, + }); + }, 20); + return null; + }; + }, pattern); + await page.keyboard.press("Meta+Shift+r"); + const popup = page.getByRole("dialog", { name: "Replace in Files", exact: true }); + await popup.getByRole("textbox", { name: "Text to find", exact: true }).fill(pattern); + const replacementInput = popup.getByRole("textbox", { name: "Replace with", exact: true }); + await replacementInput.fill(replacement); + await expect(popup.getByRole("listbox", { name: "Matches" }).getByRole("option")).toHaveCount(2); + await page.setViewportSize({ width: 440, height: 520 }); + await popup.getByRole("button", { name: "Replace All", exact: true }).click(); + + const dialog = page.getByRole("dialog", { name: "Replace All", exact: true }); + const findText = dialog.getByRole("region", { name: "Text to find", exact: true }); + const replaceText = dialog.getByRole("region", { name: "Replace with", exact: true }); + const replace = dialog.getByRole("button", { name: "Replace", exact: true }); + const cancel = dialog.getByRole("button", { name: "Cancel", exact: true }); + await expect(findText).toHaveText(pattern); + await expect(replaceText).toHaveText(replacement); + await expect(dialog.getByText("Replace 2 occurrences in 2 files?", { exact: true })).toBeVisible(); + const bottom = (await replace.boundingBox())!.y; + for (const item of [findText, replaceText]) { + await expect(item).toHaveCSS("font-size", "13px"); + expect(await item.evaluate((el) => el.scrollHeight > el.clientHeight && el.scrollWidth === el.clientWidth)).toBe( + true, + ); + await item.focus(); + await page.keyboard.press("End"); + await expect.poll(() => item.evaluate((el) => el.scrollTop)).toBeGreaterThan(0); + } + expect((await replace.boundingBox())!.y).toBeCloseTo(bottom, 0); + await expect(replace).toBeInViewport({ ratio: 1 }); + await expect(cancel).toBeInViewport({ ratio: 1 }); + await cancel.click(); + await expect(dialog).toBeHidden(); + + await page.setViewportSize({ width: 1040, height: 700 }); + await replacementInput.fill(""); + await popup.getByRole("button", { name: "Open in Find Window", exact: true }).click(); + const findWindow = page.getByRole("region", { name: "Find", exact: true }); + await findWindow.getByRole("button", { name: "Replace All", exact: true }).click(); + await expect(findText).toHaveText(pattern); + await expect(replaceText).toHaveText("Empty text"); + await cancel.click(); + expect(await ipcCalls(page, "replace_in_files")).toHaveLength(0); +}); diff --git a/e2e/run.spec.ts b/e2e/run.spec.ts index 0861c7b95..4ce9d8aec 100644 --- a/e2e/run.spec.ts +++ b/e2e/run.spec.ts @@ -581,3 +581,54 @@ test("CMake builds the selected target in Build before starting only the applica await expect(run.getByRole("tab", { name: "hello [Release, release]" })).toBeVisible(); await expect(run.getByText("COMPILER_OUTPUT", { exact: true })).toHaveCount(0); }); + +test("test report export separates the format and destination in a narrow window", async ({ workbench: page }) => { + await page.setViewportSize({ width: 410, height: 500 }); + await stubRun( + page, + [ + { + kind: "stdout", + text: '{"Package":"example.com/checkout","Action":"pass","Test":"TestReceipt","Elapsed":0.1}\n', + }, + ], + 0, + { id: "go:report-tests", name: "Checkout tests", kind: "go", command: "go", args: ["test", "-json"], isTest: true }, + ); + await page.evaluate(() => { + window.__ipc.handlers.fs_entry_kind = () => { + throw { kind: "NotFound", message: "Not found" }; + }; + window.__ipc.handlers.fs_create_file_bytes = () => null; + }); + + await page.keyboard.press("Control+r"); + const results = page.getByRole("toolbar", { name: "Test results" }); + await results.getByRole("button", { name: "More Actions" }).click(); + const exportItem = page.getByRole("menuitem", { name: "Export Test Results…" }); + await expect(exportItem).toBeEnabled(); + await exportItem.click(); + + const dialog = page.getByRole("dialog", { name: "Export Test Results" }); + const html = dialog.getByRole("radio", { name: "HTML", exact: true }); + const xml = dialog.getByRole("radio", { name: "XML", exact: true }); + await expect(html).toBeVisible(); + expect((await xml.boundingBox())!.y).toBeGreaterThan((await html.boundingBox())!.y); + const file = dialog.getByLabel("File name", { exact: true }); + const folder = dialog.getByLabel("Folder", { exact: true }); + const browse = dialog.getByRole("button", { name: "Browse…" }); + await expect(file).toBeFocused(); + await expect(file).toHaveValue("Test Results - Checkout tests.html"); + await expect(folder).toHaveValue("/dev/acme-api"); + await expect(browse).toBeInViewport({ ratio: 1 }); + expect((await folder.boundingBox())!.width).toBeGreaterThan(180); + await file.fill("receipts.html"); + await folder.fill("reports"); + await xml.check(); + await expect(file).toHaveValue("receipts.xml"); + await expect(dialog.getByRole("checkbox", { name: "Open exported file in browser" })).toBeDisabled(); + await dialog.getByRole("button", { name: "OK", exact: true }).click(); + await expect(dialog).toBeHidden(); + const [write] = await ipcCalls(page, "fs_create_file_bytes"); + expect(write).toMatchObject({ path: "/dev/acme-api/reports/receipts.xml" }); +}); diff --git a/e2e/runConfigLayout.spec.ts b/e2e/runConfigLayout.spec.ts index 0f050c956..4d3c6fab0 100644 --- a/e2e/runConfigLayout.spec.ts +++ b/e2e/runConfigLayout.spec.ts @@ -1,4 +1,5 @@ import type { Page } from "@playwright/test"; +import type { BeforeLaunchTask } from "../src/bindings"; import { expect, test } from "./fixtures"; test("expands VM options beside the field and returns edited text to the configuration", async ({ @@ -64,39 +65,81 @@ test("expands VM options beside the field and returns edited text to the configu await expect(field).toHaveValue(original + "\n-Ddemo.mode=local"); }); -async function openConfigurations(page: Page, target?: string) { - await page.evaluate(async (target) => { - const path = "/src/features/run/store.ts"; - const { useRun } = await import(/* @vite-ignore */ path); - const base = { - kind: "shell", - command: "/Users/developer/projects/acme/services/payments/scripts/start-development-server", - args: ["--watch"], - cwd: "/Users/developer/projects/acme/services/payments", - env: { NODE_ENV: "development" }, - detected: false, - isTest: false, - debugAdapter: null, - }; - useRun.setState({ - configs: [ - { - ...base, - id: "layout:app", - name: "Payments development server", - target, - beforeLaunch: [{ kind: "run", target: "layout:prepare" }], - }, - { ...base, id: "layout:prepare", name: "Prepare generated sources for the payments development server" }, - ], - selectedId: "layout:app", - loaded: true, - editorOpen: true, - }); - }, target); +async function openConfigurations(page: Page, target?: string, beforeLaunch?: BeforeLaunchTask[]) { + await page.evaluate( + async ({ target, beforeLaunch }) => { + const path = "/src/features/run/store.ts"; + const { useRun } = await import(/* @vite-ignore */ path); + const base = { + kind: "shell", + command: "/Users/developer/projects/acme/services/payments/scripts/start-development-server", + args: ["--watch"], + cwd: "/Users/developer/projects/acme/services/payments", + env: { NODE_ENV: "development" }, + detected: false, + isTest: false, + debugAdapter: null, + }; + useRun.setState({ + configs: [ + { + ...base, + id: "layout:app", + name: "Payments development server", + target, + beforeLaunch: beforeLaunch ?? [{ kind: "run", target: "layout:prepare" }], + }, + { ...base, id: "layout:prepare", name: "Prepare generated sources for the payments development server" }, + ], + selectedId: "layout:app", + loaded: true, + editorOpen: true, + }); + }, + { target, beforeLaunch }, + ); await expect(page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true })).toBeVisible(); } +test("before-launch tasks wrap as ordered tags and keep their edit controls", async ({ workbench: page }) => { + await page.setViewportSize({ width: 1150, height: 820 }); + await openConfigurations(page, undefined, [ + { kind: "build" }, + { kind: "buildArtifacts" }, + { kind: "command", target: "make generate" }, + ]); + const dialog = page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true }); + const tasks = dialog.getByRole("list", { name: "Before launch tasks", exact: true }); + const build = tasks.getByRole("button", { name: "1. Build Project", exact: true }); + const artifacts = tasks.getByRole("button", { name: "2. Build Artifacts", exact: true }); + await tasks.scrollIntoViewIfNeeded(); + await expect(build).toBeVisible(); + expect((await build.boundingBox())!.y).toBeCloseTo((await artifacts.boundingBox())!.y, 0); + await expect(build).toHaveCSS("font-size", "13px"); + + await page.setViewportSize({ width: 520, height: 820 }); + await expect.poll(() => tasks.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); + const command = tasks.getByRole("textbox", { name: "Before launch command 3" }); + expect((await command.boundingBox())!.y).toBeGreaterThan((await build.boundingBox())!.y + 20); + await command.fill("make report"); + + await build.press("Enter"); + const actions = page.getByRole("menu", { name: "Task Actions", exact: true }); + const moveDown = actions.getByRole("menuitem", { name: "Move Down", exact: true }); + await expect(moveDown).toBeVisible(); + await moveDown.click(); + await expect(tasks.getByRole("button", { name: "1. Build Artifacts", exact: true })).toBeVisible(); + const moved = tasks.getByRole("listitem").filter({ + has: page.getByRole("button", { name: "2. Build Project", exact: true }), + }); + await moved.getByRole("button", { name: "Remove Task" }).click(); + await expect(tasks.getByRole("textbox", { name: "Before launch command 2" })).toHaveValue("make report"); + + await tasks.getByRole("button", { name: "Add task", exact: true }).click(); + await page.getByRole("menuitem", { name: "Build Project", exact: true }).click(); + await expect(tasks.getByRole("button", { name: "3. Build Project", exact: true })).toBeVisible(); +}); + test("long run target names leave room for configuration names in the sidebar", async ({ workbench: page }) => { const target = "payments-development-shared-staging-runner-west"; await openConfigurations(page, target); @@ -118,6 +161,32 @@ test("long run target names leave room for configuration names in the sidebar", await expect(dialog.getByRole("textbox", { name: "Name", exact: true })).toHaveValue("Payments development server"); }); +test("the configuration type list scrolls below its search field in a short window", async ({ workbench: page }) => { + await page.setViewportSize({ width: 780, height: 370 }); + await openConfigurations(page); + const dialog = page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true }); + await dialog.getByRole("button", { name: "Add New Configuration", exact: true }).click(); + const chooser = page.getByRole("dialog", { name: "Add New Configuration", exact: true }); + const search = chooser.getByRole("textbox", { name: "Search configuration types" }); + const list = chooser.getByRole("listbox", { name: "Configuration types" }); + await expect(search).toBeFocused(); + expect(await chooser.evaluate((el) => el.scrollHeight - el.clientHeight)).toBeLessThanOrEqual(1); + expect(await list.evaluate((el) => el.scrollHeight - el.clientHeight)).toBeGreaterThan(0); + + await search.press("End"); + const active = list.getByRole("option", { selected: true }); + await expect(active).toBeInViewport({ ratio: 0.98 }); + expect(await list.evaluate((el) => el.scrollTop)).toBeGreaterThan(0); + await expect(active.locator("svg")).toHaveAttribute("width", "16"); + await expect(search).toBeInViewport({ ratio: 1 }); + + await search.fill("Tomcat"); + await expect(list.getByRole("option", { name: "Tomcat Server", selected: true })).toBeVisible(); + await search.press("Enter"); + await expect(chooser).toBeHidden(); + await expect(dialog.getByRole("tab", { name: "Server", exact: true })).toBeVisible(); +}); + test("run configuration sidebar resizes with mouse and keyboard and remembers the layout", async ({ workbench: page, }) => { diff --git a/e2e/runGutterMenuLayout.spec.ts b/e2e/runGutterMenuLayout.spec.ts new file mode 100644 index 000000000..3728f3c0d --- /dev/null +++ b/e2e/runGutterMenuLayout.spec.ts @@ -0,0 +1,63 @@ +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; + +const prefix = "reconcile-regional-inventory-and-rebuild-order-settlement-cache-for-warehouse-"; +const east = prefix + "east-stage"; +const west = prefix + "west-stage"; +const content = JSON.stringify( + { name: "warehouse-tools", scripts: { [east]: "node east.js", [west]: "node west.js", build: "node build.js" } }, + null, + 2, +); + +test("the npm gutter keeps distinct ends of long names and runs the selected script", async ({ workbench: page }) => { + await page.setViewportSize({ width: 440, height: 520 }); + await stubDesktop(page); + await page.evaluate(async (text) => { + const backendPath = "/src/editor/core/backend.ts"; + const servicePath = "/src/workbench/contributions.ts"; + const { docBackend } = await import(/* @vite-ignore */ backendPath); + const { editorService } = await import(/* @vite-ignore */ servicePath); + const path = "/dev/acme-api/package.json"; + docBackend().files.set(path, text); + const handlers = window.__ipc.handlers; + handlers.fs_probe = () => ({ size: text.length, binary: false, tooLarge: false }); + handlers.fs_read_text = ({ path }) => docBackend().files.get(String(path)) ?? ""; + handlers.fs_read_dir = () => []; + handlers.run_configs = () => []; + handlers.run_start = ({ config }) => ({ + id: 7, + configId: (config as { id: string }).id, + name: (config as { name: string }).name, + pid: 4242, + running: true, + pty: false, + }); + await editorService().openFile(path); + }, content); + const editor = page.locator(".cm-editor"); + const menu = page.getByRole("menu", { name: "Context menu" }); + for (const name of [east, west]) { + await editor.getByTitle("Run '" + name + "'", { exact: true }).click(); + const label = "Run 'npm run " + name + "'"; + const run = menu.getByRole("menuitem", { name: label, exact: true }); + const end = run.getByText(label.slice(-12), { exact: true }); + await expect(end).toBeVisible(); + await expect(end.locator("..")).toHaveAttribute("title", label); + expect(await end.evaluate((node) => node.clientWidth >= node.scrollWidth)).toBe(true); + const start = end.locator("..").locator(":scope > span").first(); + expect(await start.evaluate((node) => node.clientWidth < node.scrollWidth)).toBe(true); + await expect(start).toHaveCSS("text-overflow", "ellipsis"); + const titleUnderPointer = await start.evaluate((node) => { + const { x, y, width, height } = node.getBoundingClientRect(); + return document.elementFromPoint(x + width / 2, y + height / 2)?.getAttribute("title"); + }); + expect(titleUnderPointer).toBe(label); + await expect(run).toBeFocused(); + if (name === east) await run.press("Escape"); + else await run.press("Enter"); + await expect(menu).toBeHidden(); + } + await expect + .poll(async () => ipcCalls(page, "run_start")) + .toMatchObject([{ config: { args: ["run", west], kind: "npm" } }]); +}); diff --git a/e2e/searchEverywhereLayout.spec.ts b/e2e/searchEverywhereLayout.spec.ts index abc760a18..f75ceb75c 100644 --- a/e2e/searchEverywhereLayout.spec.ts +++ b/e2e/searchEverywhereLayout.spec.ts @@ -1,4 +1,64 @@ import { doubleShift, expect, stubDesktop, test } from "./fixtures"; + +test("Search Everywhere keeps line numbers visible beside long Text result filenames", async ({ workbench: page }) => { + const relPath = "config/InternationalSettlementReconciliationEndpointsForStagingEnvironments.ts"; + const query = "settlementEndpoint"; + const text = `const ${query} = "/staging/settlement";`; + await stubDesktop(page); + await page.evaluate( + ({ relPath, text, query }) => { + window.__ipc.handlers.search_start = (args) => { + setTimeout(() => { + const matches = [12344, 12345].map((line) => ({ + line, + text, + ranges: [[6, 6 + query.length]], + textOffset: 0, + })); + window.__ipc.send(args.onEvent, { + type: "file", + file: { path: `/dev/acme-api/${relPath}`, relPath, matches }, + }); + window.__ipc.send(args.onEvent, { + type: "done", + summary: { files: 1, matches: 2, limitHit: false, cancelled: false, elapsedMs: 4 }, + }); + }, 20); + return null; + }; + }, + { relPath, text, query }, + ); + + await doubleShift(page); + const dialog = page.getByRole("dialog", { name: "Search Everywhere" }); + await dialog.getByRole("tab", { name: "Text", exact: true }).click(); + const search = dialog.getByRole("combobox", { name: "Search query" }); + await search.fill(query); + const rows = dialog.getByRole("option"); + await expect(rows).toHaveCount(2); + for (const width of [920, 440]) { + await page.setViewportSize({ width, height: 640 }); + for (const line of [12345, 12346]) { + const row = rows.filter({ hasText: String(line) }); + await expect(row.locator("mark")).toHaveText(query); + expect( + await row.evaluate((el) => { + const location = el.lastElementChild!; + const lineText = location.lastChild!; + const range = document.createRange(); + range.selectNodeContents(lineText); + const bounds = range.getBoundingClientRect(); + const clip = location.getBoundingClientRect(); + return bounds.width > 0 && bounds.left >= clip.left && bounds.right <= clip.right + 1; + }), + ).toBe(true); + await expect(row.getByText(relPath.split("/").at(-1)!, { exact: true })).toHaveAttribute("title", relPath); + } + } + await search.press("ArrowDown"); + await expect(rows.nth(1)).toHaveAttribute("aria-selected", "true"); +}); import type { Page } from "@playwright/test"; test("action names stay readable beside shortcuts and categories", async ({ workbench: page }) => { diff --git a/e2e/searchPopupsNarrow.spec.ts b/e2e/searchPopupsNarrow.spec.ts index e869ecbad..7ac1c5ab6 100644 --- a/e2e/searchPopupsNarrow.spec.ts +++ b/e2e/searchPopupsNarrow.spec.ts @@ -15,7 +15,7 @@ async function run(page: Page, id: string) { }, id); } -async function stubFindMatches(page: Page) { +async function stubFindMatches(page: Page, firstPath = LONG_RESULT_PATH) { await stubDesktop(page); await page.evaluate((longPath) => { window.__ipc.handlers.search_validate = () => null; @@ -39,7 +39,7 @@ async function stubFindMatches(page: Page) { }, 20); return null; }; - }, LONG_RESULT_PATH); + }, firstPath); } async function expectControlsFit(page: Page) { @@ -205,3 +205,29 @@ test("Find in Files prioritizes the preview and remembers an adjusted split", as await expect(handle).toBeAttached(); await expect.poll(resultsShare).toBeCloseTo(adjusted, 2); }); + +test("Find in Files keeps the file and its parent folder visible in the preview caption", async ({ + workbench: page, +}) => { + await page.setViewportSize({ width: 400, height: 570 }); + const prefix = "config/generated/regional-integrations/sandbox/development/notifications"; + const name = "RegionalLedgerSettings.txt"; + const path = `${prefix}/runtime/${name}`; + await stubFindMatches(page, path); + await run(page, "find.inPath"); + const dialog = page.getByRole("dialog", { name: "Find in Files" }); + const search = dialog.getByPlaceholder("Search"); + await search.fill("http://localhost:8080"); + const preview = dialog.locator("[data-panel][id=preview]"); + const caption = preview.getByTitle(path, { exact: true }); + const folder = caption.getByText("/runtime", { exact: true }); + const beginning = caption.getByText(prefix, { exact: true }); + await expect(caption.getByText(name, { exact: true })).toBeInViewport({ ratio: 1 }); + await expect(folder).toBeInViewport({ ratio: 1 }); + await expect(folder).toHaveCSS("font-size", "13px"); + expect(await beginning.evaluate((el) => el.scrollWidth > el.clientWidth)).toBe(true); + expect(await folder.evaluate((el) => el.scrollWidth <= el.clientWidth)).toBe(true); + await search.press("ArrowDown"); + await search.press("ArrowDown"); + await expect(preview.getByTitle("config/endpoint-1.txt", { exact: true })).toContainText("endpoint-1.txt"); +}); diff --git a/e2e/searchScopesDialogLayout.spec.ts b/e2e/searchScopesDialogLayout.spec.ts new file mode 100644 index 000000000..9c93ad66c --- /dev/null +++ b/e2e/searchScopesDialogLayout.spec.ts @@ -0,0 +1,59 @@ +import { expect, test } from "./fixtures"; + +test("Find in Files keeps the scope list and pattern editor usable in a narrow window", async ({ workbench: page }) => { + await page.setViewportSize({ width: 1040, height: 700 }); + const longName = "Regional settlement reconciliation sources for month-end audit and publication"; + await page.evaluate(async (longName) => { + const search = "/src/platform/search.ts"; + const { saveCustomScopes } = await import(/* @vite-ignore */ search); + saveCustomScopes( + Array.from({ length: 26 }, (_, i) => ({ + name: i ? `Reconciliation scope ${i + 1}` : longName, + pattern: i ? `file:src/scope-${i + 1}//*` : "file:src/reconciliation//*", + })), + ); + }, longName); + await page.keyboard.press("Meta+Shift+F"); + const find = page.getByRole("dialog", { name: "Find in Files", exact: true }); + await find.getByRole("tab", { name: "Scope", exact: true }).click(); + const openScopes = find.getByRole("button", { name: "Edit Scopes…", exact: true }); + await openScopes.click(); + + const dialog = page.getByRole("dialog", { name: "Scopes", exact: true }); + const list = dialog.getByRole("list", { name: "Scopes", exact: true }); + const name = dialog.getByRole("textbox", { name: "Name:", exact: true }); + const pattern = dialog.getByRole("textbox", { name: "Pattern:", exact: true }); + await expect(pattern).toHaveValue("file:src/reconciliation//*"); + expect(await list.evaluate((el) => el.scrollHeight - el.clientHeight)).toBeGreaterThan(100); + await expect(list.getByRole("button", { name: longName })).toHaveAttribute("title", longName); + expect((await list.boundingBox())!.x).toBeLessThan((await name.boundingBox())!.x); + + await page.setViewportSize({ width: 460, height: 530 }); + const fields = (await pattern.boundingBox())!; + expect(fields.y).toBeGreaterThanOrEqual((await list.boundingBox())!.y + (await list.boundingBox())!.height); + expect(fields.width).toBeGreaterThan(250); + await list.evaluate((el) => (el.scrollTop = el.scrollHeight)); + expect((await pattern.boundingBox())!.y).toBeCloseTo(fields.y, 0); + const toolbar = dialog.getByRole("toolbar", { name: "Scopes actions" }); + const add = toolbar.getByRole("button", { name: "Add Scope", exact: true }); + const ok = dialog.getByRole("button", { name: "OK", exact: true }); + await expect(add).toBeInViewport({ ratio: 1 }); + await expect(ok).toBeInViewport({ ratio: 1 }); + + await name.fill("Unsaved selection"); + await dialog.getByRole("button", { name: "Cancel", exact: true }).click(); + await openScopes.click(); + await expect(name).toHaveValue(longName); + await add.click(); + const draft = list.getByRole("button", { name: "Unnamed", exact: true }); + await expect(draft).toHaveAttribute("aria-current", "true"); + await expect(draft).toBeInViewport({ ratio: 1 }); + await expect(ok).toBeDisabled(); + await name.fill("Release inputs"); + await pattern.fill("file:src/release//*"); + await ok.click(); + await expect(dialog).toBeHidden(); + await openScopes.click(); + await list.getByRole("button", { name: "Release inputs", exact: true }).click(); + await expect(pattern).toHaveValue("file:src/release//*"); +}); diff --git a/e2e/settingsNavigationLayout.spec.ts b/e2e/settingsNavigationLayout.spec.ts new file mode 100644 index 000000000..cf19bc3c6 --- /dev/null +++ b/e2e/settingsNavigationLayout.spec.ts @@ -0,0 +1,38 @@ +import { expect, test } from "./fixtures"; + +test("Settings aligns search results with their parent pages and honors smaller tree indents", async ({ + workbench: page, +}) => { + await page.keyboard.press("Meta+,"); + const dialog = page.getByRole("dialog", { name: "Settings", exact: true }); + const search = dialog.getByRole("textbox", { name: "Search settings" }); + const tree = dialog.getByRole("tree", { name: "Settings pages" }); + await search.fill("Language Defaults"); + + const editor = tree.getByRole("treeitem", { name: "Editor", exact: true }); + const scheme = tree.getByRole("treeitem", { name: "Color Scheme", exact: true }); + const defaults = tree.getByRole("treeitem", { name: "Language Defaults", exact: true }); + await expect(defaults).toHaveAttribute("aria-selected", "true"); + await expect(defaults.locator("mark")).toHaveText(["Language", "Defaults"]); + + const insets = () => + Promise.all( + [editor, scheme, defaults].map((row) => + row.locator(":scope > span:last-child").evaluate((label) => { + const left = label.closest('[role="tree"]')!.getBoundingClientRect().left; + return Math.round(label.getBoundingClientRect().left - left); + }), + ), + ); + await expect.poll(insets).toEqual([28, 44, 60]); + await page.setViewportSize({ width: 580, height: 720 }); + await expect.poll(insets).toEqual([28, 44, 60]); + await page.evaluate(() => document.documentElement.style.setProperty("--tree-indent", "12px")); + await expect.poll(insets).toEqual([28, 40, 52]); + + await search.press("ArrowUp"); + await expect(scheme).toHaveAttribute("aria-selected", "true"); + await search.press("ArrowUp"); + await expect(editor).toHaveAttribute("aria-selected", "true"); + await expect(search).toBeFocused(); +}); diff --git a/e2e/shortcutRecorderLayout.spec.ts b/e2e/shortcutRecorderLayout.spec.ts new file mode 100644 index 000000000..aaaffafd8 --- /dev/null +++ b/e2e/shortcutRecorderLayout.spec.ts @@ -0,0 +1,44 @@ +import { expect, test } from "./fixtures"; + +test("shortcut assignment fits the first stroke and conflict names in a narrow window", async ({ workbench: page }) => { + await page.setViewportSize({ width: 336, height: 540 }); + await page.keyboard.press("Meta+,"); + const settings = page.getByRole("dialog", { name: "Settings", exact: true }); + await settings.getByRole("treeitem", { name: "Keymap", exact: true }).click(); + await settings.getByRole("textbox", { name: "Search actions" }).fill("Find Action"); + const action = settings.getByRole("treeitem", { name: /Find Action/ }); + await action.click(); + await settings.getByRole("button", { name: "Add Keyboard Shortcut", exact: true }).click(); + + const dialog = page.getByRole("dialog", { name: "Keyboard Shortcut: Find Action…", exact: true }); + const first = dialog.getByRole("textbox", { name: "First stroke" }); + const body = dialog.locator("[data-dialog-body]"); + const titleBar = dialog.locator("[data-dialog-titlebar]"); + await expect(first).toBeFocused(); + await expect(titleBar).toHaveText("Keyboard Shortcut"); + await expect(body.getByText("Find Action…", { exact: true })).toBeVisible(); + const firstBounds = (await first.boundingBox())!; + const bodyBounds = (await body.boundingBox())!; + expect(firstBounds.width).toBeGreaterThan(bodyBounds.width - 32); + const conflicts = dialog.getByRole("list", { name: "Conflicts:" }); + await expect(conflicts).toHaveCount(0); + + await first.press("Meta+Alt+L"); + await expect(conflicts).toBeVisible(); + await expect(conflicts.getByRole("listitem").filter({ hasText: "Reformat Code" }).first()).toBeVisible(); + expect(await conflicts.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); + expect( + await conflicts + .getByRole("listitem") + .evaluateAll((rows) => rows.every((row) => row.scrollHeight <= row.clientHeight)), + ).toBe(true); + expect(await body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1); + + const ok = dialog.getByRole("button", { name: "OK", exact: true }); + await ok.click(); + const confirmation = page.getByRole("dialog", { name: "Warning", exact: true }); + await expect(confirmation.getByRole("list").getByText("Reformat Code", { exact: true })).toHaveCount(2); + await confirmation.getByRole("button", { name: "Leave", exact: true }).click(); + await expect(dialog).toBeHidden(); + await expect(action.locator("kbd").filter({ hasText: "⌥⌘L" })).toHaveCount(1); +}); diff --git a/e2e/stagedEditor.spec.ts b/e2e/stagedEditor.spec.ts index ff8a1691c..fff7452c5 100644 --- a/e2e/stagedEditor.spec.ts +++ b/e2e/stagedEditor.spec.ts @@ -102,6 +102,9 @@ test("edits the staged version and keeps an unsaved draft when the index changes await expect(headPane).toContainText("val committed = 0"); await expect(indexPane).toContainText("val external = 3"); await expect(localPane).not.toBeEmpty(); + const indexHeading = page.getByTitle(`Staged (index) ${path}`, { exact: true }); + await expect(indexHeading.getByText("build.gradle.kts", { exact: true })).toBeVisible(); + await expect(indexHeading.getByText("Staged (index)", { exact: true })).toBeVisible(); const working = await localPane.textContent(); await page.getByRole("button", { name: "Unstage Change", exact: true }).click(); diff --git a/e2e/terminal-ui.spec.ts b/e2e/terminal-ui.spec.ts index 88ca6488c..c52cdbd63 100644 --- a/e2e/terminal-ui.spec.ts +++ b/e2e/terminal-ui.spec.ts @@ -71,7 +71,15 @@ for (const { width, split } of [{ width: 220 }, { width: 280 }, { width: 520 }, const search = terminal.getByRole("search", { name: "Find in terminal" }); const input = search.getByRole("textbox", { name: "Find in terminal" }); await input.fill("alpha"); - await expect(search.locator("[aria-live=polite]")).toHaveText(/\d+\/3/); + const count = search.locator("[aria-live=polite]"); + await expect(count).toHaveText(/\d+\/3/); + await expect(count).toHaveCSS("font-size", "13px"); + const match = await count.textContent(); + // The incremental search can report after the first Enter; retry until Enter moves on. + await expect(async () => { + await input.press("Enter"); + await expect(count).not.toHaveText(match!, { timeout: 1000 }); + }).toPass(); if (process.env.OPENIDEA_TERMINAL_SHOTS) await terminal.screenshot({ path: `${process.env.OPENIDEA_TERMINAL_SHOTS}/terminal-${width}${split ? "-split" : ""}.png`, @@ -83,9 +91,19 @@ for (const { width, split } of [{ width: 220 }, { width: 280 }, { width: 520 }, expect(rect.x).toBeGreaterThanOrEqual(bounds.x); expect(rect.x + rect.width).toBeLessThanOrEqual(bounds.x + bounds.width + 1); } - expect((await input.boundingBox())!.width).toBeGreaterThan(40); - const matchCase = search.getByRole("button", { name: "Match Case", exact: true }); + const inputBox = (await input.boundingBox())!; + if (width <= 280 || split) { + expect(inputBox.width).toBeGreaterThan(bounds.width * 0.62); + expect((await matchCase.boundingBox())!.y).toBeGreaterThan(inputBox.y + inputBox.height); + } else { + expect(inputBox.width).toBeGreaterThan(80); + } + const countBox = (await count.boundingBox())!; + const previousBox = (await search.getByRole("button", { name: "Previous Occurrence", exact: true }).boundingBox())!; + expect(previousBox.x - countBox.x - countBox.width).toBeLessThanOrEqual(4); + expect(countBox.y + countBox.height / 2).toBeCloseTo(previousBox.y + previousBox.height / 2, 0); + await matchCase.focus(); await page.keyboard.press("Enter"); await expect(matchCase).toHaveAttribute("aria-pressed", "true"); @@ -130,7 +148,7 @@ test("wide terminal search leaves the grid in place and avoids covering the acti const top = (await search.boundingBox())!; expect(top.y).toBeCloseTo(before.y, 0); expect(top.x + top.width).toBeCloseTo(before.x + before.width, 0); - expect(top.width).toBeLessThan(before.width); + expect(top.width).toBeLessThan(420); await input.fill("right-edge"); await expect(search.locator("[aria-live=polite]")).toHaveText("1/1"); diff --git a/src/editor/core/view/FindBar.tsx b/src/editor/core/view/FindBar.tsx index ca1efc7bc..9717ca317 100644 --- a/src/editor/core/view/FindBar.tsx +++ b/src/editor/core/view/FindBar.tsx @@ -8,12 +8,13 @@ * Exclude with Preserve Case, Esc closes. `FindPanel` is the bar itself, for * any CodeMirror view (the diff viewer's sides); `FindBar` is it on an editor pane. */ +import { SearchHistoryMenu } from "@/ui/SearchHistoryMenu"; import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react"; import { create } from "zustand"; import clsx from "clsx"; import type { EditorView } from "@codemirror/view"; import { Button, IconButton, Menu, SearchField, T, type MenuItem } from "@/ui"; -import { SEARCH_CONTEXTS, rememberSearch, searchHistory } from "@/platform/search"; +import { SEARCH_CONTEXTS, rememberSearch } from "@/platform/search"; import { editorController, useFindBars, useTabs } from "../controller"; import { countMatches, @@ -557,19 +558,6 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo ? "0 results" : `${count.current || "?"}/${count.total}${count.capped ? "+" : ""}`; - const historyItems = (kind: "find" | "replace"): MenuItem[] => { - const h = searchHistory(kind); - return h.length - ? [ - { kind: "header", label: kind === "find" ? "Recent Searches" : "Recent Replacements" }, - ...h.map((q) => ({ - label: q.replace(/\n/g, "⏎"), - verbatim: true, - run: () => setOpts(kind === "find" ? { search: q } : { replace: q }), - })), - ] - : [{ label: kind === "find" ? "No recent searches" : "No recent replacements", disabled: true }]; - }; const filterItems: MenuItem[] = [ { label: "Search In Selection", @@ -765,12 +753,10 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo )} - setOpts(historyMenu === "replace" ? { replace: value } : { search: value })} onClose={() => setHistoryMenu(null)} /> span, .cm-lsp-completion-sort": { + minWidth: "0", + overflow: "hidden", + textOverflow: "ellipsis", + whiteSpace: "nowrap", + }, ".cm-lsp-completion-sort": { - flex: "none", - maxWidth: "100%", padding: "0", border: "none", background: "none", @@ -490,7 +496,14 @@ export const lspTheme = EditorView.theme({ '.cm-lsp-inplace-suggestions button[aria-current="true"]': { backgroundColor: "var(--bg-list-selected, var(--bg-tree-selected, var(--bg-selected-strong)))", }, - ".cm-lsp-inplace-footer": { overflowWrap: "anywhere" }, + ".cm-lsp-inplace-footer": { + display: "flex", + flexWrap: "wrap", + padding: "5px 12px", + gap: "var(--space-1) var(--space-3)", + justifyContent: "space-between", + overflowWrap: "anywhere", + }, // --- floating lightbulb (intentions.ts) ----------------------------------- ".cm-lsp-bulb": { diff --git a/src/features/build/Build.module.css b/src/features/build/Build.module.css index 9cb036ae7..1165dbbc6 100644 --- a/src/features/build/Build.module.css +++ b/src/features/build/Build.module.css @@ -30,6 +30,16 @@ .strong { color: var(--fg-strong); } +.strong, +.rootDetail, +.directory { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; +} +.row > svg { + flex: none; +} .selected { color: var(--fg-strong); } @@ -37,6 +47,26 @@ flex: none; color: var(--fg-subtle); } +.rootDetail { + max-width: 50%; +} +.fileLabel { + display: flex; + min-width: 0; + gap: var(--space-1-5); +} +.fileName { + flex: none; + max-width: 100%; +} +.muted.directory { + flex: 0 1 auto; +} +.duration { + margin-inline-start: auto; + font-size: var(--fs-small); + font-variant-numeric: tabular-nums; +} .fileIcon { flex: none; color: var(--fg-muted); diff --git a/src/features/build/BuildView.tsx b/src/features/build/BuildView.tsx index 104e7beab..8554fc1f1 100644 --- a/src/features/build/BuildView.tsx +++ b/src/features/build/BuildView.tsx @@ -67,13 +67,12 @@ function StatusIcon({ status }: { status: BuildStatus }) { return ; } -function rootDetail(status: BuildStatus, durationMs: number | null, errors: number, warnings: number): string { +function rootDetail(status: BuildStatus, errors: number, warnings: number): string { if (status === "running") return "running…"; if (status === "cancelled") return "cancelled"; - const summary = finishSummary({ success: status === "success", errors, warnings, durationMs }); - return status === "success" - ? `finished ${formatDuration(durationMs ?? 0)}` - : summary.replace(/^Build failed:?\s*/, "") || "failed"; + if (status === "success") return tx("Finished"); + const summary = finishSummary({ success: false, errors, warnings, durationMs: null }); + return summary.replace(/^Build failed:?\s*/, "") || "failed"; } export function BuildHeaderActions() { @@ -130,15 +129,19 @@ function BuildTree() { const renderNode = (n: BuildNode, state: TreeRowState) => { if (n.kind === "root") { + const detail = rootDetail(n.status, n.errors, n.warnings); + const elapsed = n.status !== "running" && durationMs != null ? formatDuration(durationMs) : null; return ( - + {n.title} - {rootDetail(n.status, durationMs, n.errors, n.warnings)} + {detail} + {elapsed && {elapsed}} ); } if (n.kind === "file") { + const directory = relativeDir(root, n.path); const errors = n.messages.filter((m) => m.severity === "error").length; const warnings = n.messages.filter((m) => m.severity === "warning").length; const counts = [ @@ -148,13 +151,22 @@ function BuildTree() { .filter(Boolean) .join(", "); return ( - + - 0 && styles.fileError, state.selected && styles.selected)}> - {basename(n.path)} + + 0 && styles.fileError, + state.selected && styles.selected, + )} + > + {basename(n.path)} + + {directory && {directory}} - {relativeDir(root, n.path)} - {counts} + {counts && {counts}} ); } diff --git a/src/features/debugger/__tests__/valueHint.test.ts b/src/features/debugger/__tests__/valueHint.test.ts index 6f0fa5329..1e41084e6 100644 --- a/src/features/debugger/__tests__/valueHint.test.ts +++ b/src/features/debugger/__tests__/valueHint.test.ts @@ -38,7 +38,7 @@ afterEach(() => { describe("value hint", () => { it("keeps a hint whose value was expanded past the hint's timeout", () => { - showHint(view, () => valueHint("order", order, session), { pos: 0, timeout: 4000 }); + showHint(view, () => valueHint(view, "order", order, session), { pos: 0, timeout: 4000 }); expand(); expect(document.querySelector(".cm-lsp-hint .tree")).not.toBeNull(); vi.advanceTimersByTime(60_000); @@ -47,7 +47,7 @@ describe("value hint", () => { it("hands an expanded hover hint to its pin instead of growing in place", () => { const pin = vi.fn(); - showHint(view, () => valueHint("order", order, session, 400, { pin }), { pos: 0 }); + showHint(view, () => valueHint(view, "order", order, session, 400, { pin }), { pos: 0 }); expand(); expect(pin).toHaveBeenCalled(); expect(document.querySelector(".tree")).toBeNull(); diff --git a/src/features/debugger/editor/editor.module.css b/src/features/debugger/editor/editor.module.css index 840180e24..422e9ddcd 100644 --- a/src/features/debugger/editor/editor.module.css +++ b/src/features/debugger/editor/editor.module.css @@ -169,13 +169,25 @@ /* Data Views › Show value tooltip on mouse hover. */ .valueTooltip { - max-width: 520px; - padding: 4px 8px; - font-family: var(--font-mono); - font-weight: var(--fw-code); - font-size: var(--fs-code); + display: flex; + align-items: flex-start; + gap: var(--space-1); + max-width: min(90vw, calc(var(--debug-value-editor-width, 100vw) - var(--space-2))); + padding: var(--space-1) var(--space-2); + font-family: var(--font-ui); + font-size: var(--fs-ui); + font-weight: 700; + line-height: 1.4; +} +.valueText { + min-width: 0; white-space: pre-wrap; - word-break: break-word; + overflow-wrap: anywhere; +} +.valueGlyph { + display: inline-flex; + flex: none; + margin-top: 1px; } .valueTooltipTree { display: flex; @@ -194,19 +206,22 @@ padding: 0; overflow: hidden; } +:global(.cm-lsp-hint):has(> .valueTooltip) { + padding: 0; +} .valueExpand { display: inline-flex; align-items: center; justify-content: center; width: 16px; height: 16px; - margin-right: 4px; + flex: none; + margin-top: 1px; padding: 0; border: 0; border-radius: var(--radius-small); background: transparent; color: var(--fg-muted); - vertical-align: -3px; cursor: pointer; } .valueExpand:hover { diff --git a/src/features/debugger/editor/execution.ts b/src/features/debugger/editor/execution.ts index 1efbf209c..b7e393ecf 100644 --- a/src/features/debugger/editor/execution.ts +++ b/src/features/debugger/editor/execution.ts @@ -49,7 +49,7 @@ class InlineValues extends WidgetType { e.stopPropagation(); const session = activeSession(); if (!session || session.status !== "paused") return; - showHint(view, () => valueHint(part.name, part.variable, session.id, null), { + showHint(view, () => valueHint(view, part.name, part.variable, session.id, null), { pos: view.posAtDOM(piece), timeout: 60_000, }); @@ -65,7 +65,7 @@ class InlineValues extends WidgetType { e.stopPropagation(); const session = activeSession(); if (!session || session.status !== "paused") return; - showHint(view, () => valueHint(part.name, part.variable, session.id, null), { + showHint(view, () => valueHint(view, part.name, part.variable, session.id, null), { pos: view.posAtDOM(show), timeout: 60_000, }); diff --git a/src/features/debugger/editor/valueTooltip.ts b/src/features/debugger/editor/valueTooltip.ts index f587a4218..2e5264945 100644 --- a/src/features/debugger/editor/valueTooltip.ts +++ b/src/features/debugger/editor/valueTooltip.ts @@ -13,6 +13,7 @@ import { activeSession, evaluate, useDebug } from "../state"; import { inlineValue, shownValue } from "../values"; import { tx } from "@/platform/i18n"; import { iconMarkup, selectableText } from "@/ui"; +import { iconNode } from "@/ui/iconNode"; import { mountValueTree } from "../ui/ValueHintTree"; import styles from "./editor.module.css"; @@ -96,6 +97,7 @@ export function expressionAt( /** IDEA's value hint: `expression = value {type}`, objects expandable into a variables tree in place. */ export function valueHint( + view: EditorView, expression: string, value: Variable, session: DebugSessionId, @@ -104,15 +106,21 @@ export function valueHint( ): { dom: HTMLElement; destroy: () => void } { const dom = document.createElement("div"); dom.className = `${styles.valueTooltip} ${selectableText}`; + const stopSizing = watchHintWidth(view, dom); let tree: { unmount(): void } | null = null; + const destroy = () => { + stopSizing(); + tree?.unmount(); + }; const expandTree = () => { + dom.classList.remove(styles.valueTooltip!); dom.classList.replace(selectableText, styles.valueTooltipTree!); dom.replaceChildren(); tree = mountValueTree(dom, expression, value, session); }; if (value.variablesReference > 0 && opts.expanded) { expandTree(); - return { dom, destroy: () => tree?.unmount() }; + return { dom, destroy }; } if (value.variablesReference > 0) { // IDEA's value hint: the "+" expands the object into a variables tree in place. @@ -131,6 +139,8 @@ export function valueHint( }); dom.append(expand); } + const summary = document.createElement("span"); + summary.className = styles.valueText!; const name = document.createElement("span"); name.className = styles.valueName!; name.textContent = `${expression} = `; @@ -143,11 +153,33 @@ export function valueHint( span.textContent = text; return span; }; - dom.append(name); - if (leading) dom.append(type(`${shown.label} `)); - dom.append(max === null ? shown.text : inlineValue(shown.text, max)); - if (shown.label && !leading) dom.append(type(` ${shown.label}`)); - return { dom, destroy: () => tree?.unmount() }; + summary.append(name); + if (leading) summary.append(type(`${shown.label} `)); + summary.append(max === null ? shown.text : inlineValue(shown.text, max)); + if (shown.label && !leading) summary.append(type(` ${shown.label}`)); + dom.append(iconNode("variable", 16, styles.valueGlyph), summary); + return { dom, destroy }; +} + +function watchHintWidth(view: EditorView, dom: HTMLElement): () => void { + let width = 0; + let resizeFrame = 0; + const updateWidth = () => { + const next = view.dom.clientWidth; + if (!next || next === width) return; + width = next; + dom.style.setProperty("--debug-value-editor-width", `${width}px`); + }; + updateWidth(); + const resize = new ResizeObserver(() => { + cancelAnimationFrame(resizeFrame); + resizeFrame = requestAnimationFrame(updateWidth); + }); + resize.observe(view.dom); + return () => { + resize.disconnect(); + cancelAnimationFrame(resizeFrame); + }; } export function showQuickValue( @@ -158,7 +190,7 @@ export function showQuickValue( session: DebugSessionId, ) { if (value.variablesReference > 0) showValueTree(view, pos, expression, value, session); - else showHint(view, () => valueHint(expression, value, session), { pos, timeout: 60_000 }); + else showHint(view, () => valueHint(view, expression, value, session), { pos, timeout: 60_000 }); } export function valueTooltip(): Extension { @@ -185,7 +217,7 @@ export function valueTooltip(): Extension { end: expr.to, above: true, create: (view) => - valueHint(expr.text, value, session.id, 400, { + valueHint(view, expr.text, value, session.id, 400, { // The tree outgrows the hint and may move to the other side of the line, away from the // mouse, which closed the hover tooltip before it could be reached. Like IDEA's value // popup it stays until Escape, a click in the editor or the next step. @@ -208,21 +240,7 @@ function pinnedTree(view: EditorView, expression: string, value: Variable, sessi const unsubscribe = useDebug.subscribe((s) => { if (s.stopSeq !== stop || s.sessions[session]?.status !== "paused") hideHint(view); }); - const hint = valueHint(expression, value, session, 400, { expanded: true }); - let width = 0; - let resizeFrame = 0; - const updateWidth = () => { - const next = view.dom.clientWidth; - if (!next || next === width) return; - width = next; - hint.dom.style.setProperty("--debug-value-editor-width", `${width}px`); - }; - updateWidth(); - const resize = new ResizeObserver(() => { - cancelAnimationFrame(resizeFrame); - resizeFrame = requestAnimationFrame(updateWidth); - }); - resize.observe(view.dom); + const hint = valueHint(view, expression, value, session, 400, { expanded: true }); // The tree has the focus, so the editor's Escape doesn't reach the hint. hint.dom.addEventListener("keydown", (e) => { if (e.key !== "Escape" || e.defaultPrevented) return; @@ -233,8 +251,6 @@ function pinnedTree(view: EditorView, expression: string, value: Variable, sessi return { dom: hint.dom, destroy: () => { - resize.disconnect(); - cancelAnimationFrame(resizeFrame); unsubscribe(); hint.destroy(); }, @@ -287,7 +303,10 @@ export function selectionValueTooltip(): Extension { } // The selection moved on while evaluating. if (seq !== this.seq) return; - showHint(this.view, () => valueHint(expr.text, value, session.id), { pos: expr.from, timeout: 60_000 }); + showHint(this.view, () => valueHint(this.view, expr.text, value, session.id), { + pos: expr.from, + timeout: 60_000, + }); } destroy() { diff --git a/src/features/debugger/ui/Overlays.module.css b/src/features/debugger/ui/Overlays.module.css index b288a515a..0b9f7b8c4 100644 --- a/src/features/debugger/ui/Overlays.module.css +++ b/src/features/debugger/ui/Overlays.module.css @@ -1,7 +1,3 @@ -.spacer { - flex: 1; -} - .empty { padding: 16px; color: var(--fg-faint); @@ -21,12 +17,53 @@ } /* breakpoint popover */ -.bpEditor { - width: 340px; - padding: 10px 12px; +.bpPopover { + display: flex; + flex-direction: column; + width: 400px; + overflow: hidden; + font-size: var(--fs-ui); +} + +.bpPopoverTitle, +.bpFooter { + flex: none; + display: flex; + align-items: center; + gap: var(--space-2); + padding: var(--space-2) var(--space-3); +} + +.bpPopoverTitle { + color: var(--fg-strong); + font-weight: 600; + white-space: nowrap; +} + +.bpPopoverTitle > svg { + flex: none; +} + +.bpPopoverTitle .bpFile { + font-family: var(--font-ui); +} + +.bpPopoverFields { display: flex; flex-direction: column; gap: var(--space-2); + min-height: 0; + padding: var(--space-1) var(--space-3) var(--space-2); + overflow: auto; + overscroll-behavior: contain; +} + +.bpPopoverFields > * { + flex: none; +} + +.bpPopoverFields .label { + font-size: var(--fs-ui); } .bpActions { @@ -86,21 +123,27 @@ } .bpFooter { - display: flex; - align-items: center; - gap: var(--space-1-5); - margin-top: 2px; + flex-wrap: wrap; + border-block-start: 1px solid var(--border-popup); } -.link { +.bpFooterButtons { + display: flex; + flex-wrap: wrap; + gap: var(--space-1); + margin-inline-start: auto; +} + +.bpMore { display: inline-flex; + flex-wrap: wrap; align-items: center; gap: var(--space-1-5); color: var(--accent); font-size: var(--fs-ui); cursor: pointer; } -.link:hover { +.bpMore:hover { color: var(--accent-hover); } diff --git a/src/features/debugger/ui/Overlays.tsx b/src/features/debugger/ui/Overlays.tsx index ced8b8e45..70f6ac4ac 100644 --- a/src/features/debugger/ui/Overlays.tsx +++ b/src/features/debugger/ui/Overlays.tsx @@ -10,6 +10,7 @@ import { type CSSProperties, type KeyboardEvent, type MutableRefObject, + type ReactNode, } from "react"; import { basename, relativePath, useProject } from "@/platform/project"; import { executeAction, getAction } from "@/platform/actions"; @@ -137,6 +138,62 @@ function BreakpointPopover() { return ; } +function BreakpointPropertiesPopup({ + at, + title, + onClose, + onRemove, + children, +}: { + at: { x: number; y: number }; + title: ReactNode; + onClose: () => void; + onRemove: () => void; + children: ReactNode; +}) { + return ( + +
{title}
+
{children}
+
+ +
+ + +
+
+
+ ); +} + function BreakpointEditor({ path, bp, @@ -155,49 +212,25 @@ function BreakpointEditor({ }; return ( - -
-
+ removeBreakpoint(path, bp.id)} + title={ + <> - - {basename(path)}:{bp.line + 1} - -
- -
- -
- - -
-
- + + + } + > + + ); } @@ -365,66 +398,46 @@ function SpecialEditor({ bp, at }: { bp: SpecialBreakpoint; at: { x: number; y: closeBreakpointPopover(); }; return ( - -
-
+ removeSpecial(bp.id)} + title={ + <> - {specialTitle(bp)} -
- updateSpecial(bp.id, { enabled })} label="Enabled" /> - - -
- -
- - -
-
- + + } + > + updateSpecial(bp.id, { enabled })} label="Enabled" /> + + + ); } diff --git a/src/features/project-tree/FileRefactor.module.css b/src/features/project-tree/FileRefactor.module.css index 5806671bc..f2207948d 100644 --- a/src/features/project-tree/FileRefactor.module.css +++ b/src/features/project-tree/FileRefactor.module.css @@ -1,8 +1,25 @@ -.form { - display: flex; - flex-direction: column; +.renameForm { + display: grid; gap: var(--space-2); - padding: 14px; + padding: var(--space-3) var(--space-4); +} + +.renameName { + display: grid; + gap: var(--space-1); +} + +.renameOptions { + display: flex; + flex-wrap: wrap; + align-items: flex-start; + gap: var(--space-2) var(--space-4); + overflow-wrap: anywhere; +} + +.renameOptions > label { + min-width: 0; + max-width: 100%; } .refactorForm { diff --git a/src/features/project-tree/FileRefactorDialogs.tsx b/src/features/project-tree/FileRefactorDialogs.tsx index 8eaa9c67c..269bc39aa 100644 --- a/src/features/project-tree/FileRefactorDialogs.tsx +++ b/src/features/project-tree/FileRefactorDialogs.tsx @@ -143,7 +143,7 @@ function Options({ disabled: boolean; }) { return ( -
+
{ e.preventDefault(); submit(); }} > - - setName(e.target.value)} - /> - {error && ( -
- {error} -
- )} +
+ + setName(e.target.value)} + /> + {error && ( +
+ {error} +
+ )} +
diff --git a/src/features/run/AddConfigPopup.tsx b/src/features/run/AddConfigPopup.tsx index 6eed4fd1d..fcc2b400b 100644 --- a/src/features/run/AddConfigPopup.tsx +++ b/src/features/run/AddConfigPopup.tsx @@ -1,6 +1,17 @@ -import { useMemo, useState, type KeyboardEvent } from "react"; +import { useMemo, useRef, useState, type KeyboardEvent } from "react"; import clsx from "clsx"; -import { HighlightedText, Icon, List, Popup, SearchField, fuzzyMatch, listNavigate, T, type PopupAnchor } from "@/ui"; +import { + HighlightedText, + Icon, + List, + Popup, + SearchField, + firstSelectable, + fuzzyMatch, + listNavigate, + T, + type PopupAnchor, +} from "@/ui"; import { useRowHeight } from "@/ui/density"; import { useRunConfigTypes, runConfigTypes, type RunConfigTypeContribution } from "@/workbench/contributions"; import styles from "./Run.module.css"; @@ -64,12 +75,11 @@ export function AddConfigPopup({ const [query, setQuery] = useState(""); const rows = useMemo(() => typeRows(runConfigTypes(types), query), [types, query]); const isSection = (r: TypeRow) => r.kind === "group"; - const first = Math.max( - 0, - rows.findIndex((r) => r.kind === "type"), - ); - const [active, setActive] = useState(first); + const [active, setActive] = useState(-1); const clamped = Math.min(active, rows.length - 1); + const selected = rows[clamped]?.kind === "type" ? clamped : firstSelectable(rows, isSection); + const viewport = useRef(null); + const height = Math.max(1, Math.min(rows.length, 30)) * rowHeight; const pick = (row: TypeRow | undefined) => { if (row?.kind !== "type") return; @@ -80,10 +90,11 @@ export function AddConfigPopup({ const onKeyDown = (e: KeyboardEvent) => { if (e.key === "Enter") { e.preventDefault(); - pick(rows[clamped]); + pick(rows[selected]); return; } - const next = listNavigate(e.key, { items: rows, active: clamped, isSection, wrap: true }); + const pageSize = Math.max(1, Math.floor((viewport.current?.clientHeight ?? height) / rowHeight) - 1); + const next = listNavigate(e.key, { items: rows, active: selected, isSection, pageSize, wrap: true }); if (next !== null) { e.preventDefault(); setActive(next); @@ -97,7 +108,7 @@ export function AddConfigPopup({ onClose={onClose} placement="bottom-start" aria-label="Add New Configuration" - className={styles.chooser} + className={clsx(styles.chooser, styles.typeChooser)} trapFocus >
@@ -108,7 +119,7 @@ export function AddConfigPopup({ value={query} onChange={(v) => { setQuery(v); - setActive(0); + setActive(-1); }} placeholder="Search types" aria-label="Search configuration types" @@ -117,7 +128,7 @@ export function AddConfigPopup({ variant="bare" />
-
+
aria-label="Configuration types" className={styles.chooserList} @@ -125,7 +136,7 @@ export function AddConfigPopup({ getKey={(r) => r.key} isSection={isSection} renderSection={(r) => (r.kind === "group" ? r.label : null)} - activeIndex={rows[clamped]?.kind === "type" ? clamped : first} + activeIndex={selected} onActiveChange={setActive} focusable={false} hoverSelects @@ -139,7 +150,7 @@ export function AddConfigPopup({ renderItem={(r) => r.kind === "type" ? ( - + {r.indices?.length ? : r.type.label} diff --git a/src/features/run/ConfigForm.tsx b/src/features/run/ConfigForm.tsx index a9e7a20c3..40c5c6354 100644 --- a/src/features/run/ConfigForm.tsx +++ b/src/features/run/ConfigForm.tsx @@ -6,7 +6,16 @@ import { writeClipboardText } from "@/platform/clipboard"; import { isJvmApplication, parseJavaArgs } from "@/platform/javaLaunch"; import { useRunTargets } from "@/platform/pluginRunTargets"; -import { useEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode, type RefObject } from "react"; +import { + useEffect, + useMemo, + useRef, + useState, + type KeyboardEvent, + type MouseEvent, + type ReactNode, + type RefObject, +} from "react"; import clsx from "clsx"; import { isTauri, type BeforeLaunchTask, type BuildPolicy, type RunConfig } from "@/platform/ipc"; import { useWorkflowSettings } from "@/platform/workflowSettings"; @@ -54,6 +63,16 @@ import { TomcatSettings } from "./TomcatSettings"; import { toolWindowTitle } from "@/workbench/toolwindows/title"; import styles from "./Run.module.css"; +const TASK_ICONS: Readonly>> = { + build: "build-project", + buildModule: "build-project", + buildArtifacts: "build-rebuild", + dotnetBuild: "build-project", + run: "run", + tool: "settings", + command: "terminal", +}; + /** * Debug adapters with a real launch template (`debugger/launch.ts`, `debugger/java.ts`), * verified against small programs. Others (dart, …) only got @@ -332,7 +351,7 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi const [envOpen, setEnvOpen] = useState(false); const [modifyOpen, setModifyOpen] = useState(false); const [lastRequest, setLastRequest] = useState(modifyRequest); - const [taskMenu, setTaskMenu] = useState(false); + const [taskMenu, setTaskMenu] = useState<"add" | { index: number; anchor: HTMLButtonElement } | null>(null); const modifyRef = useRef(null); const taskRef = useRef(null); @@ -406,23 +425,23 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi run: () => addTask("run", c.id), })), }, - { label: TASK_LABELS.build, icon: "build-project", run: () => addTask("build") }, + { label: TASK_LABELS.build, icon: TASK_ICONS.build, run: () => addTask("build") }, { label: TASK_LABELS.buildModule, - icon: "build-project", + icon: TASK_ICONS.buildModule, disabled: config.module == null, run: () => addTask("buildModule", config.module ?? ""), }, - { label: TASK_LABELS.buildArtifacts, icon: "build-rebuild", run: () => addTask("buildArtifacts") }, + { label: TASK_LABELS.buildArtifacts, icon: TASK_ICONS.buildArtifacts, run: () => addTask("buildArtifacts") }, ...(config.kind === "dotnet" - ? [{ label: TASK_LABELS.dotnetBuild, icon: "build-project", run: () => addTask("dotnetBuild") }] + ? [{ label: TASK_LABELS.dotnetBuild, icon: TASK_ICONS.dotnetBuild, run: () => addTask("dotnetBuild") }] : []), { label: TASK_LABELS.tool, disabled: !externalTools.length, submenu: externalTools.map((t) => ({ label: t.name, verbatim: true, run: () => addTask("tool", t.id) })), }, - { label: TASK_LABELS.command, icon: "terminal", run: () => addTask("command") }, + { label: TASK_LABELS.command, icon: TASK_ICONS.command, run: () => addTask("command") }, { label: TASK_LABELS.toolWindow, submenu: [...toolWindows.values()] @@ -442,6 +461,7 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi [next[i], next[j]] = [next[j]!, next[i]!]; setTasks(next); }; + const taskActions = taskMenu === "add" ? null : taskMenu; const adapterOptions: SelectOption[] = [ { value: "", label: "None" }, @@ -763,62 +783,103 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi {isShown("beforeLaunch") && ( -
- {tasks.map((t, i) => ( -
- {t.kind === "command" ? ( - - setTasks(tasks.map((x, j) => (j === i ? { ...x, target: e.target.value } : x))) - } - /> - ) : ( - - {txTemplate(taskLabel(t, all))} - - )} - +
+ {tasks.map((t, i) => { + const label = txTemplate(taskLabel(t, all)); + const target = t.kind === "run" ? all.find((c) => c.id === t.target) : undefined; + const icon = target ? configIcon(target) : TASK_ICONS[t.kind]; + const prefix = ( + <> + {icon && } + {i + 1}. + + ); + const actions = { + "aria-haspopup": "menu" as const, + "aria-expanded": taskActions?.index === i, + onClick: (e: MouseEvent) => setTaskMenu({ index: i, anchor: e.currentTarget }), + }; + return ( +
+ {t.kind === "command" ? ( + <> + {prefix} + + setTasks(tasks.map((x, j) => (j === i ? { ...x, target: e.target.value } : x))) + } + /> + + + ) : ( + + )} moveTask(i, -1)} - /> - moveTask(i, 1)} - /> - setTasks(tasks.filter((_, j) => j !== i))} /> - -
- ))} - - setTaskMenu(false)} /> +
+ ); + })} +
+ {tasks.length ? ( + setTaskMenu("add")} + /> + ) : ( + + )} +
+ setTaskMenu(null)} /> + {taskActions && ( + moveTask(taskActions.index, -1), + }, + { + label: "Move Down", + icon: "arrow-down", + disabled: taskActions.index === tasks.length - 1, + run: () => moveTask(taskActions.index, 1), + }, + ]} + onClose={() => setTaskMenu(null)} + /> + )}
)} diff --git a/src/features/run/ExportTestResultsDialog.test.tsx b/src/features/run/ExportTestResultsDialog.test.tsx index 5b6c65ced..1d60c9175 100644 --- a/src/features/run/ExportTestResultsDialog.test.tsx +++ b/src/features/run/ExportTestResultsDialog.test.tsx @@ -1,7 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import { commands } from "@/platform/ipc"; -import { ExportTestResultsDialog, defaultExportPath, loadExportOptions } from "./ExportTestResultsDialog"; +import { ExportTestResultsDialog, defaultExportName, loadExportOptions } from "./ExportTestResultsDialog"; import { TestResults } from "./testing"; const actions = vi.hoisted(() => ({ executeAction: vi.fn(async () => {}) })); @@ -56,13 +56,15 @@ function open(onClose = vi.fn()) { return onClose; } -const file = () => screen.getByLabelText("Output file"); +const file = () => screen.getByLabelText("File name"); +const folder = () => screen.getByLabelText("Folder"); const press = (name: string) => fireEvent.click(screen.getByRole("button", { name })); describe("ExportTestResultsDialog", () => { - it("writes an HTML report to the project folder under IDEA's name and opens it in the browser", async () => { + it("writes an HTML report to the project folder and opens it in the browser", async () => { const onClose = open(); - expect(file()).toHaveValue("/work/app/Test Results - go test _calc.html"); + expect(file()).toHaveValue("Test Results - go test _calc.html"); + expect(folder()).toHaveValue("/work/app/"); expect(screen.getByRole("radio", { name: "HTML" })).toBeChecked(); press("OK"); await waitFor(() => expect(onClose).toHaveBeenCalled()); @@ -92,7 +94,7 @@ describe("ExportTestResultsDialog", () => { it("switches the extension with the format, keeps XML out of the browser, and remembers the choice", async () => { const onClose = open(); fireEvent.click(screen.getByRole("radio", { name: "XML" })); - expect(file()).toHaveValue("/work/app/Test Results - go test _calc.xml"); + expect(file()).toHaveValue("Test Results - go test _calc.xml"); // Only an HTML report opens in the browser. expect(screen.getByRole("checkbox", { name: "Open exported file in browser" })).toBeDisabled(); press("OK"); @@ -143,18 +145,36 @@ describe("ExportTestResultsDialog", () => { }); it("doesn't ask again for a file the save dialog already confirmed", async () => { - onDisk["/tmp/picked.html"] = "file"; - dialog.save.mockResolvedValueOnce("/tmp/picked.html"); + const path = "C:\\reports\\picked.html"; + onDisk[path] = "file"; + dialog.save.mockResolvedValueOnce(path); const onClose = open(); press("Browse…"); - await waitFor(() => expect(file()).toHaveValue("/tmp/picked.html")); + await waitFor(() => expect(file()).toHaveValue("picked.html")); + expect(folder()).toHaveValue("C:\\reports\\"); expect(dialog.save).toHaveBeenCalledWith( - expect.objectContaining({ filters: [{ name: "HTML", extensions: ["html"] }] }), + expect.objectContaining({ + defaultPath: "/work/app/Test Results - go test _calc.html", + filters: [{ name: "HTML", extensions: ["html"] }], + }), ); press("OK"); await waitFor(() => expect(onClose).toHaveBeenCalled()); expect(messages.confirm).not.toHaveBeenCalled(); - expect(written.map((w) => w.path)).toEqual(["/tmp/picked.html"]); + expect(written.map((w) => w.path)).toEqual([path]); + }); + + it("confirms again when the destination changes after using the save dialog", async () => { + dialog.save.mockResolvedValueOnce("/tmp/picked.html"); + onDisk["/work/app/reports/picked.html"] = "file"; + messages.confirm.mockResolvedValueOnce(false); + open(); + press("Browse…"); + await waitFor(() => expect(file()).toHaveValue("picked.html")); + fireEvent.change(folder(), { target: { value: "reports" } }); + press("OK"); + await waitFor(() => expect(messages.confirm).toHaveBeenCalledOnce()); + expect(written).toHaveLength(0); }); it("reports a directory or a failed write and stays open", async () => { @@ -187,15 +207,11 @@ describe("ExportTestResultsDialog", () => { }); }); -describe("defaultExportPath", () => { +describe("defaultExportName", () => { it("replaces characters file systems refuse in the configuration's name", () => { - expect(defaultExportPath("C:\\proj\\", 'a/b\\c:d*e?f"gi|j', "xml")).toBe( - "C:\\proj/Test Results - a_b_c_d_e_f_g_h_i_j.xml", - ); - expect(defaultExportPath("/p", "go test ./...", "html")).toBe("/p/Test Results - go test.html"); - expect(defaultExportPath("/p", "Tests in 'com.acme.Cart'", "html")).toBe( - "/p/Test Results - Tests in 'com_acme_Cart'.html", - ); - expect(defaultExportPath("/p", "...", "html")).toBe("/p/Test Results - Tests.html"); + expect(defaultExportName('a/b\\c:d*e?f"gi|j', "xml")).toBe("Test Results - a_b_c_d_e_f_g_h_i_j.xml"); + expect(defaultExportName("go test ./...", "html")).toBe("Test Results - go test.html"); + expect(defaultExportName("Tests in 'com.acme.Cart'", "html")).toBe("Test Results - Tests in 'com_acme_Cart'.html"); + expect(defaultExportName("...", "html")).toBe("Test Results - Tests.html"); }); }); diff --git a/src/features/run/ExportTestResultsDialog.tsx b/src/features/run/ExportTestResultsDialog.tsx index 34dab76cc..c3db1d907 100644 --- a/src/features/run/ExportTestResultsDialog.tsx +++ b/src/features/run/ExportTestResultsDialog.tsx @@ -2,7 +2,7 @@ * IDEA's Export Test Results dialog: HTML or XML, the output file, and whether to * open an HTML report in the browser once it is written. */ -import { useState } from "react"; +import { useId, useState } from "react"; import { executeAction } from "@/platform/actions"; import { tx } from "@/platform/i18n"; import { call, commands } from "@/platform/ipc"; @@ -38,13 +38,35 @@ function saveExportOptions(o: ExportOptions) { } } -/** - * IDEA's default name, `Test Results - .html`. Like IDEA's `PathUtil.suggestFileName`, runs of - * dots and characters file systems refuse become one `_` (`go test ./...` gives `go test`). - */ -export function defaultExportPath(dir: string, name: string, format: TestExportFormat): string { +/** Runs of dots and characters file systems refuse become one `_`. */ +export function defaultExportName(name: string, format: TestExportFormat): string { const safe = name.replace(/[/\\:*?"<>|.]+/g, "_").replace(/^[\s_]+|[\s_]+$/g, ""); - return `${dir.replace(/[\\/]+$/, "")}/Test Results - ${safe || "Tests"}.${format}`; + return `Test Results - ${safe || "Tests"}.${format}`; +} + +interface Destination { + folder: string; + fileName: string; + /** The native picker already asked before replacing this exact path. */ + pickedPath?: string; +} + +function destinationFromPicker(path: string): Destination { + const slash = path.lastIndexOf("/"); + const posix = path.startsWith("/") && !path.startsWith("//"); + const end = (posix ? slash : Math.max(slash, path.lastIndexOf("\\"))) + 1; + return { folder: path.slice(0, end), fileName: path.slice(end), pickedPath: path }; +} + +function resolveDestination({ folder, fileName, pickedPath }: Destination, cwd: string): string { + if (pickedPath) return pickedPath; + const file = fileName.trim(); + if (!file || isAbsolutePath(file)) return file; + const dir = folder.trim(); + const posix = dir.startsWith("/") && !dir.startsWith("//"); + const base = dir.replace(posix ? /\/+$/ : /[\\/]+$/, ""); + const path = dir ? `${base}/${file}` : file; + return isAbsolutePath(path) ? path : `${cwd.replace(/[\\/]+$/, "")}/${path}`; } async function exists(path: string): Promise<"file" | "dir" | null> { @@ -111,44 +133,47 @@ export function ExportTestResultsDialog({ cwd: string; onClose: () => void; }) { + const fileNameId = useId(); + const folderId = useId(); const [options, setOptions] = useState(loadExportOptions); - const [path, setPath] = useState(() => defaultExportPath(cwd, name, options.format)); - // The save dialog already asked before replacing this file. - const [picked, setPicked] = useState(null); + const [destination, setDestination] = useState(() => ({ + folder: cwd, + fileName: defaultExportName(name, options.format), + })); const [busy, setBusy] = useState(false); const html = options.format === "html"; + const { folder, fileName, pickedPath } = destination; + const target = resolveDestination(destination, cwd); const update = (next: Partial) => { const merged = { ...options, ...next }; setOptions(merged); saveExportOptions(merged); // The file follows the format's extension, as in the Export Data dialog. - if (next.format) setPath((p) => p.replace(/\.(html|xml)$/i, `.${next.format}`)); + if (next.format) { + const nextName = fileName.replace(/\.(html|xml)$/i, `.${next.format}`); + if (nextName !== fileName) setDestination({ folder, fileName: nextName }); + } }; const browse = async () => { try { const { save } = await import("@/platform/dialog"); const chosen = await save({ - defaultPath: path, + defaultPath: target || folder || cwd, filters: [{ name: html ? "HTML" : "XML", extensions: [options.format] }], }); - if (chosen) { - setPath(chosen); - setPicked(chosen); - } + if (chosen) setDestination(destinationFromPicker(chosen)); } catch { // No dialog (tests): keep typing the path. } }; const run = async () => { - const raw = path.trim(); - if (!raw) return; - const target = isAbsolutePath(raw) ? raw : `${cwd.replace(/[\\/]+$/, "")}/${raw}`; + if (!target) return; setBusy(true); const text = exportTestResults(options.format, results, { name, cwd, date: new Date() }); - const ok = await writeTestReport(target, text, picked === raw); + const ok = await writeTestReport(target, text, pickedPath !== undefined); setBusy(false); if (!ok) return; onClose(); @@ -167,29 +192,46 @@ export function ExportTestResultsDialog({ open title="Export Test Results" onClose={onClose} - width={520} + width={500} buttons={[ - { label: "OK", role: "default", disabled: busy || !path.trim(), onClick: () => void run() }, + { label: "OK", role: "default", disabled: busy || !target, onClick: () => void run() }, { label: "Cancel", role: "cancel" }, ]} > -
-
- +
+
+ Export format: - + update({ format: "html" })} /> update({ format: "xml" })} /> -
-