Compare commits

..
Author SHA1 Message Date
l0ng-ai edb92495b0 Merge remote-tracking branch 'origin/main' into fix/vcs-push-layout
# Conflicts:
#	src/features/vcs/remoteUi.tsx
2026-11-20 04:49:54 +08:00
l0ng-ai 8629a3c6c7 fix(vcs): keep push review readable in narrow windows 2026-11-20 03:01:51 +08:00
42 changed files with 192 additions and 592 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 -1
View File
@@ -559,7 +559,7 @@ test("indexed single-file rename previews all anchors and applies only after con
}
await expect.poll(() => ipcCalls(page, "apply_workspace_edit")).toHaveLength(1);
const [apply] = await ipcCalls(page, "apply_workspace_edit");
expect(apply?.edit).toMatchObject({ preconditions: [{ path: FILE, hash: "indexed-snapshot" }] });
expect(apply.edit).toMatchObject({ preconditions: [{ path: FILE, hash: "indexed-snapshot" }] });
});
test("rename keeps the typed name, uses the editor font and shows long preview names in a narrow dialog", async ({
+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) => {
-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);
});
+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();
});
+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;
+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 };
},
};
}
+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": {
@@ -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,10 +23,7 @@
}
.name {
min-width: 0;
max-width: 45%;
overflow: hidden;
text-overflow: ellipsis;
flex: none;
color: var(--fg);
}
@@ -44,6 +41,7 @@
.nodeIcon {
flex: none;
margin-right: 1px;
}
.eq {
@@ -51,28 +49,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 +112,6 @@
.type {
min-width: 0;
max-width: 25%;
flex: 0 1 auto;
overflow: hidden;
text-overflow: ellipsis;
@@ -152,7 +136,7 @@
.editInput {
flex: 1;
min-width: min(80px, 40%);
min-width: 80px;
height: 18px;
padding: 0 4px;
font: inherit;
+23 -34
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 (
@@ -494,7 +489,7 @@ function VarRow({
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 && (
<>
@@ -516,29 +511,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;
+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 -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 -3
View File
@@ -2738,7 +2738,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 -3
View File
@@ -9108,7 +9108,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": "按持续时间排序"
}