дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-06 01:57:13 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
19ff82668e | ||
|
|
4b58b2a5a5 | ||
|
|
39068cffb3 | ||
|
|
bef9223913 |
No files matched your search
@@ -163,3 +163,68 @@ for (const theme of ["light", "dark"] as const) {
|
||||
await expect(popup).toBeHidden();
|
||||
});
|
||||
}
|
||||
|
||||
test("Find Usages lines use the tree font and keep line numbers beside the snippet", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const modulePath = "/src/features/code-insight/usages.ts";
|
||||
const { useUsagesPopup } = await import(modulePath);
|
||||
const path = "/dev/acme-api/src/TaskScheduler.ts";
|
||||
const lines = Array<string>(1001).fill("");
|
||||
const usageLines = [6, 97, 1001];
|
||||
const text = " scheduler.schedule(task);";
|
||||
for (const line of usageLines) lines[line - 1] = text;
|
||||
window.__ipc.handlers.fs_read_text = () => lines.join("\n");
|
||||
useUsagesPopup.setState({
|
||||
open: true,
|
||||
anchor: { x: 100, y: 150 },
|
||||
symbol: "scheduler",
|
||||
loading: false,
|
||||
groups: [
|
||||
{
|
||||
path,
|
||||
usages: usageLines.map((line) => ({
|
||||
path,
|
||||
line: line - 1,
|
||||
col: 2,
|
||||
endCol: 11,
|
||||
text,
|
||||
})),
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
|
||||
const popupMatch = popup.getByRole("option").first().locator("mark");
|
||||
const popupFont = await popupMatch.evaluate((node) => getComputedStyle(node).fontFamily);
|
||||
await popup.getByRole("button", { name: /Open in Find Window/ }).click();
|
||||
|
||||
const usages = page.getByRole("region", { name: "Find Usages", exact: true });
|
||||
await expect(usages.locator("mark")).toHaveCount(3);
|
||||
for (const width of [1200, 540]) {
|
||||
await page.setViewportSize({ width, height: 740 });
|
||||
for (const line of ["6", "97", "1001"]) {
|
||||
const row = usages.getByRole("treeitem").filter({ has: page.getByText(line, { exact: true }) });
|
||||
const mark = row.locator("mark");
|
||||
await expect(mark).toHaveText("scheduler");
|
||||
const number = await row.getByText(line, { exact: true }).evaluate((node) => {
|
||||
const text = new Range();
|
||||
text.selectNodeContents(node);
|
||||
const { right } = text.getBoundingClientRect();
|
||||
return { right, font: getComputedStyle(node).fontFamily, size: getComputedStyle(node).fontSize };
|
||||
});
|
||||
const snippet = await mark.evaluate((node) => ({
|
||||
left: node.getBoundingClientRect().left,
|
||||
font: getComputedStyle(node).fontFamily,
|
||||
size: getComputedStyle(node).fontSize,
|
||||
}));
|
||||
const treeFont = await row.evaluate((node) => getComputedStyle(node).fontFamily);
|
||||
expect(snippet.font).toBe(treeFont);
|
||||
expect(number.font).toBe(treeFont);
|
||||
expect(popupFont).not.toBe(treeFont);
|
||||
expect(snippet.size).toBe(number.size);
|
||||
expect(snippet.left - number.right).toBeCloseTo(4, 0);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -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" });
|
||||
});
|
||||
@@ -228,6 +228,10 @@
|
||||
.conversationRow[data-measured] {
|
||||
content-visibility: auto;
|
||||
}
|
||||
/* WebKit leaves a stale selection highlight on rows that skipped rendering (`useOffscreenRows`). */
|
||||
.stream[data-selection] > .conversationRow[data-measured] {
|
||||
content-visibility: visible;
|
||||
}
|
||||
/* Keep turns distinct and the work within a turn close to its author. Not `* + *`: a
|
||||
universal adjacent-sibling rule makes Chromium restyle whole sibling subtrees on every
|
||||
DOM insertion anywhere in the window, which costs every editor scroll frame. */
|
||||
|
||||
@@ -144,6 +144,39 @@ function useOffscreenRows(
|
||||
resize.disconnect();
|
||||
};
|
||||
}, [ref, visible, enabled, fitWindowWidth, fontZoom]);
|
||||
// WebKit never clears the selection highlight of a row that skips rendering: once the
|
||||
// selection moves, rows it covered off screen still show it when scrolled back. While the
|
||||
// stream holds a selection every row renders (`data-selection`), and keeps rendering until
|
||||
// the frame after it goes, when WebKit applies the change.
|
||||
useEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el || !enabled || !visible) return;
|
||||
let frame = 0;
|
||||
const selected = () => {
|
||||
const sel = window.getSelection();
|
||||
return !!sel && !sel.isCollapsed && sel.rangeCount > 0 && sel.getRangeAt(0).intersectsNode(el);
|
||||
};
|
||||
const update = () => {
|
||||
cancelAnimationFrame(frame);
|
||||
if (selected()) {
|
||||
el.setAttribute("data-selection", "");
|
||||
return;
|
||||
}
|
||||
if (!el.hasAttribute("data-selection")) return;
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = requestAnimationFrame(() => {
|
||||
if (!selected()) el.removeAttribute("data-selection");
|
||||
});
|
||||
});
|
||||
};
|
||||
update();
|
||||
document.addEventListener("selectionchange", update);
|
||||
return () => {
|
||||
cancelAnimationFrame(frame);
|
||||
document.removeEventListener("selectionchange", update);
|
||||
el.removeAttribute("data-selection");
|
||||
};
|
||||
}, [ref, visible, enabled]);
|
||||
}
|
||||
|
||||
interface StreamProps {
|
||||
|
||||
@@ -98,13 +98,13 @@
|
||||
flex: none;
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.occurrence {
|
||||
gap: var(--space-1);
|
||||
}
|
||||
.line {
|
||||
flex: none;
|
||||
min-width: 3ch;
|
||||
text-align: right;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-ui);
|
||||
color: var(--fg-line-number);
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.preview {
|
||||
min-width: 0;
|
||||
@@ -114,6 +114,9 @@
|
||||
font-size: var(--fs-code);
|
||||
color: var(--fg);
|
||||
}
|
||||
.occurrence .preview {
|
||||
font: inherit;
|
||||
}
|
||||
.match {
|
||||
background: var(--bg-search-match);
|
||||
color: var(--fg-search-match, inherit);
|
||||
|
||||
@@ -261,7 +261,7 @@ export function UsagesView() {
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className={clsx(styles.row, excluded.has(n.key) && styles.excluded)}>
|
||||
<span className={clsx(styles.row, styles.occurrence, excluded.has(n.key) && styles.excluded)}>
|
||||
<span className={styles.line}>{n.usage.line + 1}</span>
|
||||
<UsagePreview usage={n.usage} />
|
||||
</span>
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
createTableSql,
|
||||
draftOf,
|
||||
dropDatabaseSql,
|
||||
renameDatabaseSql,
|
||||
dropSql,
|
||||
ident,
|
||||
reference,
|
||||
@@ -33,6 +34,7 @@ import {
|
||||
connectedTargets,
|
||||
createDatabase,
|
||||
dropDatabase,
|
||||
renameDatabase,
|
||||
loadDetails,
|
||||
openSourceDialog,
|
||||
readableDdl,
|
||||
@@ -103,20 +105,34 @@ function useRunner() {
|
||||
|
||||
// ---- Rename ------------------------------------------------------------------
|
||||
|
||||
function RenameDialog({ id, object }: { id: string; object: DbObjectRef | null }) {
|
||||
/** Renames a data source, a schema object, or (with `database`) a database of the server. */
|
||||
function RenameDialog({ id, object, database }: { id: string; object: DbObjectRef | null; database?: string }) {
|
||||
const source = sourceById(id);
|
||||
const initial = object ? objectName(object) : (source?.name ?? "");
|
||||
const initial = database ?? (object ? objectName(object) : (source?.name ?? ""));
|
||||
const [name, setName] = useState(initial);
|
||||
const { busy, runAndClose } = useRunner();
|
||||
const [renaming, setRenaming] = useState(false);
|
||||
const driver = driverOf(id);
|
||||
const changed = !!name.trim() && name.trim() !== initial;
|
||||
const sql = object && changed ? renameSql(driver, object, name.trim()) : "";
|
||||
const submit = () => {
|
||||
const sql = !changed
|
||||
? ""
|
||||
: database !== undefined
|
||||
? renameDatabaseSql(driver, database, name.trim())
|
||||
: object
|
||||
? renameSql(driver, object, name.trim())
|
||||
: "";
|
||||
const submit = async () => {
|
||||
if (!changed) return closeDialog();
|
||||
if (database !== undefined) {
|
||||
setRenaming(true);
|
||||
if (await renameDatabase(id, database, sql)) closeDialog();
|
||||
else setRenaming(false);
|
||||
return;
|
||||
}
|
||||
if (!object) return void renameSource(id, name).then(closeDialog);
|
||||
void runAndClose(id, [sql]);
|
||||
};
|
||||
const what = object ? KIND_LABEL[object.kind] : "data source";
|
||||
const what = database !== undefined ? "database" : object ? KIND_LABEL[object.kind] : "data source";
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
@@ -125,7 +141,12 @@ function RenameDialog({ id, object }: { id: string; object: DbObjectRef | null }
|
||||
width={480}
|
||||
buttons={[
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
{ label: "Refactor", role: "default", disabled: busy || !name.trim(), onClick: () => void submit() },
|
||||
{
|
||||
label: "Refactor",
|
||||
role: "default",
|
||||
disabled: busy || renaming || !name.trim(),
|
||||
onClick: () => void submit(),
|
||||
},
|
||||
]}
|
||||
>
|
||||
<div className={styles.dialogBody}>
|
||||
@@ -139,7 +160,7 @@ function RenameDialog({ id, object }: { id: string; object: DbObjectRef | null }
|
||||
onFocus={(e) => e.currentTarget.select()}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
{object && <SqlPreview sql={sql || `-- ${what} keeps its name`} />}
|
||||
{(object || database !== undefined) && <SqlPreview sql={sql || `-- ${what} keeps its name`} />}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
@@ -895,6 +916,10 @@ export function ObjectDialogs() {
|
||||
switch (dialog.kind) {
|
||||
case "rename":
|
||||
return <RenameDialog key={`${dialog.id}`} id={dialog.id} object={dialog.object} />;
|
||||
case "renameDatabase":
|
||||
return (
|
||||
<RenameDialog key={`${dialog.id}:${dialog.database}`} id={dialog.id} object={null} database={dialog.database} />
|
||||
);
|
||||
case "drop":
|
||||
return <DropDialog id={dialog.id} object={dialog.object} />;
|
||||
case "truncate":
|
||||
|
||||
@@ -13,7 +13,9 @@ import {
|
||||
dropSql,
|
||||
ident,
|
||||
reference,
|
||||
canRename,
|
||||
renameSql,
|
||||
renameDatabaseSql,
|
||||
scriptSql,
|
||||
truncateSql,
|
||||
quoteIdent,
|
||||
@@ -114,6 +116,17 @@ describe("database object SQL", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("renames schemas and databases where the server can", () => {
|
||||
const schema = { kind: "schema" as const, schema: "sales", name: "sales" };
|
||||
expect(canRename("postgres", schema)).toBe(true);
|
||||
expect(canRename("snowflake", schema)).toBe(true);
|
||||
expect(canRename("mysql", schema)).toBe(false);
|
||||
expect(canRename("sqlServer", schema)).toBe(false);
|
||||
expect(renameSql("postgres", schema, "Old Sales")).toBe('alter schema sales rename to "Old Sales";');
|
||||
expect(renameDatabaseSql("postgres", "shop", "store")).toBe("alter database shop rename to store;");
|
||||
expect(renameDatabaseSql("sqlServer", "shop", "store")).toBe("alter database shop modify name = store;");
|
||||
});
|
||||
|
||||
it("drops with IF EXISTS / CASCADE", () => {
|
||||
const t = { kind: "table" as const, schema: "public", name: "users" };
|
||||
expect(dropSql("postgres", t, { ifExists: true, cascade: true })).toBe(
|
||||
|
||||
@@ -86,12 +86,15 @@ export const canRename = (driver: DbDriver, o: DbObjectRef) =>
|
||||
(o.kind === "table" ||
|
||||
o.kind === "column" ||
|
||||
(o.kind === "view" && driver !== "sqlite") ||
|
||||
(o.kind === "index" && driver === "postgres"));
|
||||
(o.kind === "index" && driver === "postgres") ||
|
||||
(o.kind === "schema" && (driver === "postgres" || driver === "snowflake")));
|
||||
|
||||
/** The statement renaming `o` to `to`. */
|
||||
export function renameSql(driver: DbDriver, o: DbObjectRef, to: string): string {
|
||||
const q = qualifiedName(driver, o.schema, o.name);
|
||||
switch (o.kind) {
|
||||
case "schema":
|
||||
return `alter schema ${ident(driver, o.name)} rename to ${ident(driver, to)};`;
|
||||
case "column":
|
||||
return `alter table ${q} rename column ${ident(driver, o.column ?? "")} to ${ident(driver, to)};`;
|
||||
case "index":
|
||||
@@ -239,6 +242,12 @@ export function dropDatabaseSql(driver: DbDriver, name: string, force: boolean):
|
||||
return `drop database ${db}${force && driver === "postgres" ? " with (force)" : ""};`;
|
||||
}
|
||||
|
||||
/** The statement renaming database `name` of a server to `to` (PostgreSQL, SQL Server). */
|
||||
export function renameDatabaseSql(driver: DbDriver, name: string, to: string): string {
|
||||
if (driver === "sqlServer") return `alter database ${ident(driver, name)} modify name = ${ident(driver, to)};`;
|
||||
return `alter database ${ident(driver, name)} rename to ${ident(driver, to)};`;
|
||||
}
|
||||
|
||||
export type ScriptKind = "selectAll" | "selectFirst" | "insert" | "update" | "delete";
|
||||
|
||||
export const SCRIPT_LABELS: Record<ScriptKind, string> = {
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { getAction } from "@/platform/actions";
|
||||
import type { DbNode } from "./nodes";
|
||||
import { useDatabase } from "./store";
|
||||
import { registerDatabaseTreeActions } from "./treeActions";
|
||||
import { nodeMenu } from "./treeMenu";
|
||||
|
||||
const database = (current: boolean): DbNode => ({ kind: "database", key: "db", id: "pg:shop", name: "shop", current });
|
||||
const schema: DbNode = { kind: "schema", id: "pg:shop", key: "schema", schema: "sales" };
|
||||
|
||||
const renameItem = (n: DbNode) =>
|
||||
nodeMenu(n).find((item) => "action" in item && item.action === "db.rename") as { disabled?: boolean } | undefined;
|
||||
|
||||
let dispose: () => void;
|
||||
beforeEach(() => {
|
||||
dispose = registerDatabaseTreeActions();
|
||||
useDatabase.setState({ sources: [{ id: "pg", driver: "postgres" }], dialog: null, loaded: true });
|
||||
});
|
||||
afterEach(() => dispose());
|
||||
|
||||
describe("Rename on databases and schemas", () => {
|
||||
it("is offered on a database other than the connected one", () => {
|
||||
expect(renameItem(database(false))?.disabled).toBe(false);
|
||||
expect(renameItem(database(true))?.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("is offered on a schema", () => {
|
||||
expect(renameItem(schema)?.disabled).toBe(false);
|
||||
});
|
||||
|
||||
it("is not offered on a read-only data source", () => {
|
||||
useDatabase.setState({ sources: [{ id: "pg", driver: "postgres", readOnly: true }] });
|
||||
expect(renameItem(database(false))?.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("opens the rename dialog through db.rename", async () => {
|
||||
await getAction("db.rename")!.run({ arg: database(false) } as never);
|
||||
expect(useDatabase.getState().dialog).toEqual({ kind: "renameDatabase", id: "pg", database: "shop" });
|
||||
useDatabase.setState({ dialog: null });
|
||||
await getAction("db.rename")!.run({ arg: database(true) } as never);
|
||||
expect(useDatabase.getState().dialog).toBeNull();
|
||||
await getAction("db.rename")!.run({ arg: schema } as never);
|
||||
expect(useDatabase.getState().dialog).toMatchObject({
|
||||
kind: "rename",
|
||||
id: "pg:shop",
|
||||
object: { kind: "schema", name: "sales" },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -135,6 +135,7 @@ export type DialogState =
|
||||
| { kind: "sourceUrl" }
|
||||
/** Rename a data source (`object` null) or a schema object of target `id`. */
|
||||
| { kind: "rename"; id: string; object: DbObjectRef | null }
|
||||
| { kind: "renameDatabase"; id: string; database: string }
|
||||
/** Confirm Drop / Truncate, with a preview of the statement. */
|
||||
| { kind: "drop"; id: string; object: DbObjectRef }
|
||||
| { kind: "truncate"; id: string; schema: string; table: string }
|
||||
@@ -1349,6 +1350,14 @@ export async function dropDatabase(id: string, database: string, sql: string): P
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Renames `database` of data source `id` with `sql` after closing the sessions on it. */
|
||||
export async function renameDatabase(id: string, database: string, sql: string): Promise<boolean> {
|
||||
await disconnect(`${id}:${database}`);
|
||||
if (!(await runSql(id, [sql]))) return false;
|
||||
void refresh(id);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Opens the query console of `id` with `text` appended and selected (SQL Scripts › …). */
|
||||
export async function openConsoleWith(id: string, text: string): Promise<void> {
|
||||
let path: string;
|
||||
|
||||
@@ -346,6 +346,9 @@ export function registerDatabaseTreeActions(): () => void {
|
||||
if (!n) return;
|
||||
const id = nodeTarget(n);
|
||||
if (n.kind === "source" && id) return openDialog({ kind: "rename", id, object: null });
|
||||
const source = sourceById(id);
|
||||
if (n.kind === "database" && !n.current && !source?.readOnly && createsDatabases(source))
|
||||
return openDialog({ kind: "renameDatabase", id: splitTarget(n.id).id, database: n.name });
|
||||
const o = objectOf(n);
|
||||
if (id && o && canRename(driverOf(id), o)) openDialog({ kind: "rename", id, object: o });
|
||||
},
|
||||
|
||||
@@ -178,6 +178,7 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
|
||||
{ label: "Copy/Paste", submenu: [copyRef] },
|
||||
refresh,
|
||||
act("db.disconnect", n, { disabled: !useDatabase.getState().connected.has(id) || n.current }),
|
||||
...(createsDatabases(sourceById(id)) ? [sep, act("db.rename", n, { disabled: n.current || readOnly })] : []),
|
||||
sep,
|
||||
navigation(),
|
||||
sqlScripts(n, false),
|
||||
@@ -191,7 +192,7 @@ export function nodeMenu(n: DbNode | null): MenuItem[] {
|
||||
...(n.kind === "schema" ? [{ label: "Copy/Paste", submenu: [copyRef] }] : []),
|
||||
refresh,
|
||||
sep,
|
||||
...(n.kind === "schema" ? [quickDoc] : []),
|
||||
...(n.kind === "schema" ? [rename, sep, quickDoc] : []),
|
||||
navigation(),
|
||||
sep,
|
||||
sqlScripts(n, false),
|
||||
|
||||
@@ -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"g<h>i|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"g<h>i|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");
|
||||
});
|
||||
});
|
||||
@@ -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 - <configuration>.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<string | null>(null);
|
||||
const [destination, setDestination] = useState<Destination>(() => ({
|
||||
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<ExportOptions>) => {
|
||||
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" },
|
||||
]}
|
||||
>
|
||||
<div className={styles.dialogBody}>
|
||||
<div className={styles.exportFormats} role="radiogroup" aria-label="Export format">
|
||||
<span>
|
||||
<div className={styles.exportReport}>
|
||||
<fieldset className={styles.exportFormats} role="radiogroup">
|
||||
<legend>
|
||||
<T>Export format:</T>
|
||||
</span>
|
||||
</legend>
|
||||
<Radio name="test-export-format" label="HTML" checked={html} onChange={() => update({ format: "html" })} />
|
||||
<Radio name="test-export-format" label="XML" checked={!html} onChange={() => update({ format: "xml" })} />
|
||||
</div>
|
||||
<label className={styles.exportField}>
|
||||
<span>
|
||||
<T>Output file:</T>
|
||||
</span>
|
||||
</fieldset>
|
||||
<fieldset className={styles.exportOutput}>
|
||||
<legend>
|
||||
<T>Output</T>
|
||||
</legend>
|
||||
<label htmlFor={fileNameId}>
|
||||
<T>File name</T>
|
||||
</label>
|
||||
<Input
|
||||
id={fileNameId}
|
||||
autoSelect
|
||||
data-autofocus=""
|
||||
value={fileName}
|
||||
onChange={(e) => setDestination({ folder, fileName: e.target.value })}
|
||||
/>
|
||||
<label htmlFor={folderId}>
|
||||
<T>Folder</T>
|
||||
</label>
|
||||
<div className={styles.inputWithButton}>
|
||||
<Input mono aria-label="Output file" value={path} onChange={(e) => setPath(e.target.value)} />
|
||||
<Input
|
||||
id={folderId}
|
||||
value={folder}
|
||||
onChange={(e) => setDestination({ folder: e.target.value, fileName })}
|
||||
/>
|
||||
<IconButton icon="folder" title="Browse…" onClick={() => void browse()} />
|
||||
</div>
|
||||
</label>
|
||||
</fieldset>
|
||||
<Checkbox
|
||||
checked={html && options.openInBrowser}
|
||||
disabled={!html}
|
||||
|
||||
@@ -1134,18 +1134,48 @@
|
||||
gap: var(--space-2);
|
||||
padding: 12px 16px;
|
||||
}
|
||||
.exportFormats {
|
||||
.exportReport {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-4);
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-3) var(--space-4) var(--space-1);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
.exportField {
|
||||
|
||||
.exportFormats,
|
||||
.exportOutput {
|
||||
min-inline-size: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.exportReport legend {
|
||||
margin-block-end: var(--space-2);
|
||||
padding: 0;
|
||||
color: var(--fg-strong);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.exportFormats {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
justify-items: start;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.exportOutput {
|
||||
display: grid;
|
||||
grid-template-columns: max-content minmax(0, 1fr);
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.exportOutput > label {
|
||||
max-inline-size: 120px;
|
||||
overflow-wrap: anywhere;
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
/* Folded console lines ("<N internal lines>"). */
|
||||
.fold {
|
||||
color: var(--fg-fold-placeholder);
|
||||
|
||||
@@ -375,7 +375,8 @@ describe("Export Test Results", () => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
||||
act(() => testTree.exportResults!());
|
||||
expect(screen.getByRole("dialog", { name: "Export Test Results" })).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Output file")).toHaveValue("/p/Test Results - calc tests.html");
|
||||
expect(screen.getByLabelText("File name")).toHaveValue("Test Results - calc tests.html");
|
||||
expect(screen.getByLabelText("Folder")).toHaveValue("/p");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
||||
expect(screen.queryByRole("dialog", { name: "Export Test Results" })).toBeNull();
|
||||
unmount();
|
||||
|
||||
@@ -1485,6 +1485,7 @@
|
||||
"Installed: {0} · No newer npm release.": "Installed: {0} · No newer npm release.",
|
||||
"Installed: {0}. Use your installer to manage this release channel.": "Installed: {0}. Use your installer to manage this release channel.",
|
||||
"npm scripts": "npm scripts",
|
||||
"database": "database",
|
||||
"npm could not complete the operation ({0}).": "npm could not complete the operation ({0}).",
|
||||
"An update for this agent is already running.": "An update for this agent is already running.",
|
||||
"This is not a global npm install OpenIDEA can update. Use its original installer.": "This is not a global npm install OpenIDEA can update. Use its original installer.",
|
||||
|
||||
@@ -5561,6 +5561,7 @@
|
||||
"trigger": "触发器",
|
||||
"sequence": "序列",
|
||||
"data source": "数据源",
|
||||
"database": "数据库",
|
||||
"{count} library frames hidden": "已隐藏 {count} 个库帧",
|
||||
"unverified": "未验证",
|
||||
"temp": "临时",
|
||||
|
||||
Reference in new issue
Заблокувати користувача