Compare commits

..
Author SHA1 Message Date
l0ng-ai 0d3c8d0061 Merge remote-tracking branch 'origin/main' into fix/run-anything-layout
# Conflicts:
#	src/features/run-anything/RunAnything.tsx
2026-11-20 03:26:59 +08:00
l0ng-ai ad3a968713 chore(run): remove replaced Run Anything text from catalogs 2026-11-20 01:33:29 +08:00
l0ng-ai 83ecbc7b1c fix(run): keep Run Anything controls visible on short windows 2026-11-20 01:30:46 +08:00
77 changed files with 787 additions and 2641 deletions

No files matched your search

+1 -1
View File
@@ -29,7 +29,7 @@ Conventions:
| ---------- | --------------------------------------- | --------------------------------------------------------------------------------------- |
| oxfmt | `pnpm format` (CI: `pnpm format:check`) | `.oxfmtrc.json`: print width 120, double quotes, semicolons, trailing commas everywhere |
| oxlint | `pnpm lint` | `.oxlintrc.json`: TypeScript and React plugins |
| Type check | `pnpm typecheck` | `tsconfig.json` and the configs of `e2e/`, `evals/`, `perf/`, `scripts/`, `smoke/` |
| Type check | `pnpm typecheck` | `tsconfig.json` and the configs of `perf/`, `scripts/`, `smoke/` |
| knip | `pnpm knip` | `knip.ts`: unused files, exports and dependencies |
`pnpm knip` fails on an export nobody imports, a file nobody reaches or a dependency nobody uses. Delete dead code rather than suppressing it; exports used only inside their own file are allowed.
+6 -6
View File
@@ -25,12 +25,12 @@ description: "Rust 与 TypeScript 的格式化、lint 和死代码检查,以
## TypeScript 与 React
| 工具 | 命令 | 配置 |
| -------- | ---------------------------------------- | --------------------------------------------------------------------------- |
| oxfmt | `pnpm format`(CI:`pnpm format:check`) | `.oxfmtrc.json`:行宽 120、双引号、处处尾逗号 |
| oxlint | `pnpm lint` | `.oxlintrc.json`:TypeScript 和 React 插件 |
| 类型检查 | `pnpm typecheck` | `tsconfig.json` 以及 `e2e/`、`evals/`、`perf/`、`scripts/`、`smoke/` 的配置 |
| knip | `pnpm knip` | `knip.ts`:未使用的文件、导出和依赖 |
| 工具 | 命令 | 配置 |
| -------- | ---------------------------------------- | --------------------------------------------------------- |
| oxfmt | `pnpm format`(CI:`pnpm format:check`) | `.oxfmtrc.json`:行宽 120、双引号、分号、处处尾逗号 |
| oxlint | `pnpm lint` | `.oxlintrc.json`:TypeScript 和 React 插件 |
| 类型检查 | `pnpm typecheck` | `tsconfig.json` 以及 `perf/`、`scripts/`、`smoke/` 的配置 |
| knip | `pnpm knip` | `knip.ts`:未使用的文件、导出和依赖 |
`pnpm knip` 发现没人 import 的导出、没人引用的文件或没人用的依赖时会失败。请删掉死代码,而不是屏蔽检查;只在本文件内使用的导出是允许的。
+1 -1
View File
@@ -26,7 +26,7 @@ const firstTask: AgentTask = {
const secondTask: AgentTask = { ...firstTask, id: "focus-second", title: "Second focus task" };
const draft = "draft keep this unsent";
const reboundShortcut = "Control+Meta+Shift+J";
const subagent: Extract<AgentEntry, { type: "subagent" }> = {
const subagent: AgentEntry = {
type: "subagent",
id: "focus-child",
title: "Inspect focus behavior",
+1 -1
View File
@@ -149,7 +149,7 @@ test("opens slash-prefixed Windows Markdown links with preview content and hover
for (const [label, path, heading] of [
["Specification", spec, "Windows specification"],
["Work skill", skill, "Work specification skill"],
] as const) {
]) {
const link = reply.getByRole("link", { name: label, exact: true });
await link.hover();
await expect(link).toHaveAttribute("title", path);
+7 -7
View File
@@ -1,7 +1,5 @@
import { expect, test } from "./fixtures";
import type { AgentQuestion, AgentTask } from "../src/bindings";
import type * as AgentStore from "../src/features/agents/store";
import type * as Ipc from "../src/platform/ipc";
const task: AgentTask = {
id: "questions",
@@ -51,12 +49,14 @@ for (const status of ["running", "ready"] as const) {
const key = JSON.stringify(["request_user_input_async", "call-1", 0]);
await page.evaluate(
async ({ task, status, key }) => {
// Keep the workbench imports in the browser's Vite realm.
const storePath = "/src/features/agents/store.ts";
const ipcPath = "/src/platform/ipc.ts";
const store: typeof AgentStore = await import(storePath);
const { commands }: typeof Ipc = await import(ipcPath);
commands.agentAnswerQuestion = async (id, question, answer) => {
const store = await import(storePath);
(await import(ipcPath)).commands.agentAnswerQuestion = async (
id: string,
question: string,
answer: string | null,
) => {
document.documentElement.dataset.asyncAnswer = JSON.stringify({ id, question, answer });
const entries = store.useAgents.getState().entries.get(id)!;
store.useAgents.setState({
@@ -111,7 +111,7 @@ for (const status of ["running", "ready"] as const) {
if (status === "running") {
await page.evaluate(async (id) => {
const storePath = "/src/features/agents/store.ts";
const { useAgents }: typeof AgentStore = await import(storePath);
const { useAgents } = await import(storePath);
useAgents.setState((s) => ({ tasks: new Map(s.tasks).set(id, { ...s.tasks.get(id)!, status: "ready" }) }));
}, task.id);
await expect(card.getByRole("radio", { name: /^Read latest content/ })).toBeChecked();
+4 -7
View File
@@ -1,4 +1,3 @@
import type * as ProjectStore from "../src/platform/project";
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
test.use({ video: "on" });
@@ -115,11 +114,9 @@ test("restricting an attached folder leaves the current project untouched", asyn
test("restricted attachments can be trusted individually from the banner", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
// Load the running workbench's store in the browser.
const projectPath = "/src/platform/project.ts";
const { useProject }: typeof ProjectStore = await import(/* @vite-ignore */ projectPath);
const m = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ m);
const primary = useProject.getState().project;
if (!primary) throw new Error("Expected the sample project to be open");
let current = {
...primary,
trusted: false,
@@ -129,11 +126,11 @@ test("restricted attachments can be trusted individually from the banner", async
const trusted = new Set([primary.root]);
window.__ipc.handlers.project_trust_status = ({ path }) => ({
root: path,
trusted: typeof path === "string" && trusted.has(path),
trusted: trusted.has(path),
decided: true,
});
window.__ipc.handlers.project_trust_set = ({ path, trusted: allow }) => {
if (allow && typeof path === "string") trusted.add(path);
if (allow) trusted.add(path);
current = { ...current, trusted: current.workspace.projects.every((path) => trusted.has(path)) };
};
window.__ipc.handlers.project_current = () => current;
+1 -76
View File
@@ -559,82 +559,7 @@ test("indexed single-file rename previews all anchors and applies only after con
}
await expect.poll(() => ipcCalls(page, "apply_workspace_edit")).toHaveLength(1);
const [apply] = await ipcCalls(page, "apply_workspace_edit");
expect(apply?.edit).toMatchObject({ preconditions: [{ path: FILE, hash: "indexed-snapshot" }] });
});
test("rename keeps the typed name, uses the editor font and shows long preview names in a narrow dialog", async ({
workbench: page,
}) => {
const editor = await openSample(page);
await page.evaluate(
async ({ file, prepared }) => {
const projectModule = "/src/platform/project.ts";
const schemaModule = "/src/features/settings/model/schema.ts";
const [{ useProject }, { DEFAULT_SETTINGS }] = await Promise.all([
import(/* @vite-ignore */ projectModule),
import(/* @vite-ignore */ schemaModule),
]);
const base = useProject.getState().settings ?? DEFAULT_SETTINGS;
useProject.setState({ settings: { ...base, editor: { ...base.editor, fontSize: 17 } } });
window.__ipc.handlers.lsp_prepare_rename = () => prepared;
window.__ipc.handlers.lsp_rename = (args) => ({
preview: true,
incomplete: null,
edit: {
files: [
{
kind: "edit",
path: file,
edits: [{ range: prepared, new_text: args.newName }],
},
],
},
});
window.__ipc.handlers.apply_workspace_edit = () => null;
},
{ file: FILE, prepared: range(20, 12, 17) },
);
await caretAt(editor, page, "val order: Order", "order");
await page.keyboard.press("Shift+F6");
await expect(page.getByText(/Press ⇧F6 to show dialog/)).toBeVisible();
const name = "checkoutOrderWithDeliveryInstructionsAndInventoryReservation";
await page.keyboard.insertText(name);
await page.keyboard.press("Shift+F6");
await page.setViewportSize({ width: 440, height: 520 });
const dialog = page.getByRole("dialog", { name: "Rename 'order'", exact: true });
const input = dialog.getByRole("textbox", { name: "New name" });
await expect(input).toBeFocused();
await expect(input).toHaveValue(name);
await expect(input).toHaveCSS("font-size", "17px");
const [label, field] = await Promise.all([
dialog.getByText("New name", { exact: true }).boundingBox(),
input.boundingBox(),
]);
expect(label!.x + label!.width).toBeLessThan(field!.x);
const rename = dialog.getByRole("button", { name: "Rename", exact: true });
await input.fill("");
await expect(rename).toBeDisabled();
await input.press("Enter");
await expect(dialog).toBeVisible();
expect(await ipcCalls(page, "lsp_rename")).toHaveLength(0);
await input.fill(name);
await input.press("Enter");
const summary = `Rename 'order' to '${name}'`;
const preview = page.getByRole("dialog", { name: summary, exact: true });
const context = preview.getByText(summary, { exact: true });
await expect(context).toBeVisible();
const geometry = await context.evaluate((element) => ({
client: element.clientWidth,
content: element.scrollWidth,
}));
expect(geometry.content).toBeLessThanOrEqual(geometry.client + 1);
await expect(preview.getByText("1 occurrence in 1 file")).toBeVisible();
expect(await ipcCalls(page, "apply_workspace_edit")).toHaveLength(0);
await preview.getByRole("button", { name: "Do Refactor" }).click();
await expect.poll(() => ipcCalls(page, "apply_workspace_edit")).toHaveLength(1);
expect(apply.edit).toMatchObject({ preconditions: [{ path: FILE, hash: "indexed-snapshot" }] });
});
test("intention previews fit narrow windows and wrap long code lines", async ({ workbench: page }) => {
+2 -2
View File
@@ -6,7 +6,7 @@ for (const [id, selector] of [
["keymap", "[class*='presetLabel']"],
["editor.inspections", "[class*='profileRow'] > span:first-child"],
["vcs.issueNavigation", "[class*='pageBody'] button:not([aria-label])"],
] as const) {
]) {
test(`${id} keeps compact labels inside their controls`, async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog");
@@ -41,7 +41,7 @@ for (const [id, selector] of [
for (const [id, selector] of [
["general", "[class*='fontRow'] > label"],
["build.console", "[class*='inlineRow'] > label"],
] as const) {
]) {
test(`${id} keeps a readable width for inline text`, async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
await expect(page.getByRole("dialog", { name: "Settings", exact: true })).toBeVisible();
+1 -1
View File
@@ -49,7 +49,7 @@ commands.lspHover = async () => {
};
commands.lspDocumentLinks = async () => ({ status: "ok", data: [] });
commands.lspDocumentHighlights = async () => ({ status: "ok", data: [] });
commands.cancelRequest = async () => {};
commands.cancelRequest = async () => ({ status: "ok", data: null });
const java = new EditorView({
parent: javaHost,
state: EditorState.create({
+1 -1
View File
@@ -10,7 +10,7 @@ test("data source tabs share a stable layout and scroll within a short window",
const dialog = page.getByRole("dialog", { name: "New Data Source" });
const panel = dialog.getByRole("tabpanel");
const dialogSize = () => dialog.evaluate((element: HTMLElement) => [element.offsetWidth, element.offsetHeight]);
const dialogSize = () => dialog.evaluate((element) => [element.offsetWidth, element.offsetHeight]);
await expect(panel.getByRole("textbox", { name: "Host:" })).toBeVisible();
const size = await dialogSize();
await dialog.getByRole("tab", { name: "SSH/SSL" }).click();
+1 -1
View File
@@ -187,7 +187,7 @@ test("result context menu fits the viewport, responds to hover and keyboard, and
for (const [theme, label] of [
["solarized-light", "Solarized Light"],
["solarized-dark", "Solarized Dark"],
] as const) {
]) {
test(`${label}: retains the inactive context-menu target's hover until dismissal without selecting it`, async ({
workbench: page,
}, info) => {
-57
View File
@@ -113,60 +113,3 @@ test("stops at a breakpoint, shows frames and variables, steps and resumes", asy
await expect.poll(() => ipcCalls(page, "debug_resume")).toHaveLength(1);
await expect(debug.getByText("CreateOrderRequest(sku='A-1', qty=2)")).toBeHidden();
});
test("Evaluate keeps a multiline expression and its result visible in a short dialog", async ({ workbench: page }) => {
await page.setViewportSize({ width: 580, height: 420 });
await stubDesktop(page);
await page.evaluate(async (session) => {
const handlers = window.__ipc.handlers;
handlers.debug_capabilities = () => ({});
handlers.debug_completions = () => [];
handlers.debug_evaluate_in = () => ({
name: "orderSummary",
typeName: "OrderSummary",
value: "total = 36",
variablesReference: 210,
evaluateName: null,
});
handlers.debug_variables = () => [
{ name: "tax", value: "4", typeName: "int", variablesReference: 0, evaluateName: null },
];
const stateModule = "/src/features/debugger/state.ts";
const { adoptSession } = await import(/* @vite-ignore */ stateModule);
adoptSession(session, { name: "Checkout", adapter: "debugpy", status: "paused", selectedFrame: 11 });
}, SESSION);
await page.keyboard.press("Alt+F8");
const dialog = page.getByRole("dialog", { name: "Evaluate expression" });
const field = dialog.getByRole("textbox", { name: "Expression" });
const expression = ["orderSummary(", ...Array.from({ length: 12 }, (_, i) => ` item${i},`), ")"].join("\n");
await field.fill(expression);
await field.press("Enter");
const result = dialog.getByRole("tree", { name: "Evaluation result" });
const row = result.getByRole("treeitem").first();
await expect(row).toContainText("total = 36");
await expect
.poll(() =>
dialog.locator("[data-dialog-body]").evaluate((body) => {
const area = body.querySelector("textarea")!;
const resultRow = body.querySelector('[role="treeitem"]')!.getBoundingClientRect();
const bounds = body.getBoundingClientRect();
return (
body.scrollHeight <= body.clientHeight + 1 &&
area.scrollHeight > area.clientHeight &&
resultRow.top >= bounds.top &&
resultRow.bottom <= bounds.bottom
);
}),
)
.toBe(true);
await row.click();
await row.press("ArrowRight");
await expect(result.getByText("tax", { exact: true })).toBeVisible();
await field.fill("otherExpression");
await dialog.getByRole("button", { name: "History", exact: true }).click();
await page.getByRole("menuitem", { name: /orderSummary/ }).click();
await expect(field).toHaveValue(expression);
await expect(field).toBeFocused();
});
-63
View File
@@ -1,63 +0,0 @@
import { expect, stubDesktop, test } from "./fixtures";
const amountName = "regionalSettlementAmountFromExternalProcessorBeforeRounding";
const routingName = "settlementRoutingReferenceForCrossBorderReconciliation";
const routingValue = "'APR-2026 / eu-west / batch-701 / settlement complete'";
test("keeps values and their full-value action readable in a narrow debugger", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1220, height: 760 });
await stubDesktop(page);
await page.evaluate(
async ({ amountName, routingName, routingValue }) => {
const debugModule = "/src/features/debugger/state.ts";
const layoutModule = "/src/workbench/toolwindows/store.ts";
const servicesModule = "/src/workbench/contributions.ts";
const { adoptSession } = await import(/* @vite-ignore */ debugModule);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
const { toolWindowService } = await import(/* @vite-ignore */ servicesModule);
const h = window.__ipc.handlers;
h.debug_scopes = () => [{ name: "Locals", variablesReference: 100, expensive: false }];
h.debug_variables = () => [
{ name: amountName, value: "47.74", typeName: "float", variablesReference: 0, evaluateName: amountName },
{ name: routingName, value: routingValue, typeName: "str", variablesReference: 0, evaluateName: routingName },
];
adoptSession(91, {
name: "Checkout",
adapter: "debugpy",
status: "paused",
selectedFrame: 11,
frames: [{ id: 11, name: "checkout", path: null, line: 0, column: 0, presentationHint: null }],
});
moveToolWindow("debug", "right");
setToolWindowSize("right", 390);
toolWindowService().show("debug", true);
},
{ amountName, routingName, routingValue },
);
const debug = page.getByRole("region", { name: "Debug", exact: true });
await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click();
const amount = debug.getByText("47.74", { exact: true });
await expect
.poll(() => amount.evaluate((el) => el.clientWidth > 0 && el.scrollWidth <= el.clientWidth + 1))
.toBe(true);
const routing = debug.getByRole("treeitem").filter({ hasText: routingName });
const show = routing.getByTitle("Show", { exact: true });
await expect(show).toBeInViewport({ ratio: 1 });
await show.click();
const dialog = page.getByRole("dialog", { name: `Value of ${routingName}` });
await expect(dialog.getByText(routingValue, { exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await expect(dialog).toBeHidden();
await page.setViewportSize({ width: 1640, height: 760 });
await page.evaluate(async () => {
const layoutModule = "/src/workbench/toolwindows/store.ts";
const { moveToolWindow } = await import(/* @vite-ignore */ layoutModule);
moveToolWindow("debug", "bottom");
});
await expect(show).toBeHidden();
await expect
.poll(() => routing.getByText(routingValue, { exact: true }).evaluate((el) => el.scrollWidth <= el.clientWidth + 1))
.toBe(true);
});
-54
View File
@@ -232,48 +232,6 @@ test("⌘R replaces every match in the file", async ({ workbench: page }) => {
await expect(editor.locator(".cm-line", { hasText: "OrderDto" })).toHaveCount(2);
});
test("the inline find and replace controls stay inside a narrow editor pane", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 760 });
const editor = await openFromTree(page, "build.gradle.kts");
await editor.locator(".cm-content").click();
await page.keyboard.press("Meta+r");
const bar = page.getByRole("search", { name: "Replace in file" });
const find = bar.getByRole("textbox", { name: "Find" });
const replace = bar.getByRole("textbox", { name: "Replace" });
const next = bar.getByRole("button", { name: /Next Occurrence/ });
await find.fill("OrderDto");
await find.press("Tab");
await expect(replace).toBeFocused();
await replace.fill("OrderView");
const navigationIsBelowFind = async () => {
const [input, button] = await Promise.all([find.boundingBox(), next.boundingBox()]);
return !!input && !!button && button.y >= input.y + input.height;
};
const controlsFit = () =>
bar.evaluate((panel) => {
const bounds = panel.getBoundingClientRect();
return [...panel.querySelectorAll("button, textarea")].every((element) => {
const control = element.getBoundingClientRect();
return control.width > 0 && control.left >= bounds.left && control.right <= bounds.right;
});
});
await expect.poll(navigationIsBelowFind).toBe(false);
await page.setViewportSize({ width: 590, height: 760 });
await expect.poll(controlsFit).toBe(true);
await expect.poll(navigationIsBelowFind).toBe(true);
await page.setViewportSize({ width: 495, height: 760 });
await expect.poll(controlsFit).toBe(true);
await expect(find).toHaveValue("OrderDto");
await expect(replace).toHaveValue("OrderView");
await next.click();
await expect(bar.getByText(/^[12]\/2$/)).toBeVisible();
await bar.getByRole("button", { name: "Replace All" }).click();
await expect(editor.locator(".cm-line", { hasText: "OrderView" })).toHaveCount(2);
await bar.getByRole("button", { name: "Close", exact: true }).click();
await expect(bar).toBeHidden();
});
test("Markdown preview highlights ⌘F matches, selected words and scales diagrams with font zoom", async ({
workbench: page,
}) => {
@@ -638,15 +596,3 @@ test("dragging the Markdown split divider resizes and reflows editor and preview
.poll(async () => Math.round((await reopenedEditor.boundingBox())!.width))
.toBe(Math.round(initialEditor));
});
test("Markdown Preview only leaves the Project view clickable", async ({ workbench: page }) => {
await openFromTree(page, "README.md");
await page.getByRole("button", { name: "Preview Only" }).click();
await expect(page.getByRole("document", { name: "Markdown preview" })).toBeVisible();
const row = page.getByRole("treeitem", { name: "build.gradle.kts", exact: true });
// A hidden editor panel used to leave an implicit resize region over everything left of the preview,
// which swallowed the click.
await row.click();
await expect(row).toHaveAttribute("aria-selected", "true");
});
+4 -3
View File
@@ -45,10 +45,11 @@ POST https://example.test/messages
const json = document.createElement("div");
json.id = "json";
document.body.append(json);
const jsonSupport = await loadSupport(findLanguageDescription("JSON", "body.json")!);
if (!jsonSupport) throw new Error("Failed to load JSON support for the highlighting fixture");
new EditorView({
parent: json,
doc: '{"name": "World", "count": 12, "enabled": true, "ready": false, "empty": null, "items": [1]}',
extensions: [jsonSupport, syntaxHighlighting(openideaHighlightStyle)],
extensions: [
await loadSupport(findLanguageDescription("JSON", "body.json")!),
syntaxHighlighting(openideaHighlightStyle),
],
});
+4 -7
View File
@@ -1,5 +1,4 @@
import { readFileSync } from "node:fs";
import type * as EditorBackend from "../src/editor/core/backend";
import { expect, test } from "./fixtures";
const xml = readFileSync(
@@ -11,14 +10,13 @@ test("imported PHP colours stay separate from Java and preserve regular text on
workbench: page,
}, info) => {
await page.evaluate(async (xml) => {
// Load the workbench modules in the browser's Vite realm.
const iclsPath = "/src/platform/icls.ts";
const projectPath = "/src/platform/project.ts";
const backendPath = "/src/editor/core/backend.ts";
const contributionsPath = "/src/workbench/contributions.ts";
const { parseIcls } = await import(iclsPath);
const { useProject } = await import(projectPath);
const { docBackend }: typeof EditorBackend = await import(backendPath);
const { docBackend } = await import(backendPath);
const { editorService } = await import(contributionsPath);
const previous = useProject.getState().settings ?? {};
useProject.setState({
@@ -33,11 +31,10 @@ test("imported PHP colours stay separate from Java and preserve regular text on
},
});
const backend = docBackend();
if (!("files" in backend) || !(backend.files instanceof Map)) throw new Error("Expected the in-memory backend");
const open = backend.open.bind(backend);
backend.open = async (path) => {
const result = await open(path);
return path.endsWith(".php") ? { ...result, language: "php", uiMode: "PHP" } : result;
backend.open = async (...args: Parameters<typeof open>) => {
const result = await open(...args);
return args[0].endsWith(".php") ? { ...result, language: "php", uiMode: "PHP" } : result;
};
backend.files.set(
"/dev/acme-api/palette.php",
+1 -2
View File
@@ -1,6 +1,5 @@
import { EditorView } from "@codemirror/view";
import type { InlayHint, Range } from "../src/bindings";
import { commands } from "../src/platform/ipc";
import { commands, type InlayHint, type Range } from "../src/platform/ipc";
import { setInvokeRoute } from "../src/platform/tauriCore";
import { lspDoc } from "../src/editor/lsp/lsp";
import { inlayExtension } from "../src/editor/lsp/inlay";
+11 -16
View File
@@ -1,4 +1,3 @@
import type { DataSource_Deserialize, DbJdbcDriver } from "../src/bindings";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("configures a local JDBC profile and a source through mocked IPC", async ({ workbench: page }, info) => {
@@ -103,25 +102,21 @@ test("configures a local JDBC profile and a source through mocked IPC", async ({
await source.getByLabel("Property value", { exact: true }).fill("true");
await test.click();
await expect(source.getByRole("status")).toHaveText("Succeeded: Mock JDBC database");
const [tested] = await ipcCalls(page, "db_test");
const [{ source: tested, password }] = await ipcCalls(page, "db_test");
expect(password).toBe("mock secret");
expect(tested).toMatchObject({
password: "mock secret",
source: {
driver: "jdbc",
url,
user: "example-user",
readOnly: true,
properties: [{ name: "ssl", value: "true" }],
},
driver: "jdbc",
url,
user: "example-user",
readOnly: true,
properties: [{ name: "ssl", value: "true" }],
});
await source.getByRole("button", { name: "OK", exact: true }).click();
await expect(source).not.toBeVisible();
const [save] = await ipcCalls(page, "db_save_sources");
const saved = (save?.sources as DataSource_Deserialize[] | undefined)?.[0];
const [profile] = await ipcCalls(page, "db_save_jdbc_driver");
const driver = profile?.driver as DbJdbcDriver | undefined;
if (!saved || !driver) throw new Error("Expected the JDBC source and driver to be saved");
const [{ sources }] = await ipcCalls(page, "db_save_sources");
const [saved] = sources as Record<string, unknown>[];
const [{ driver }] = await ipcCalls(page, "db_save_jdbc_driver");
expect(saved.readOnly).toBe(true);
expect(saved.jdbcDriver).toBe(driver.id);
expect(saved.jdbcDriver).toBe((driver as Record<string, unknown>).id);
for (const key of ["jars", "className", "classpath", "exec", "password"]) expect(saved).not.toHaveProperty(key);
});
+3 -3
View File
@@ -1,5 +1,5 @@
/** Linked Gradle builds use isolated native stubs; no real builds or files are touched. */
import type { GradleModel, RunConfig_Deserialize } from "../src/bindings";
import type { GradleModel, RunConfig } from "../src/platform/ipc";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const build = (dir: string): GradleModel => ({
@@ -46,7 +46,7 @@ test("links independent Gradle roots, runs identical task paths in their own bui
};
h["plugin:dialog|open"] = () => ["/dev/acme-api/second/settings.gradle"];
h.run_start = (args) => {
const config = args.config as RunConfig_Deserialize;
const config = args.config as RunConfig;
const id = ++runId;
setTimeout(() => window.__ipc.emit({ type: "runExited", run: id, code: 0 }), 50);
return { id, configId: config.id, name: config.name, pid: 4242 + id, running: true, pty: false };
@@ -89,7 +89,7 @@ test("links independent Gradle roots, runs identical task paths in their own bui
await expect.poll(async () => (await ipcCalls(page, "run_start")).length).toBe(1);
await tasks.nth(1).dblclick();
await expect.poll(async () => (await ipcCalls(page, "run_start")).length).toBe(2);
const runs = (await ipcCalls(page, "run_start")).map((args) => args.config as RunConfig_Deserialize);
const runs = (await ipcCalls(page, "run_start")).map((args) => args.config as RunConfig);
expect(runs[0]!.id).not.toBe(runs[1]!.id);
for (const [index, dir] of ["first", "second"].entries()) {
expect(runs[index]).toMatchObject({
-38
View File
@@ -63,44 +63,6 @@ const result = (page: Page) => page.getByRole("region", { name: "Result" });
const text = async (pane: Locator) => (await pane.locator(".cm-content").innerText()).replace(/​/g, "");
const status = (page: Page) => page.locator("#merge-host [class*=status]").first();
test("merge controls and pane titles fit while resizing the result", async ({ page }) => {
await page.setViewportSize({ width: 400, height: 600 });
await mountMerge(page);
const host = page.locator("#merge-host");
for (const name of ["Accept Yours", "Accept Theirs", "Cancel", "Apply"])
await expect(host.getByRole("button", { name, exact: true })).toBeInViewport({ ratio: 1 });
await expect(status(page)).toHaveText("3 changes left, 2 conflicts");
await expect(status(page)).toBeInViewport({ ratio: 1 });
const ours = page.getByRole("region", { name: "Your version" });
await expect(ours.getByText("Your version", { exact: true })).toBeVisible();
await expect(
page.getByRole("region", { name: "Their version" }).getByText("Their version", { exact: true }),
).toBeVisible();
await ours.locator(".cm-merge-accept").nth(1).focus();
await page.keyboard.press("Enter");
await expect.poll(() => text(result(page))).toContain("\nmine\n");
await page.setViewportSize({ width: 980, height: 660 });
const resultWidth = async () => (await result(page).boundingBox())!.width;
const initial = await resultWidth();
const left = host.getByRole("separator", { name: "Resize left merge pane" });
await left.press("ArrowLeft");
await expect.poll(resultWidth).toBeGreaterThan(initial + 1);
const right = host.getByRole("separator", { name: "Resize right merge pane" });
const grip = (await right.boundingBox())!;
const withLeftResized = await resultWidth();
await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2);
await page.mouse.down();
await page.mouse.move(grip.x + grip.width / 2 + 36, grip.y + grip.height / 2, { steps: 4 });
await page.mouse.up();
await expect.poll(resultWidth).toBeGreaterThan(withLeftResized + 20);
await expect(result(page).getByText("Result", { exact: true })).toBeVisible();
await expect(ours.getByText("Changes from main", { exact: true })).toBeVisible();
await expect.poll(() => text(result(page))).toContain("\nmine\n");
});
/** Capture the save boundary, keeping real editor state, dialogs and Apply behavior. */
async function captureWrites(page: Page) {
await page.evaluate(async () => {
-76
View File
@@ -1,76 +0,0 @@
import type { Page } from "@playwright/test";
import type { SignatureHelp } from "../src/bindings";
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
function signature(name: string, parameters: string[]) {
let offset = name.length + 1;
const ranges: [number, number][] = parameters.map((parameter) => {
const range: [number, number] = [offset, offset + parameter.length];
offset = range[1] + 2;
return range;
});
return { label: `${name}(${parameters.join(", ")}): Invoice`, parameters: ranges, documentation: null };
}
async function openParameterInfo(page: Page, help: SignatureHelp) {
const editor = await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate((help) => {
window.__ipc.handlers.lsp_signature_help = () => help;
}, help);
await editor.locator(".cm-line", { hasText: "return order.toDto()" }).click();
await page.keyboard.press("End");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("Meta+p");
const popup = page.locator(".cm-lsp-signature");
await expect(popup).toBeVisible();
return { editor, popup };
}
test("parameter info wraps long parameters and follows the editor width", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1120, height: 700 });
const parameter = "roundingPolicyForThirdPartyPaymentsWithMultipleSettlementCurrencies: RoundingPolicy";
const { editor, popup } = await openParameterInfo(page, {
signatures: [signature("formatInvoice", ["order: Cart", parameter, "currency: string"])],
activeSignature: 0,
activeParameter: 1,
});
await page.setViewportSize({ width: 560, height: 650 });
await expect
.poll(async () => {
const [pane, hint] = await Promise.all([editor.boundingBox(), popup.boundingBox()]);
return !!pane && !!hint && hint.x >= pane.x - 1 && hint.x + hint.width <= pane.x + pane.width + 1;
})
.toBe(true);
await expect.poll(() => popup.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(popup.locator("b")).toHaveText(parameter);
const fontSize = await editor.locator(".cm-content").evaluate((el) => getComputedStyle(el).fontSize);
await expect(popup).toHaveCSS("font-size", fontSize);
await page.keyboard.press("Escape");
await expect(popup).toBeHidden();
});
test("parameter info keeps the active overload visible and scrolls to the others", async ({ workbench: page }) => {
const signatures = Array.from({ length: 20 }, (_, i) =>
signature("formatInvoice", [`order: Cart${i}`, "currency: string"]),
);
const { popup } = await openParameterInfo(page, { signatures, activeSignature: 16, activeParameter: 1 });
await expect(popup.locator(".cm-lsp-signature-row")).toHaveCount(signatures.length);
const active = popup.locator(".cm-lsp-signature-active b");
await expect(active).toHaveText("currency: string");
await expect
.poll(async () => {
const [frame, parameter] = await Promise.all([popup.boundingBox(), active.boundingBox()]);
return (
!!frame && !!parameter && parameter.y >= frame.y && parameter.y + parameter.height <= frame.y + frame.height
);
})
.toBe(true);
expect(await popup.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
await popup.hover();
await page.mouse.wheel(0, -1200);
await expect.poll(() => popup.evaluate((el) => el.scrollTop)).toBe(0);
await expect(
popup.getByText("formatInvoice(order: Cart0, currency: string): Invoice", { exact: true }),
).toBeInViewport();
});
+42 -120
View File
@@ -9,75 +9,50 @@ import { expect, stubDesktop, test } from "./fixtures";
const ROOT = "/dev/acme-api";
const HUGE = `feature/wrap-${"x".repeat(140)}`;
const OUTGOING = "Apply order-level discounts before calculating checkout taxes";
async function openPushDialog(page: Page, { outgoing = false, multi = false } = {}) {
async function openPushDialog(page: Page) {
await stubDesktop(page);
await page.evaluate(
async ({ root, outgoing, multi, subject }) => {
const h = window.__ipc.handlers;
const head = multi ? "feature/refine-checkout-pricing-and-order-summary-for-regional-release" : "main";
const roots = multi ? [root, `${root}/billing-and-refunds`] : [root];
h.vcs_roots = () => roots.map((root) => ({ root, operation: null, head, headCommit: "1111111" }));
h.vcs_branch_info = () => ({
head,
headCommit: "1111111",
upstream: `origin/${head}`,
ahead: outgoing ? 1 : 0,
behind: 0,
operation: null,
});
h.vcs_status = () => [];
h.vcs_log = () =>
outgoing
? [
{
id: "2222222",
shortId: "2222222",
parents: ["1111111"],
summary: subject,
message: subject + "\n\nKeep the new totals consistent with receipts.",
author: "Sam Rivera",
email: "[email protected]",
timeMs: 1795100000000,
},
]
: [];
h.vcs_commit_files = () => [{ path: "checkout.ts", oldPath: null, kind: "modified" }];
h.vcs_has_hook = () => false;
h.vcs_remotes = () => [{ name: "origin", url: "[email protected]:acme/api.git" }];
const branch = (name: string, remote: boolean, upstream: string | null = null) => ({
name,
remote,
current: !remote,
upstream,
ahead: 0,
behind: 0,
lastCommitMs: 0,
});
h.vcs_branches = () => [
branch("main", false, "origin/main"),
branch("feature/login", false),
branch("origin/main", true),
branch("origin/feature/login", true),
branch("origin/fix/error-auth", true),
branch("origin/feature/PLATFORM-12345-order-history-export", true),
branch(`origin/feature/wrap-${"x".repeat(140)}`, true),
];
const vcsModule = "/src/features/vcs/store.ts";
const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsModule);
useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false });
await refreshNow();
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
void executeAction("vcs.push");
},
{ root: ROOT, outgoing, multi, subject: OUTGOING },
);
await page.evaluate(async (root) => {
const h = window.__ipc.handlers;
h.vcs_roots = () => [{ root, operation: null, head: "main", headCommit: "1111111" }];
h.vcs_branch_info = () => ({
head: "main",
headCommit: "1111111",
upstream: "origin/main",
ahead: 0,
behind: 0,
operation: null,
});
h.vcs_status = () => [];
h.vcs_log = () => [];
h.vcs_remotes = () => [{ name: "origin", url: "[email protected]:acme/api.git" }];
const branch = (name: string, remote: boolean, upstream: string | null = null) => ({
name,
remote,
current: !remote,
upstream,
ahead: 0,
behind: 0,
lastCommitMs: 0,
});
h.vcs_branches = () => [
branch("main", false, "origin/main"),
branch("feature/login", false),
branch("origin/main", true),
branch("origin/feature/login", true),
branch("origin/fix/error-auth", true),
branch("origin/feature/PLATFORM-12345-order-history-export", true),
branch(`origin/feature/wrap-${"x".repeat(140)}`, true),
];
const vcsModule = "/src/features/vcs/store.ts";
const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsModule);
useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false });
await refreshNow();
const actionsModule = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
void executeAction("vcs.push");
}, ROOT);
const dialog = page.getByRole("dialog", { name: /Push/ });
const input = multi
? dialog.getByRole("textbox", { name: "Target branch of acme-api" })
: dialog.getByRole("combobox", { name: "Target branch" });
const input = dialog.getByRole("combobox", { name: "Target branch" });
await expect(input).toBeVisible();
return { dialog, input };
}
@@ -152,56 +127,3 @@ test("Escape closes the list but keeps the dialog", async ({ workbench: page })
await expect(page.getByRole("listbox", { name: "Remote branches" })).toHaveCount(0);
await expect(dialog).toBeVisible();
});
test("Push keeps commit subjects and changed files readable in a narrow window", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1140, height: 760 });
const { dialog, input } = await openPushDialog(page, { outgoing: true });
const outgoing = dialog.getByRole("listbox", { name: "Outgoing commits" });
const files = dialog.getByRole("tree", { name: "Changed files" });
const commit = outgoing.getByRole("option", { name: new RegExp(OUTGOING) });
await commit.click();
await expect(files.getByText("checkout.ts")).toBeVisible();
const filesBelowCommits = async () => {
const [list, tree] = await Promise.all([outgoing.boundingBox(), files.boundingBox()]);
return !!list && !!tree && tree.y >= list.y + list.height;
};
await expect.poll(filesBelowCommits).toBe(false);
await page.setViewportSize({ width: 540, height: 630 });
await expect.poll(filesBelowCommits).toBe(true);
await expect(commit).toHaveAttribute("aria-selected", "true");
const subject = commit.getByText(OUTGOING, { exact: true });
await expect(subject).toHaveAttribute("title", /Sam Rivera/);
await expect.poll(() => subject.evaluate((el) => el.scrollWidth <= el.clientWidth)).toBe(true);
await expect(input).toHaveValue("main");
await expect(dialog.getByRole("button", { name: "Push", exact: true })).toBeInViewport();
const details = dialog.getByRole("region", { name: "Commit details" });
await expect(details).toContainText("Keep the new totals consistent with receipts.");
await expect
.poll(async () => {
const [tree, message] = await Promise.all([files.boundingBox(), details.boundingBox()]);
return !!tree && !!message && message.y >= tree.y + tree.height;
})
.toBe(true);
});
test("Push keeps per-repository targets editable with long source branches", async ({ workbench: page }) => {
await page.setViewportSize({ width: 475, height: 620 });
const { dialog, input } = await openPushDialog(page, { outgoing: true, multi: true });
const other = dialog.getByRole("textbox", { name: "Target branch of billing-and-refunds" });
for (const field of [input, other]) {
await expect
.poll(() =>
field.evaluate((target) => {
const row = target.closest('[role="treeitem"]')!.getBoundingClientRect();
const bounds = target.getBoundingClientRect();
return bounds.width >= 42 && bounds.left >= row.left && bounds.right <= row.right;
}),
)
.toBe(true);
}
await input.fill("release/checkout");
await expect(input).toHaveValue("release/checkout");
await expect(other).toHaveValue(/^feature\//);
await expect(dialog.getByRole("checkbox", { name: "acme-api" })).toBeChecked();
});
+3 -76
View File
@@ -3,21 +3,15 @@
* the process. Processes are stubbed at the IPC layer; `crates/ide-run` covers spawning them.
*/
import type { Page } from "@playwright/test";
import type { RunConfig } from "../src/bindings";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const RUN_ID = 7;
/** One saved `npm run dev` configuration; `run_start` prints `output` and exits with `exit` unless null. */
async function stubRun(
page: Page,
output: { kind: string; text: string }[],
exit: number | null,
overrides: Partial<RunConfig> = {},
) {
async function stubRun(page: Page, output: { kind: string; text: string }[], exit: number | null) {
await stubDesktop(page);
await page.evaluate(
async ({ output, exit, runId, overrides }) => {
async ({ output, exit, runId }) => {
const config = {
id: "npm:dev",
name: "dev",
@@ -29,7 +23,6 @@ async function stubRun(
detected: false,
isTest: false,
debugAdapter: null,
...overrides,
};
const h = window.__ipc.handlers;
h.run_configs = () => [config];
@@ -50,7 +43,7 @@ async function stubRun(
await loadConfigs();
selectConfig(config.id);
},
{ output, exit, runId: RUN_ID, overrides },
{ output, exit, runId: RUN_ID },
);
}
@@ -184,72 +177,6 @@ test("Go reruns keep each package's exact failures and the original configuratio
]);
});
test("test results keep counts, actions and selected output visible as the pane narrows", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 1060, height: 740 });
const goPackage = "example.com/checkout";
const name = "TestCheckoutTotalsWithDiscountsAndPendingInventoryReservations";
const message = "expected subtotal 42, got 37";
const records = [
{ Action: "run", Test: name },
{ Action: "output", Test: name, Output: message + "\n" },
{ Action: "fail", Test: name, Elapsed: 0.125 },
{ Action: "pass", Test: "TestPayment", Elapsed: 0.02 },
{ Action: "skip", Test: "TestDelayedShipping" },
{ Action: "fail", Elapsed: 0.17 },
];
await stubRun(
page,
records.map((record) => ({ kind: "stdout", text: JSON.stringify({ Package: goPackage, ...record }) + "\n" })),
1,
{
id: "go:checkout-tests",
name: "Checkout tests",
kind: "go",
command: "go",
args: ["test", "-json"],
isTest: true,
},
);
await page.keyboard.press("Control+r");
const run = page.getByRole("region", { name: "Run", exact: true });
const tree = run.getByRole("tree", { name: "Test results" });
const row = tree.getByRole("treeitem", { name: new RegExp(name) });
await row.click();
const output = run.getByRole("log");
await expect(output).toContainText(message);
await expect.poll(async () => (await output.boundingBox())!.x > (await tree.boundingBox())!.x).toBe(true);
await page.setViewportSize({ width: 540, height: 740 });
await expect
.poll(async () => {
const [list, console] = await Promise.all([tree.boundingBox(), output.boundingBox()]);
return !!list && !!console && console.y >= list.y + list.height - 1;
})
.toBe(true);
const summary = run.getByRole("status").filter({ hasText: "1 failing" });
for (const count of ["1 failing", "1 passed", "1 ignored"]) await expect(summary.getByText(count)).toBeVisible();
await expect(row).toHaveAttribute("aria-selected", "true");
await expect(row.getByText("125 ms")).toBeVisible();
await expect(output).toContainText(message);
const toolbar = run.getByRole("toolbar", { name: "Test results" });
await toolbar.getByRole("button", { name: "More Actions" }).click();
await expect(page.getByRole("menuitem", { name: "Collapse All" })).toBeVisible();
await expect(page.getByRole("menuitem", { name: "Export Test Results…" })).toBeVisible();
await page.keyboard.press("Escape");
const divider = run.getByRole("separator");
const treeHeight = async () => (await tree.boundingBox())!.height;
const beforeResize = await treeHeight();
await divider.press("ArrowDown");
await expect.poll(treeHeight).toBeGreaterThan(beforeResize + 1);
const customizedHeight = await treeHeight();
await page.setViewportSize({ width: 1060, height: 740 });
await expect.poll(async () => (await output.boundingBox())!.x > (await tree.boundingBox())!.x).toBe(true);
await page.setViewportSize({ width: 540, height: 740 });
await expect.poll(async () => Math.abs((await treeHeight()) - customizedHeight)).toBeLessThan(2);
await expect(output).toContainText(message);
});
test("CMake builds the selected target in Build before starting only the application in Run", async ({
workbench: page,
}) => {
+4 -8
View File
@@ -1,4 +1,3 @@
import type { SearchQuery } from "../src/bindings";
import { doubleShift, expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
test("double Shift opens Search Everywhere with its tabs; Escape closes it", async ({ workbench: page }) => {
@@ -101,14 +100,11 @@ test("Find in Files streams matches by file and opens the chosen one at its line
await expect
.poll(
async () =>
(await ipcCalls(page, "search_start"))
.filter(({ query }) => {
const pattern = query && typeof query === "object" && "pattern" in query ? query.pattern : undefined;
return typeof pattern !== "string" || !/\bTODO\b/.test(pattern);
})
.at(-1)?.query,
(await ipcCalls(page, "search_start")).filter((c) => !/\bTODO\b/.test(c.query?.pattern ?? "")).at(-1)?.query,
)
.toMatchObject({ pattern: "OrderService" } satisfies Pick<SearchQuery, "pattern">);
.toMatchObject({
pattern: "OrderService",
});
const preview = dialog.getByRole("region", { name: "Preview", exact: true }).locator(".cm-content");
await expect(preview).toHaveAttribute("contenteditable", "true");
// Matches take the editor scheme's search result background (IDEA's SEARCH_RESULT_ATTRIBUTES) and keep the syntax colours.
+1 -1
View File
@@ -79,7 +79,7 @@ test.describe("search popups at the minimum window width", () => {
[400, 500],
[600, 700],
[1120, 750],
] as const) {
]) {
await page.setViewportSize({ width, height });
await expectControlsFit(page);
// Room enough for the title and the reporter's count: shown whole, on one line.
+2 -2
View File
@@ -9,9 +9,9 @@ test("semantic roles honor all Color Scheme attributes and keep modifier styles"
[".cm-sem-function:not(.cm-sem-static)", "rgb(102, 136, 170)"],
[".cm-sem-parameter", "rgb(119, 153, 187)"],
[".cm-sem-constant", "rgb(136, 170, 204)"],
] as const) {
]) {
const role = page.locator(selector);
await expect(role).toHaveCSS("color", color);
await expect(role).toHaveCSS("color", color!);
await expect(role).toHaveCSS("background-color", "rgb(221, 238, 255)");
}
await expect(page.locator(".cm-sem-namespace")).toHaveCSS("font-style", "italic");
+1 -1
View File
@@ -6,7 +6,7 @@ for (const [id, selector] of [
["languages.servers", "[class*='body'] > [class*='language'][aria-label]"],
["plugins", "[class*='body'] > [class*='details']"],
["agents.list", "section[aria-label='Codex']"],
] as const) {
]) {
test(`${id} keeps its details usable beside the list`, async ({ workbench: page }) => {
await page.keyboard.press("Meta+,");
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
+8 -4
View File
@@ -1,8 +1,12 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"lib": ["ES2024", "DOM", "DOM.Iterable"],
"types": ["node", "vite/client"]
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": [".", "../playwright.config.ts", "../src/**/*.d.ts"]
"include": ["./**/*.ts", "../playwright.config.ts"]
}
+1 -1
View File
@@ -17,7 +17,7 @@
"format": "oxfmt",
"format:check": "oxfmt --check",
"knip": "knip",
"typecheck": "tsrs --noEmit && tsrs -p tsconfig.node.json --noEmit && tsrs -p perf --noEmit && tsrs -p evals --noEmit && tsrs -p scripts --noEmit && tsrs -p smoke --noEmit && tsrs -p e2e --noEmit",
"typecheck": "tsrs --noEmit && tsrs -p tsconfig.node.json --noEmit && tsrs -p perf --noEmit && tsrs -p evals --noEmit && tsrs -p scripts --noEmit && tsrs -p smoke --noEmit",
"gen:bindings": "cargo test -p openidea --test export_bindings",
"gen:windows-icons": "node scripts/gen-windows-icons.ts",
"gen:angular-grammar": "lezer-generator src/editor/core/cm/angular/angular.grammar --typeScript -o src/editor/core/cm/angular/parser.ts",
+2 -2
View File
@@ -47,7 +47,7 @@ import { useDistractionFree } from "@/workbench/distractionFree";
import { restoreMaximizedToolWindow } from "@/workbench/toolwindows/store";
import { ask, confirm } from "@/workbench/messages";
import { t, tx } from "@/platform/i18n";
import { call, commands, isErrorKind, isTauri } from "@/platform/ipc";
import { call, commands, isTauri } from "@/platform/ipc";
import { openLightweightEditor } from "./openLightweightEditor";
import { windowBackgroundHex } from "@/workbench/theme";
import { hoverActionsAt } from "@/platform/hoverActions";
@@ -736,7 +736,7 @@ export class EditorController implements SlotHost {
return this.slots.get(tabId) ?? this.createSlot(tabId, m, init);
})
.catch((e: unknown) => {
if (this.restoredTabs.has(tabId) && isErrorKind(e, "notFound")) {
if (this.restoredTabs.has(tabId) && (e as { kind?: string } | null)?.kind === "notFound") {
// A file from the saved session no longer exists: drop its tab quietly.
this.restoredTabs.delete(tabId);
this.restoredViews.delete(path);
+2 -2
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import { ChangeSet, Text } from "@codemirror/state";
import type { IdeError, TextChange } from "@/platform/ipc";
import type { TextChange } from "@/platform/ipc";
import { DocSync, toTextChanges } from "./DocSync";
import { minimalChanges } from "./diff";
@@ -19,7 +19,7 @@ function numberedLines(count: number) {
}
class OutOfSync extends Error {
readonly kind: IdeError["kind"] = "outOfSync";
kind = "outOfSync";
}
/** Backend double: requests are queued and processed explicitly, in order. */
+6 -2
View File
@@ -25,7 +25,7 @@
* the snapshot, selections mapped).
*/
import { ChangeSet, Text } from "@codemirror/state";
import { isErrorKind, type TextChange } from "@/platform/ipc";
import type { TextChange } from "@/platform/ipc";
import { minimalChanges } from "./diff";
export interface SyncTransport {
@@ -64,6 +64,10 @@ export const frameScheduler: Scheduler = (fn) => {
setTimeout(once, 50);
};
function isOutOfSync(e: unknown): boolean {
return typeof e === "object" && e !== null && (e as { kind?: string }).kind === "outOfSync";
}
export function toTextChanges(cs: ChangeSet): TextChange[] {
const out: TextChange[] = [];
cs.iterChanges((fromA, toA, _fromB, _toB, inserted) => {
@@ -206,7 +210,7 @@ export class DocSync {
}
private onReject(error: unknown) {
if (!isErrorKind(error, "outOfSync")) {
if (!isOutOfSync(error)) {
this.host.onError?.(error);
this.hardResync(error);
return;
+25 -99
View File
@@ -151,126 +151,52 @@
}
/* Find / replace bar */
.findContainer {
.find {
flex: none;
min-width: 0;
container: editor-find / inline-size;
display: grid;
grid-template-columns: minmax(220px, 420px) auto 1fr;
align-items: center;
column-gap: var(--space-1-5);
row-gap: var(--space-1-5);
padding: 6px 8px 6px 10px;
background: var(--bg-editor-inline, var(--bg-elev));
border-bottom: 1px solid var(--border-editor-tabs, var(--border));
}
.find {
display: grid;
grid-template-columns: [mode] auto [field] minmax(0, 420px) [actions] fit-content(50%) [close] minmax(
min-content,
1fr
);
align-items: start;
row-gap: var(--space-1);
padding: var(--space-1-5) var(--space-2);
.findExpandable {
grid-template-columns: auto minmax(220px, 420px) auto 1fr;
}
.findExpand {
grid-area: 1 / mode;
margin-inline-end: var(--space-1);
grid-column: 1;
grid-row: 1;
}
.findExpandable .findField {
grid-column: 2;
}
.findField {
grid-area: 1 / field;
}
.replaceField {
grid-area: 2 / field;
}
.findField,
.replaceField {
min-width: 0;
}
.findClose {
grid-area: 1 / close;
justify-self: end;
margin-inline-start: var(--space-1);
}
.findExpand,
.findClose {
margin-block-start: var(--space-1);
}
.findButtons,
.replaceButtons {
display: flex;
flex-wrap: wrap;
align-items: center;
min-width: 0;
min-height: var(--h-field);
margin-inline-start: var(--space-1-5);
}
.findButtons {
grid-area: 1 / actions;
display: flex;
align-items: center;
gap: var(--space-0-5);
}
.replaceButtons {
grid-area: 2 / actions;
gap: var(--space-1);
}
.findCount {
min-inline-size: 5ch;
padding-inline: var(--space-1);
font-size: var(--fs-small);
font-variant-numeric: tabular-nums;
font-size: var(--fs-ui);
color: var(--fg-subtle);
padding: 0 8px 0 4px;
min-width: 56px;
white-space: nowrap;
}
.findCountNone {
color: var(--danger);
}
@container editor-find (width < 500px) {
.find {
grid-template-columns: [mode] auto [field] minmax(0, 1fr) [close] auto;
}
.findButtons,
.replaceButtons {
grid-column: field / -1;
min-height: 0;
margin-inline-start: 0;
}
.findButtons {
grid-row: 2;
}
.replaceField {
grid-row: 3;
}
.replaceButtons {
grid-row: 4;
}
.replaceButtons > button {
max-width: 100%;
height: auto;
min-height: var(--h-control);
white-space: normal;
overflow-wrap: anywhere;
}
.findClose {
justify-self: end;
}
@container editor-find (width < 224px) {
.findField,
.replaceField,
.replaceButtons {
grid-column: mode / -1;
}
.findExpand,
.findClose {
grid-row: 2;
margin-block-start: 0;
}
.findButtons {
grid-column: field;
}
.findInput {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(20px, 1fr));
height: auto;
padding-block: var(--space-1);
}
.findInput textarea {
grid-column: 2 / -1;
}
.replaceButtons {
display: flex;
align-items: center;
gap: var(--space-1-5);
}
/* Go to line */
+173 -176
View File
@@ -608,185 +608,182 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
const canReplace = !!opts.search && !invalid;
return (
<div className={styles.findContainer}>
<div
ref={panelRef}
onFocusCapture={() => {
focusedTarget = target;
setContext("findBarFocus", true);
setContext(
"findBarHasResults",
!!target.results && !!opts.search && (!opts.regexp || regexValid(opts.search)) && !!count?.total,
);
}}
onBlurCapture={(e) => {
if (!panelRef.current?.contains(e.relatedTarget as Node | null)) setContext("findBarFocus", false);
}}
className={styles.find}
role="search"
aria-label={replace ? "Replace in file" : "Find in file"}
>
{onReplaceShown && (
<IconButton
icon={replace ? "chevron-down" : "chevron-right"}
title={replace ? "Hide Replace" : "Show Replace"}
size="small"
className={styles.findExpand}
aria-expanded={replace}
onMouseDown={(e) => e.preventDefault()}
onClick={() => {
if (replaceBoxRef.current?.contains(document.activeElement)) inputRef.current?.focus();
onReplaceShown(!replace);
}}
/>
)}
<div ref={findBoxRef} className={styles.findField}>
<SearchField
ref={inputRef}
value={opts.search}
onChange={(search) => setOpts({ search })}
placeholder="Find"
aria-label="Find"
invalid={invalid || none}
multiline
onHistory={() => setHistoryMenu("find")}
onKeyDown={(e) => onKeyDown(e, "find")}
className={styles.findInput}
toggles={[
{
id: "case",
icon: "case",
title: "Match Case",
shortcut: formatBinding("Alt+C"),
pressed: opts.caseSensitive,
onToggle: () => toggle("caseSensitive"),
},
{
id: "word",
icon: "word",
title: "Words",
shortcut: formatBinding("Alt+W"),
pressed: opts.wholeWord,
onToggle: () => toggle("wholeWord"),
},
{
id: "regex",
icon: "regex",
title: "Regex",
shortcut: formatBinding("Alt+X"),
pressed: opts.regexp,
onToggle: () => toggle("regexp"),
},
]}
/>
</div>
<div className={styles.findButtons}>
<span className={clsx(styles.findCount, (none || invalid) && styles.findCountNone)} aria-live="polite">
{counter}
</span>
<IconButton
icon="arrow-up"
title="Previous Occurrence"
shortcut={formatBinding("Shift+Enter")}
size="small"
onClick={() => run(findPrevious)}
/>
<IconButton
icon="arrow-down"
title="Next Occurrence"
shortcut={formatBinding("Enter")}
size="small"
onClick={() => run(findNext)}
/>
<IconButton
ref={filterRef}
icon="filter"
title="Filter Search Results"
size="small"
pressed={scoped || inChanges || opts.context !== "any"}
onClick={() => setFilterMenu(true)}
/>
<IconButton ref={moreRef} icon="more" title="More" size="small" onClick={() => setMoreMenu(true)} />
</div>
<IconButton icon="close" title="Close" shortcut="⎋" size="small" className={styles.findClose} onClick={close} />
{replace && (
<>
<div ref={replaceBoxRef} className={styles.replaceField}>
<SearchField
ref={replaceRef}
value={opts.replace}
onChange={(value) => setOpts({ replace: value })}
placeholder="Replace"
aria-label="Replace"
multiline
onHistory={() => setHistoryMenu("replace")}
onKeyDown={(e) => onKeyDown(e, "replace")}
toggles={[
{
id: "preserveCase",
icon: "preserve-case",
title: "Preserve Case",
pressed: opts.preserveCase,
onToggle: () => toggle("preserveCase"),
},
]}
/>
</div>
<div className={styles.replaceButtons}>
<Button
size="small"
title={tx`Replace (${formatBinding("Alt+P")})`}
onClick={doReplace}
disabled={!canReplace}
>
<T>Replace</T>
</Button>
<Button
size="small"
title={tx`Replace All (${formatBinding("Alt+A")})`}
onClick={doReplaceAll}
disabled={!canReplace}
>
<T>Replace All</T>
</Button>
<Button
size="small"
title={
count?.excluded ? tx`Include (${formatBinding("Alt+L")})` : tx`Exclude (${formatBinding("Alt+L")})`
}
onClick={() => run(excludeCurrent)}
disabled={!canReplace || (!count?.total && !count?.excluded)}
>
{count?.excluded ? <T>Include</T> : <T>Exclude</T>}
</Button>
</div>
</>
)}
<Menu
open={historyMenu !== null}
anchor={historyMenu === "replace" ? replaceBoxRef : findBoxRef}
items={historyMenu ? historyItems(historyMenu) : []}
placement="bottom-start"
aria-label="Recent searches"
onClose={() => setHistoryMenu(null)}
<div
ref={panelRef}
onFocusCapture={() => {
focusedTarget = target;
setContext("findBarFocus", true);
setContext(
"findBarHasResults",
!!target.results && !!opts.search && (!opts.regexp || regexValid(opts.search)) && !!count?.total,
);
}}
onBlurCapture={(e) => {
if (!panelRef.current?.contains(e.relatedTarget as Node | null)) setContext("findBarFocus", false);
}}
className={clsx(styles.find, onReplaceShown && styles.findExpandable)}
role="search"
aria-label={replace ? "Replace in file" : "Find in file"}
>
{onReplaceShown && (
<IconButton
icon={replace ? "chevron-down" : "chevron-right"}
title={replace ? "Hide Replace" : "Show Replace"}
size="small"
className={styles.findExpand}
aria-expanded={replace}
onMouseDown={(e) => e.preventDefault()}
onClick={() => {
if (replaceBoxRef.current?.contains(document.activeElement)) inputRef.current?.focus();
onReplaceShown(!replace);
}}
/>
<Menu
open={moreMenu}
anchor={moreRef}
items={moreItems}
placement="bottom-end"
aria-label="Find options"
onClose={() => setMoreMenu(false)}
/>
<Menu
open={filterMenu}
anchor={filterRef}
items={filterItems}
placement="bottom-end"
aria-label="Filter search results"
onClose={() => setFilterMenu(false)}
)}
<div ref={findBoxRef} className={styles.findField}>
<SearchField
ref={inputRef}
value={opts.search}
onChange={(search) => setOpts({ search })}
placeholder="Find"
aria-label="Find"
invalid={invalid || none}
multiline
onHistory={() => setHistoryMenu("find")}
onKeyDown={(e) => onKeyDown(e, "find")}
toggles={[
{
id: "case",
icon: "case",
title: "Match Case",
shortcut: formatBinding("Alt+C"),
pressed: opts.caseSensitive,
onToggle: () => toggle("caseSensitive"),
},
{
id: "word",
icon: "word",
title: "Words",
shortcut: formatBinding("Alt+W"),
pressed: opts.wholeWord,
onToggle: () => toggle("wholeWord"),
},
{
id: "regex",
icon: "regex",
title: "Regex",
shortcut: formatBinding("Alt+X"),
pressed: opts.regexp,
onToggle: () => toggle("regexp"),
},
]}
/>
</div>
<div className={styles.findButtons}>
<span className={clsx(styles.findCount, (none || invalid) && styles.findCountNone)} aria-live="polite">
{counter}
</span>
<IconButton
icon="arrow-up"
title="Previous Occurrence"
shortcut={formatBinding("Shift+Enter")}
size="small"
onClick={() => run(findPrevious)}
/>
<IconButton
icon="arrow-down"
title="Next Occurrence"
shortcut={formatBinding("Enter")}
size="small"
onClick={() => run(findNext)}
/>
<IconButton
ref={filterRef}
icon="filter"
title="Filter Search Results"
size="small"
pressed={scoped || inChanges || opts.context !== "any"}
onClick={() => setFilterMenu(true)}
/>
<IconButton ref={moreRef} icon="more" title="More" size="small" onClick={() => setMoreMenu(true)} />
</div>
<IconButton icon="close" title="Close" shortcut="⎋" size="small" className={styles.findClose} onClick={close} />
{replace && (
<>
<div ref={replaceBoxRef} className={styles.findField}>
<SearchField
ref={replaceRef}
value={opts.replace}
onChange={(value) => setOpts({ replace: value })}
placeholder="Replace"
aria-label="Replace"
multiline
onHistory={() => setHistoryMenu("replace")}
onKeyDown={(e) => onKeyDown(e, "replace")}
toggles={[
{
id: "preserveCase",
icon: "preserve-case",
title: "Preserve Case",
pressed: opts.preserveCase,
onToggle: () => toggle("preserveCase"),
},
]}
/>
</div>
<div className={styles.replaceButtons}>
<Button
size="small"
title={tx`Replace (${formatBinding("Alt+P")})`}
onClick={doReplace}
disabled={!canReplace}
>
<T>Replace</T>
</Button>
<Button
size="small"
title={tx`Replace All (${formatBinding("Alt+A")})`}
onClick={doReplaceAll}
disabled={!canReplace}
>
<T>Replace All</T>
</Button>
<Button
size="small"
title={
count?.excluded ? tx`Include (${formatBinding("Alt+L")})` : tx`Exclude (${formatBinding("Alt+L")})`
}
onClick={() => run(excludeCurrent)}
disabled={!canReplace || (!count?.total && !count?.excluded)}
>
{count?.excluded ? <T>Include</T> : <T>Exclude</T>}
</Button>
</div>
</>
)}
<Menu
open={historyMenu !== null}
anchor={historyMenu === "replace" ? replaceBoxRef : findBoxRef}
items={historyMenu ? historyItems(historyMenu) : []}
placement="bottom-start"
aria-label="Recent searches"
onClose={() => setHistoryMenu(null)}
/>
<Menu
open={moreMenu}
anchor={moreRef}
items={moreItems}
placement="bottom-end"
aria-label="Find options"
onClose={() => setMoreMenu(false)}
/>
<Menu
open={filterMenu}
anchor={filterRef}
items={filterItems}
placement="bottom-end"
aria-label="Filter search results"
onClose={() => setFilterMenu(false)}
/>
</div>
);
}
-70
View File
@@ -261,34 +261,6 @@
font-size: var(--fs-tiny);
color: var(--fg-faint);
}
.symbolRename {
display: grid;
grid-template-columns: auto minmax(0, 1fr);
align-items: center;
gap: var(--space-2) var(--space-3);
padding: var(--space-3);
font-family: var(--font-ui);
font-size: var(--fs-ui);
}
.renameContext,
.symbolRenameNote {
grid-column: 1 / -1;
min-width: 0;
overflow-wrap: anywhere;
}
.renameContext {
color: var(--fg-emphasis);
}
.symbolRename .renameField {
width: 100%;
height: max(var(--h-field), calc(var(--openidea-editor-font-size, var(--fs-code)) + var(--space-2)));
font-family: var(--openidea-editor-font, var(--font-mono));
font-size: var(--openidea-editor-font-size, var(--fs-code));
}
.symbolRenameNote {
color: var(--fg-muted);
font-size: var(--fs-small);
}
/* Fits its content up to a cap; resized (`data-resized`), it keeps that size and the body scrolls. */
.docPopup {
@@ -426,36 +398,6 @@
flex-direction: column;
overflow: hidden;
}
.renamePreview [data-dialog-body] {
display: block;
overflow: auto;
}
.previewContext {
padding: var(--space-2) 14px 0;
overflow-wrap: anywhere;
color: var(--fg-emphasis);
font-size: var(--fs-ui);
}
.renamePreview .previewList {
overflow: visible;
}
.renamePreview .previewName {
min-width: 0;
max-width: 55%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.renamePreview .previewOp {
flex: 0 1 auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.renamePreview .previewWarning {
overflow-wrap: anywhere;
}
.previewSummary {
flex: none;
padding: 10px 14px 6px;
@@ -527,18 +469,6 @@
font-size: var(--fs-small);
color: var(--fg-editor);
}
.renamePreview .previewOccurrences .previewRow {
min-height: var(--h-row);
height: auto;
align-items: baseline;
padding-block: var(--space-1);
}
.renamePreview .previewCode {
font-family: var(--openidea-editor-font, var(--font-mono));
font-size: var(--openidea-editor-font-size, var(--fs-code));
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.previewMatch {
background: var(--bg-search-match);
color: var(--fg-search-match, inherit);
+5 -63
View File
@@ -1,5 +1,5 @@
/** React popups for LSP editor features, rendered as a workbench overlay. */
import { useEffect, useId, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent } from "react";
import { useEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent } from "react";
import clsx from "clsx";
import {
Checkbox,
@@ -392,54 +392,6 @@ function RenamePopup({ popup }: { popup: Extract<LspPopup, { kind: "rename" }> }
);
}
function SymbolRenameDialog({ popup }: { popup: Extract<LspPopup, { kind: "symbolRename" }> }) {
const [value, setValue] = useState(popup.initial);
const field = useId();
const name = value.trim();
return (
<Dialog
open
title="Rename"
aria-label={popup.title}
onClose={closePopup}
blockWorkbenchShortcuts
width={440}
buttons={[
{
label: "Rename",
role: "default",
disabled: !name,
onClick: () => {
closePopup();
popup.onSubmit(name);
},
},
{ label: "Cancel", role: "cancel" },
]}
>
<div className={popup.themeClasses}>
<div className={styles.symbolRename}>
<div className={styles.renameContext}>{popup.title}</div>
<label htmlFor={field}>
<T>New name</T>
</label>
<Input
id={field}
className={styles.renameField}
mono
data-autofocus
autoSelect
value={value}
onChange={(e) => setValue(e.target.value)}
invalid={!name}
/>
{popup.note && <div className={styles.symbolRenameNote}>{popup.note}</div>}
</div>
</div>
</Dialog>
);
}
function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
const focusSeq = useLspPopup((s) => s.focusSeq);
const scope = useRef<HTMLDivElement>(null);
@@ -584,7 +536,6 @@ function savePreviewSize(size: { w: number; h: number }) {
}
function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }> }) {
const rename = popup.renameThemeClasses !== undefined;
const root = useProject((s) => s.project?.root ?? "");
const { summary } = popup;
const [initialSize] = useState(loadPreviewSize);
@@ -592,9 +543,8 @@ function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }
<Dialog
open
onClose={closePopup}
title={rename ? "Rename" : popup.title}
aria-label={popup.title}
className={clsx(styles.previewDialog, rename && styles.renamePreview)}
title={popup.title}
className={styles.previewDialog}
width={560}
minWidth={400}
minHeight={220}
@@ -615,7 +565,6 @@ function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }
{ label: "Cancel", role: "cancel" },
]}
>
{rename && <div className={styles.previewContext}>{popup.title}</div>}
{popup.warnings?.map((w) => (
<div key={w} className={styles.previewWarning} role="note">
<Icon name="warning" size={14} />
@@ -624,10 +573,7 @@ function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }
))}
<div className={styles.previewSummary}>{describeSummary(summary)}</div>
{popup.occurrences ? (
<ul
className={clsx(styles.previewList, styles.previewOccurrences, popup.renameThemeClasses)}
aria-label={tx("Occurrences")}
>
<ul className={styles.previewList} aria-label={tx("Occurrences")}>
{popup.occurrences.map((o, i) => {
const lead = o.text.length - o.text.trimStart().length;
const text = o.text.trim();
@@ -650,9 +596,7 @@ function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }
{summary.entries.map((e) => (
<li key={e.path} className={styles.previewRow}>
<Icon name={fileIconName(basename(e.path), e.path)} size={14} className={styles.itemIcon} />
<span className={styles.previewName} title={relativePath(root, e.path)}>
{basename(e.path)}
</span>
<span className={styles.previewName}>{basename(e.path)}</span>
<span className={styles.previewPath} title={relativePath(root, e.path)}>
{relativePath(root, e.path)}
</span>
@@ -798,8 +742,6 @@ export function LspPopups() {
return <ListPopup key={seq} popup={popup} />;
case "rename":
return <RenamePopup key={seq} popup={popup} />;
case "symbolRename":
return <SymbolRenameDialog key={seq} popup={popup} />;
case "doc":
return <DocPopup key={seq} popup={popup} />;
case "definition":
-10
View File
@@ -130,14 +130,6 @@ export type LspPopup =
hint?: string;
onSubmit: (name: string) => void;
}
| {
kind: "symbolRename";
title: string;
initial: string;
note?: string;
themeClasses: string;
onSubmit: (name: string) => void;
}
| {
kind: "preview";
title: string;
@@ -148,8 +140,6 @@ export type LspPopup =
warnings?: string[];
/** Individual occurrences with line previews (single-file syntax-based renames). */
occurrences?: PreviewOccurrence[];
/** The editor theme for a symbol rename and its occurrence snippets. */
renameThemeClasses?: string;
};
export interface PreviewOccurrence {
+7 -8
View File
@@ -27,9 +27,9 @@ import { executeAction } from "@/platform/actions";
import { whenAllSynced, whenSynced, type EditorDocContext } from "@/editor/api";
import { structure } from "@/editor/structure";
import { docOf, incompleteNote, isUnavailable, lspRequest, reportLspError } from "./lsp";
import { offsetToPos, rangeToOffsets } from "./positions";
import { comparePos, offsetToPos, rangeToOffsets } from "./positions";
import { showHint } from "./hint";
import { openPopup, type PreviewOccurrence } from "./popupStore";
import { caretAnchor, openPopup, type PreviewOccurrence } from "./popupStore";
import { needsPreview, summarizeWorkspaceEdit } from "./workspaceEdit";
import { endInplaceRename, inplaceSession, startInplaceRename, type Span } from "./inplaceRename";
import { shortcutLabel } from "@/platform/keymap";
@@ -127,10 +127,10 @@ export async function startRename(view: EditorView) {
const oldName = view.state.sliceDoc(from, to);
const dialog = (initial: string) =>
openPopup({
kind: "symbolRename",
kind: "rename",
anchor: caretAnchor(view, from),
title: tx`Rename '${oldName}'`,
initial,
themeClasses: view.themeClasses,
onSubmit: (newName) => void finishRename(view, doc, pos, oldName, newName),
});
if (from === to) {
@@ -304,7 +304,6 @@ async function finishRename(view: EditorView, doc: EditorDocContext, pos: Pos, o
kind: "preview",
title: tx`Rename '${oldName}' to '${newName}'`,
summary,
renameThemeClasses: view.themeClasses,
...(note ? { warnings: [note] } : {}),
confirmLabel: note ? "Rename Anyway" : "Do Refactor",
onConfirm: () => void applyEdit(view, edit),
@@ -351,12 +350,13 @@ async function startSyntaxRename(
return true;
}
const { plan } = result;
const at = plan.occurrences.find((o) => comparePos(o.range.start, pos) <= 0 && comparePos(pos, o.range.end) <= 0);
openPopup({
kind: "symbolRename",
kind: "rename",
anchor: caretAnchor(view, rangeToOffsets(view.state.doc, (at ?? plan.occurrences[0]!).range).from),
title: tx`Rename '${plan.symbol.name}'`,
initial: plan.symbol.name,
note: `${SYNTAX_NOTE}: local occurrences only`,
themeClasses: view.themeClasses,
onSubmit: (newName) => void commitSyntaxRename(view, doc, plan, newName),
});
return true;
@@ -418,7 +418,6 @@ export async function commitSyntaxRename(
},
warnings: [...risks, `${SYNTAX_NOTE}. Only the occurrences below will be renamed.`],
occurrences,
renameThemeClasses: view.themeClasses,
confirmLabel: "Rename Anyway",
onConfirm: apply,
});
+10 -51
View File
@@ -6,17 +6,8 @@
*/
import { EditorSelection, Prec, StateEffect, StateField, type Extension } from "@codemirror/state";
import { completionStatus, hasNextSnippetField, hasPrevSnippetField } from "@codemirror/autocomplete";
import {
EditorView,
ViewPlugin,
keymap,
repositionTooltips,
showTooltip,
type Tooltip,
type ViewUpdate,
} from "@codemirror/view";
import { EditorView, ViewPlugin, keymap, showTooltip, type Tooltip, type ViewUpdate } from "@codemirror/view";
import { commands, type SignatureHelp } from "@/platform/ipc";
import { tooltipBounds } from "@/editor/core/cm/setup";
import { docOf, lspRequest, reportLspError, debounce } from "./lsp";
import { offsetToPos } from "./positions";
import { showHint } from "./hint";
@@ -49,6 +40,8 @@ export function splitSignature(label: string, params: ReadonlyArray<[number, num
return { before: label.slice(0, s), param: label.slice(s, e), after: label.slice(e) };
}
const MAX_ROWS = 12;
/** Whether an overload can take an argument at `index` (varargs take any number). */
export function acceptsParameter(sig: { label: string; parameters: ReadonlyArray<[number, number]> }, index: number) {
if (index < sig.parameters.length) return true;
@@ -61,27 +54,23 @@ function signatureTooltip(s: SigState): Tooltip {
pos: s.pos,
above: true,
strictSide: false,
create: (view) => {
create: () => {
const dom = document.createElement("div");
dom.className = "cm-lsp-signature";
dom.setAttribute("role", "tooltip");
const { signatures, activeSignature, activeParameter } = s.help;
let active: HTMLElement | null = null;
signatures.forEach((sig, i) => {
const start = Math.max(0, Math.min(activeSignature - 6, signatures.length - MAX_ROWS));
signatures.slice(start, start + MAX_ROWS).forEach((sig, j) => {
const i = start + j;
const row = document.createElement("div");
row.className = "cm-lsp-signature-row";
if (i === activeSignature) {
row.classList.add("cm-lsp-signature-active");
row.setAttribute("aria-current", "true");
active = row;
} else if (!acceptsParameter(sig, activeParameter)) row.classList.add("cm-lsp-signature-disabled");
if (i === activeSignature) row.classList.add("cm-lsp-signature-active");
else if (!acceptsParameter(sig, activeParameter)) row.classList.add("cm-lsp-signature-disabled");
const parts = splitSignature(sig.label, sig.parameters, activeParameter);
row.append(parts.before);
if (parts.param) {
const b = document.createElement("b");
b.textContent = parts.param;
row.appendChild(b);
if (i === activeSignature) active = b;
}
row.append(parts.after);
dom.appendChild(row);
@@ -92,37 +81,7 @@ function signatureTooltip(s: SigState): Tooltip {
d.classList.add("cm-lsp-signature-doc");
dom.appendChild(d);
}
const fit = ({ left, right }: { left: number; right: number }) => {
const width = `${Math.max(0, Math.floor(right - left))}px`;
const fontSize = getComputedStyle(view.contentDOM).fontSize;
const changed = dom.style.getPropertyValue("--cm-signature-width") !== width || dom.style.fontSize !== fontSize;
if (changed) {
dom.style.setProperty("--cm-signature-width", width);
dom.style.fontSize = fontSize;
}
return changed;
};
// Reveal the current parameter after wrapping or a vertical clamp. Leave manual scrolling alone.
let fittedWidth = 0;
let fittedHeight = 0;
return {
dom,
mount: () => void fit(tooltipBounds(view)),
positioned: (space) => {
if (fit(space)) {
repositionTooltips(view);
return;
}
if (!active || (fittedWidth === dom.clientWidth && fittedHeight === dom.clientHeight)) return;
fittedWidth = dom.clientWidth;
fittedHeight = dom.clientHeight;
const top = dom.getBoundingClientRect().top + dom.clientTop;
const parameter = active.getBoundingClientRect();
const below = parameter.bottom - (top + fittedHeight);
if (parameter.top < top || parameter.height >= fittedHeight) dom.scrollTop += parameter.top - top;
else if (below > 0) dom.scrollTop += below;
},
};
return { dom };
},
};
}
+6 -6
View File
@@ -646,8 +646,8 @@ describe("rename wiring", () => {
const view = editor("const x = 1;\nf({ x });", "typescript", 6);
await startRename(view);
const popup = useLspPopup.getState().popup;
expect(popup?.kind).toBe("symbolRename");
if (popup?.kind !== "symbolRename") return;
expect(popup?.kind).toBe("rename");
if (popup?.kind !== "rename") return;
expect(popup.note).toContain("Based on syntax");
popup.onSubmit("y");
await vi.waitFor(() => expect(view.state.doc.toString()).toBe("const y = 1;\nf({ x: y });"));
@@ -661,7 +661,7 @@ describe("rename wiring", () => {
const view = editor("const x = 1;\nx;\nvar x;", "typescript", 6);
await startRename(view);
const popup = useLspPopup.getState().popup;
if (popup?.kind !== "symbolRename") throw new Error("no rename dialog");
if (popup?.kind !== "rename") throw new Error("no rename popup");
popup.onSubmit("y");
await vi.waitFor(() => expect(useLspPopup.getState().popup?.kind).toBe("preview"));
const preview = useLspPopup.getState().popup;
@@ -860,12 +860,12 @@ describe("rename wiring", () => {
await startRename(view);
expect(inplaceSession(view.state)?.oldName).toBe("x");
await startRename(view);
expect(useLspPopup.getState().popup?.kind).toBe("symbolRename");
expect(useLspPopup.getState().popup?.kind).toBe("rename");
if (finish === "cancel") closePopup();
release({ status: "ok", data: r(0, 6, 7) });
await older;
expect(inplaceSession(view.state)).toBeNull();
expect(useLspPopup.getState().popup?.kind ?? null).toBe(finish === "dialog" ? "symbolRename" : null);
expect(useLspPopup.getState().popup?.kind ?? null).toBe(finish === "dialog" ? "rename" : null);
});
it.each(["text", "document"])("drops pending preparation when the editor %s changes", async (change) => {
@@ -938,7 +938,7 @@ describe("rename wiring", () => {
);
cmd.syntaxLocals.mockReturnValueOnce(ok(local({ references: [] })));
await startRename(view);
expect(useLspPopup.getState().popup?.kind).toBe("symbolRename");
expect(useLspPopup.getState().popup?.kind).toBe("rename");
});
});
+10 -17
View File
@@ -270,35 +270,28 @@ export const lspTheme = EditorView.theme({
cursor: "pointer",
},
".cm-lsp-link-button:hover": { color: "var(--link-hover)", textDecoration: "underline" },
".cm-tooltip.cm-lsp-signature": {
".cm-lsp-signature": {
fontFamily: "var(--openidea-editor-font, var(--font-mono))",
fontWeight: "var(--fw-code, 400)",
fontSize: "var(--openidea-editor-font-size, var(--fs-code))",
maxWidth: "min(640px, var(--cm-signature-width, 100%))",
maxHeight: "min(380px, 65vh)",
paddingBlock: "var(--space-0-5)",
overflow: "auto",
overscrollBehavior: "contain",
},
".cm-lsp-signature-row": {
color: "var(--fg-secondary)",
whiteSpace: "pre-wrap",
overflowWrap: "anywhere",
lineHeight: "1.5",
padding: "var(--space-0-5) var(--space-2)",
paddingInlineStart: "calc(var(--space-2) + 2ch)",
textIndent: "-2ch",
padding: "6px 10px",
maxWidth: "640px",
},
".cm-lsp-signature-row": { color: "var(--fg-subtle)", whiteSpace: "pre-wrap", lineHeight: "max(20px, 1.5em)" },
".cm-lsp-signature-active": {
color: "var(--fg-strong)",
backgroundColor: "var(--bg-identifier-under-caret, color-mix(in srgb, var(--accent) 14%, transparent))",
margin: "0 -10px",
padding: "0 10px",
},
".cm-lsp-signature-disabled": { opacity: "0.55" },
".cm-lsp-signature b": { fontWeight: "var(--fw-code-bold, 700)", color: "var(--fg-strong)" },
".cm-lsp-signature-doc": {
borderTop: "1px solid var(--border-popup)",
marginTop: "var(--space-1)",
padding: "var(--space-2)",
marginTop: "6px",
paddingTop: "6px",
maxHeight: "160px",
overflow: "auto",
},
".cm-tooltip:has(> .cm-lsp-hint)": { background: "none", border: "none", boxShadow: "none" },
".cm-lsp-hint": {
-28
View File
@@ -154,28 +154,6 @@
flex: 1;
min-height: 0;
}
/* A console's request in flight; the previous result stays below it. */
.executing {
flex: none;
display: flex;
align-items: center;
gap: var(--space-2);
min-width: 0;
padding: var(--space-1) var(--space-3);
border-bottom: 1px solid var(--border);
color: var(--fg-muted);
font-size: var(--fs-small);
}
.executingText {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.executingTime {
flex: none;
font-variant-numeric: tabular-nums;
}
/* Gives way before the name does. */
.treeDetail {
color: var(--fg-muted);
@@ -679,12 +657,6 @@
}
/* Console run feedback: timing after a statement, gutter check / error, error banner. */
:global(.cm-openidea-db-executing) {
background: var(--accent-soft);
}
:global(.cm-openidea-db-elapsed) {
font-variant-numeric: tabular-nums;
}
:global(.cm-openidea-db-timing) {
margin-left: 1.5em;
color: var(--fg-muted);
+1 -39
View File
@@ -16,8 +16,6 @@ import {
type MouseEvent,
} from "react";
import clsx from "clsx";
import { useShallow } from "zustand/react/shallow";
import { basename } from "@/platform/project";
import { call, commands, type DbPlanNode, type DbQueryResult } from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
import { setContext } from "@/platform/context";
@@ -37,7 +35,7 @@ import {
resolveTarget,
type EditBlockReason,
} from "./resultEditing";
import { formatElapsed, pageWindow } from "./resultView";
import { pageWindow } from "./resultView";
import { resultTabMenu } from "./resultTabActions";
import { analyze } from "./sql/analyze";
import { nameMatcher } from "./sql/dialect";
@@ -57,7 +55,6 @@ import {
rerunResult,
useDatabase,
withConnection,
type ConsoleExecution,
type OutputLine,
type ResultTab,
} from "./store";
@@ -747,40 +744,8 @@ function PinButton({ tab }: { tab: ResultTab }) {
);
}
/** The most recently started console request, while it runs. */
function useLatestExecution(): [string, ConsoleExecution] | undefined {
return useDatabase(
useShallow((s) => {
let latest: [string, ConsoleExecution] | undefined;
for (const entry of Object.entries(s.executions))
if (!latest || entry[1].startedAt > latest[1].startedAt) latest = entry;
return latest;
}),
);
}
function ExecutingBar({ path, execution }: { path: string; execution: ConsoleExecution }) {
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const timer = setInterval(() => setNow(Date.now()), 100);
return () => clearInterval(timer);
}, [execution.startedAt]);
const name = basename(path);
const count = execution.statements;
return (
<div className={styles.executing} role="status">
<Spinner size={12} label={tx("Executing")} />
<span className={styles.executingText} title={path}>
{count > 1 ? tx`Executing ${count} statements in ${name}…` : tx`Executing in ${name}…`}
</span>
<span className={styles.executingTime}>{formatElapsed(Math.max(0, now - execution.startedAt))}</span>
</div>
);
}
export function ResultsView() {
const results = useDatabase((s) => s.results);
const execution = useLatestExecution();
const active = useDatabase((s) => s.activeResult);
const hasOutput = useDatabase((s) => s.output.length > 0);
const root = useRef<HTMLDivElement>(null);
@@ -807,8 +772,6 @@ export function ResultsView() {
owner: e.currentTarget,
});
};
const executing = execution && <ExecutingBar path={execution[0]} execution={execution[1]} />;
if (!results.length && !hasOutput && executing) return <div className={styles.view}>{executing}</div>;
if (!results.length && !hasOutput)
return (
<EmptyState title="No results">
@@ -862,7 +825,6 @@ export function ResultsView() {
]}
/>
</ToolWindowContentTabs>
{executing}
<div
ref={panel}
className={styles.fill}
+12 -126
View File
@@ -23,7 +23,6 @@ import {
Facet,
Prec,
RangeSet,
type Range,
StateEffect,
StateField,
type Extension,
@@ -43,15 +42,8 @@ import {
import { useEffect, useMemo, useRef, useState, type PointerEvent } from "react";
import { createRoot } from "react-dom/client";
import type { EditorDocContext } from "@/editor/api";
import { iconNode, spinnerNode } from "@/ui/iconNode";
import {
call,
commands,
type DbDriver,
type DbSessionContext,
type DbStatementOutcome,
type SqlStatement,
} from "@/platform/ipc";
import { iconNode } from "@/ui/iconNode";
import { call, commands, type DbDriver, type DbSessionContext, type DbStatementOutcome } from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
import { Icon, IconButton, Select, Toolbar, lazyComponent } from "@/ui";
import { useProject } from "@/platform/project";
@@ -101,7 +93,6 @@ import type { ResultTab } from "./store";
/** `templates` feature's language-data key for finer template contexts. */
const TEMPLATE_CONTEXT_KEY = "openideaTemplateContexts";
import { formatElapsed } from "./resultView";
import { SQL_LANGUAGE } from "./sqlLanguage";
export { SQL_LANGUAGE };
const ROW_LIMITS = ["100", "500", "1000", "5000", "50000"];
@@ -116,40 +107,19 @@ interface RunMark {
ms: number | null;
}
/** The statements a running request submitted (a batch: all of them, in order). */
interface Executing {
/** Tells this run from a later one on the same console. */
token: number;
/** The statements' offsets in the text sent. */
sent: readonly { from: number; to: number }[];
/** Where they are now. */
spans: readonly { from: number; to: number }[];
/** Where the elapsed time shows: after the last statement's `;`. */
at: number;
startedAt: number;
}
interface RunState {
marks: readonly RunMark[];
/** Message of the bottom error banner (`null`: hidden). */
banner: string | null;
executing: Executing | null;
}
const setRun = StateEffect.define<RunState>();
const runField = StateField.define<RunState>({
create: () => ({ marks: [], banner: null, executing: null }),
create: () => ({ marks: [], banner: null }),
update(value, tr) {
for (const e of tr.effects) if (e.is(setRun)) return e.value;
if (!tr.docChanged) return value;
// The request runs the text it was sent; edits only move where that shows.
const ex = value.executing;
const executing = ex && {
...ex,
spans: ex.spans.map((r) => ({ from: tr.changes.mapPos(r.from, 1), to: tr.changes.mapPos(r.to, -1) })),
at: tr.changes.mapPos(ex.at),
};
// Editing a statement drops its mark.
const marks: RunMark[] = [];
for (const m of value.marks) {
@@ -165,18 +135,12 @@ const runField = StateField.define<RunState>({
timingAt: tr.changes.mapPos(m.timingAt),
});
}
return { ...value, marks, executing };
return { ...value, marks };
},
provide: (f) => [
EditorView.decorations.from(f, (st) => {
const ranges = [];
const ex = st.executing;
for (const r of ex?.spans ?? [])
if (r.from < r.to) ranges.push(Decoration.mark({ class: "cm-openidea-db-executing" }).range(r.from, r.to));
if (ex) ranges.push(Decoration.widget({ widget: new ElapsedWidget(ex.startedAt), side: 1 }).range(ex.at));
for (const m of st.marks) {
// The new run takes the place of a statement's last outcome.
if (ex?.spans.some((r) => r.from <= m.to && m.from <= r.to)) continue;
if (m.error)
ranges.push(
Decoration.mark({ class: "cm-openidea-db-error", attributes: { title: m.error } }).range(m.from, m.to),
@@ -200,47 +164,11 @@ class TimingWidget extends WidgetType {
toDOM() {
const span = document.createElement("span");
span.className = "cm-openidea-db-timing";
span.textContent = formatElapsed(this.ms);
span.textContent = this.ms < 1000 ? `${Math.round(this.ms)} ms` : `${(this.ms / 1000).toFixed(1)} s`;
return span;
}
}
/** The running time of the request, ticking until it ends. */
class ElapsedWidget extends WidgetType {
private timer: ReturnType<typeof setInterval> | undefined;
constructor(readonly startedAt: number) {
super();
}
eq(other: ElapsedWidget) {
return other.startedAt === this.startedAt;
}
toDOM() {
const span = document.createElement("span");
span.className = "cm-openidea-db-timing cm-openidea-db-elapsed";
const tick = () => {
const elapsed = formatElapsed(Date.now() - this.startedAt);
span.textContent = tx`Executing… ${elapsed}`;
};
tick();
this.timer = setInterval(tick, 100);
return span;
}
destroy() {
clearInterval(this.timer);
}
}
class ExecutingMarker extends GutterMarker {
eq(other: GutterMarker) {
return other instanceof ExecutingMarker;
}
toDOM() {
const el = spinnerNode(12, "cm-openidea-db-run-executing");
el.title = tx("Executing");
return el;
}
}
class RunMarker extends GutterMarker {
constructor(readonly error: string | null) {
super();
@@ -264,12 +192,9 @@ const runGutter = gutter({
markers: (view) => {
const st = view.state.field(runField);
const doc = view.state.doc;
const ex = st.executing;
const ranges: Range<GutterMarker>[] = st.marks
.filter((m) => m.from <= doc.length && !ex?.spans.some((r) => r.from <= m.to && m.from <= r.to))
const ranges = st.marks
.filter((m) => m.from <= doc.length)
.map((m) => new RunMarker(m.error).range(doc.lineAt(m.from).from));
const first = ex?.spans[0];
if (first && first.from <= doc.length) ranges.push(new ExecutingMarker().range(doc.lineAt(first.from).from));
return RangeSet.of(ranges, true);
},
});
@@ -308,59 +233,20 @@ export function markOutcomes(view: EditorView, outcomes: readonly DbStatementOut
}));
const failed = outcomes.find((o) => o.error);
const name = failed ? (sourceById(consoleSource(view.state.facet(consolePath)))?.name ?? "") : "";
view.dispatch({
effects: setRun.of({ ...view.state.field(runField), marks, banner: failed ? `[${name}] ${failed.error}` : null }),
});
}
let nextExecution = 0;
/** `outcomes` at where their statements are now, when the text was edited while they ran. */
function placed(
executing: Executing | null,
token: number,
outcomes: readonly DbStatementOutcome[],
): readonly DbStatementOutcome[] {
if (executing?.token !== token) return outcomes;
return outcomes.map((o) => {
const i = executing.sent.findIndex((r) => r.from === o.statement.from && r.to === o.statement.to);
const now = executing.spans[i];
return now ? { ...o, statement: { ...o.statement, from: now.from, to: now.to } } : o;
});
}
/** Runs `from`–`to` of `view`, showing the submitted statements as executing until the request ends. */
async function executeRange(view: EditorView, path: string, from: number, to: number) {
const token = ++nextExecution;
const sent = view.state.doc;
const start = (statements: readonly SqlStatement[]) => {
// The offsets are into the text sent; an edit since (while asking for parameters) leaves them unplaced.
if (view.state.doc !== sent) return;
const spans = statements.map((st) => ({ from: st.from, to: st.to }));
const last = spans.at(-1);
if (!last) return;
const at = view.state.sliceDoc(last.to, last.to + 1) === ";" ? last.to + 1 : last.to;
const executing = { token, sent: spans, spans, at, startedAt: Date.now() };
view.dispatch({ effects: setRun.of({ ...view.state.field(runField), executing }) });
};
try {
const outcomes = await executeConsole(path, sent.toString(), from, to, start);
if (outcomes.length) markOutcomes(view, placed(view.state.field(runField).executing, token, outcomes));
} finally {
const st = view.state.field(runField, false);
if (st?.executing?.token === token) view.dispatch({ effects: setRun.of({ ...st, executing: null }) });
}
view.dispatch({ effects: setRun.of({ marks, banner: failed ? `[${name}] ${failed.error}` : null }) });
}
/** Runs the statement at the caret (or the selected ones) of `view`. */
export async function executeInView(view: EditorView, path: string) {
const sel = view.state.selection.main;
await executeRange(view, path, sel.from, sel.to);
const outcomes = await executeConsole(path, view.state.doc.toString(), sel.from, sel.to);
if (outcomes.length) markOutcomes(view, outcomes);
}
/** Runs every statement of `view`, in order (stops at the first that fails). */
export async function executeScriptInView(view: EditorView, path: string) {
await executeRange(view, path, 0, view.state.doc.length);
const outcomes = await executeConsole(path, view.state.doc.toString(), 0, view.state.doc.length);
if (outcomes.length) markOutcomes(view, outcomes);
}
/** Explain Plan of the statement at the caret (or the first selected one) of `view`. */
+1 -59
View File
@@ -3,10 +3,9 @@ import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useProject } from "@/platform/project";
import { consoleExtension, executeScriptInView } from "./console";
import { consoleExtension } from "./console";
import { SQL_LANGUAGE } from "./sqlLanguage";
import { executeConsole, rerunResult, useDatabase } from "./store";
import { provideToolWindowService } from "@/workbench/contributions";
const backend = vi.hoisted(() => ({ execute: vi.fn(), statements: vi.fn() }));
@@ -31,7 +30,6 @@ const initial = useDatabase.getState();
let runs = 0;
beforeEach(() => {
provideToolWindowService({ show: () => {} } as never);
runs = 0;
useProject.setState({
project: { name: "p", root: "/p", trusted: true } as never,
@@ -136,59 +134,3 @@ describe("In-Editor Results", () => {
view.destroy();
});
});
describe("statements in flight", () => {
it("marks what was submitted with its running time, then the outcome", async () => {
const parent = document.createElement("div");
document.body.append(parent);
const doc = "SELECT 1;\nSELECT 2;\n";
const view = new EditorView({
parent,
state: EditorState.create({
doc,
extensions: consoleExtension({ language: SQL_LANGUAGE, path: PATH } as never),
}),
});
let finish!: () => void;
const gate = new Promise<void>((resolve) => {
finish = resolve;
});
const execute = backend.execute.getMockImplementation()!;
backend.execute.mockImplementationOnce(async (...args: unknown[]) => {
await gate;
return execute(...(args as Parameters<typeof execute>));
});
const executing = () => [...view.dom.querySelectorAll(".cm-openidea-db-executing")].map((e) => e.textContent);
const elapsed = () => view.dom.querySelector(".cm-openidea-db-elapsed")?.textContent;
let pending!: Promise<void>;
await act(async () => {
pending = executeScriptInView(view, PATH);
await vi.waitFor(() => expect(backend.execute).toHaveBeenCalled());
});
expect(executing()).toEqual(["SELECT 1", "SELECT 2"]);
expect(elapsed()).toMatch(/^Executing… \d+ ms$/);
expect(view.dom.querySelector(".cm-openidea-db-run-executing")).not.toBeNull();
// Typing above moves the marks with their text.
act(() => view.dispatch({ changes: { from: 0, insert: "-- a longer note above\n" } }));
expect(executing()).toEqual(["SELECT 1", "SELECT 2"]);
await act(async () => {
finish();
await pending;
});
expect(executing()).toEqual([]);
expect(elapsed()).toBeUndefined();
// The outcomes land on the statements, not on where they were when sent.
const lines = [...view.dom.querySelectorAll(".cm-openidea-db-gutter .cm-gutterElement")]
.filter((e) => e.querySelector(".cm-openidea-db-run-ok"))
.map((e) => e.getBoundingClientRect().top);
expect(lines).toHaveLength(2);
expect(view.dom.querySelectorAll(".cm-openidea-db-timing")).toHaveLength(2);
expect(view.state.doc.lineAt(view.posAtDOM(view.dom.querySelector(".cm-openidea-db-timing")!)).text).toBe(
"SELECT 1;",
);
view.destroy();
});
});
-1
View File
@@ -157,7 +157,6 @@ export function activate(): () => void {
manualCommit: new Set(),
pendingTx: new Set(),
running: {},
executions: {},
dialog: null,
newMenuOpen: false,
});
@@ -67,7 +67,6 @@ import {
useDatabase,
withConnection,
} from "./store";
import { provideToolWindowService } from "@/workbench/contributions";
const initial = useDatabase.getState();
const initialProject = useProject.getState();
@@ -130,8 +129,6 @@ function switchProject(project: ProjectInfo) {
}
beforeEach(() => {
// `showServiceView` reaches the real service, not the mocked accessor above.
provideToolWindowService({ show: ui.show } as never);
vi.resetAllMocks();
useProject.setState({ project: projectA });
savedSources = [pg, other];
+1 -6
View File
@@ -1,7 +1,7 @@
/**
* Pure helpers of the result views: IDEA's local filter and client-side sort
* of loaded rows, search in the grid, paging of console results, the
* Aggregates of a selection, the series of the chart, and how long a statement took.
* Aggregates of a selection, and the series of the chart.
*/
import type { Cell } from "./model";
@@ -462,8 +462,3 @@ export function pageWindow({ page, pageSize, rows, hasMore, total }: PageState):
export function pageFetch(page: number, pageSize: number): { maxRows: number; skip: number } {
return { maxRows: pageSize, skip: page * pageSize };
}
/** A statement's run time as IDEA shows it: `840 ms`, `3.2 s`. */
export function formatElapsed(ms: number): string {
return ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`;
}
@@ -9,7 +9,6 @@ import { ResultsView } from "./ResultsView";
import { executeConsole, explainConsole, pinResult, rerunResult, useDatabase, type ResultTab } from "./store";
import { registerResultTabActions } from "./resultTabActions";
import { activeTableEditor, installTableEditorFocus } from "./tableEditorFocus";
import { provideToolWindowService } from "@/workbench/contributions";
const backend = vi.hoisted(() => ({
driver: "postgres" as DbDriver,
@@ -96,7 +95,6 @@ function show(text: string, columns: Array<{ name: string }>, rows: (string | nu
}
beforeEach(() => {
provideToolWindowService({ show: () => {} } as never);
vi.clearAllMocks();
backend.statements.mockImplementation((_id: unknown, text: string) =>
Promise.resolve({ status: "ok", data: [{ from: 0, to: text.length, text }] }),
@@ -811,64 +809,3 @@ describe("result tab reuse (IDEA: new results replace the console's unpinned tab
expect(useDatabase.getState().activeResult).toBe(fresh);
});
});
describe("a console request in flight", () => {
const hold = () => {
let finish!: () => void;
const gate = new Promise<void>((resolve) => {
finish = resolve;
});
const execute = backend.execute.getMockImplementation()!;
backend.execute.mockImplementationOnce(async (...args: unknown[]) => {
await gate;
return execute(...(args as Parameters<typeof execute>));
});
return () => finish();
};
it("shows that it is executing instead of No results on a first run", async () => {
show("SELECT 1", [{ name: "id" }], [["1"]]);
useDatabase.setState({ results: [], activeResult: null, consoles: { "console.sql": "pg" } });
const finish = hold();
await act(async () => render(<ResultsView />));
let pending!: Promise<unknown>;
await act(async () => {
pending = executeConsole("console.sql", "SELECT pg_sleep(5)", 0, 0);
await vi.waitFor(() => expect(backend.execute).toHaveBeenCalled());
});
expect(screen.queryByText("No results")).toBeNull();
expect(screen.getByText("Executing in console.sql…").parentElement).toHaveTextContent(/\d+ ms$/);
await act(async () => {
finish();
await pending;
});
expect(screen.queryByText(/Executing in/)).toBeNull();
expect(useDatabase.getState().executions).toEqual({});
});
it("keeps the previous result visible while the next run executes", async () => {
show("SELECT * FROM users", [{ name: "id" }, { name: "name" }], [["1", "Ann"]]);
useDatabase.setState({ consoles: { "console.sql": "pg" } });
backend.statements.mockResolvedValueOnce({
status: "ok",
data: [
{ from: 0, to: 8, text: "SELECT 1" },
{ from: 10, to: 18, text: "SELECT 2" },
],
});
const finish = hold();
await act(async () => render(<ResultsView />));
let pending!: Promise<unknown>;
await act(async () => {
pending = executeConsole("console.sql", "SELECT 1; SELECT 2", 0, 18);
await vi.waitFor(() => expect(backend.execute).toHaveBeenCalled());
});
expect(screen.getByText("Executing 2 statements in console.sql…")).toBeTruthy();
expect(screen.getByText("Ann")).toBeTruthy();
await act(async () => {
finish();
await pending;
});
expect(screen.queryByText(/Executing/)).toBeNull();
});
});
+2 -21
View File
@@ -174,12 +174,6 @@ export interface SourceCatalog {
databases: Record<string, DbCatalogSchema[]>;
}
export interface ConsoleExecution {
startedAt: number;
/** Statements submitted (a batch runs them in order; the backend doesn't say which one is current). */
statements: number;
}
interface DatabaseState {
sources: DataSource[];
loaded: boolean;
@@ -211,8 +205,6 @@ interface DatabaseState {
output: OutputLine[];
/** Console path → running request. */
running: Record<string, RequestId>;
/** Console path → what its running request submitted, and since when (ms since the epoch). */
executions: Record<string, ConsoleExecution>;
maxRows: number;
dialog: DialogState | null;
/** Target of the tree's lead node. */
@@ -279,7 +271,6 @@ export const useDatabase = create<DatabaseState>(() => ({
activeResult: null,
output: [],
running: {},
executions: {},
maxRows: 500,
dialog: null,
selectedSource: null,
@@ -1242,8 +1233,6 @@ export async function executeConsole(
text: string,
from: number,
to: number,
/** Called once the statements are submitted, with what was submitted. */
onStart?: (statements: readonly SqlStatement[]) => void,
): Promise<DbStatementOutcome[]> {
const id = consoleSource(path);
if (!id) {
@@ -1263,14 +1252,8 @@ export async function executeConsole(
const prev = useDatabase.getState().running[path];
if (prev) void commands.cancelRequest(prev);
const request = nextRequestId();
useDatabase.setState((s) => ({
running: { ...s.running, [path]: request },
executions: { ...s.executions, [path]: { startedAt: Date.now(), statements: statements.length } },
}));
onStart?.(statements);
useDatabase.setState((s) => ({ running: { ...s.running, [path]: request } }));
try {
// IDEA brings the results up as the run starts, showing it executing.
if (!inEditorResults()) showServiceView(RESULTS_VIEW, false);
const pageSize = useDatabase.getState().maxRows;
const schema = consoleSchema(path) || (await loadCompletion(id))?.defaultSchema || "";
if (!current()) return [];
@@ -1313,9 +1296,7 @@ export async function executeConsole(
if (s.running[path] !== request) return s;
const running = { ...s.running };
delete running[path];
const executions = { ...s.executions };
delete executions[path];
return { running, executions };
return { running };
});
}
}
+20 -66
View File
@@ -172,72 +172,31 @@
}
/* evaluate dialog */
.evalDialog {
height: min(440px, 100%);
}
.evalBody {
height: 100%;
padding: var(--space-2) var(--space-3) 0;
box-sizing: border-box;
padding: 12px 14px;
display: flex;
flex-direction: column;
gap: var(--space-2);
}
.evalExpression,
.evalResult {
display: flex;
flex-direction: column;
min-height: 0;
gap: var(--space-1);
}
/* Long fragments scroll inside the field so the result keeps its own space. */
.evalExpression {
max-height: 50%;
gap: 10px;
}
.evalImport {
flex: none;
max-height: 40%;
overflow: auto;
padding: var(--space-1);
display: flex;
flex-wrap: wrap;
align-items: center;
align-content: start;
gap: var(--space-1) var(--space-2);
border-bottom: 1px solid var(--border);
}
.evalImport > button {
max-width: 100%;
height: auto;
min-height: var(--h-control);
white-space: normal;
overflow-wrap: anywhere;
}
/* Grows with the dialog when it is resized. */
.evalResult {
flex: 1;
}
.evalResultContent {
flex: 1;
min-height: 0;
min-height: 220px;
display: flex;
flex-direction: column;
border: 1px solid var(--border-popup);
border-radius: var(--radius-small);
padding: var(--space-0-5) var(--space-1);
overflow: hidden;
}
.evalHint {
padding: var(--space-2);
color: var(--fg-muted);
font-size: var(--fs-small);
overflow: auto;
padding: 4px 6px;
}
.chooser {
@@ -300,38 +259,33 @@
/* Evaluate: a field that grows with ⇧Enter, like IDEA's expression editor. */
.evalInputRow {
display: flex;
min-height: 0;
border-radius: var(--radius-control, 4px);
background: var(--bg-field, var(--bg-button));
box-shadow: inset 0 0 0 1px var(--border-button);
}
.evalInputRow:focus-within {
box-shadow:
inset 0 0 0 1px var(--focus-ring),
0 0 0 1px var(--focus-ring);
align-items: flex-start;
gap: var(--space-1);
}
.evalInput {
flex: 1;
min-width: 0;
min-height: 0;
padding: var(--space-1) var(--space-2);
min-height: var(--h-field, 28px);
padding: 5px 8px;
resize: none;
appearance: none;
border: 0;
background: none;
border-radius: var(--radius-control, 4px);
background: var(--bg-field, var(--bg-button));
box-shadow: inset 0 0 0 1px var(--border-button);
color: var(--fg-strong);
font-family: var(--font-mono);
font-size: var(--fs-code);
font-weight: var(--fw-code);
line-height: var(--lh-code);
font-size: var(--fs-ui);
line-height: 18px;
outline: none;
-webkit-user-select: text;
user-select: text;
}
.evalInput:focus {
box-shadow:
inset 0 0 0 1px var(--focus-ring),
0 0 0 1px var(--focus-ring);
}
.evalInput::placeholder {
color: var(--fg-faint);
}
.evalHistory {
align-self: flex-start;
margin: var(--space-1);
}
+40 -53
View File
@@ -764,9 +764,8 @@ function EvaluateDialogInner({ initial }: { initial: string }) {
const [history, setHistory] = useState(() => readHistory("evaluate"));
const [historyMenu, setHistoryMenu] = useState(false);
const historyPos = useRef(-1);
const historyButton = useRef<HTMLButtonElement>(null);
const historyButton = useRef<HTMLSpanElement>(null);
const field = useRef<HTMLTextAreaElement>(null);
const expressionId = useId();
const session = useDebug((s) => (s.active != null ? s.sessions[s.active] : undefined));
const paused = session?.status === "paused";
const close = () => useOverlays.setState({ evaluate: null });
@@ -825,10 +824,7 @@ function EvaluateDialogInner({ initial }: { initial: string }) {
onClose={close}
title="Evaluate"
width={620}
minWidth={340}
minHeight={240}
resizable="both"
className={styles.evalDialog}
aria-label="Evaluate expression"
footerStart={
<Button
@@ -848,14 +844,13 @@ function EvaluateDialogInner({ initial }: { initial: string }) {
]}
>
<div className={styles.evalBody}>
<div className={styles.evalExpression}>
<label className={styles.label} htmlFor={expressionId}>
<div className={styles.field}>
<span className={styles.label}>
<T>Expression</T>
</label>
</span>
<div className={styles.evalInputRow}>
<textarea
ref={field}
id={expressionId}
className={styles.evalInput}
rows={lines}
value={expression}
@@ -871,22 +866,19 @@ function EvaluateDialogInner({ initial }: { initial: string }) {
spellCheck={false}
autoComplete="off"
data-autofocus=""
placeholder={tx(
paused ? "Expression to evaluate in the selected frame" : "Pause the program to evaluate",
)}
aria-label={tx("Expression")}
placeholder={paused ? "Expression to evaluate in the selected frame" : "Pause the program to evaluate"}
/>
{completion.popup}
<IconButton
ref={historyButton}
className={styles.evalHistory}
icon="history"
title="History"
size="small"
aria-haspopup="menu"
aria-expanded={historyMenu}
disabled={!history.length}
onClick={() => setHistoryMenu(true)}
/>
<span ref={historyButton}>
<IconButton
icon="history"
title="History"
size="small"
disabled={!history.length}
onClick={() => setHistoryMenu(true)}
/>
</span>
</div>
<Menu
open={historyMenu}
@@ -899,37 +891,32 @@ function EvaluateDialogInner({ initial }: { initial: string }) {
.map((h) => ({ label: h.replace(/\s+/g, " "), verbatim: true, run: () => recall(h) }))}
/>
</div>
<div className={styles.evalResult}>
<span className={styles.label}>
<T>Result</T>
</span>
<div className={styles.evalResultContent}>
{ambiguous && (
<div className={styles.evalImport} role="group" aria-label={tx("Class to import")}>
<span className={styles.label}>{tx`Choose the class to import for ${className}:`}</span>
{ambiguous.candidates.map((c) => (
<Button
key={c}
variant="ghost"
size="small"
onClick={() => {
if (session) rememberImport(session.id, c);
void run();
}}
>
{c}
</Button>
))}
</div>
)}
{result ? (
<VariablesView roots={[result]} session={session?.id ?? null} aria-label="Evaluation result" />
) : (
<div className={styles.evalHint}>
{paused ? tx("Press Enter to evaluate") : tx("Evaluation is available while the program is suspended")}
</div>
)}
{ambiguous && (
<div className={styles.evalImport} role="group" aria-label={tx("Class to import")}>
<span className={styles.label}>{tx`Choose the class to import for ${className}:`}</span>
{ambiguous.candidates.map((c) => (
<Button
key={c}
variant="ghost"
size="small"
onClick={() => {
if (session) rememberImport(session.id, c);
void run();
}}
>
{c}
</Button>
))}
</div>
)}
<div className={styles.evalResult}>
{result ? (
<VariablesView roots={[result]} session={session?.id ?? null} aria-label="Evaluation result" />
) : (
<div className={styles.empty}>
{paused ? tx("Press Enter to evaluate") : tx("Evaluation is available while the program is suspended")}
</div>
)}
</div>
</div>
</Dialog>
@@ -10,12 +10,12 @@
.row {
display: flex;
align-items: center;
gap: var(--space-1);
gap: 5px;
min-width: 0;
width: 100%;
max-width: 100%;
box-sizing: border-box;
font-family: var(--font-ui);
font-family: var(--font-mono);
font-size: var(--fs-ui);
white-space: pre;
color: var(--fg);
@@ -23,27 +23,17 @@
}
.name {
min-width: 0;
max-width: 45%;
overflow: hidden;
text-overflow: ellipsis;
flex: none;
color: var(--fg);
}
.evalName {
flex: 0 1 auto;
max-width: 45%;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
.varName {
color: var(--debug-name, var(--syn-property));
}
.nodeIcon {
flex: none;
margin-right: 1px;
}
.eq {
@@ -51,28 +41,15 @@
color: var(--fg-subtle);
}
.valueGroup {
display: flex;
align-items: center;
gap: var(--space-1);
min-width: min(8ch, 45%);
flex: 1 1 0;
}
.value {
min-width: 0;
flex: 1 1 0;
overflow: hidden;
text-overflow: ellipsis;
font-family: var(--font-mono);
}
.showValue {
flex: 0 0 auto;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: none;
padding: 0;
border: 0;
background: none;
@@ -127,7 +104,6 @@
.type {
min-width: 0;
max-width: 25%;
flex: 0 1 auto;
overflow: hidden;
text-overflow: ellipsis;
@@ -152,7 +128,7 @@
.editInput {
flex: 1;
min-width: min(80px, 40%);
min-width: 80px;
height: 18px;
padding: 0 4px;
font: inherit;
+25 -45
View File
@@ -415,9 +415,7 @@ function VarEditRow({
useEffect(() => acquirePopup(), []);
return (
<span className={styles.row}>
<span className={styles.name} title={node.name}>
{node.name}
</span>
<span className={styles.name}>{node.name}</span>
<span className={styles.eq}>=</span>
<input
className={clsx(styles.editInput, error && styles.editInvalid)}
@@ -467,21 +465,18 @@ function VarRow({
const valueRef = useRef<HTMLSpanElement>(null);
const [overflow, setOverflow] = useState(false);
useLayoutEffect(() => {
const text = valueRef.current;
const group = text?.parentElement;
if (!text || !group) {
const el = valueRef.current;
if (!el) {
setOverflow(false);
return;
}
// The group measures the space available before the Show button takes any of it.
const update = () => setOverflow(text.scrollWidth > group.clientWidth + 1);
const update = () => setOverflow(el.scrollWidth > el.clientWidth + 1);
update();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(update);
observer.observe(group);
observer.observe(text);
observer.observe(el);
return () => observer.disconnect();
}, [node.value, node.typeName, node.error]);
}, [node.value]);
if (node.kind === "message") return <span className={styles.message}>{node.name}</span>;
if (node.kind === "scope")
return (
@@ -492,22 +487,13 @@ function VarRow({
);
const kind = node.error ? null : classifyValue(node.value, node.typeName);
const shown = shownValue(node.value, node.typeName);
const evaluation = node.kind === "eval";
return (
<span className={styles.row} title={node.name}>
<span className={styles.row}>
<Icon name={nodeIcon(node)} size={16} className={styles.nodeIcon} />
{!shown.entry && (
<>
<span
className={clsx(
styles.name,
evaluation && styles.evalName,
node.kind === "var" && styles.varName,
changed && styles.changed,
)}
title={evaluation ? node.name : undefined}
>
{evaluation ? oneLine(node.name) : node.name}
<span className={clsx(styles.name, node.kind === "var" && styles.varName, changed && styles.changed)}>
{node.name}
</span>
<span className={styles.eq}>=</span>
</>
@@ -516,29 +502,23 @@ function VarRow({
<span className={styles.error}>{oneLine(node.error)}</span>
) : (
<>
{shown.label && (
<span className={styles.type} title={shown.label}>
{shown.label}
</span>
)}
<span className={styles.valueGroup}>
<span ref={valueRef} className={clsx(styles.value, kind && styles[kind])} title={node.value}>
{oneLine(shown.text)}
</span>
{overflow && (
<button
type="button"
className={styles.showValue}
title={tx("Show")}
onClick={(e) => {
e.stopPropagation();
onShowValue(node);
}}
>
…{tx("Show")}
</button>
)}
{shown.label && <span className={styles.type}>{shown.label}</span>}
<span ref={valueRef} className={clsx(styles.value, kind && styles[kind])} title={node.value}>
{oneLine(shown.text)}
</span>
{overflow && (
<button
type="button"
className={styles.showValue}
title={tx("Show")}
onClick={(e) => {
e.stopPropagation();
onShowValue(node);
}}
>
…{tx("Show")}
</button>
)}
</>
)}
</span>
@@ -1,5 +1,5 @@
/** Bounded local configuration evidence, never an effective runtime identity. */
import { isErrorKind, type FileEntry } from "@/platform/ipc";
import type { FileEntry } from "@/platform/ipc";
import { ipcPath } from "@/platform/paths";
export interface ServiceReader {
@@ -90,7 +90,7 @@ export async function loadServiceName(module: string, reader: ServiceReader): Pr
try {
entries = await reader.directory(directory);
} catch (error) {
if (isErrorKind(error, "notFound")) continue;
if ((error as { kind?: string }).kind === "notFound") continue;
return null;
}
for (const file of entries) {
+1 -2
View File
@@ -1,7 +1,6 @@
/** Installed plugins, their UI contributions, the selected plugin theme, and the operations on them. */
import { create } from "zustand";
import { tx } from "@/platform/i18n";
import { isErrorKind } from "@/platform/ipc";
import type {
ActiveTheme,
CapabilityInfo,
@@ -413,7 +412,7 @@ export async function runPluginCommand(
const status = usePlugins.getState().plugins.find((p) => p.id === pluginId)?.status;
// A trap disables the plugin and the backend already announced why; a
// consent request opens its own dialog.
const permission = isErrorKind(e, "permissionDenied");
const permission = (e as { kind?: string }).kind === "permissionDenied";
if (status !== "failed" && !permission)
notifications().notify({ group: "plugins", level: "error", title: `${title} failed`, body: errorText(e) });
return null;
+8 -29
View File
@@ -253,44 +253,26 @@
flex-direction: column;
height: 100%;
min-width: 0;
border-right: 1px solid var(--border);
}
.testToolbar,
.testStatusBar {
.testHeader {
flex: none;
display: flex;
flex-wrap: wrap;
align-items: center;
min-height: 28px;
gap: var(--space-2);
height: 28px;
padding: 0 4px 0 10px;
border-bottom: 1px solid var(--border);
}
.testToolbar {
gap: var(--space-0-5);
padding: var(--space-0-5) var(--space-1);
}
.testStatusBar {
gap: var(--space-0-5) var(--space-2);
padding: var(--space-0-5) var(--space-2);
font-size: var(--fs-ui);
color: var(--fg-secondary);
}
.testCounts {
flex: 1 1 auto;
display: flex;
flex-wrap: wrap;
gap: var(--space-0-5) var(--space-2);
gap: 10px;
min-width: 0;
overflow: hidden;
white-space: nowrap;
}
.testStatus,
.testTotalDuration {
flex: none;
}
.testTotalDuration {
margin-left: auto;
color: var(--fg-subtle);
font-size: var(--fs-small);
font-variant-numeric: tabular-nums;
}
.testTree {
flex: 1;
min-height: 0;
@@ -317,11 +299,8 @@
flex: none;
padding-right: 8px;
color: var(--fg-subtle);
font-family: var(--font-mono);
font-size: var(--fs-small);
font-variant-numeric: tabular-nums;
}
.testTree [aria-selected="true"] .testDuration {
color: var(--fg);
}
.testEmpty {
padding: 12px;
+6 -41
View File
@@ -1,6 +1,5 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import clsx from "clsx";
import type { GroupImperativeHandle, Layout } from "react-resizable-panels";
import type { RunConfig } from "@/platform/ipc";
import type { RunTargetValid } from "@/platform/remoteSettings";
import { useAgentRunSettings, useWorkflowSettings } from "@/platform/workflowSettings";
@@ -48,7 +47,7 @@ import {
} from "./store";
import { rerunFailedConfigs } from "./testing/rerun";
import { formatDuration, nodeOutput } from "./testing";
import { TestStatusBar, TestTreeView } from "./TestTreeView";
import { TestTreeView } from "./TestTreeView";
import { StackTracePanel, useStackTraces, type StackTraceTab } from "./stackTrace";
import { closeRunTab, runTabMenu } from "./runTabs";
import { showApplicationUpdate, useApplicationUpdates } from "./applicationUpdate";
@@ -60,11 +59,6 @@ import { archivedAgentSessions, closeAgentArchive } from "./agentRuns";
import styles from "./Run.module.css";
import { tx } from "@/platform/i18n";
const TEST_SPLIT_DEFAULTS = {
horizontal: { tests: 34, console: 66 },
vertical: { tests: 48, console: 52 },
};
function failed(s: RunSession): boolean {
return s.status === "failed" || (s.status === "finished" && s.exitCode !== 0 && !s.stopped);
}
@@ -99,25 +93,6 @@ export function SessionPanel({
const softWrap = wrapOverride ?? defaultWrap;
const [selectedTest, setSelectedTest] = useState<string | null>(null);
const [findOpen, setFindOpen] = useState(false);
const body = useRef<HTMLDivElement>(null);
const [stackedTests, setStackedTests] = useState(false);
const testSplit = useRef<GroupImperativeHandle>(null);
const testLayouts = useRef<Record<keyof typeof TEST_SPLIT_DEFAULTS, Layout>>({ ...TEST_SPLIT_DEFAULTS });
const testOrientation = stackedTests ? "vertical" : "horizontal";
const hasTests = !!rt?.tests;
useLayoutEffect(() => {
const pane = body.current;
if (!hasTests || !pane) return;
const measure = () => setStackedTests(pane.clientWidth < 560);
measure();
if (typeof ResizeObserver === "undefined") return;
const resize = new ResizeObserver(measure);
resize.observe(pane);
return () => resize.disconnect();
}, [hasTests]);
useLayoutEffect(() => {
if (hasTests) testSplit.current?.setLayout(testLayouts.current[testOrientation]);
}, [hasTests, testOrientation]);
const running = isLive(session);
const cwd = runDirectory(session.config.cwd);
const baseConfig = useRun(() => baseConfigOf(session));
@@ -161,7 +136,6 @@ export function SessionPanel({
const consoleColumn = (
<div className={styles.consoleColumn}>
{rt.tests && <TestStatusBar results={rt.tests} version={version} running={running} />}
{rt.console.dropped > 0 && !testModel && (
<div className={styles.notice}>{tx`${rt.console.dropped.toLocaleString()} earlier lines were discarded`}</div>
)}
@@ -305,19 +279,10 @@ export function SessionPanel({
/>
</div>
</div>
<div ref={body} className={styles.sessionBody}>
<div className={styles.sessionBody}>
{rt.tests ? (
<SplitGroup
orientation={testOrientation}
id={`run-tests-${session.id}`}
className={styles.testSplit}
groupRef={testSplit}
defaultLayout={TEST_SPLIT_DEFAULTS[testOrientation]}
onLayoutChanged={(layout, meta) => {
if (meta.isUserInteraction) testLayouts.current[testOrientation] = meta.requestedLayout ?? layout;
}}
>
<SplitPanel id="tests" minSize={stackedTests ? "28%" : "140px"}>
<SplitGroup orientation="horizontal" id={`run-tests-${session.id}`} className={styles.testSplit}>
<SplitPanel id="tests" defaultSize="32%" minSize="140px">
<TestTreeView
results={rt.tests}
version={version}
@@ -331,7 +296,7 @@ export function SessionPanel({
/>
</SplitPanel>
<SplitHandle />
<SplitPanel id="console" minSize={stackedTests ? "28%" : "200px"}>
<SplitPanel id="console" minSize="200px">
{consoleColumn}
</SplitPanel>
</SplitGroup>
+12 -18
View File
@@ -49,12 +49,6 @@ function Host(props: {
);
}
function moreItem(name: string) {
const trigger = screen.getByRole("button", { name: "More Actions" });
if (trigger.getAttribute("aria-expanded") !== "true") fireEvent.click(trigger);
return screen.getByRole("menuitem", { name });
}
describe("TestTreeView", () => {
beforeEach(() => localStorage.clear());
afterEach(() => vi.clearAllMocks());
@@ -270,17 +264,17 @@ describe("Expand All / Collapse All", () => {
expect(rows()).toContain("reuses()");
});
it("the menu runs the actions, and they are unavailable without suites", () => {
it("the buttons run the actions, and are unavailable without suites", () => {
const dispose = registerActions([
{ id: "run.expandAllTests", title: "Expand All", run: () => {} },
{ id: "run.collapseAllTests", title: "Collapse All", run: () => {} },
]);
onTestFinished(dispose);
const { unmount } = render(view(nested()));
fireEvent.click(moreItem("Expand All"));
expect(actions.executeAction).toHaveBeenCalledWith("run.expandAllTests");
fireEvent.click(moreItem("Collapse All"));
expect(actions.executeAction).toHaveBeenCalledWith("run.collapseAllTests");
fireEvent.click(screen.getByRole("button", { name: "Expand All" }));
expect(actions.executeAction).toHaveBeenCalledWith("run.expandAllTests", undefined);
fireEvent.click(screen.getByRole("button", { name: "Collapse All" }));
expect(actions.executeAction).toHaveBeenCalledWith("run.collapseAllTests", undefined);
unmount();
expect(testTree.expandAll).toBeNull();
@@ -288,8 +282,8 @@ describe("Expand All / Collapse All", () => {
flat.apply([{ type: "result", path: ["main_test"], status: "failed" }]);
flat.finish(1);
render(view(flat));
expect(moreItem("Expand All")).toHaveAttribute("aria-disabled", "true");
expect(moreItem("Collapse All")).toHaveAttribute("aria-disabled", "true");
expect(screen.getByRole("button", { name: "Expand All" })).toBeDisabled();
expect(screen.getByRole("button", { name: "Collapse All" })).toBeDisabled();
});
});
@@ -312,9 +306,9 @@ describe("Export Test Results", () => {
/>
);
it("the menu and the action open the dialog for the finished run", () => {
it("the button and the action open the dialog for the finished run", () => {
const { unmount } = render(view(finished(), false));
fireEvent.click(moreItem("Export Test Results…"));
fireEvent.click(screen.getByRole("button", { name: "Export Test Results…" }));
expect(screen.getByRole("dialog", { name: "Export Test Results" })).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
act(() => testTree.exportResults!());
@@ -328,13 +322,13 @@ describe("Export Test Results", () => {
it("is unavailable while the tests run and without results", () => {
const { rerender } = render(view(finished(), true));
expect(moreItem("Export Test Results…")).toHaveAttribute("aria-disabled", "true");
expect(screen.getByRole("button", { name: "Export Test Results…" })).toBeDisabled();
expect(testTree.exportResults).toBeNull();
rerender(view(new TestResults(), false));
expect(moreItem("Export Test Results…")).toHaveAttribute("aria-disabled", "true");
expect(screen.getByRole("button", { name: "Export Test Results…" })).toBeDisabled();
expect(testTree.exportResults).toBeNull();
rerender(view(finished(), false));
expect(moreItem("Export Test Results…")).not.toHaveAttribute("aria-disabled", "true");
expect(screen.getByRole("button", { name: "Export Test Results…" })).toBeEnabled();
expect(testTree.exportResults).not.toBeNull();
});
});
+28 -75
View File
@@ -9,7 +9,6 @@ import {
showContextMenu,
useContextMenuStore,
Spinner,
Toolbar,
Tree,
type MenuItem,
type TreeHandle,
@@ -84,41 +83,6 @@ export function StatusIcon({ status }: { status: TestStatus | null }) {
}
}
export function TestStatusBar({
results,
version,
running,
}: {
results: TestResults;
version: number;
running: boolean;
}) {
const counts = useMemo(() => results.counts(), [results, version]); // eslint-disable-line react-hooks/exhaustive-deps
const status = running
? "running"
: counts.failed
? "failed"
: counts.passed
? "passed"
: counts.skipped
? "skipped"
: null;
const duration = results.summary.durationMs;
return (
<div className={styles.testStatusBar} role="status">
<StatusIcon status={status} />
<span className={styles.testCounts}>
{counts.failed > 0 && <span className={styles.failed}>{tx`${counts.failed} failing`}</span>}
{counts.passed > 0 && <span>{tx`${counts.passed} passed`}</span>}
{counts.skipped > 0 && <span className={styles.skipped}>{tx`${counts.skipped} ignored`}</span>}
{counts.total === 0 && <span className={styles.skipped}>{running ? tx("Running…") : tx("No tests")}</span>}
</span>
{duration !== undefined && <span className={styles.testTotalDuration}>{formatDuration(duration)}</span>}
</div>
);
}
const isFailedTest = (n: TestNode) => n.children.length === 0 && nodeStatus(n) === "failed";
const treeModel = {
@@ -199,8 +163,6 @@ export function TestTreeView({
});
const sortButton = useRef<HTMLButtonElement>(null);
const [sortMenu, setSortMenu] = useState(false);
const moreButton = useRef<HTMLButtonElement>(null);
const [moreMenu, setMoreMenu] = useState(false);
const [expanded, setExpanded] = useState<Set<string> | null>(null);
const [exporting, setExporting] = useState(false);
const [selection, setSelection] = useState<Set<string>>(new Set());
@@ -264,6 +226,7 @@ export function TestTreeView({
}
};
const counts = useMemo(() => results.counts(), [results, version]); // eslint-disable-line react-hooks/exhaustive-deps
// Like IDEA, Sort by Duration applies once the run has finished, so rows don't jump while tests report.
const byDuration = sortByDuration && !running;
const roots = useMemo(() => {
@@ -313,9 +276,21 @@ export function TestTreeView({
const hasPrevFailed = findOccurrence(roots, selected, -1, treeModel) !== null;
const hasNextFailed = findOccurrence(roots, selected, 1, treeModel) !== null;
const status = running ? "running" : counts.failed > 0 ? "failed" : counts.total > 0 ? "passed" : null;
const duration = results.summary.durationMs;
return (
<div className={styles.testPane}>
<Toolbar className={styles.testToolbar} aria-label="Test results">
<div className={styles.testHeader}>
<StatusIcon status={status} />
<span className={styles.testCounts}>
{counts.failed > 0 && <span className={styles.failed}>{tx`${counts.failed} failing`}</span>}
{counts.passed > 0 && <span>{tx`${counts.passed} passed`}</span>}
{counts.skipped > 0 && <span className={styles.skipped}>{tx`${counts.skipped} ignored`}</span>}
{counts.total === 0 && <span className={styles.skipped}>{running ? tx("Running…") : tx("No tests")}</span>}
{duration !== undefined && <span className={styles.skipped}>{formatDuration(duration)}</span>}
</span>
<span className={styles.spacer} />
<IconButton
icon="test-show-passed"
size="small"
@@ -357,6 +332,14 @@ export function TestTreeView({
]}
onClose={() => setSortMenu(false)}
/>
<IconButton icon="expand-all" action="run.expandAllTests" size="small" iconSize={16} disabled={!hasSuites} />
<IconButton
icon="collapse-all"
action="run.collapseAllTests"
size="small"
iconSize={16}
disabled={!hasSuites}
/>
<IconButton
icon="arrow-up"
action="navigate.prevOccurrence"
@@ -374,42 +357,14 @@ export function TestTreeView({
disabled={!hasNextFailed}
/>
<IconButton
ref={moreButton}
icon="more-horizontal"
icon="export"
size="small"
iconSize={16}
title="More Actions"
aria-haspopup="menu"
aria-expanded={moreMenu}
onClick={() => setMoreMenu((open) => !open)}
title="Export Test Results…"
disabled={!canExport}
onClick={() => setExporting(true)}
/>
<Menu
open={moreMenu}
anchor={moreButton}
onClose={() => setMoreMenu(false)}
items={[
{
icon: "expand-all",
label: "Expand All",
disabled: !hasSuites,
run: () => void executeAction("run.expandAllTests"),
},
{
icon: "collapse-all",
label: "Collapse All",
disabled: !hasSuites,
run: () => void executeAction("run.collapseAllTests"),
},
{ kind: "separator" },
{
icon: "export",
label: "Export Test Results…",
disabled: !canExport,
run: () => setExporting(true),
},
]}
/>
</Toolbar>
</div>
{exporting && (
<ExportTestResultsDialog results={results} name={name} cwd={cwd} onClose={() => setExporting(false)} />
)}
@@ -441,9 +396,7 @@ export function TestTreeView({
return (
<span className={styles.testRow}>
<StatusIcon status={s} />
<span className={clsx(styles.testName, s === "skipped" && styles.skipped)} title={n.name}>
{n.name}
</span>
<span className={clsx(styles.testName, s === "skipped" && styles.skipped)}>{n.name}</span>
{d !== undefined && <span className={styles.testDuration}>{formatDuration(d)}</span>}
</span>
);
+24 -92
View File
@@ -1,9 +1,6 @@
.root {
--merge-band-width: 30px;
container: merge-editor / inline-size;
flex: 1;
height: 100%;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
@@ -12,16 +9,14 @@
}
.toolbar {
flex: none;
min-height: var(--h-header);
height: var(--h-header);
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1);
padding: var(--space-0-5) var(--space-1-5);
padding: 0 6px;
border-bottom: 1px solid var(--border);
}
.sep {
flex: none;
width: 1px;
height: 14px;
margin: 0 4px;
@@ -29,96 +24,59 @@
}
.status {
margin-left: auto;
padding: 0 var(--space-2);
max-width: 100%;
padding: 0 8px;
color: var(--vcs-conflict);
font-size: var(--fs-small);
text-align: end;
}
.statusDone {
color: var(--fg-muted);
}
.paneTitle,
.resultTitle {
.labels {
flex: none;
height: var(--h-row);
padding: 0 var(--space-2);
display: grid;
/* The panes' columns, so each title sits over its pane. */
grid-template-columns: 1fr 30px 1fr 30px 1fr;
border-bottom: 1px solid var(--border);
color: var(--fg-secondary);
font-size: var(--fs-small);
line-height: var(--h-row);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.resultTitle {
color: var(--fg-strong);
font-weight: 500;
text-align: center;
.labels > span {
display: flex;
align-items: center;
padding: 0 12px;
}
.sideColumn {
container: merge-side / inline-size;
.labels > span:nth-child(2) {
grid-column: 3;
}
.sideTitle {
display: none;
}
@container merge-side (max-width: 180px) {
.branchTitle {
display: none;
}
.sideTitle {
display: inline;
}
.labels > span:nth-child(3) {
grid-column: 5;
}
.panes {
flex: 1;
min-height: 0;
display: flex;
display: grid;
grid-template-columns: 1fr 30px 1fr 30px 1fr;
}
.panes[hidden] {
display: none;
}
.paneGroup {
flex: 1;
}
.pane {
flex: 1;
min-width: 0;
min-height: 0;
display: flex;
overflow: hidden;
}
.divider[data-separator] {
width: var(--merge-band-width);
background: var(--bg-app);
}
.divider[data-separator]:is([data-separator="hover"], [data-separator="active"]) {
background: var(--bg-toolbar-hover);
}
.divider[data-separator]:focus-visible {
outline: 1px solid var(--focus-ring);
outline-offset: -1px;
}
.divider::before {
content: "";
position: absolute;
inset-block-start: calc((var(--h-row) - 12px) / 2);
inset-inline-start: calc(50% - 1px);
height: 12px;
width: 2px;
border-radius: var(--radius-small);
background: var(--border-strong);
}
/* The headings share the splitter geometry. The curves start below them. */
.band {
position: absolute;
inset: var(--h-row) 0 0;
/* Between two panes, as the diff viewer's divider: the bands of the changes on either side. */
.divider {
position: relative;
min-height: 0;
overflow: hidden;
pointer-events: none;
background: var(--bg-app);
border-left: 1px solid var(--border);
border-right: 1px solid var(--border);
}
.band > svg {
.divider > svg {
position: absolute;
inset: 0;
}
@@ -145,42 +103,16 @@
.footer {
flex: none;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
padding: var(--space-2) var(--space-3);
padding: 8px 12px;
border-top: 1px solid var(--border);
}
.footerGroup {
display: flex;
flex-wrap: wrap;
min-width: 0;
gap: var(--space-2);
}
.footerGroup:last-child {
margin-inline-start: auto;
justify-content: flex-end;
}
@container merge-editor (max-width: 680px) {
.divider[data-separator] {
width: 20px;
}
}
@container merge-editor (max-width: 440px) {
.divider[data-separator] {
width: 14px;
}
.toolbar > .sep {
display: none;
}
.status {
flex-basis: 100%;
order: 1;
padding: 0;
text-align: start;
}
}
.message {
flex: 1;
outline: none;
+32 -58
View File
@@ -1,5 +1,5 @@
/** Three-pane merge editor: Yours | Result | Theirs, after IntelliJ's merge tool. */
import { useCallback, useEffect, useId, useRef, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { Transaction, type EditorState, type Extension, type TransactionSpec } from "@codemirror/state";
import { EditorView, keymap } from "@codemirror/view";
import { history, historyKeymap, undoDepth } from "@codemirror/commands";
@@ -11,7 +11,7 @@ import { setContext } from "@/platform/context";
import { tx, useTxTemplate } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { copyText } from "@/ui/selectableText";
import { Button, Spinner, SplitGroup, SplitHandle, SplitPanel, T } from "@/ui";
import { Button, Spinner, T } from "@/ui";
import { editorService, type EditorInput } from "@/workbench/contributions";
import { blameSlot, toggleAnnotations } from "./blame";
import { firstLineOf, languageFor, viewerBase } from "./cm";
@@ -114,7 +114,6 @@ export function MergeEditor({ input }: { input: EditorInput }) {
const [summary, setSummary] = useState<MergeSummary>(NOTHING_LEFT);
const [autoApply, setAutoApply] = useState(readAutoApply);
const [resolved, setResolved] = useState(false);
const paneId = useId();
const rootRef = useRef<HTMLDivElement>(null);
const paneRef = useRef<MergeSide | "result">("result");
const [actionHost] = useState<MergeActionHost>(() => ({
@@ -608,70 +607,45 @@ export function MergeEditor({ input }: { input: EditorInput }) {
</div>
);
const yourTitle = txt(titles.yours);
const resultTitle = tx("Result");
const theirTitle = txt(titles.theirs);
return (
<div ref={rootRef} className={styles.root} {...focusProps}>
<MergeToolbar summary={summary} step={goto} run={(c) => void runAction(c)} />
<div className={styles.labels}>
<span>{txt(titles.yours)}</span>
<span>
<T>Result</T>
</span>
<span>{txt(titles.theirs)}</span>
</div>
{!state || lang === null ? (
<div className={styles.message}>
<Spinner size={14} />
</div>
) : null}
<div className={styles.panes} hidden={!state || lang === null}>
<SplitGroup className={styles.paneGroup} orientation="horizontal">
<SplitPanel
id={`${paneId}-yours`}
role="region"
aria-label={tx("Your version")}
className={styles.sideColumn}
minSize="18%"
defaultSize="30%"
>
<div className={styles.paneTitle} title={yourTitle}>
<span className={styles.branchTitle}>{yourTitle}</span>
<span className={styles.sideTitle}>{tx("Your version")}</span>
</div>
<div
ref={oursRef}
className={styles.pane}
onContextMenu={(e) => oursView.current && showSideMenu(e, oursView.current, "left")}
/>
</SplitPanel>
<SplitHandle className={styles.divider} aria-label={tx("Resize left merge pane")}>
<div ref={leftDividerRef} className={styles.band} aria-hidden />
</SplitHandle>
<SplitPanel id={`${paneId}-result`} role="region" aria-label={resultTitle} minSize="24%" defaultSize="40%">
<div className={styles.resultTitle}>{resultTitle}</div>
<div
ref={resultRef}
className={styles.pane}
onContextMenu={(e) => resultView.current && showResultMenu(e, resultView.current)}
/>
</SplitPanel>
<SplitHandle className={styles.divider} aria-label={tx("Resize right merge pane")}>
<div ref={rightDividerRef} className={styles.band} aria-hidden />
</SplitHandle>
<SplitPanel
id={`${paneId}-theirs`}
role="region"
aria-label={tx("Their version")}
className={styles.sideColumn}
minSize="18%"
defaultSize="30%"
>
<div className={styles.paneTitle} title={theirTitle}>
<span className={styles.branchTitle}>{theirTitle}</span>
<span className={styles.sideTitle}>{tx("Their version")}</span>
</div>
<div
ref={theirsRef}
className={styles.pane}
onContextMenu={(e) => theirsView.current && showSideMenu(e, theirsView.current, "right")}
/>
</SplitPanel>
</SplitGroup>
<div
ref={oursRef}
className={styles.pane}
aria-label={tx("Your version")}
role="region"
onContextMenu={(e) => oursView.current && showSideMenu(e, oursView.current, "left")}
/>
<div ref={leftDividerRef} className={styles.divider} aria-hidden />
<div
ref={resultRef}
className={styles.pane}
aria-label={tx("Result")}
role="region"
onContextMenu={(e) => resultView.current && showResultMenu(e, resultView.current)}
/>
<div ref={rightDividerRef} className={styles.divider} aria-hidden />
<div
ref={theirsRef}
className={styles.pane}
aria-label={tx("Their version")}
role="region"
onContextMenu={(e) => theirsView.current && showSideMenu(e, theirsView.current, "right")}
/>
</div>
<MergeFooter run={(c) => void runAction(c)} />
</div>
+1 -3
View File
@@ -97,9 +97,7 @@ export function MergeToolbar({ summary, step, run }: ToolbarProps) {
onClick={direct(() => run("compare"))}
data-merge-menu="compare"
/>
<span className={clsx(styles.status, !summary.pending && styles.statusDone)} role="status">
{statusText(summary)}
</span>
<span className={clsx(styles.status, !summary.pending && styles.statusDone)}>{statusText(summary)}</span>
<IconButton
icon="refresh"
title="Reload from Disk"
+4 -4
View File
@@ -134,12 +134,12 @@ export function PushChanges({
</div>
{count === 1 ? (
<SplitGroup orientation="vertical" storageKey={DETAILS_SPLIT_KEY} className={styles.pushDetailsSplit}>
<SplitPanel id="files" minSize="40%" defaultSize="67%" className={styles.pushDetailsPanel}>
{files}
<SplitPanel id="details" minSize="40px" defaultSize="25%" className={styles.pushDetailsPanel}>
<PushCommitDetails commit={commits[0]!} />
</SplitPanel>
<SplitHandle />
<SplitPanel id="details" minSize="24%" className={styles.pushDetailsPanel}>
<PushCommitDetails commit={commits[0]!} />
<SplitPanel id="files" minSize="80px" className={styles.pushDetailsPanel}>
{files}
</SplitPanel>
</SplitGroup>
) : (
+7 -49
View File
@@ -1,5 +1,4 @@
import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
import type { GroupImperativeHandle } from "react-resizable-panels";
import { useState, type ReactNode } from "react";
import { tx } from "@/platform/i18n";
import { IconButton, SplitGroup, SplitHandle, SplitPanel, lazyComponent } from "@/ui";
import { diffInput } from "./diffInput";
@@ -9,10 +8,6 @@ import styles from "./common.module.css";
const DiffEditor = lazyComponent(() => import("./DiffEditor").then((m) => m.DiffEditor));
const PUSH_DIFF_SPLIT_KEY = "openidea.vcs.push.diffSplit";
const PUSH_SIDES_SPLIT_KEY = "openidea.vcs.pushSides";
const PUSH_STACKED_SPLIT_KEY = "openidea.vcs.push.stackedSplit";
const SIDE_LAYOUT = { commits: 50, changes: 50 };
const STACKED_LAYOUT = { commits: 34, changes: 66 };
export function usePushDiff(shownKey: string) {
const [state, setState] = useState<{ key: string; change: LogChange } | null>(null);
@@ -23,59 +18,22 @@ export function usePushDiff(shownKey: string) {
};
}
interface PushReviewProps {
interface PushDiffSplitProps {
diff: LogChange | null;
onClose: () => void;
commits: ReactNode;
changes: ReactNode;
children: ReactNode;
}
export function PushReview({ diff, onClose, commits, changes }: PushReviewProps) {
const summary = useRef<HTMLDivElement>(null);
const group = useRef<GroupImperativeHandle>(null);
const [stacked, setStacked] = useState(false);
const previous = useRef(stacked);
const layout = stacked ? STACKED_LAYOUT : SIDE_LAYOUT;
useLayoutEffect(() => {
const el = summary.current;
if (!el) return;
const measure = () => setStacked(el.clientWidth < 640);
measure();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(measure);
observer.observe(el);
return () => observer.disconnect();
}, []);
useLayoutEffect(() => {
if (previous.current === stacked) return;
previous.current = stacked;
group.current?.setLayout(layout);
}, [stacked, layout]);
export function PushDiffSplit({ diff, onClose, children }: PushDiffSplitProps) {
return (
<SplitGroup orientation="vertical" storageKey={diff ? PUSH_DIFF_SPLIT_KEY : undefined} className={styles.pushSplit}>
<SplitPanel id="sides" minSize="32%" defaultSize="58%" className={styles.pushSplitPanel}>
<SplitGroup
elementRef={summary}
groupRef={group}
orientation={stacked ? "vertical" : "horizontal"}
storageKey={stacked ? PUSH_STACKED_SPLIT_KEY : PUSH_SIDES_SPLIT_KEY}
defaultLayout={layout}
className={styles.pushSides}
>
<SplitPanel id="commits" minSize={stacked ? "24%" : "240px"} className={styles.pushSplitPanel}>
{commits}
</SplitPanel>
<SplitHandle />
<SplitPanel id="changes" minSize={stacked ? "32%" : "240px"} className={styles.pushSplitPanel}>
{changes}
</SplitPanel>
</SplitGroup>
<SplitPanel id="sides" minSize="120px" defaultSize="50%" className={styles.pushSplitPanel}>
{children}
</SplitPanel>
{diff && (
<>
<SplitHandle />
<SplitPanel id="diff" minSize="25%" className={styles.pushSplitPanel}>
<SplitPanel id="diff" minSize="120px" defaultSize="50%" className={styles.pushSplitPanel}>
<PushDiff change={diff} onClose={onClose} />
</SplitPanel>
</>
+14 -84
View File
@@ -150,58 +150,22 @@
display: flex;
flex-direction: column;
}
.pushOptions,
.pushTagOptions {
display: flex;
align-items: center;
gap: var(--space-2);
}
.pushOptions {
flex-wrap: wrap;
max-width: 100%;
font-size: var(--fs-ui);
}
.pushTargetBar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-1) var(--space-2);
padding: var(--space-2) var(--space-3) 0;
}
.pushTargetSource {
max-width: 100%;
overflow-wrap: anywhere;
color: var(--fg-secondary);
}
.pushTargetControls {
display: flex;
align-items: center;
flex: 1 1 240px;
min-width: 0;
gap: var(--space-1);
}
.pushTargetControls .targetInput {
flex: 0 1 330px;
min-width: 8ch;
width: auto;
margin: 0;
}
.pushTreeWrap {
flex: 1;
min-height: 220px;
display: flex;
flex-direction: column;
padding: var(--space-2) var(--space-3) var(--space-3);
padding: 14px;
}
.pushListWrap {
flex: 1;
min-height: 180px;
display: flex;
flex-direction: column;
padding: var(--space-2) var(--space-3) var(--space-3);
padding: 0 14px 14px;
}
.pushSplit {
flex: 1 1 min(450px, 65vh);
flex: 1 1 min(540px, 60vh);
min-height: 0;
}
/* The panel's own `height: 100%` doesn't resolve against a flex-basis height in WebKit: stretch instead. */
@@ -245,8 +209,8 @@
.pushSplitPanel > .pushTreeWrap {
min-height: 0;
}
.pushRepoRow[data-idle],
.pushRepoRow[data-idle] label {
.pushTreeWrap .commitRow[data-idle],
.pushTreeWrap .commitRow[data-idle] label {
color: var(--fg-subtle);
}
.pushChanges {
@@ -254,23 +218,21 @@
display: flex;
flex-direction: column;
min-height: 0;
padding-top: var(--space-2);
padding-top: 8px;
}
.pushChanges .comparison {
flex: 1;
height: auto;
min-height: 0;
padding: 0 var(--space-3) var(--space-2);
padding: 0 14px 14px;
}
.pushChangesTitle {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-2);
min-height: var(--h-control);
padding: 0 var(--space-3) var(--space-1);
min-height: 24px;
padding: 0 14px 6px;
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.pushGrouping {
margin-left: auto;
@@ -288,8 +250,8 @@
display: flex;
flex-direction: column;
gap: var(--space-1);
margin: var(--space-1) var(--space-3);
padding: var(--space-1) var(--space-2);
margin: 0 14px 8px;
padding: 6px 8px;
overflow: auto;
border: 1px solid var(--border);
border-radius: var(--radius-small);
@@ -454,55 +416,23 @@
white-space: nowrap;
}
/* Fits the remote and target fields into a 22px tree row. */
.pushRepoRow {
display: flex;
align-items: center;
gap: var(--space-1);
flex: 1;
min-width: 0;
}
.pushRepoName {
min-width: 20px;
}
.pushRepoLabel,
.pushSourceBranch,
.pushRemoteName {
display: block;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.pushSourceBranch,
.pushRemoteName {
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.pushRemoteName {
flex: none;
max-width: 14ch;
}
.pushRowTarget {
--h-field: var(--h-control-small);
--h-control: var(--h-control-small);
display: inline-flex;
align-items: center;
gap: var(--space-0-5);
min-width: 10ch;
min-width: 0;
font-size: var(--fs-small);
}
.pushTargetControls > button,
.pushRowTarget > button {
min-width: 0;
max-width: 18ch;
.pushRowTarget button {
font-size: var(--fs-small);
}
.pushRowSeparator {
flex: none;
color: var(--fg-faint);
}
.pushRowInput {
min-width: 7ch;
min-width: 0;
font-size: var(--fs-small);
}
.pushRowInput[data-changed]:not(:focus-visible) {
+169 -189
View File
@@ -5,14 +5,27 @@ import { call, commands } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { workflowSettings, type UpdateMethod } from "@/platform/workflowSettings";
import { notifications } from "@/workbench/contributions";
import { Button, Checkbox, Dialog, Input, List, Select, Spinner, T, Tree } from "@/ui";
import {
Button,
Checkbox,
Dialog,
Input,
List,
Select,
Spinner,
SplitGroup,
SplitHandle,
SplitPanel,
T,
Tree,
} from "@/ui";
import { ask } from "@/workbench/messages";
import { openDialog } from "./dialogs";
import { saveVcsSetting } from "./settingsUi";
import { formatTime } from "./model";
import { allRepos, lastRemoteFailure, runRemote, saveAll } from "./ops";
import { PushChanges, pushChangesKey } from "./PushChanges";
import { PushReview, usePushDiff } from "./PushDiff";
import { PushDiffSplit, usePushDiff } from "./PushDiff";
import { pushOperation, splitTracked, type PushChoice } from "./pushTarget";
import { currentRepo, currentRepoRoot, loadBranches, refreshNow, repoName, useVcs } from "./store";
import { stripRemotePrefix, TargetBranchInput } from "./TargetBranchInput";
@@ -233,18 +246,10 @@ interface PushNode {
children?: PushNode[];
}
// A long outgoing list scrolls inside the dialog instead of growing it to the screen (IDEA: 800×450 centre panel).
const PUSH_DIALOG_MAX_HEIGHT = 720;
const PUSH_DIALOG_WIDTH = 800;
const PUSH_DIALOG_MIN_WIDTH = 420;
function PushCommitSubject({ commit }: { commit: Commit }) {
const metadata = [commit.shortId, commit.author, formatTime(commit.timeMs)].filter(Boolean).join(" · ");
return (
<span className={styles.commitSubject} title={`${metadata}\n${commit.message.trimEnd() || commit.summary}`}>
{commit.summary}
</span>
);
}
const PUSH_DIALOG_WIDTH = 960;
const PUSH_SPLIT_KEY = "openidea.vcs.pushSides";
interface MultiPushDialogProps {
only?: string;
@@ -407,17 +412,15 @@ function MultiPushDialog({ only, onClose }: MultiPushDialogProps) {
title={only === undefined ? "Push Commits" : tx`Push Commits to ${repoName(only)}`}
onClose={onClose}
width={PUSH_DIALOG_WIDTH}
minWidth={PUSH_DIALOG_MIN_WIDTH}
minHeight={340}
maxHeight={PUSH_DIALOG_MAX_HEIGHT}
className={styles.pushDialog}
resizable="both"
footerStart={
<div className={styles.pushOptions}>
<>
<Checkbox checked={force} onChange={setForce} label="Force (with lease)" />
{hasHook && <Checkbox checked={runHooks} onChange={setRunHooks} label="Run Git hooks" />}
{!retargeted && (
<span className={styles.pushTagOptions}>
<>
<Checkbox checked={pushTags} onChange={setPushTags} label="Push tags:" />
<Select<PushTags>
value={tagsMode}
@@ -429,9 +432,9 @@ function MultiPushDialog({ only, onClose }: MultiPushDialogProps) {
{ value: "currentBranch", label: "Current Branch" },
]}
/>
</span>
</>
)}
</div>
</>
}
buttons={[
{
@@ -444,114 +447,107 @@ function MultiPushDialog({ only, onClose }: MultiPushDialogProps) {
{ label: "Cancel", role: "cancel" },
]}
>
<PushReview
diff={diff}
onClose={closeDiff}
commits={
<div className={styles.pushTreeWrap}>
{error ? (
<div className={styles.error}>{error}</div>
) : !repos ? (
<div className={styles.empty}>
<Spinner size={14} />
</div>
) : (
<Tree<PushNode>
roots={nodes}
getKey={(n) => n.key}
getLabel={(n) => (n.commit ? n.commit.summary : repoName(n.repo.root))}
getChildren={(n) => n.children}
isExpandable={(n) => !!n.children?.length}
expanded={expanded}
onExpandedChange={(_next, node, open) =>
setExpanded((e) => {
const s = new Set(e);
if (open) s.add(node.key);
else s.delete(node.key);
return s;
})
}
selected={new Set(shown ? [shown.key] : [])}
multiSelect={false}
onSelectionChange={(_sel, lead) => setShown(lead)}
rowHeight={rowHeight}
aria-label="Outgoing commits"
className={styles.boxList}
empty={
<span>
<T>Everything is up to date</T>
</span>
}
renderNode={(n) =>
n.commit ? (
<PushCommitSubject commit={n.commit} />
) : (
<span
className={styles.pushRepoRow}
data-idle={hasNothingToPush(n.repo) || undefined}
// A row click toggles the checkbox, like before; only the chevron collapses.
onClick={(e) => {
if (only === undefined && !(e.target as HTMLElement | null)?.closest?.("label"))
toggle(n.repo.root);
}}
>
{only === undefined ? (
<Checkbox
checked={checked.has(n.repo.root)}
onChange={() => toggle(n.repo.root)}
className={styles.pushRepoName}
label={
<span className={styles.pushRepoLabel} title={repoName(n.repo.root)}>
{repoName(n.repo.root)}
</span>
}
/>
) : (
<span className={styles.pushRepoLabel} title={repoName(n.repo.root)}>
{repoName(n.repo.root)}
</span>
)}
<span className={styles.pushSourceBranch} title={n.repo.branch.head ?? undefined}>
{n.repo.branch.head}
</span>
<span className={styles.pushRowSeparator} aria-hidden>
→
</span>
<PushRowTarget
name={repoName(n.repo.root)}
remotes={remotesOf[n.repo.root] ?? []}
remote={shownRemoteOf(n.repo)}
onRemote={(remote) => edit(n.repo.root, { remote })}
target={edits[n.repo.root]?.target ?? targetOf(n.repo)}
onTarget={(target) => edit(n.repo.root, { target })}
changed={pushOperation(choiceOf(n.repo, null)).op === "pushBranch"}
onEnter={() => {
if (picked.length) void push();
}}
/>
{!n.repo.branch.upstream && (
<span className={styles.pushSourceBranch} title={tx("new remote branch")}>
{tx("new remote branch")}
</span>
)}
<PushDiffSplit diff={diff} onClose={closeDiff}>
<SplitGroup orientation="horizontal" storageKey={PUSH_SPLIT_KEY} className={styles.pushSides}>
<SplitPanel id="commits" minSize="240px" defaultSize="50%" className={styles.pushSplitPanel}>
<div className={styles.pushTreeWrap}>
{error ? (
<div className={styles.error}>{error}</div>
) : !repos ? (
<div className={styles.empty}>
<Spinner size={14} />
</div>
) : (
<Tree<PushNode>
roots={nodes}
getKey={(n) => n.key}
getLabel={(n) => (n.commit ? n.commit.summary : repoName(n.repo.root))}
getChildren={(n) => n.children}
isExpandable={(n) => !!n.children?.length}
expanded={expanded}
onExpandedChange={(_next, node, open) =>
setExpanded((e) => {
const s = new Set(e);
if (open) s.add(node.key);
else s.delete(node.key);
return s;
})
}
selected={new Set(shown ? [shown.key] : [])}
multiSelect={false}
onSelectionChange={(_sel, lead) => setShown(lead)}
rowHeight={rowHeight}
aria-label="Outgoing commits"
className={styles.boxList}
empty={
<span>
<T>Everything is up to date</T>
</span>
)
}
}
renderNode={(n) =>
n.commit ? (
<span className={styles.commitRow} style={{ flex: 1, padding: 0 }}>
<span className={styles.commitHash}>{n.commit.shortId}</span>
<span className={styles.commitSubject}>{n.commit.summary}</span>
<span className={styles.commitMeta}>{n.commit.author}</span>
<span className={styles.commitMeta}>{formatTime(n.commit.timeMs)}</span>
</span>
) : (
<span
className={styles.commitRow}
data-idle={hasNothingToPush(n.repo) || undefined}
style={{ flex: 1, padding: 0 }}
// A row click toggles the checkbox, like before; only the chevron collapses.
onClick={(e) => {
if (only === undefined && !(e.target as HTMLElement | null)?.closest?.("label"))
toggle(n.repo.root);
}}
>
{only === undefined ? (
<Checkbox
checked={checked.has(n.repo.root)}
onChange={() => toggle(n.repo.root)}
label={repoName(n.repo.root)}
/>
) : (
<span className={styles.commitSubject}>{repoName(n.repo.root)}</span>
)}
<span className={styles.commitMeta}>{n.repo.branch.head} →</span>
<PushRowTarget
name={repoName(n.repo.root)}
remotes={remotesOf[n.repo.root] ?? []}
remote={shownRemoteOf(n.repo)}
onRemote={(remote) => edit(n.repo.root, { remote })}
target={edits[n.repo.root]?.target ?? targetOf(n.repo)}
onTarget={(target) => edit(n.repo.root, { target })}
changed={pushOperation(choiceOf(n.repo, null)).op === "pushBranch"}
onEnter={() => {
if (picked.length) void push();
}}
/>
{!n.repo.branch.upstream && (
<span className={styles.commitMeta}>{tx("new remote branch")}</span>
)}
</span>
)
}
/>
)}
</div>
</SplitPanel>
<SplitHandle />
<SplitPanel id="changes" minSize="240px" className={styles.pushSplitPanel}>
{shownRepo && (
<PushChanges
key={pushChangesKey(shownRepo.root, shownCommits)}
repo={shownRepo.root}
commits={shownCommits}
onSelectFile={showDiff}
/>
)}
</div>
}
changes={
shownRepo && (
<PushChanges
key={pushChangesKey(shownRepo.root, shownCommits)}
repo={shownRepo.root}
commits={shownCommits}
onSelectFile={showDiff}
/>
)
}
/>
</SplitPanel>
</SplitGroup>
</PushDiffSplit>
</Dialog>
);
}
@@ -587,11 +583,7 @@ function PushRowTarget(props: {
options={props.remotes.map((r) => ({ value: r, label: r }))}
/>
) : (
props.remote && (
<span className={styles.pushRemoteName} title={props.remote}>
{props.remote}
</span>
)
props.remote && <span className={styles.commitMeta}>{props.remote}</span>
)}
{props.remote && <span className={styles.pushRowSeparator}>/</span>}
<Input
@@ -752,7 +744,14 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
aria-label="Outgoing commits"
className={styles.boxList}
empty={<span>{upstream ? tx("Everything is up to date") : tx("No commits")}</span>}
renderItem={(c) => <PushCommitSubject commit={c} />}
renderItem={(c) => (
<span className={styles.commitRow} style={{ flex: 1, padding: 0 }}>
<span className={styles.commitHash}>{c.shortId}</span>
<span className={styles.commitSubject}>{c.summary}</span>
<span className={styles.commitMeta}>{c.author}</span>
<span className={styles.commitMeta}>{formatTime(c.timeMs)}</span>
</span>
)}
/>
)}
</div>
@@ -763,13 +762,11 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
title={head ? tx`Push Commits to ${upstream ?? "remote"}` : "Push"}
onClose={onClose}
width={commits?.length ? PUSH_DIALOG_WIDTH : 620}
minWidth={PUSH_DIALOG_MIN_WIDTH}
minHeight={340}
maxHeight={PUSH_DIALOG_MAX_HEIGHT}
className={styles.pushDialog}
resizable="both"
footerStart={
<div className={styles.pushOptions}>
<>
<span title={protectedTarget ? `Force push to protected branch '${target}' is prohibited` : undefined}>
<Checkbox
checked={force && !protectedTarget}
@@ -788,7 +785,7 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
/>
)}
{!explicit && !retarget && !remoteChanged && (
<span className={styles.pushTagOptions}>
<>
<Checkbox checked={pushTags} onChange={setPushTags} label="Push tags:" />
<Select<PushTags>
value={tagsMode}
@@ -800,9 +797,9 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
{ value: "currentBranch", label: "Current Branch" },
]}
/>
</span>
</>
)}
</div>
</>
}
buttons={[
{
@@ -815,62 +812,45 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
{ label: "Cancel", role: "cancel" },
]}
>
<div className={styles.pushTargetBar}>
<span className={styles.pushTargetSource}>
{!head
? tx("HEAD is detached; check out a branch to push.")
: trackedBranch
? `${head}${revision ? ` up to ${revision.slice(0, 8)}` : ""} →`
: revision
? tx`${head} has no upstream: commits up to ${revision.slice(0, 8)} will be pushed as a new branch:`
: tx`${head} has no upstream: it will be pushed as a new branch and tracked:`}
</span>
{head && (
<div className={styles.pushTargetControls}>
{remotes.length > 1 ? (
<Select<string>
value={remote ?? ""}
aria-label="Remote"
onChange={setRemote}
options={remotes.map((r) => ({ value: r, label: r }))}
/>
) : (
remote && (
<span className={styles.pushRemoteName} title={remote}>
{remote}
</span>
)
)}
{remote && (
<span className={styles.pushRowSeparator} aria-hidden>
/
</span>
)}
<TargetBranchInput
value={targetName}
onChange={setTargetName}
branches={remoteBranchNames}
remote={remote}
/>
{retarget && !remoteBranchNames.includes(edited) && <span className={styles.hint}>{tx("New")}</span>}
</div>
<div className={styles.section}>
{!head
? tx("HEAD is detached; check out a branch to push.")
: trackedBranch
? `${head}${revision ? ` up to ${revision.slice(0, 8)}` : ""} → ${remote ?? trackedRemote ?? ""}/`
: revision
? tx`${head} has no upstream: commits up to ${revision.slice(0, 8)} will be pushed as a new branch:`
: tx`${head} has no upstream: it will be pushed as a new branch and tracked:`}
{head && remotes.length > 1 && (
<Select<string>
value={remote ?? ""}
aria-label="Remote"
onChange={setRemote}
options={remotes.map((r) => ({ value: r, label: r }))}
/>
)}
{head && (
<TargetBranchInput value={targetName} onChange={setTargetName} branches={remoteBranchNames} remote={remote} />
)}
{retarget && !remoteBranchNames.includes(edited) && <span className={styles.hint}> {tx("New")}</span>}
</div>
{commits?.length && !error ? (
<PushReview
diff={diff}
onClose={closeDiff}
commits={commitList}
changes={
<PushChanges
key={pushChangesKey(repo, shownCommits)}
repo={repo}
commits={shownCommits}
onShowAll={shownCommit >= 0 && commits.length > 1 ? () => setShownCommit(-1) : undefined}
onSelectFile={showDiff}
/>
}
/>
<PushDiffSplit diff={diff} onClose={closeDiff}>
<SplitGroup orientation="horizontal" storageKey={PUSH_SPLIT_KEY} className={styles.pushSides}>
<SplitPanel id="commits" minSize="240px" defaultSize="50%" className={styles.pushSplitPanel}>
{commitList}
</SplitPanel>
<SplitHandle />
<SplitPanel id="changes" minSize="240px" className={styles.pushSplitPanel}>
<PushChanges
key={pushChangesKey(repo, shownCommits)}
repo={repo}
commits={shownCommits}
onShowAll={shownCommit >= 0 && commits.length > 1 ? () => setShownCommit(-1) : undefined}
onSelectFile={showDiff}
/>
</SplitPanel>
</SplitGroup>
</PushDiffSplit>
) : (
commitList
)}
-208
View File
@@ -1,208 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { BranchInfo, FileStatus, ProjectInfo, VcsRoot } from "@/bindings";
import { commands, isTauri } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { deferred } from "@/test/deferred";
import { getFileDecoration } from "@/workbench/contributions";
import {
discoverRoots,
installVcsStore,
onConflictsAppeared,
onConflictsCleared,
refreshNow,
refreshPathsNow,
useVcs,
} from "./store";
vi.mock(import("@/platform/ipc"), async (original) => ({
...(await original()),
isTauri: vi.fn(() => false),
}));
const git: ProjectInfo = { root: "/a", name: "a", isGit: true, trusted: true, settings: {} };
const nonGit: ProjectInfo = { root: "/b", name: "b", isGit: false, trusted: true, settings: {} };
const branch: BranchInfo = {
head: "feature-a",
headCommit: "abc1234",
upstream: null,
ahead: 0,
behind: 0,
operation: "merge",
};
const roots: VcsRoot[] = [{ root: git.root, head: branch.head, headCommit: branch.headCommit, operation: "merge" }];
const conflicted: FileStatus = {
path: "/a/src/conflict.ts",
relPath: "src/conflict.ts",
staged: null,
unstaged: "conflicted",
renamedFrom: null,
};
const modified: FileStatus = {
...conflicted,
path: "/a/src/edited.ts",
relPath: "src/edited.ts",
unstaged: "modified",
};
const status = [conflicted, modified];
type Ok<T> = { status: "ok"; data: T };
const ok = <T>(data: T): Ok<T> => ({ status: "ok", data });
let dispose: () => void;
const appeared = vi.fn();
const cleared = vi.fn();
beforeEach(() => {
vi.spyOn(commands, "vcsRoots").mockResolvedValue(ok(roots));
vi.spyOn(commands, "vcsStatus").mockResolvedValue(ok(status));
vi.spyOn(commands, "vcsBranchInfo").mockResolvedValue(ok(branch));
onConflictsAppeared(appeared);
onConflictsCleared(cleared);
dispose = installVcsStore();
});
afterEach(() => {
dispose();
onConflictsAppeared(() => undefined);
onConflictsCleared(() => undefined);
appeared.mockClear();
cleared.mockClear();
vi.restoreAllMocks();
vi.mocked(isTauri).mockReset();
useProject.setState(useProject.getInitialState(), true);
useVcs.setState(useVcs.getInitialState(), true);
});
describe("VCS status ownership", () => {
it.each([
{ command: "status", reopen: false },
{ command: "roots", reopen: false },
{ command: "status", reopen: true },
])("drops a late $command response after switching projects (reopen: $reopen)", async ({ command, reopen }) => {
const response = deferred<void>();
const request =
command === "status"
? vi.mocked(commands.vcsStatus).mockReturnValueOnce(response.promise.then(() => ok(status)))
: vi.mocked(commands.vcsRoots).mockReturnValueOnce(response.promise.then(() => ok(roots)));
useProject.setState({ project: git });
const refreshing = refreshNow();
try {
await vi.waitFor(() => expect(request).toHaveBeenCalledOnce());
// Emulate desktop discovery of nested roots for the non-Git project; there are none.
vi.mocked(isTauri).mockReturnValueOnce(true);
vi.mocked(commands.vcsRoots).mockResolvedValueOnce(ok([]));
useProject.setState({ project: nonGit });
const current = reopen ? { ...git } : nonGit;
if (reopen) useProject.setState({ project: current });
const reset = useVcs.getState();
expect(reset).toMatchObject({ root: current.root, status: [], branch: null, statusLoaded: false });
response.resolve();
await refreshing;
expect(useProject.getState().project).toBe(current);
expect.soft(useVcs.getState()).toEqual(reset);
expect.soft(getFileDecoration(conflicted.path)).toBeUndefined();
expect.soft(getFileDecoration(modified.path)).toBeUndefined();
expect.soft(appeared).not.toHaveBeenCalled();
expect.soft(cleared).not.toHaveBeenCalled();
} finally {
response.resolve();
await refreshing;
}
});
it("does not publish an old refresh error in the new project", async () => {
const reply = deferred<Ok<FileStatus[]>>();
const request = vi.mocked(commands.vcsStatus).mockReturnValueOnce(reply.promise);
useProject.setState({ project: git });
const refreshing = refreshNow();
try {
await vi.waitFor(() => expect(request).toHaveBeenCalledOnce());
useProject.setState({ project: nonGit });
const reset = useVcs.getState();
reply.reject(new Error("project A's Git status failed"));
await refreshing;
expect(useVcs.getState()).toEqual(reset);
} finally {
reply.resolve(ok(status));
await refreshing;
}
});
it("does not enable VCS from a discovery started before reopening the same folder", async () => {
const reply = deferred<Ok<VcsRoot[]>>();
const request = vi.mocked(commands.vcsRoots).mockReturnValueOnce(reply.promise);
const folder = { ...git, isGit: false };
useProject.setState({ project: folder });
vi.mocked(isTauri).mockReturnValueOnce(true);
const discovering = discoverRoots();
// Drain any incorrectly started full refresh before disposing.
const refreshed = deferred<void>();
const offRefresh = useVcs.subscribe((s, prev) => {
if (prev.loading && !s.loading) refreshed.resolve();
});
try {
await vi.waitFor(() => expect(request).toHaveBeenCalledOnce());
useProject.setState({ project: nonGit });
useProject.setState({ project: { ...folder } });
reply.resolve(ok(roots));
await discovering;
if (useVcs.getState().loading) await refreshed.promise;
expect.soft(useVcs.getState()).toMatchObject({ root: folder.root, available: false, roots: [], status: [] });
expect.soft(commands.vcsStatus).not.toHaveBeenCalled();
} finally {
reply.resolve(ok([]));
await discovering;
if (useVcs.getState().loading) await refreshed.promise;
offRefresh();
}
});
it("drains a queued refresh for the new project without retrying the old incremental refresh", async () => {
useProject.setState({ project: git });
await refreshNow();
const reply = deferred<Ok<FileStatus[]>>();
const request = vi.spyOn(commands, "vcsStatusPaths").mockReturnValueOnce(reply.promise);
const refreshing = refreshPathsNow([conflicted.path]);
let next: Promise<void> | undefined;
try {
await vi.waitFor(() => expect(request).toHaveBeenCalledWith([conflicted.path]));
const nextBranch = { ...branch, head: "main", operation: null };
vi.mocked(commands.vcsRoots).mockResolvedValue(
ok([{ root: nonGit.root, head: nextBranch.head, headCommit: nextBranch.headCommit, operation: null }]),
);
vi.mocked(commands.vcsStatus).mockResolvedValue(ok([]));
vi.mocked(commands.vcsBranchInfo).mockResolvedValue(ok(nextBranch));
vi.mocked(isTauri).mockReturnValueOnce(true);
useProject.setState({ project: { ...nonGit, isGit: true } });
next = refreshNow();
reply.resolve(ok([conflicted]));
await Promise.all([refreshing, next]);
expect(useVcs.getState()).toMatchObject({ root: nonGit.root, status: [], branch: nextBranch });
expect(getFileDecoration(conflicted.path)).toBeUndefined();
expect(commands.vcsStatus).toHaveBeenCalledTimes(2);
} finally {
reply.resolve(ok([]));
await Promise.all([refreshing, next]);
}
});
it("applies branch, changed files, decorations and conflict notifications for the active project", async () => {
useProject.setState({ project: git });
await refreshNow();
expect(useVcs.getState()).toMatchObject({ root: git.root, roots: [git.root], branch, status, statusLoaded: true });
expect(useVcs.getState().byPath).toEqual(new Map(status.map((file) => [file.path, file])));
expect(getFileDecoration(conflicted.path)?.color).toBe("var(--vcs-conflict)");
expect(getFileDecoration(modified.path)?.color).toBe("var(--vcs-modified)");
expect(appeared).toHaveBeenCalledExactlyOnceWith([conflicted]);
expect(cleared).not.toHaveBeenCalled();
});
});
+6 -19
View File
@@ -152,9 +152,6 @@ export function conflictedFiles(status: readonly FileStatus[] = useVcs.getState(
return status.filter((f) => effectiveKind(f) === "conflicted");
}
// Reopening the same root starts a new lifetime.
let projectGeneration = 0;
let timer: ReturnType<typeof setTimeout> | undefined;
/** A full refresh is queued; it answers for every path an incremental one would. */
let pendingFull = false;
@@ -224,7 +221,6 @@ export function refreshNow(): Promise<void> {
});
return followUp;
}
const generation = projectGeneration;
inflight = (async () => {
useVcs.setState({ loading: true });
try {
@@ -242,7 +238,6 @@ export function refreshNow(): Promise<void> {
call(commands.vcsStatus()),
scoped,
]);
if (generation !== projectGeneration) return;
const roots = vcsRoots.map((r) => r.root);
if ("error" in selected) {
// The selected repository is gone (removed since the last scan): fall back to the primary one.
@@ -268,13 +263,9 @@ export function refreshNow(): Promise<void> {
void refreshNow();
}
} catch (e) {
if (generation === projectGeneration) {
useVcs.setState({ error: e instanceof Error ? e.message : String(e) });
}
useVcs.setState({ error: e instanceof Error ? e.message : String(e) });
} finally {
if (generation === projectGeneration) {
useVcs.setState((st) => ({ loading: false, version: st.version + 1 }));
}
useVcs.setState((st) => ({ loading: false, version: st.version + 1 }));
inflight = null;
}
})();
@@ -301,11 +292,9 @@ export function refreshPathsNow(paths: readonly string[]): Promise<void> {
});
return followUp;
}
const generation = projectGeneration;
const run = (async () => {
try {
const fresh = await call(commands.vcsStatusPaths([...paths]));
if (generation !== projectGeneration) return false;
const current = useVcs.getState();
if (!current.statusLoaded || pairsRenames(current.status, paths, fresh)) return false;
applyStatus(mergeStatus(current.status, paths, fresh), current.branch);
@@ -317,7 +306,7 @@ export function refreshPathsNow(paths: readonly string[]): Promise<void> {
})();
const done = run.then((ok) => {
inflight = null;
return ok || generation !== projectGeneration ? undefined : refreshNow();
return ok ? undefined : refreshNow();
});
inflight = done;
return done;
@@ -407,10 +396,10 @@ export function statusOf(path: string): FileStatus | undefined {
/** Repositories found below a project that is not itself under git (scanned in the background). */
export async function discoverRoots() {
if (!useVcs.getState().root || !isTauri()) return;
const generation = projectGeneration;
const root = useVcs.getState().root;
if (!root || !isTauri()) return;
const roots = await call(commands.vcsRoots()).catch(() => []);
if (!roots.length || generation !== projectGeneration || useVcs.getState().available) return;
if (!roots.length || useVcs.getState().root !== root || useVcs.getState().available) return;
useVcs.setState({ available: true });
setContext("vcsAvailable", true);
void refreshNow();
@@ -423,9 +412,7 @@ export function installVcsStore(): () => void {
const available = !!project?.isGit;
const root = project?.root ?? null;
if (useVcs.getState().root === root && useVcs.getState().available === available) return;
projectGeneration++;
clearTimeout(timer);
pendingPaths.clear();
useVcs.setState({ ...initial, available, root, version: useVcs.getState().version + 1 });
setContext("vcsAvailable", available);
setFileDecorations("vcs", new Map());
@@ -122,10 +122,7 @@ export function MarkdownEditor({
className={styles.group}
storageKey={mode === "split" ? SPLIT_STORAGE_KEY : undefined}
>
{/* Hidden but mounted in Preview only (its caret drives the preview). Disabled, it leaves the group a
single resizable panel: two enabled panels without a separator get an implicit resize region between
them, which for a hidden panel spans everything left of the preview. */}
<SplitPanel id="editor" style={{ overflow: "hidden" }} disabled={mode === "preview"} {...splitBounds}>
<SplitPanel id="editor" style={{ overflow: "hidden" }} {...splitBounds}>
<div ref={editorRef} className={styles.editor}>
{children}
</div>
+4 -6
View File
@@ -5,7 +5,6 @@ import {
commands,
IpcError,
isCancelled,
isErrorKind,
isTauri,
type RecentProject,
type RecentProjectGroup,
@@ -118,10 +117,10 @@ export async function removeRecent(path: string) {
}
/** An open failure's kind and message, whether it is an `IpcError` or a raw rejected invoke. */
function failure(e: unknown): { kind?: unknown; message: string } {
function failure(e: unknown): { kind?: string; message: string } {
if (e instanceof IpcError) return { kind: e.kind, message: e.message };
if (e && typeof e === "object" && "message" in e)
return { kind: "kind" in e ? e.kind : undefined, message: String(e.message) };
return { kind: (e as { kind?: string }).kind, message: String((e as { message: unknown }).message) };
return { message: e instanceof Error ? e.message : String(e) };
}
@@ -150,9 +149,8 @@ export async function openRecent(project: Pick<RecentProject, "path" | "name">):
return true;
} catch (e) {
if (isCancelled(e)) return false;
const error = failure(e);
const { message } = error;
if (isErrorKind(error, "notFound") || (!error.kind && /not found|no such/i.test(message))) {
const { kind, message } = failure(e);
if (kind === "notFound" || (!kind && /not found|no such/i.test(message))) {
// A balloon can be switched off for this group and the welcome screen has no log to open.
const remove = await confirm({
title: tx`Project folder not found: ${project.name}`,
+1 -29
View File
@@ -1,6 +1,6 @@
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import type { IdeEvent } from "@/bindings";
import { emitLocalIdeEvent, ideEventsReady, IpcError, isErrorKind, onIdeEvent, type IdeError } from "./ipc";
import { emitLocalIdeEvent, ideEventsReady, onIdeEvent } from "./ipc";
type Listener = (e: { payload: IdeEvent }) => void;
const backend = vi.hoisted(() => ({ listener: null as Listener | null }));
@@ -60,31 +60,3 @@ describe("IDE event dispatch", () => {
expect(handler).toHaveBeenCalledTimes(1);
});
});
describe("isErrorKind", () => {
const versionMismatch: IdeError = { kind: "outOfSync", message: "document version changed" };
it.each([
["a wrapped IPC error", new IpcError(versionMismatch), true],
["a raw IPC rejection", versionMismatch, true],
["a different IPC kind", new IpcError({ kind: "notFound", message: "file missing" }), false],
["null", null, false],
["undefined", undefined, false],
["a string", "outOfSync", false],
["a number", 1, false],
["an object without a kind", { message: "version changed" }, false],
["a non-string kind", { kind: 1 }, false],
["an unknown kind", { kind: "unknown" }, false],
])("classifies %s", (_name, error, matches) => {
expect(isErrorKind(error, "outOfSync")).toBe(matches);
});
it("treats an unreadable kind as a non-match", () => {
const error = {
get kind() {
throw new Error("unreadable");
},
};
expect(isErrorKind(error, "outOfSync")).toBe(false);
});
});
-10
View File
@@ -24,16 +24,6 @@ export class IpcError extends Error {
}
}
/** Matches both wrapped IPC errors and raw invoke rejections by kind. */
export function isErrorKind(e: unknown, kind: IdeError["kind"]): boolean {
if (typeof e !== "object" || e === null) return false;
try {
return "kind" in e && e.kind === kind;
} catch {
return false;
}
}
type Result<T> = { status: "ok"; data: T } | { status: "error"; error: IdeError };
/** Unwraps a fallible command result: `await call(commands.docOpen(path))`. */
+1 -7
View File
@@ -166,10 +166,6 @@
"Select Next Tab": "Select Next Tab",
"Select Previous Tab": "Select Previous Tab",
"Result {n}-{index}": "Result {n}-{index}",
"Executing": "Executing",
"Executing {count} statements in {name}…": "Executing {count} statements in {name}…",
"Executing in {name}…": "Executing in {name}…",
"Executing… {elapsed}": "Executing… {elapsed}",
"Absolute": "Absolute",
"Relative": "Relative",
"Hybrid": "Hybrid",
@@ -2738,7 +2734,5 @@
"{count} hover actions": "{count} hover actions",
"{description}; JVM options: {flags}": "{description}; JVM options: {flags}",
"Sorting Options": "Sorting Options",
"Sort by Duration": "Sort by Duration",
"Resize left merge pane": "Resize left merge pane",
"Resize right merge pane": "Resize right merge pane"
"Sort by Duration": "Sort by Duration"
}
+1 -7
View File
@@ -4861,10 +4861,6 @@
"Remove data source '{name}'? Its query console file stays on disk.": "是否移除数据源 '{name}'?其查询控制台文件将保留在磁盘上。",
"Result {n}": "结果 {n}",
"Result {n}-{index}": "结果 {n}-{index}",
"Executing": "正在执行",
"Executing {count} statements in {name}…": "正在 {name} 中执行 {count} 条语句…",
"Executing in {name}…": "正在 {name} 中执行…",
"Executing… {elapsed}": "正在执行… {elapsed}",
"{name} has uncommitted changes. Commit or roll them back before switching to auto-commit?": "{name} 有未提交的更改。是否在切换到自动提交前提交或回滚这些更改?",
"Cannot copy the name": "无法复制名称",
"Cannot copy the reference": "无法复制引用",
@@ -9108,7 +9104,5 @@
"{count} hover actions": "{count} 个悬停操作",
"{description}; JVM options: {flags}": "{description};JVM 选项:{flags}",
"Sorting Options": "排序选项",
"Sort by Duration": "按持续时间排序",
"Resize left merge pane": "调整左侧合并窗格宽度",
"Resize right merge pane": "调整右侧合并窗格宽度"
"Sort by Duration": "按持续时间排序"
}
-9
View File
@@ -1,9 +0,0 @@
export function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason: unknown) => void;
const promise = new Promise<T>((done, fail) => {
resolve = done;
reject = fail;
});
return { promise, resolve, reject };
}
-14
View File
@@ -1,6 +1,5 @@
/** Design-system icons as DOM nodes for CodeMirror widgets. */
import { iconMarkupOrFallback, type IconName } from "./icons";
import spinnerStyles from "./Spinner.module.css";
export function iconNode(name: IconName | (string & {}), size = 16, className?: string): HTMLElement {
const span = document.createElement("span");
@@ -9,16 +8,3 @@ export function iconNode(name: IconName | (string & {}), size = 16, className?:
span.innerHTML = iconMarkupOrFallback(name, size);
return span;
}
/** The ring `Spinner` as a DOM node for CodeMirror widgets and gutters. */
export function spinnerNode(size = 14, className?: string): HTMLElement {
const span = document.createElement("span");
span.className = className ? `cm-openidea-icon ${className}` : "cm-openidea-icon";
span.setAttribute("aria-hidden", "true");
span.innerHTML =
`<svg class="${spinnerStyles.spinner}" width="${size}" height="${size}" viewBox="0 0 24 24">` +
'<circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-opacity="0.2" stroke-width="2.4"/>' +
'<path d="M21 12a9 9 0 0 0-9-9" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"/>' +
"</svg>";
return span;
}