mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-23 17:49:47 -10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
60882d647f | ||
|
|
9c0dcb94cf |
No files matched your search
@@ -217,8 +217,7 @@ impl ManageConnection for MssqlConnectionManager {
|
||||
let row = client.simple_query("SELECT DB_NAME()").await?.into_row().await?;
|
||||
let default = row
|
||||
.and_then(|r| r.get::<&str, _>(0).map(str::to_owned))
|
||||
// Statements that `USE` another database must not move the pooled connection for good.
|
||||
.map(|db| format!("USE {}", crate::sql::quote_ident(DbDriver::SqlServer, &db)));
|
||||
.and_then(|db| crate::sql::use_schema(DbDriver::SqlServer, &db));
|
||||
Ok(MssqlConnection(Some(client), Context::new(default)))
|
||||
}
|
||||
|
||||
|
||||
@@ -442,8 +442,7 @@ pub fn current_schema(driver: DbDriver) -> Option<&'static str> {
|
||||
DbDriver::Sqlite | DbDriver::Jdbc => None,
|
||||
DbDriver::Postgres => Some("SELECT current_schema()"),
|
||||
DbDriver::Mysql => Some("SELECT DATABASE()"),
|
||||
// The login's default schema; the database is the console's target (IDEA's `database.schema`).
|
||||
DbDriver::SqlServer => Some("SELECT SCHEMA_NAME()"),
|
||||
DbDriver::SqlServer => Some("SELECT DB_NAME()"),
|
||||
DbDriver::Oracle => Some("SELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') FROM DUAL"),
|
||||
DbDriver::Snowflake => Some("SELECT CURRENT_SCHEMA()"),
|
||||
}
|
||||
@@ -451,13 +450,12 @@ pub fn current_schema(driver: DbDriver) -> Option<&'static str> {
|
||||
|
||||
/// The statement that makes unqualified names resolve in `schema` on the
|
||||
/// connection that runs it (a query console's active schema; `None`: the driver
|
||||
/// has no schema to switch — SQLite's `main`, ClickHouse's `USE` differs, and SQL Server
|
||||
/// cannot change a session's default schema, so its console schema only scopes resolution).
|
||||
/// has no schema to switch — SQLite's `main`, ClickHouse's `USE` differs).
|
||||
pub fn use_schema(driver: DbDriver, schema: &str) -> Option<String> {
|
||||
match driver {
|
||||
DbDriver::Sqlite | DbDriver::Clickhouse | DbDriver::Jdbc | DbDriver::SqlServer => None,
|
||||
DbDriver::Sqlite | DbDriver::Clickhouse | DbDriver::Jdbc => None,
|
||||
DbDriver::Postgres => Some(format!("SET search_path TO {}", quote_ident(driver, schema))),
|
||||
DbDriver::Mysql => Some(format!("USE {}", quote_ident(driver, schema))),
|
||||
DbDriver::Mysql | DbDriver::SqlServer => Some(format!("USE {}", quote_ident(driver, schema))),
|
||||
DbDriver::Oracle => Some(format!("ALTER SESSION SET CURRENT_SCHEMA = {}", quote_ident(driver, schema))),
|
||||
DbDriver::Snowflake => Some(format!("USE SCHEMA {}", quote_ident(driver, schema))),
|
||||
}
|
||||
@@ -1032,7 +1030,7 @@ mod tests {
|
||||
assert_eq!(quote_ident(DbDriver::SqlServer, "a]b"), "[a]]b]");
|
||||
assert_eq!(qualified(DbDriver::SqlServer, "dbo", "t"), "[dbo].[t]");
|
||||
assert_eq!(qualified(DbDriver::SqlServer, "", "t"), "[t]");
|
||||
assert_eq!(current_schema(DbDriver::SqlServer), Some("SELECT SCHEMA_NAME()"));
|
||||
assert_eq!(current_schema(DbDriver::SqlServer), Some("SELECT DB_NAME()"));
|
||||
assert_eq!(crate::conn::begin_statement(DbDriver::SqlServer), "BEGIN TRAN");
|
||||
assert_eq!(
|
||||
schemas(DbDriver::SqlServer, true),
|
||||
@@ -1151,7 +1149,7 @@ mod tests {
|
||||
fn schema_switch_statement_per_dialect() {
|
||||
assert_eq!(use_schema(DbDriver::Postgres, "app data"), Some("SET search_path TO \"app data\"".into()));
|
||||
assert_eq!(use_schema(DbDriver::Mysql, "a`b"), Some("USE `a``b`".into()));
|
||||
assert_eq!(use_schema(DbDriver::SqlServer, "dbo"), None);
|
||||
assert_eq!(use_schema(DbDriver::SqlServer, "app] data"), Some("USE [app]] data]".into()));
|
||||
assert_eq!(use_schema(DbDriver::Postgres, "a\"b"), Some("SET search_path TO \"a\"\"b\"".into()));
|
||||
assert_eq!(use_schema(DbDriver::Oracle, "a\"b"), Some("ALTER SESSION SET CURRENT_SCHEMA = \"a\"\"b\"".into()));
|
||||
assert!(sqlserver_databases().contains("state = 0 AND HAS_DBACCESS(name) = 1"));
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 的导出、没人引用的文件或没人用的依赖时会失败。请删掉死代码,而不是屏蔽检查;只在本文件内使用的导出是允许的。
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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,50 +0,0 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("keeps breakpoint details editable when the dialog gets narrow", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 500, height: 480 });
|
||||
await page.evaluate(async () => {
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const storeModule = "/src/features/debugger/breakpoints/store.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
const { addBreakpoint } = await import(/* @vite-ignore */ storeModule);
|
||||
addBreakpoint("/dev/acme-api/CheckInternationalSettlementBeforeDispatch.java", 7, {
|
||||
condition: "amount > 100",
|
||||
});
|
||||
addBreakpoint("/dev/acme-api/Receipt.java", 4);
|
||||
await executeAction("debug.viewBreakpoints");
|
||||
});
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Breakpoints" });
|
||||
const list = dialog.getByRole("listbox", { name: "All breakpoints" });
|
||||
const condition = dialog.locator('input[aria-label="Condition"]');
|
||||
await expect(condition).toHaveValue("amount > 100");
|
||||
await expect.poll(async () => (await condition.boundingBox())?.width ?? 0).toBeGreaterThanOrEqual(240);
|
||||
await expect(dialog.getByRole("button", { name: "Done", exact: true })).toBeInViewport({ ratio: 1 });
|
||||
await condition.fill("amount > 250");
|
||||
await dialog.getByRole("checkbox", { name: "Evaluate and log", exact: true }).check();
|
||||
await dialog.getByRole("textbox", { name: "Evaluate and log", exact: true }).fill("total: {amount}");
|
||||
const first = list.getByRole("option", { name: /CheckInternationalSettlementBeforeDispatch\.java:8/ });
|
||||
await expect(first.getByText(":8", { exact: true })).toBeInViewport({ ratio: 1 });
|
||||
await list.getByRole("option", { name: /Receipt\.java:5/ }).click();
|
||||
await expect(condition).toHaveValue("");
|
||||
await first.click();
|
||||
await expect(condition).toHaveValue("amount > 250");
|
||||
await expect(dialog.getByRole("textbox", { name: "Evaluate and log", exact: true })).toHaveValue("total: {amount}");
|
||||
|
||||
await page.setViewportSize({ width: 1080, height: 760 });
|
||||
const divider = dialog.locator('[data-separator][aria-orientation="vertical"]');
|
||||
await expect(divider).toBeInViewport();
|
||||
const oldWidth = (await list.boundingBox())!.width;
|
||||
const handle = (await divider.boundingBox())!;
|
||||
await page.mouse.move(handle.x + handle.width / 2, handle.y + handle.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(handle.x + 60, handle.y + handle.height / 2, { steps: 4 });
|
||||
await page.mouse.up();
|
||||
await expect.poll(async () => (await list.boundingBox())?.width ?? 0).toBeGreaterThan(oldWidth + 20);
|
||||
await expect(condition).toHaveValue("amount > 250");
|
||||
const request = dialog.getByRole("textbox", { name: "Part of a request URL" });
|
||||
await request.scrollIntoViewIfNeeded();
|
||||
await expect(request).toBeInViewport({ ratio: 1 });
|
||||
await dialog.getByRole("button", { name: "Done", exact: true }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
});
|
||||
@@ -1,75 +0,0 @@
|
||||
import type { MethodSignature } from "../src/bindings";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const signature: MethodSignature = {
|
||||
methodIdentifier: "invoice",
|
||||
modifier: "",
|
||||
returnType: "Invoice",
|
||||
methodName: "prepareInvoiceForInternationalSettlement",
|
||||
parameters: [
|
||||
["Order", "order"],
|
||||
["String", "billingCurrency"],
|
||||
["BigDecimal", "amountBeforeDiscount"],
|
||||
["Map<String, BigDecimal>", "taxRatesByJurisdiction"],
|
||||
["List<Adjustment>", "settlementAdjustments"],
|
||||
["RoundingMode", "roundingMode"],
|
||||
["LocalDate", "scheduledSettlementDate"],
|
||||
["boolean", "includeTaxBreakdown"],
|
||||
].map(([type, name], originalIndex) => ({ type: type!, name: name!, originalIndex, defaultValue: "" })),
|
||||
exceptions: [],
|
||||
};
|
||||
|
||||
test("keeps parameter rows and a long signature preview usable in a short dialog", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 490, height: 520 });
|
||||
await page.evaluate(async () => {
|
||||
const workbench = "/src/workbench/contributions.ts";
|
||||
const { editorService } = await import(/* @vite-ignore */ workbench);
|
||||
await editorService().openFile("/dev/acme-api/InvoiceService.java");
|
||||
});
|
||||
const editor = page.locator(".cm-editor .cm-content");
|
||||
await expect(editor).toBeVisible();
|
||||
await stubDesktop(page);
|
||||
const fontSize = await editor.evaluate(async (content, signature) => {
|
||||
window.__ipc.handlers.lsp_signature_info = () => signature;
|
||||
const viewModule = "/node_modules/.vite/deps/@codemirror_view.js";
|
||||
const prefsModule = "/src/editor/core/cm/prefs.ts";
|
||||
const { EditorView } = await import(/* @vite-ignore */ viewModule);
|
||||
const { stepFontZoom } = await import(/* @vite-ignore */ prefsModule);
|
||||
const base = Number.parseFloat(getComputedStyle(content).fontSize);
|
||||
const view = EditorView.findFromDOM(content as HTMLElement)!;
|
||||
stepFontZoom(view, 4);
|
||||
view.focus();
|
||||
return `${base + 4}px`;
|
||||
}, signature);
|
||||
await expect(editor).toHaveCSS("font-size", fontSize);
|
||||
await page.keyboard.press("Meta+F6");
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Change Signature" });
|
||||
const table = dialog.getByRole("table", { name: "Parameters" });
|
||||
const names = table.getByRole("textbox", { name: "Name", exact: true });
|
||||
await expect(names.first()).toBeInViewport({ ratio: 1 });
|
||||
const defaults = table.getByRole("columnheader", { name: "Default value", exact: true });
|
||||
await expect(defaults).toHaveCount(0);
|
||||
const preview = dialog.locator("pre");
|
||||
await expect(preview).toBeInViewport({ ratio: 1 });
|
||||
await expect(preview).toHaveCSS("font-size", fontSize);
|
||||
await expect(names.first()).toHaveCSS("font-size", fontSize);
|
||||
expect(
|
||||
await preview.evaluate((el) => el.scrollHeight > el.clientHeight && el.scrollWidth <= el.clientWidth + 1),
|
||||
).toBe(true);
|
||||
await expect(dialog.getByRole("button", { name: "Cancel" })).toBeInViewport({ ratio: 1 });
|
||||
|
||||
await dialog.getByRole("button", { name: "Add", exact: true }).click();
|
||||
await expect(defaults).toBeInViewport({ ratio: 1 });
|
||||
const addedType = table.getByRole("textbox", { name: "Type", exact: true }).last();
|
||||
await expect(addedType).toBeInViewport({ ratio: 1 });
|
||||
await addedType.fill("boolean");
|
||||
await names.last().fill("attachReceipt");
|
||||
await table.getByRole("textbox", { name: "Default value", exact: true }).last().fill("false");
|
||||
await dialog.getByRole("button", { name: "Move Up", exact: true }).click();
|
||||
await expect(names.nth(7)).toHaveValue("attachReceipt");
|
||||
await expect(preview).toContainText("boolean attachReceipt");
|
||||
await expect(dialog.getByRole("button", { name: "Preview", exact: true })).toBeEnabled();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(dialog).toBeHidden();
|
||||
});
|
||||
@@ -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 ({
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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),
|
||||
],
|
||||
});
|
||||
@@ -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,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
@@ -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);
|
||||
});
|
||||
@@ -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({
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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
@@ -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();
|
||||
});
|
||||
+4
-8
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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
@@ -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
@@ -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",
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorController, openFilePaths, useEditorStatus, useTabErrors, useTabs } from "./controller";
|
||||
import { EditorController, openFilePaths, useEditorStatus, useTabs } from "./controller";
|
||||
import { createMemoryBackend } from "./backend";
|
||||
import { initialTabsState } from "./model/tabs";
|
||||
import { useDocMeta } from "./model/document";
|
||||
import { storeSession } from "./model/session";
|
||||
import { resetDistractionFree, setDistractionFree } from "@/workbench/distractionFree";
|
||||
import * as contributions from "@/workbench/contributions";
|
||||
import {
|
||||
registerEditorKind,
|
||||
registerTextEditorWrapper,
|
||||
@@ -13,7 +11,6 @@ import {
|
||||
useProjectViewLead,
|
||||
} from "@/workbench/contributions";
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { IpcError, type ErrorKind } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { useRemote } from "@/platform/remote";
|
||||
import { hideContextMenu, resolveMenuItems, useContextMenuStore } from "@/ui";
|
||||
@@ -32,75 +29,6 @@ afterEach(() => {
|
||||
useEditorStatus.setState({ status: null });
|
||||
});
|
||||
|
||||
describe("restoring an editor session", () => {
|
||||
const root = "/session-restore";
|
||||
const existing = `${root}/existing.txt`;
|
||||
const unavailable = `${root}/unavailable.txt`;
|
||||
const text = "first\nsecond";
|
||||
let controller: EditorController | undefined;
|
||||
|
||||
afterEach(() => {
|
||||
controller?.stop();
|
||||
controller = undefined;
|
||||
storeSession(root, null);
|
||||
useTabErrors.setState({}, true);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
async function restoreWithOpenError(kind: ErrorKind, message: string) {
|
||||
storeSession(root, {
|
||||
version: 1,
|
||||
layout: { kind: "pane", tabs: [{ path: existing }, { path: unavailable }], active: 1 },
|
||||
activePane: 0,
|
||||
files: { [existing]: { anchor: 6, head: 6 } },
|
||||
});
|
||||
const backend = createMemoryBackend({ [existing]: text });
|
||||
// For an absent path the memory backend serves sample text, not a disk error.
|
||||
const open = backend.open.bind(backend);
|
||||
vi.spyOn(backend, "open").mockImplementation(async (path) => {
|
||||
if (path === unavailable) throw new IpcError({ kind, message });
|
||||
return open(path);
|
||||
});
|
||||
const editor = (controller = new EditorController(backend));
|
||||
editor.start();
|
||||
|
||||
const restoring = editor.restoreSession(root);
|
||||
const state = useTabs.getState();
|
||||
const selected = state.panes[state.activePane]!.active!;
|
||||
// Restore opens the selected tab in the background. Join the same slot request.
|
||||
await Promise.all([restoring, editor.ensureSlot(selected)]);
|
||||
return { editor, selected };
|
||||
}
|
||||
|
||||
it("silently drops a deleted selected file and restores the remaining tab", async () => {
|
||||
const notify = vi.fn();
|
||||
vi.spyOn(contributions, "notifications").mockReturnValue({ notify });
|
||||
const { editor, selected } = await restoreWithOpenError("notFound", `No such file: ${unavailable}`);
|
||||
|
||||
expect(notify).not.toHaveBeenCalled();
|
||||
expect(useTabErrors.getState()).toEqual({});
|
||||
expect(openFilePaths(useTabs.getState())).toEqual([existing]);
|
||||
expect(editor.slotFor(selected)).toBeNull();
|
||||
expect(editor.activeInput()?.path).toBe(existing);
|
||||
|
||||
// In the app the visible tab's editor host requests this slot after selection changes.
|
||||
const state = useTabs.getState();
|
||||
const slot = await editor.ensureSlot(state.panes[state.activePane]!.active!);
|
||||
expect(slot?.model.path).toBe(existing);
|
||||
expect(slot?.state.doc.toString()).toBe(text);
|
||||
expect(slot?.caret()).toMatchObject({ line: 1, col: 0 });
|
||||
});
|
||||
|
||||
it("keeps a tab and reports its open error when access is denied", async () => {
|
||||
const message = `Permission denied: ${unavailable}`;
|
||||
const { editor, selected } = await restoreWithOpenError("permissionDenied", message);
|
||||
|
||||
expect(openFilePaths(useTabs.getState())).toEqual([existing, unavailable]);
|
||||
expect(editor.activeInput()?.path).toBe(unavailable);
|
||||
expect(useTabErrors.getState()).toEqual({ [selected]: message });
|
||||
});
|
||||
});
|
||||
|
||||
describe("EditorController", () => {
|
||||
it("returns navigation context to the editor when activating a non-text tab", async () => {
|
||||
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "one\n" }));
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
initialTabsState,
|
||||
moveTabToNewSplit,
|
||||
@@ -9,15 +9,7 @@ import {
|
||||
togglePin,
|
||||
type TabsState,
|
||||
} from "./tabs";
|
||||
import {
|
||||
loadSession,
|
||||
parseSession,
|
||||
restoreTabsState,
|
||||
serializeSession,
|
||||
slashPath,
|
||||
storeSession,
|
||||
type EditorSession,
|
||||
} from "./session";
|
||||
import { loadSession, parseSession, restoreTabsState, serializeSession, slashPath } from "./session";
|
||||
|
||||
const file = (path: string) => ({ kind: "file", key: `file:${path}`, path });
|
||||
const fileKey = (p: string) => `file:${p}`;
|
||||
@@ -111,44 +103,6 @@ describe("editor session", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("loading a session with malformed JSON", () => {
|
||||
const root = "/malformed-session";
|
||||
const key = `openidea.editorSession.v1:${root}`;
|
||||
const malformed = '{"version":1,"layout":{"kind":"pane","tabs":[';
|
||||
|
||||
beforeEach(() => localStorage.setItem(key, malformed));
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
localStorage.removeItem(key);
|
||||
});
|
||||
|
||||
it("returns null without writing to storage or changing the saved bytes", () => {
|
||||
const before = localStorage.getItem(key);
|
||||
expect(before).toBe(malformed);
|
||||
const setItem = vi.spyOn(Storage.prototype, "setItem");
|
||||
|
||||
expect(loadSession(root)).toBeNull();
|
||||
expect(localStorage.getItem(key)).toBe(before);
|
||||
expect(setItem).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("loads a valid session after an explicit save replaces malformed JSON", () => {
|
||||
expect(loadSession(root)).toBeNull();
|
||||
const path = `${root}/recovered.ts`;
|
||||
const recovered: EditorSession = {
|
||||
version: 1,
|
||||
layout: { kind: "pane", tabs: [{ path }], active: 0 },
|
||||
activePane: 0,
|
||||
files: { [path]: { anchor: 1, head: 2 } },
|
||||
};
|
||||
|
||||
storeSession(root, recovered);
|
||||
|
||||
expect(JSON.parse(localStorage.getItem(key)!)).toEqual(recovered);
|
||||
expect(loadSession(root)).toEqual(recovered);
|
||||
});
|
||||
});
|
||||
|
||||
describe("moveTabToNewSplit", () => {
|
||||
it("moves a tab into a new pane on the given edge", () => {
|
||||
let s = initialTabsState();
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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
@@ -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
@@ -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": {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
.dialog [data-dialog-body] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.body {
|
||||
@@ -8,8 +9,8 @@
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-3);
|
||||
gap: var(--space-3);
|
||||
padding: 14px;
|
||||
font-size: var(--fs-ui);
|
||||
color: var(--fg);
|
||||
}
|
||||
@@ -17,34 +18,54 @@
|
||||
.header {
|
||||
flex: none;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 0.75fr) minmax(0, 1fr) minmax(0, 1.25fr);
|
||||
align-items: end;
|
||||
gap: var(--space-2);
|
||||
grid-template-columns: 150px 1fr 1fr;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.field {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
gap: var(--space-1-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.parameters {
|
||||
flex: 1 1 auto;
|
||||
min-height: calc(var(--h-list-row) * 5);
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-control);
|
||||
overflow: hidden;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
flex: none;
|
||||
display: flex;
|
||||
gap: var(--space-1);
|
||||
padding: var(--space-0-5) var(--space-1);
|
||||
padding: 2px 4px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.table {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.head,
|
||||
.row {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr 1fr;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: 0 8px;
|
||||
min-height: var(--h-list-row);
|
||||
}
|
||||
|
||||
.head {
|
||||
color: var(--fg-muted);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
@@ -52,57 +73,6 @@
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
scroll-padding-block-start: var(--h-list-row);
|
||||
}
|
||||
|
||||
.table {
|
||||
width: 100%;
|
||||
table-layout: fixed;
|
||||
border-spacing: 0;
|
||||
}
|
||||
|
||||
.table :is(th, td) {
|
||||
padding: 0 var(--space-2);
|
||||
}
|
||||
|
||||
.table th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
height: var(--h-list-row);
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--bg-dialog, var(--bg-elev));
|
||||
color: var(--fg-muted);
|
||||
text-align: start;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.table th:first-child {
|
||||
width: 42%;
|
||||
}
|
||||
|
||||
.table th:first-child:nth-last-child(3) {
|
||||
width: 36%;
|
||||
}
|
||||
|
||||
.table th:nth-child(3) {
|
||||
width: 28%;
|
||||
}
|
||||
|
||||
.body .code,
|
||||
.preview {
|
||||
font-family: var(--signature-font-family, var(--font-mono));
|
||||
font-size: var(--signature-font-size, var(--fs-code));
|
||||
font-weight: var(--signature-font-weight, var(--fw-code));
|
||||
}
|
||||
|
||||
.body .code {
|
||||
width: 100%;
|
||||
height: max(var(--h-field), calc(var(--signature-font-size, var(--fs-code)) + var(--space-2)));
|
||||
}
|
||||
|
||||
.row .code:focus-visible {
|
||||
box-shadow: inset 0 -1px var(--focus-ring);
|
||||
}
|
||||
|
||||
.row:hover {
|
||||
@@ -114,16 +84,14 @@
|
||||
}
|
||||
|
||||
.preview {
|
||||
height: clamp(56px, 18vh, 128px);
|
||||
margin: 0;
|
||||
padding: var(--space-1-5) var(--space-2);
|
||||
padding: 6px 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-control);
|
||||
overflow: auto;
|
||||
border-radius: 4px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-code);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
line-height: 1.5;
|
||||
user-select: text;
|
||||
color: var(--fg);
|
||||
background: var(--bg-input);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** IDEA's Change Signature dialog for Java methods (`signature.ts`). */
|
||||
import { useEffect, useId, useLayoutEffect, useRef, useState, type CSSProperties } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { MethodSignature } from "@/bindings";
|
||||
import { Checkbox, Dialog, IconButton, Input, Select, Spinner, T, Toolbar } from "@/ui";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
@@ -34,16 +34,6 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
|
||||
const [delegate, setDelegate] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const previewLabel = useId();
|
||||
const selectedRow = useRef<HTMLTableRowElement>(null);
|
||||
const [codeStyle] = useState(() => {
|
||||
const { fontFamily, fontSize, fontWeight } = getComputedStyle(request.view.contentDOM);
|
||||
return {
|
||||
"--signature-font-family": fontFamily,
|
||||
"--signature-font-size": fontSize,
|
||||
"--signature-font-weight": fontWeight,
|
||||
} as CSSProperties;
|
||||
});
|
||||
|
||||
const signature: MethodSignature = {
|
||||
...info,
|
||||
@@ -55,10 +45,6 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
|
||||
const problem = signatureProblem(signature);
|
||||
const ready = !busy && !problem && signatureChanged(info, signature);
|
||||
const current = Math.min(selected, rows.length - 1);
|
||||
const hasNewParameters = rows.some((row) => row.originalIndex < 0);
|
||||
useLayoutEffect(() => {
|
||||
selectedRow.current?.scrollIntoView({ block: "nearest", inline: "nearest" });
|
||||
}, [current, rows.length]);
|
||||
|
||||
// Closing the dialog cancels a refactoring still being checked: it applies nothing.
|
||||
const running = useRef<AbortController | null>(null);
|
||||
@@ -107,8 +93,7 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
|
||||
title="Change Signature"
|
||||
className={styles.dialog}
|
||||
width={640}
|
||||
minWidth={360}
|
||||
minHeight={360}
|
||||
minHeight={380}
|
||||
maxHeight={640}
|
||||
resizable="both"
|
||||
buttons={[
|
||||
@@ -125,7 +110,7 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<div className={styles.body} style={codeStyle}>
|
||||
<div className={styles.body}>
|
||||
<div className={styles.header}>
|
||||
<label className={styles.field}>
|
||||
<T>Visibility:</T>
|
||||
@@ -138,18 +123,11 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
|
||||
</label>
|
||||
<label className={styles.field}>
|
||||
<T>Return type:</T>
|
||||
<Input className={styles.code} mono value={returnType} onChange={(e) => setReturnType(e.target.value)} />
|
||||
<Input mono value={returnType} onChange={(e) => setReturnType(e.target.value)} />
|
||||
</label>
|
||||
<label className={styles.field}>
|
||||
<T>Name:</T>
|
||||
<Input
|
||||
className={styles.code}
|
||||
mono
|
||||
data-autofocus
|
||||
autoSelect
|
||||
value={methodName}
|
||||
onChange={(e) => setMethodName(e.target.value)}
|
||||
/>
|
||||
<Input mono autoFocus autoSelect value={methodName} onChange={(e) => setMethodName(e.target.value)} />
|
||||
</label>
|
||||
</div>
|
||||
<div className={styles.parameters}>
|
||||
@@ -164,83 +142,59 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
|
||||
onClick={() => move(1)}
|
||||
/>
|
||||
</Toolbar>
|
||||
<div className={styles.rows}>
|
||||
<table className={styles.table} aria-label={tx("Parameters")}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">
|
||||
<T>Type</T>
|
||||
</th>
|
||||
<th scope="col">
|
||||
<T>Name</T>
|
||||
</th>
|
||||
{hasNewParameters && (
|
||||
<th scope="col">
|
||||
<T>Default value</T>
|
||||
</th>
|
||||
)}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row, i) => (
|
||||
<tr
|
||||
key={row.key}
|
||||
ref={i === current ? selectedRow : undefined}
|
||||
className={styles.row}
|
||||
aria-selected={i === current}
|
||||
onFocusCapture={() => setSelected(i)}
|
||||
>
|
||||
<td>
|
||||
<Input
|
||||
className={styles.code}
|
||||
mono
|
||||
variant="bare"
|
||||
aria-label={tx("Type")}
|
||||
value={row.type}
|
||||
title={row.type}
|
||||
autoFocus={row.originalIndex < 0 && !row.type}
|
||||
onChange={(e) => update(row.key, { type: e.target.value })}
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<Input
|
||||
className={styles.code}
|
||||
mono
|
||||
variant="bare"
|
||||
aria-label={tx("Name")}
|
||||
value={row.name}
|
||||
title={row.name}
|
||||
onChange={(e) => update(row.key, { name: e.target.value })}
|
||||
/>
|
||||
</td>
|
||||
{hasNewParameters && (
|
||||
<td>
|
||||
{row.originalIndex < 0 && (
|
||||
<Input
|
||||
className={styles.code}
|
||||
mono
|
||||
variant="bare"
|
||||
aria-label={tx("Default value")}
|
||||
value={row.defaultValue}
|
||||
onChange={(e) => update(row.key, { defaultValue: e.target.value })}
|
||||
/>
|
||||
)}
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<div className={styles.table} role="table" aria-label={tx("Parameters")}>
|
||||
<div className={styles.head} role="row">
|
||||
<span role="columnheader">
|
||||
<T>Type</T>
|
||||
</span>
|
||||
<span role="columnheader">
|
||||
<T>Name</T>
|
||||
</span>
|
||||
<span role="columnheader">
|
||||
<T>Default value</T>
|
||||
</span>
|
||||
</div>
|
||||
<div className={styles.rows}>
|
||||
{rows.map((row, i) => (
|
||||
<div
|
||||
key={row.key}
|
||||
className={styles.row}
|
||||
role="row"
|
||||
aria-selected={i === current}
|
||||
onFocusCapture={() => setSelected(i)}
|
||||
>
|
||||
<Input
|
||||
mono
|
||||
variant="bare"
|
||||
aria-label={tx("Type")}
|
||||
value={row.type}
|
||||
autoFocus={row.originalIndex < 0 && !row.type}
|
||||
onChange={(e) => update(row.key, { type: e.target.value })}
|
||||
/>
|
||||
<Input
|
||||
mono
|
||||
variant="bare"
|
||||
aria-label={tx("Name")}
|
||||
value={row.name}
|
||||
onChange={(e) => update(row.key, { name: e.target.value })}
|
||||
/>
|
||||
<Input
|
||||
mono
|
||||
variant="bare"
|
||||
aria-label={tx("Default value")}
|
||||
value={row.originalIndex < 0 ? row.defaultValue : ""}
|
||||
disabled={row.originalIndex >= 0}
|
||||
onChange={(e) => update(row.key, { defaultValue: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Checkbox checked={delegate} onChange={setDelegate} label={<T>Delegate via overloading method</T>} />
|
||||
<div className={styles.field}>
|
||||
<span id={previewLabel}>
|
||||
<T>Signature Preview</T>
|
||||
</span>
|
||||
<pre className={styles.preview} role="region" aria-labelledby={previewLabel} tabIndex={0}>
|
||||
{signatureText(signature)}
|
||||
</pre>
|
||||
<T>Signature Preview</T>
|
||||
<pre className={styles.preview}>{signatureText(signature)}</pre>
|
||||
</div>
|
||||
{(error ?? (signatureChanged(info, signature) ? problem : null)) && (
|
||||
<span className={styles.error} role="alert">
|
||||
|
||||
@@ -16,7 +16,7 @@ const info: MethodSignature = {
|
||||
|
||||
describe("change signature", () => {
|
||||
it("previews the signature like the declaration", () => {
|
||||
expect(signatureText(info)).toBe("public int sum(\n int a,\n int b\n) throws java.io.IOException");
|
||||
expect(signatureText(info)).toBe("public int sum(int a, int b) throws java.io.IOException");
|
||||
expect(signatureText({ ...info, modifier: "", parameters: [], exceptions: [] })).toBe("int sum()");
|
||||
});
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ export const parameterRow = (p: SignatureParameter): ParameterRow => ({ ...p, ke
|
||||
export const newParameter = (): ParameterRow =>
|
||||
parameterRow({ type: "", name: "", defaultValue: "", originalIndex: -1 });
|
||||
|
||||
/** Formats the declaration for the dialog's preview. */
|
||||
/** `public int sum(int a, int b) throws IOException`, as the dialog's preview shows it. */
|
||||
export function signatureText(sig: {
|
||||
modifier: string;
|
||||
returnType: string;
|
||||
@@ -44,9 +44,8 @@ export function signatureText(sig: {
|
||||
parameters: readonly SignatureParameter[];
|
||||
exceptions?: readonly { type: string }[];
|
||||
}): string {
|
||||
const params = sig.parameters.map((p) => `${p.type} ${p.name}`.trim());
|
||||
const args = params.length > 1 ? `\n ${params.join(",\n ")}\n` : (params[0] ?? "");
|
||||
const head = [sig.modifier, sig.returnType, `${sig.methodName}(${args})`].filter(Boolean).join(" ");
|
||||
const params = sig.parameters.map((p) => `${p.type} ${p.name}`.trim()).join(", ");
|
||||
const head = [sig.modifier, sig.returnType, `${sig.methodName}(${params})`].filter(Boolean).join(" ");
|
||||
const throws = sig.exceptions?.length ? ` throws ${sig.exceptions.map((e) => e.type).join(", ")}` : "";
|
||||
return head + throws;
|
||||
}
|
||||
|
||||
@@ -274,8 +274,8 @@ export function Result({ tab, onClose }: { tab: ResultTab; onClose?: () => void
|
||||
const editability = useMemo(() => resultEditability(text, driver), [text, driver]);
|
||||
const model = useDatabase((s) => s.completion[tab.sourceId]) ?? null;
|
||||
const target = useMemo(
|
||||
() => (editability.kind === "editable" ? resolveTarget(editability, model, tab.schema) : null),
|
||||
[editability, model, tab.schema],
|
||||
() => (editability.kind === "editable" ? resolveTarget(editability, model, tab.schema, driver) : null),
|
||||
[editability, model, tab.schema, driver],
|
||||
);
|
||||
const detailsId = target ? detailsKey(tab.sourceId, target.schema ?? "", target.table) : null;
|
||||
const details = useDatabase((s) => (detailsId ? s.details[detailsId] : undefined));
|
||||
|
||||
@@ -55,17 +55,7 @@ import {
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { Icon, IconButton, Select, Toolbar, lazyComponent } from "@/ui";
|
||||
import { useProject } from "@/platform/project";
|
||||
import {
|
||||
activeSchema,
|
||||
parseSchemaTreeValue,
|
||||
schemaSwitchable,
|
||||
schemaTreeRows,
|
||||
schemaTreeValue,
|
||||
sourceIcon,
|
||||
sourceLabel,
|
||||
splitTarget,
|
||||
targetOf,
|
||||
} from "./model";
|
||||
import { activeSchema, schemaSwitchable, sourceIcon, sourceLabel, splitTarget, targetOf } from "./model";
|
||||
import { loadSavedCatalog, offerIntrospection } from "./introspection";
|
||||
import { analyze, templateContexts, valuesSlot } from "./sql/analyze";
|
||||
import {
|
||||
@@ -100,6 +90,7 @@ import {
|
||||
setConsoleSchema,
|
||||
setManualCommit,
|
||||
sourceById,
|
||||
targetLabel,
|
||||
useDatabase,
|
||||
} from "./store";
|
||||
import styles from "./Database.module.css";
|
||||
@@ -595,6 +586,7 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
|
||||
const maxRows = useDatabase((s) => s.maxRows);
|
||||
const manual = useDatabase((s) => !!bound && s.manualCommit.has(bound));
|
||||
const pending = useDatabase((s) => !!bound && s.pendingTx.has(bound));
|
||||
const databases = useDatabase((s) => s.databases);
|
||||
const inEditor = useProject((s) => inEditorResults(s.settings));
|
||||
// SQL resolution scopes in the settings can move the console to another data source.
|
||||
useProject((s) => s.settings);
|
||||
@@ -602,6 +594,7 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
|
||||
const driver = sources.find((s) => s.id === boundId)?.driver;
|
||||
const jdbc = driver === "jdbc";
|
||||
const supportsTransactions = driver !== "clickhouse" && !jdbc;
|
||||
const sqlServer = driver === "sqlServer";
|
||||
const switchable = schemaSwitchable(driver);
|
||||
// The console's active schema: its pick, else the connection's default (`completion.defaultSchema`).
|
||||
const pickedSchema = useDatabase((s) => s.consoleSchemas[path]);
|
||||
@@ -609,35 +602,49 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
|
||||
const schemaList = useDatabase((s) => (bound ? s.schemas[bound] : undefined));
|
||||
const schema = activeSchema(pickedSchema, defaultSchema);
|
||||
useEffect(() => {
|
||||
if (boundId && listsDatabases(sourceById(boundId)) && !useDatabase.getState().databases[boundId])
|
||||
if (boundId && (sqlServer || listsDatabases(sourceById(boundId))) && !useDatabase.getState().databases[boundId])
|
||||
void loadDatabases(boundId);
|
||||
}, [boundId]);
|
||||
// Loads the list again after a refresh drops it.
|
||||
const schemasMissing = !schemaList;
|
||||
}, [boundId, sqlServer]);
|
||||
useEffect(() => {
|
||||
if (bound && switchable && schemasMissing) void loadSchemas(bound);
|
||||
}, [bound, switchable, schemasMissing]);
|
||||
if (bound && switchable && !sqlServer && !useDatabase.getState().schemas[bound]) void loadSchemas(bound);
|
||||
}, [bound, switchable, sqlServer]);
|
||||
const schemaOptions = useMemo(() => {
|
||||
if (!switchable) return [];
|
||||
const names = schemaList?.status === "ok" ? schemaList.value : [];
|
||||
const databaseList = boundId ? databases[boundId] : undefined;
|
||||
const names = sqlServer
|
||||
? databaseList?.status === "ok"
|
||||
? databaseList.value.names
|
||||
: []
|
||||
: schemaList?.status === "ok"
|
||||
? schemaList.value
|
||||
: [];
|
||||
const out = names.map((n) => ({ value: n, label: n, icon: "db-schema" }));
|
||||
// The connection's default is offered even before its schema list loads.
|
||||
if (defaultSchema && !names.includes(defaultSchema))
|
||||
out.unshift({ value: defaultSchema, label: defaultSchema, icon: "db-schema" });
|
||||
return out;
|
||||
}, [switchable, schemaList, defaultSchema]);
|
||||
// IDEA's order: pick the data source, then a database and a schema in it.
|
||||
const sourceOptions = useMemo(
|
||||
() =>
|
||||
sources.map((s) => ({
|
||||
value: s.id ?? "",
|
||||
label: s.name ?? "",
|
||||
verbatim: true,
|
||||
detail: sourceLabel(s).slice((s.name ?? "").length + 1),
|
||||
icon: sourceIcon(s),
|
||||
})),
|
||||
[sources],
|
||||
);
|
||||
}, [switchable, schemaList, defaultSchema, sqlServer, boundId, databases]);
|
||||
const targets = useMemo(() => {
|
||||
const out: Array<{ value: string; label: string; detail?: string; icon: string }> = [];
|
||||
for (const s of sources) {
|
||||
const id = s.id ?? "";
|
||||
const dbs = databases[id];
|
||||
const host = sourceLabel(s).slice((s.name ?? "").length + 1);
|
||||
if (listsDatabases(s) && dbs?.status === "ok") {
|
||||
for (const name of dbs.value.names)
|
||||
out.push({
|
||||
value: targetOf(id, name, dbs.value.current),
|
||||
label: `${s.name ?? ""}: ${name}`,
|
||||
detail: host,
|
||||
icon: sourceIcon(s),
|
||||
});
|
||||
} else out.push({ value: id, label: s.name ?? "", detail: host, icon: sourceIcon(s) });
|
||||
}
|
||||
// A console bound to a database whose list is not loaded yet still shows it.
|
||||
if (bound && !out.some((o) => o.value === bound))
|
||||
out.push({ value: bound, label: targetLabel(bound), icon: "database" });
|
||||
return out;
|
||||
}, [sources, databases, bound]);
|
||||
useEffect(() => {
|
||||
if (!loaded) void loadSources();
|
||||
}, [loaded]);
|
||||
@@ -724,28 +731,23 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label="Data source"
|
||||
value={boundId}
|
||||
value={bound ?? null}
|
||||
placeholder={sources.length ? "<data source>" : "None configured"}
|
||||
options={sourceOptions}
|
||||
searchable
|
||||
onChange={(id) => id !== boundId && bindConsole(path, id)}
|
||||
options={targets}
|
||||
onChange={(id) => bindConsole(path, id)}
|
||||
disabled={!sources.length}
|
||||
/>
|
||||
{bound && boundId && switchable && listsDatabases(sourceById(boundId)) ? (
|
||||
<DatabaseSchemaSwitcher path={path} bound={bound} sourceId={boundId} schema={schema} />
|
||||
) : (
|
||||
switchable && (
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label="Schema"
|
||||
value={schema || null}
|
||||
placeholder="<schema>"
|
||||
options={schemaOptions}
|
||||
searchable
|
||||
onChange={(v) => setConsoleSchema(path, v)}
|
||||
disabled={!bound}
|
||||
/>
|
||||
)
|
||||
{switchable && (
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label={sqlServer ? "Database" : "Schema"}
|
||||
value={schema || null}
|
||||
placeholder="<schema>"
|
||||
options={schemaOptions}
|
||||
searchable={schemaOptions.length > 10}
|
||||
onChange={(v) => setConsoleSchema(path, v)}
|
||||
disabled={!bound}
|
||||
/>
|
||||
)}
|
||||
{driver === "sqlite" && (
|
||||
<span className={styles.consoleSchema} title={tx("Schema")}>
|
||||
@@ -757,85 +759,6 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The `database.schema` switcher of a data source that shows several databases (IDEA's): a tree of
|
||||
* its databases, expanding to their schemas. Choosing a schema in another database moves the console there.
|
||||
*/
|
||||
function DatabaseSchemaSwitcher({
|
||||
path,
|
||||
bound,
|
||||
sourceId,
|
||||
schema,
|
||||
}: {
|
||||
path: string;
|
||||
bound: string;
|
||||
sourceId: string;
|
||||
schema: string;
|
||||
}) {
|
||||
const listed = useDatabase((s) => s.databases[sourceId]);
|
||||
const schemas = useDatabase((s) => s.schemas);
|
||||
const read = useDatabase((s) => s.catalogs[sourceId]?.databases);
|
||||
const current = listed?.status === "ok" ? listed.value.current : null;
|
||||
const database = splitTarget(bound).database ?? current;
|
||||
// The console's database starts expanded, again whenever the console moves to another one.
|
||||
const [opened, setOpened] = useState<{ at: string | null; open: ReadonlySet<string> } | null>(null);
|
||||
const expanded = useMemo(
|
||||
() => (opened && opened.at === database ? opened.open : new Set(database ? [database] : [])),
|
||||
[opened, database],
|
||||
);
|
||||
const targetFor = (name: string) => (name === database ? bound : targetOf(sourceId, name, current));
|
||||
// Schemas of expanded databases that are not read yet, or were dropped by a refresh.
|
||||
const missing = [...expanded]
|
||||
.filter((name) => !read?.[name] && !schemas[targetFor(name)])
|
||||
.map(targetFor)
|
||||
.join("\n");
|
||||
useEffect(() => {
|
||||
for (const target of missing ? missing.split("\n") : []) void loadSchemas(target);
|
||||
}, [missing]);
|
||||
const rows = useMemo(() => {
|
||||
const names = listed?.status === "ok" ? [...listed.value.names] : [];
|
||||
// The console's database is offered even before the list loads.
|
||||
if (database && !names.includes(database)) names.unshift(database);
|
||||
return schemaTreeRows(names, expanded, (name) => {
|
||||
const target = name === database ? bound : targetOf(sourceId, name, current);
|
||||
const list = schemas[target];
|
||||
if (list?.status === "ok") return list.value;
|
||||
if (read?.[name]) return read[name].map((s) => s.name);
|
||||
return list?.status === "error" ? { error: list.message } : undefined;
|
||||
});
|
||||
}, [listed, database, expanded, schemas, read, bound, sourceId, current]);
|
||||
const value = database && schema ? schemaTreeValue(database, schema) : null;
|
||||
return (
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label="Database and schema"
|
||||
value={value}
|
||||
placeholder="<schema>"
|
||||
options={rows}
|
||||
searchable
|
||||
renderValue={() => (database ? (schema ? `${database}.${schema}` : database) : tx("<schema>"))}
|
||||
keepOpen={(v) => parseSchemaTreeValue(v).schema === null}
|
||||
onChange={(v) => {
|
||||
const pick = parseSchemaTreeValue(v);
|
||||
if (pick.schema === null) {
|
||||
const next = new Set(expanded);
|
||||
if (!next.delete(pick.database)) {
|
||||
next.add(pick.database);
|
||||
// Expanding again retries a database whose schemas could not be read.
|
||||
const target = targetFor(pick.database);
|
||||
if (useDatabase.getState().schemas[target]?.status === "error") void loadSchemas(target);
|
||||
}
|
||||
setOpened({ at: database, open: next });
|
||||
return;
|
||||
}
|
||||
const target = targetFor(pick.database);
|
||||
if (target !== bound) bindConsole(path, target);
|
||||
setConsoleSchema(path, pick.schema);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const quoted = (name: string) => `"${name.replace(/"/g, '""')}"`;
|
||||
|
||||
/**
|
||||
|
||||
@@ -484,73 +484,3 @@ export function parseSourceUrl(raw: string): { source: Partial<DataSource>; pass
|
||||
if (properties.length) source.properties = properties;
|
||||
return { source, password };
|
||||
}
|
||||
|
||||
/** A row of the console's database › schema switcher. */
|
||||
export interface SchemaTreeRow {
|
||||
value: string;
|
||||
label: string;
|
||||
verbatim?: boolean;
|
||||
icon?: string;
|
||||
disabled?: boolean;
|
||||
/** Searching a database's name keeps its schemas visible. */
|
||||
keywords?: string;
|
||||
tree: { depth: number; expanded?: boolean };
|
||||
}
|
||||
|
||||
const TREE_SEP = "\u0000";
|
||||
|
||||
/** The switcher value of database `database`, or of its schema `schema`. */
|
||||
export function schemaTreeValue(database: string, schema?: string): string {
|
||||
return schema === undefined ? `d${TREE_SEP}${database}` : `s${TREE_SEP}${database}${TREE_SEP}${schema}`;
|
||||
}
|
||||
|
||||
/** The database (and schema, for a schema row) a switcher value names. */
|
||||
export function parseSchemaTreeValue(value: string): { database: string; schema: string | null } {
|
||||
const [kind, database = "", schema = ""] = value.split(TREE_SEP);
|
||||
return { database, schema: kind === "s" ? schema : null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Rows of the switcher (IDEA's `database.schema` popup): every database, each expanded one followed
|
||||
* by its schemas, a "Loading…" row while `schemasOf` has none for it yet, or the error reading them.
|
||||
*/
|
||||
export function schemaTreeRows(
|
||||
databases: readonly string[],
|
||||
expanded: ReadonlySet<string>,
|
||||
schemasOf: (database: string) => readonly string[] | { error: string } | undefined,
|
||||
): SchemaTreeRow[] {
|
||||
const out: SchemaTreeRow[] = [];
|
||||
for (const database of databases) {
|
||||
const open = expanded.has(database);
|
||||
out.push({
|
||||
value: schemaTreeValue(database),
|
||||
label: database,
|
||||
verbatim: true,
|
||||
icon: "database",
|
||||
tree: { depth: 0, expanded: open },
|
||||
});
|
||||
if (!open) continue;
|
||||
const schemas = schemasOf(database);
|
||||
if (!schemas || "error" in schemas) {
|
||||
out.push({
|
||||
value: `l${TREE_SEP}${database}`,
|
||||
label: schemas ? schemas.error : "Loading…",
|
||||
verbatim: !!schemas,
|
||||
disabled: true,
|
||||
keywords: database,
|
||||
tree: { depth: 1 },
|
||||
});
|
||||
continue;
|
||||
}
|
||||
for (const schema of schemas)
|
||||
out.push({
|
||||
value: schemaTreeValue(database, schema),
|
||||
label: schema,
|
||||
verbatim: true,
|
||||
icon: "db-schema",
|
||||
keywords: database,
|
||||
tree: { depth: 1 },
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -205,10 +205,12 @@ describe("resolveTarget", () => {
|
||||
expect(resolveTarget(e, model)).toEqual({ schema: "nope", table: "missing", alias: null });
|
||||
});
|
||||
|
||||
it("refuses an unresolved default and keeps an explicit schema over the console's", () => {
|
||||
it("refuses unresolved defaults and SQL Server database/schema ambiguity", () => {
|
||||
expect(resolveTarget(editable("SELECT * FROM users"), model, "")).toBeNull();
|
||||
expect(resolveTarget(editable("SELECT * FROM users"), model, "sales")?.schema).toBe("sales");
|
||||
expect(resolveTarget(editable("SELECT * FROM dbo.users"), model, "sales")).toEqual({
|
||||
expect(resolveTarget(editable("SELECT * FROM users"), model, "public", "sqlServer")).toBeNull();
|
||||
const explicit = editable("SELECT * FROM dbo.users");
|
||||
expect(resolveTarget(explicit, model, "other_database", "sqlServer")).toBeNull();
|
||||
expect(resolveTarget(explicit, model, "public", "sqlServer")).toEqual({
|
||||
schema: "dbo",
|
||||
table: "users",
|
||||
alias: null,
|
||||
|
||||
@@ -227,7 +227,10 @@ export function resolveTarget(
|
||||
e: Extract<ResultEditability, { kind: "editable" }>,
|
||||
model: DbCompletion | null,
|
||||
schema?: string,
|
||||
driver: DbDriver = "postgres",
|
||||
): { schema: string | null; table: string; alias: string | null } | null {
|
||||
// SQL Server switches databases, but table details and edits take a table schema.
|
||||
if (driver === "sqlServer" && (e.schema === null || (schema && schema !== model?.defaultSchema))) return null;
|
||||
if (e.schema === null && schema === "") return null;
|
||||
return { schema: e.schema ?? (schema || model?.defaultSchema || null), table: e.table, alias: e.alias };
|
||||
}
|
||||
|
||||
@@ -485,11 +485,15 @@ describe("read-only results with a reason", () => {
|
||||
expect(backend.applyEdits).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("resolves an unqualified SQL Server table in the console's schema", async () => {
|
||||
it("keeps an unresolved SQL Server table schema read-only", async () => {
|
||||
backend.driver = "sqlServer";
|
||||
show("SELECT * FROM users", [{ name: "id" }, { name: "name" }], [["1", "Ann"]]);
|
||||
await act(async () => render(<ResultsView />));
|
||||
expect(backend.details).toHaveBeenCalledWith("pg", "public", "users");
|
||||
expect(await screen.findByRole("note")).toHaveTextContent(
|
||||
"Read-only: the table schema could not be identified in the result database.",
|
||||
);
|
||||
expect(screen.queryByRole("button", { name: "Submit" })).toBeNull();
|
||||
expect(backend.details).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["postgres", "sqlServer"] as const)("matches case-sensitive key columns exactly for %s", async (driver) => {
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { parseSchemaTreeValue, schemaTreeRows, schemaTreeValue } from "./model";
|
||||
|
||||
describe("console database › schema switcher", () => {
|
||||
it("round-trips database and schema values", () => {
|
||||
expect(parseSchemaTreeValue(schemaTreeValue("shop"))).toEqual({ database: "shop", schema: null });
|
||||
expect(parseSchemaTreeValue(schemaTreeValue("shop", "public"))).toEqual({ database: "shop", schema: "public" });
|
||||
expect(parseSchemaTreeValue(schemaTreeValue("a.b", "c:d"))).toEqual({ database: "a.b", schema: "c:d" });
|
||||
});
|
||||
|
||||
it("lists schemas under expanded databases only", () => {
|
||||
const schemas: Record<string, string[]> = { shop: ["public", "audit"], crm: ["public"] };
|
||||
const rows = schemaTreeRows(["shop", "crm"], new Set(["shop"]), (d) => schemas[d]);
|
||||
expect(rows.map((r) => [r.label, r.tree])).toEqual([
|
||||
["shop", { depth: 0, expanded: true }],
|
||||
["public", { depth: 1 }],
|
||||
["audit", { depth: 1 }],
|
||||
["crm", { depth: 0, expanded: false }],
|
||||
]);
|
||||
expect(rows[1]!.value).toBe(schemaTreeValue("shop", "public"));
|
||||
});
|
||||
|
||||
it("shows a disabled loading row while an expanded database's schemas load", () => {
|
||||
const rows = schemaTreeRows(["shop"], new Set(["shop"]), () => undefined);
|
||||
expect(rows[1]).toMatchObject({ label: "Loading…", disabled: true, tree: { depth: 1 } });
|
||||
});
|
||||
|
||||
it("shows the error when an expanded database's schemas cannot be read", () => {
|
||||
const rows = schemaTreeRows(["shop"], new Set(["shop"]), () => ({ error: "timed out" }));
|
||||
expect(rows[1]).toMatchObject({ label: "timed out", verbatim: true, disabled: true });
|
||||
});
|
||||
|
||||
it("lets a search for the database name keep its schemas", () => {
|
||||
const rows = schemaTreeRows(["shop"], new Set(["shop"]), () => ["public"]);
|
||||
expect(rows[1]).toMatchObject({ label: "public", keywords: "shop" });
|
||||
});
|
||||
});
|
||||
@@ -24,10 +24,7 @@ describe("the Breakpoints dialog", () => {
|
||||
});
|
||||
|
||||
const dialog = () => screen.getByRole("dialog", { name: "Breakpoints" });
|
||||
const row = (location: string) =>
|
||||
within(within(dialog()).getByRole("listbox", { name: "All breakpoints" })).getByRole("option", {
|
||||
name: (name) => name.includes(`Enable breakpoint at ${location}`),
|
||||
});
|
||||
const row = (name: string) => within(within(dialog()).getByLabelText("All breakpoints")).getByText(name);
|
||||
const condition = () => within(dialog()).getByLabelText("Condition") as HTMLInputElement;
|
||||
/** A row's mouse click as the list sees it: mousedown selects, click (with its count) activates. */
|
||||
const clickRow = (name: string, detail: number) => {
|
||||
@@ -40,8 +37,8 @@ describe("the Breakpoints dialog", () => {
|
||||
render(<DebuggerOverlays />);
|
||||
clickRow("main.py:7", 1);
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
expect(row("main.py:7").getAttribute("aria-selected")).toBe("true");
|
||||
expect(condition().value).toBe("");
|
||||
// Its details show beside the list.
|
||||
expect(within(dialog()).getAllByText("main.py:7")).toHaveLength(2);
|
||||
clickRow("main.py:3", 2);
|
||||
expect(openFile).toHaveBeenCalledWith(path, { selection: { line: 2, col: 0 } });
|
||||
});
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
.section {
|
||||
flex: none;
|
||||
max-height: 40%;
|
||||
overflow: auto;
|
||||
border-top: 1px solid var(--border-popup);
|
||||
padding: 6px 12px 8px;
|
||||
display: flex;
|
||||
|
||||
@@ -88,46 +88,36 @@
|
||||
}
|
||||
|
||||
/* breakpoints dialog */
|
||||
.bpWindow [data-dialog-body] {
|
||||
.bpDialog {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
height: 420px;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.bpDialog {
|
||||
flex: 1 1 420px;
|
||||
.bpListPane {
|
||||
width: 360px;
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-right: 1px solid var(--border-popup);
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.bpListHeader {
|
||||
min-height: var(--h-header);
|
||||
height: var(--h-header);
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-1-5);
|
||||
padding: var(--space-0-5) var(--space-2);
|
||||
padding: 0 8px 0 12px;
|
||||
border-bottom: 1px solid var(--border-popup);
|
||||
}
|
||||
|
||||
.bpListActions {
|
||||
display: flex;
|
||||
gap: var(--space-1);
|
||||
margin-inline-start: auto;
|
||||
}
|
||||
|
||||
.bpList {
|
||||
flex: 1 0 calc(2 * var(--h-list-row));
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.bpAuxiliary {
|
||||
flex: 0 1 auto;
|
||||
max-height: 42%;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.bpRow,
|
||||
.chooserRow {
|
||||
display: flex;
|
||||
@@ -145,31 +135,6 @@
|
||||
color: var(--fg-emphasis);
|
||||
}
|
||||
|
||||
.bpLocation {
|
||||
display: inline-flex;
|
||||
min-width: 0;
|
||||
align-items: baseline;
|
||||
}
|
||||
|
||||
.bpRow .bpName,
|
||||
.bpLocation .bpName {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
font-family: var(--font-ui);
|
||||
}
|
||||
|
||||
.bpLine {
|
||||
flex: none;
|
||||
white-space: nowrap;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.bpRow > svg {
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.bpDir {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
@@ -191,29 +156,14 @@
|
||||
.bpDetail {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.detail {
|
||||
padding: var(--space-3);
|
||||
padding: 12px 14px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.detail .bpTitle {
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1) var(--space-2);
|
||||
}
|
||||
|
||||
.detail :is(.bpFile, .bpLocation) {
|
||||
flex: 1 1 12ch;
|
||||
font-family: var(--font-ui);
|
||||
}
|
||||
|
||||
.detail .label {
|
||||
font-size: var(--fs-ui);
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.statusLine {
|
||||
@@ -295,6 +245,9 @@
|
||||
}
|
||||
|
||||
.exceptions {
|
||||
flex: none;
|
||||
max-height: 40%;
|
||||
overflow: auto;
|
||||
border-top: 1px solid var(--border-popup);
|
||||
padding: 6px 12px 8px;
|
||||
display: flex;
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
Fragment,
|
||||
useEffect,
|
||||
useId,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
@@ -14,23 +13,7 @@ import { basename, relativePath, useProject } from "@/platform/project";
|
||||
import { executeAction, getAction } from "@/platform/actions";
|
||||
import { call, commands, type AttachableProcess, type RunConfig, type Variable } from "@/platform/ipc";
|
||||
import { maybeEditorService, notifications } from "@/workbench/contributions";
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
Dialog,
|
||||
Icon,
|
||||
IconButton,
|
||||
Input,
|
||||
Kbd,
|
||||
List,
|
||||
Menu,
|
||||
Popup,
|
||||
SplitGroup,
|
||||
SplitHandle,
|
||||
SplitPanel,
|
||||
Toggle,
|
||||
T,
|
||||
} from "@/ui";
|
||||
import { Button, Checkbox, Dialog, Icon, IconButton, Input, Kbd, List, Menu, Popup, Toggle, T } from "@/ui";
|
||||
import { isConditional, suspends, type BreakpointEntry } from "../breakpoints/model";
|
||||
import {
|
||||
removeAllBreakpoints,
|
||||
@@ -390,15 +373,6 @@ type DialogRow =
|
||||
| ({ type: "line"; key: string } & BpRow)
|
||||
| { type: "special"; key: string; bp: SpecialBreakpoint };
|
||||
|
||||
function BreakpointLocation({ path, line }: { path: string; line: number }) {
|
||||
return (
|
||||
<span className={styles.bpLocation} title={`${path}:${line + 1}`}>
|
||||
<span className={styles.bpName}>{basename(path)}</span>
|
||||
<span className={styles.bpLine}>:{line + 1}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function BreakpointsDialog() {
|
||||
const state = useOverlays((s) => s.breakpoints);
|
||||
const byFile = useBreakpoints((s) => s.byFile);
|
||||
@@ -433,18 +407,6 @@ function BreakpointsDialog() {
|
||||
// Enter on Done and a click on a row don't blur them.
|
||||
const commitRef = useRef<(() => void) | null>(null);
|
||||
const open = !!state;
|
||||
const layout = useRef<HTMLDivElement>(null);
|
||||
const [stacked, setStacked] = useState(false);
|
||||
useLayoutEffect(() => {
|
||||
const el = layout.current;
|
||||
if (!open || !el) return;
|
||||
const update = () => setStacked(el.clientWidth > 0 && el.clientWidth < 560);
|
||||
update();
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
const observer = new ResizeObserver(update);
|
||||
observer.observe(el);
|
||||
return () => observer.disconnect();
|
||||
}, [open]);
|
||||
const current = items.find((r) => r.key === (selected ?? state?.id)) ?? items[0];
|
||||
const close = () => {
|
||||
commitRef.current?.();
|
||||
@@ -468,38 +430,28 @@ function BreakpointsDialog() {
|
||||
open={open}
|
||||
onClose={close}
|
||||
title="Breakpoints"
|
||||
className={styles.bpWindow}
|
||||
width={760}
|
||||
minWidth={400}
|
||||
minHeight={340}
|
||||
resizable="both"
|
||||
aria-label="Breakpoints"
|
||||
buttons={[{ label: "Done", role: "default", onClick: close }]}
|
||||
>
|
||||
<SplitGroup
|
||||
elementRef={layout}
|
||||
orientation={stacked ? "vertical" : "horizontal"}
|
||||
storageKey={stacked ? "openidea.debug.breakpoints.stacked" : "openidea.debug.breakpoints.split"}
|
||||
className={styles.bpDialog}
|
||||
>
|
||||
<SplitPanel id="breakpoint-list" defaultSize={stacked ? "42%" : "35%"} minSize={stacked ? "34%" : "216px"}>
|
||||
<div className={styles.bpDialog}>
|
||||
<div className={styles.bpListPane}>
|
||||
<div className={styles.bpListHeader}>
|
||||
<Toggle checked={muted} onChange={setMuted} label="Mute breakpoints" />
|
||||
<div className={styles.bpListActions}>
|
||||
<IconButton
|
||||
icon="plus"
|
||||
title="Add Method Breakpoint"
|
||||
size="small"
|
||||
onClick={() => setSelected(addMethodBreakpoint("").id)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="trash"
|
||||
title="Remove All Breakpoints"
|
||||
size="small"
|
||||
disabled={!items.length}
|
||||
onClick={removeAll}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.spacer} />
|
||||
<IconButton
|
||||
icon="plus"
|
||||
title="Add Method Breakpoint"
|
||||
size="small"
|
||||
onClick={() => setSelected(addMethodBreakpoint("").id)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="trash"
|
||||
title="Remove All Breakpoints"
|
||||
size="small"
|
||||
disabled={!items.length}
|
||||
onClick={removeAll}
|
||||
/>
|
||||
</div>
|
||||
<List
|
||||
items={rows}
|
||||
@@ -534,9 +486,7 @@ function BreakpointsDialog() {
|
||||
aria-label={tx`Enable ${specialTitle(r.bp)}`}
|
||||
/>
|
||||
<Icon name={r.bp.kind === "method" ? "breakpoint-method" : "breakpoint-field"} size={14} />
|
||||
<span className={styles.bpName} title={specialTitle(r.bp)}>
|
||||
{specialTitle(r.bp)}
|
||||
</span>
|
||||
<span className={styles.bpName}>{specialTitle(r.bp)}</span>
|
||||
{r.bp.path && (
|
||||
<span className={styles.bpDir}>
|
||||
{basename(r.bp.path)}
|
||||
@@ -570,7 +520,9 @@ function BreakpointsDialog() {
|
||||
}
|
||||
aria-hidden
|
||||
/>
|
||||
<BreakpointLocation path={r.path} line={r.bp.line} />
|
||||
<span className={styles.bpName}>
|
||||
{basename(r.path)}:{r.bp.line + 1}
|
||||
</span>
|
||||
<span className={styles.bpDir}>{relativePath(root, r.path)}</span>
|
||||
{isConditional(r.bp) && <span className={styles.bpCond}>{suspends(r.bp) ? "if" : "log"}</span>}
|
||||
{r.bp.temporary && (
|
||||
@@ -582,22 +534,17 @@ function BreakpointsDialog() {
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<div className={styles.bpAuxiliary}>
|
||||
<ExceptionBreakpoints open={open} />
|
||||
<EventBreakpointsSection />
|
||||
</div>
|
||||
</SplitPanel>
|
||||
<SplitHandle />
|
||||
<SplitPanel id="breakpoint-detail" minSize={stacked ? "42%" : "284px"}>
|
||||
<div className={styles.bpDetail}>
|
||||
{current?.type === "line" ? (
|
||||
<BreakpointDetail key={current.key} row={current} onGo={() => goTo(current)} commitRef={commitRef} />
|
||||
) : current?.type === "special" ? (
|
||||
<SpecialDetail key={current.key} bp={current.bp} onGo={() => goTo(current)} commitRef={commitRef} />
|
||||
) : null}
|
||||
</div>
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
<ExceptionBreakpoints open={open} />
|
||||
<EventBreakpointsSection />
|
||||
</div>
|
||||
<div className={styles.bpDetail}>
|
||||
{current?.type === "line" ? (
|
||||
<BreakpointDetail key={current.key} row={current} onGo={() => goTo(current)} commitRef={commitRef} />
|
||||
) : current?.type === "special" ? (
|
||||
<SpecialDetail key={current.key} bp={current.bp} onGo={() => goTo(current)} commitRef={commitRef} />
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -663,7 +610,10 @@ function BreakpointDetail({
|
||||
return (
|
||||
<div className={styles.detail}>
|
||||
<div className={styles.bpTitle}>
|
||||
<BreakpointLocation path={path} line={bp.line} />
|
||||
<span className={styles.bpFile}>
|
||||
{basename(path)}:{bp.line + 1}
|
||||
</span>
|
||||
<div className={styles.spacer} />
|
||||
<Button size="small" variant="ghost" onClick={onGo}>
|
||||
<T>Go to Source</T>
|
||||
</Button>
|
||||
@@ -714,9 +664,8 @@ function SpecialDetail({
|
||||
<div className={styles.detail}>
|
||||
<div className={styles.bpTitle}>
|
||||
<Icon name={bp.kind === "method" ? "breakpoint-method" : "breakpoint-field"} size={14} />
|
||||
<span className={styles.bpFile} title={specialTitle(bp)}>
|
||||
{specialTitle(bp)}
|
||||
</span>
|
||||
<span className={styles.bpFile}>{specialTitle(bp)}</span>
|
||||
<div className={styles.spacer} />
|
||||
{bp.path && (
|
||||
<Button size="small" variant="ghost" onClick={onGo}>
|
||||
<T>Go to Source</T>
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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>
|
||||
) : (
|
||||
|
||||
@@ -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>
|
||||
</>
|
||||
|
||||
@@ -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
@@ -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
|
||||
)}
|
||||
|
||||
@@ -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,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);
|
||||
});
|
||||
});
|
||||
@@ -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))`. */
|
||||
|
||||
@@ -2738,10 +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",
|
||||
"Database and schema": "Database and schema",
|
||||
"Loading…": "Loading…",
|
||||
"<schema>": "<schema>"
|
||||
"Sort by Duration": "Sort by Duration"
|
||||
}
|
||||
@@ -9108,8 +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": "调整右侧合并窗格宽度",
|
||||
"Database and schema": "数据库和 schema"
|
||||
"Sort by Duration": "按持续时间排序"
|
||||
}
|
||||
@@ -159,16 +159,6 @@
|
||||
display: contents;
|
||||
}
|
||||
|
||||
/* Tree rows: indentation plus room for the disclosure chevron. */
|
||||
.treeIndent {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
flex: none;
|
||||
width: calc(var(--tree-depth) * 16px + 12px);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.rowAction {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
|
||||
+2
-26
@@ -1,13 +1,4 @@
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type CSSProperties,
|
||||
type KeyboardEvent,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
import { Icon, type IconName } from "./icons";
|
||||
import { Popup } from "./Popup";
|
||||
@@ -28,8 +19,6 @@ export interface SelectOption<V extends string = string> {
|
||||
disabled?: boolean;
|
||||
/** A non-selectable group heading, independent of disabled options. */
|
||||
section?: boolean;
|
||||
/** Tree row: indented by `depth`; `expanded` (when set) draws a disclosure chevron. */
|
||||
tree?: { depth: number; expanded?: boolean };
|
||||
}
|
||||
|
||||
export interface SelectProps<V extends string = string> {
|
||||
@@ -49,8 +38,6 @@ export interface SelectProps<V extends string = string> {
|
||||
searchable?: boolean;
|
||||
/** The option under the pointer or keyboard while the list is open; `null` once it closes. */
|
||||
onPreview?: (value: V | null) => void;
|
||||
/** Choosing an option this returns `true` for keeps the popup open (e.g. expanding a tree row). */
|
||||
keepOpen?: (value: V) => boolean;
|
||||
}
|
||||
|
||||
const TYPE_AHEAD_MS = 800;
|
||||
@@ -248,7 +235,6 @@ export function SelectListbox<V extends string = string>({
|
||||
{options.map((o) => (
|
||||
<div key={`${o.section ? "section" : "option"}:${o.value}`} className={styles.sizerRow}>
|
||||
<span className={styles.check} />
|
||||
{o.tree && <TreeIndent {...o.tree} />}
|
||||
{o.icon && <Icon name={o.icon} size={14} />}
|
||||
<span>{labelOf(o)}</span>
|
||||
{o.detail && <span className={styles.sizerDetail}>{given(o.detail)}</span>}
|
||||
@@ -277,7 +263,6 @@ export function SelectListbox<V extends string = string>({
|
||||
aria-disabled={o.disabled || undefined}
|
||||
>
|
||||
<span className={styles.check}>{o.value === value && <Icon name="check" size={12} />}</span>
|
||||
{o.tree && <TreeIndent {...o.tree} />}
|
||||
{o.icon && <Icon name={o.icon} size={14} />}
|
||||
<span className={clsx(styles.optionLabel, o.detail && styles.withDetail)} title={labelOf(o)}>
|
||||
{labelOf(o)}
|
||||
@@ -304,14 +289,6 @@ export function SelectListbox<V extends string = string>({
|
||||
);
|
||||
}
|
||||
|
||||
function TreeIndent({ depth, expanded }: { depth: number; expanded?: boolean }) {
|
||||
return (
|
||||
<span className={styles.treeIndent} style={{ "--tree-depth": depth } as CSSProperties}>
|
||||
{expanded !== undefined && <Icon name={expanded ? "chevron-down" : "chevron-right"} size={12} />}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** Dropdown select with a listbox popup (↑↓ Enter Esc, type-ahead). */
|
||||
export function Select<V extends string = string>({
|
||||
value,
|
||||
@@ -324,7 +301,6 @@ export function Select<V extends string = string>({
|
||||
renderValue,
|
||||
searchable = false,
|
||||
onPreview,
|
||||
keepOpen,
|
||||
...aria
|
||||
}: SelectProps<V>) {
|
||||
const given = useGivenTx();
|
||||
@@ -404,7 +380,7 @@ export function Select<V extends string = string>({
|
||||
aria-label={aria["aria-label"]}
|
||||
onChoose={(v) => {
|
||||
onChange(v);
|
||||
if (!keepOpen?.(v)) setOpen(false);
|
||||
setOpen(false);
|
||||
}}
|
||||
/>
|
||||
</Popup>
|
||||
|
||||
@@ -5,7 +5,6 @@ import { Tree, type TreeHandle } from "./Tree";
|
||||
import { getContext } from "@/platform/context";
|
||||
import { registerAction } from "@/platform/actions";
|
||||
import { installKeyboardDispatcher, useKeymap } from "@/platform/keymap";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
|
||||
interface N {
|
||||
id: string;
|
||||
@@ -309,29 +308,6 @@ describe("Tree speed search", () => {
|
||||
fireEvent.click(toggle);
|
||||
expect(labels(tree)).toHaveLength(6);
|
||||
});
|
||||
|
||||
it("⌘F / Ctrl+F opens the field before anything is typed, and Escape closes it", () => {
|
||||
const os = usePlatform.getState().os;
|
||||
try {
|
||||
for (const [platform, init] of [
|
||||
["macos", { metaKey: true }],
|
||||
["windows", { ctrlKey: true }],
|
||||
] as const) {
|
||||
usePlatform.setState({ os: platform });
|
||||
const { key, unmount } = setup({ speedSearchField: true });
|
||||
expect(screen.queryByRole("status")).toBeNull();
|
||||
key("f", init);
|
||||
expect(screen.getByRole("status")).toHaveTextContent("");
|
||||
key("u");
|
||||
expect(screen.getByRole("status")).toHaveTextContent("u");
|
||||
key("Escape");
|
||||
expect(screen.queryByRole("status")).toBeNull();
|
||||
unmount();
|
||||
}
|
||||
} finally {
|
||||
usePlatform.setState({ os });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Tree occurrences", () => {
|
||||
|
||||
+14
-34
@@ -33,7 +33,7 @@ import { acquirePopup } from "./popupState";
|
||||
import styles from "./Tree.module.css";
|
||||
import { T } from "./T";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { isMacHost, registerKeyClaim } from "@/platform/keymap";
|
||||
import { registerKeyClaim } from "@/platform/keymap";
|
||||
import { useGivenTx } from "@/platform/i18n";
|
||||
import { useTreeReorder, type TreeReorder } from "./treeReorder";
|
||||
import { startPointerDrag, type DragData } from "./pointerDrag";
|
||||
@@ -287,13 +287,6 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
const [lead, setLead] = useState<string | null>(() => [...selected][0] ?? null);
|
||||
const [anchor, setAnchor] = useState<string | null>(null);
|
||||
const [query, setQuery] = useState("");
|
||||
// ⌘F / Ctrl+F opens speed search before anything is typed (IDEA's Find in a tree).
|
||||
const [armed, setArmed] = useState(false);
|
||||
const searching = !!query || armed;
|
||||
const endSearch = () => {
|
||||
setQuery("");
|
||||
setArmed(false);
|
||||
};
|
||||
const [onlyMatches, setOnlyMatches] = useState(false);
|
||||
const filterMatches = speedSearchMode === "filter" || (speedSearchField && onlyMatches);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
@@ -393,7 +386,7 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
// Speed search owns Escape while active, and ⌫ with any modifier: the query is edited like a
|
||||
// text field instead of the view's shortcuts running (⌘⌫ is Drop… in the Database view).
|
||||
useEffect(() => {
|
||||
if (!searching) return;
|
||||
if (!query) return;
|
||||
const release = acquirePopup();
|
||||
const unclaim = registerKeyClaim(
|
||||
(e) => e.key === "Backspace" && e.target instanceof Node && !!scrollRef.current?.contains(e.target),
|
||||
@@ -402,7 +395,7 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
release();
|
||||
unclaim();
|
||||
};
|
||||
}, [searching]);
|
||||
}, [query]);
|
||||
|
||||
const setExpanded = (row: Row<T>, open: boolean) => {
|
||||
if (!row.expandable || row.expanded === open) return;
|
||||
@@ -541,18 +534,6 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
const pageSize = Math.max(1, Math.floor((scrollRef.current?.clientHeight ?? 300) / rowHeight) - 1);
|
||||
const typed =
|
||||
speedSearch && e.key.length === 1 && !e.metaKey && !e.ctrlKey && !e.altKey && !(e.key === " " && !query);
|
||||
if (
|
||||
speedSearch &&
|
||||
e.key.toLowerCase() === "f" &&
|
||||
(isMacHost() ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey) &&
|
||||
!e.altKey &&
|
||||
!e.shiftKey
|
||||
) {
|
||||
setArmed(true);
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return;
|
||||
}
|
||||
if (typed) {
|
||||
const q = query + e.key;
|
||||
setQuery(q);
|
||||
@@ -565,7 +546,7 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
// Jump to Source (F4 / ⌘↓): the tree's own handler, else it activates like Enter.
|
||||
if (e.key === "F4" || (e.key === "ArrowDown" && e.metaKey && !e.shiftKey && !e.altKey)) {
|
||||
if (!row) return;
|
||||
endSearch();
|
||||
setQuery("");
|
||||
if (onJumpToSource) {
|
||||
if (!row.loading) onJumpToSource(row.node, selected);
|
||||
} else activate(row, e);
|
||||
@@ -575,8 +556,8 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
}
|
||||
switch (e.key) {
|
||||
case "Escape":
|
||||
if (!searching) return;
|
||||
endSearch();
|
||||
if (!query) return;
|
||||
setQuery("");
|
||||
break;
|
||||
case "Backspace":
|
||||
if (!query) return;
|
||||
@@ -597,14 +578,14 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
break;
|
||||
}
|
||||
case "ArrowRight":
|
||||
endSearch();
|
||||
setQuery("");
|
||||
if (!row) return;
|
||||
if (row.expandable && !row.expanded) setExpanded(row, true);
|
||||
else if (row.expanded && rows[leadIndex + 1]?.parentKey === row.key && !rows[leadIndex + 1]!.loading)
|
||||
selectIndex(leadIndex + 1);
|
||||
break;
|
||||
case "ArrowLeft":
|
||||
endSearch();
|
||||
setQuery("");
|
||||
if (!row) return;
|
||||
if (row.expanded) setExpanded(row, false);
|
||||
else if (row.parentKey != null) {
|
||||
@@ -622,16 +603,16 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
break;
|
||||
}
|
||||
case "PageDown":
|
||||
endSearch();
|
||||
setQuery("");
|
||||
selectIndex(Math.min(rows.length - 1, Math.max(0, leadIndex) + pageSize), range ? "range" : "single");
|
||||
break;
|
||||
case "PageUp":
|
||||
endSearch();
|
||||
setQuery("");
|
||||
selectIndex(Math.max(0, leadIndex - pageSize), range ? "range" : "single");
|
||||
break;
|
||||
case "Enter":
|
||||
if (!row) return;
|
||||
endSearch();
|
||||
setQuery("");
|
||||
activate(row, e);
|
||||
break;
|
||||
case "a":
|
||||
@@ -663,7 +644,7 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
endSearch();
|
||||
setQuery("");
|
||||
if (e.shiftKey) selectIndex(i, "range");
|
||||
else if (e.metaKey || e.ctrlKey) selectIndex(i, "toggle");
|
||||
else selectIndex(i);
|
||||
@@ -720,8 +701,7 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
className={styles.tree}
|
||||
onKeyDown={onKeyDown}
|
||||
onBlur={(e) => {
|
||||
if (e.currentTarget.contains(e.relatedTarget as Node | null)) return;
|
||||
endSearch();
|
||||
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setQuery("");
|
||||
}}
|
||||
onContextMenu={
|
||||
onContextMenu
|
||||
@@ -856,7 +836,7 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
{searching &&
|
||||
{query &&
|
||||
(speedSearchField ? (
|
||||
// Typing stays in the tree: a press here must not take its focus, which would end the search.
|
||||
<div
|
||||
|
||||
Reference in new issue
Block a user