Compare commits

..
Author SHA1 Message Date
l0ng-ai 2234ac7941 Merge remote-tracking branch 'origin/main' into fix/debugger-breakpoints-dialog-layout 2026-11-20 06:05:33 +08:00
l0ng-ai 60d335eec0 fix(refactor): keep the Change Signature parameter table readable (#4602)
The Change Signature dialog's parameter table had fixed column widths and a one-line preview, so in narrow windows types and names were clipped and long signatures ran off the preview. The table columns now share the width with truncation, the preview puts each parameter on its own line as IDEA's does, and the dialog's sections keep their controls visible.
2026-11-20 06:05:24 +08:00
Hafiz Faizan ul hassanandfaizanalhassan a679e8086f feat(database): pick data source, then database and schema in the query console (#4614)
The query console's Data source dropdown mixed databases into the source list, and SQL Server's second dropdown listed databases. As in DataGrip, the dropdown now lists data sources only, and a database.schema switcher next to it opens a searchable database -> schema tree that loads a database's schemas on expand and moves the console to the picked database; one-level drivers keep a flat schema list and SQLite has none. SQL Server's console schema is now a real schema (SCHEMA_NAME()) that scopes resolution and completion, since a session's default schema can't be changed, while the pooled connection still returns to its database. Tree speed search also opens with Cmd/Ctrl+F, as in IDEA.

Closes #4577

Co-authored-by: faizanalhassan <[email protected]>
2026-11-20 06:04:34 +08:00
Mr0Bread 4c20aa5c8d test(editor): cover missing-file and malformed session restore (#4615)
Adds regression tests for editor session recovery: a deleted selected file is dropped quietly and the remaining tab restores with its caret, a permission-denied tab stays open with its error inline, and truncated session JSON loads as null without writing storage until a valid session replaces it. No production changes.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-20 06:00:56 +08:00
l0ng-ai d19d74120b fix(debugger): keep values visible in narrow variables panes (#4600)
In narrow Variables panes the name and type kept their full width, so values were cut to nothing and the Show button could be pushed out. Names and types now truncate within caps, the value and its Show button share a group that keeps a minimum width, overflow is measured against that group, and full names and types are in tooltips.
2026-11-20 06:00:12 +08:00
l0ng-ai 32de3d0bf8 test(debugger): select breakpoint rows by accessible name 2026-11-20 04:32:23 +08:00
l0ng-ai 380de4ecd5 fix(debugger): keep breakpoint details usable in narrow windows 2026-11-20 04:26:39 +08:00
27 changed files with 932 additions and 252 deletions

No files matched your search

+2 -1
View File
@@ -217,7 +217,8 @@ 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))
.and_then(|db| crate::sql::use_schema(DbDriver::SqlServer, &db));
// Statements that `USE` another database must not move the pooled connection for good.
.map(|db| format!("USE {}", crate::sql::quote_ident(DbDriver::SqlServer, &db)));
Ok(MssqlConnection(Some(client), Context::new(default)))
}
+8 -6
View File
@@ -442,7 +442,8 @@ 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()"),
DbDriver::SqlServer => Some("SELECT DB_NAME()"),
// The login's default schema; the database is the console's target (IDEA's `database.schema`).
DbDriver::SqlServer => Some("SELECT SCHEMA_NAME()"),
DbDriver::Oracle => Some("SELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') FROM DUAL"),
DbDriver::Snowflake => Some("SELECT CURRENT_SCHEMA()"),
}
@@ -450,12 +451,13 @@ 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).
/// 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).
pub fn use_schema(driver: DbDriver, schema: &str) -> Option<String> {
match driver {
DbDriver::Sqlite | DbDriver::Clickhouse | DbDriver::Jdbc => None,
DbDriver::Sqlite | DbDriver::Clickhouse | DbDriver::Jdbc | DbDriver::SqlServer => None,
DbDriver::Postgres => Some(format!("SET search_path TO {}", quote_ident(driver, schema))),
DbDriver::Mysql | DbDriver::SqlServer => Some(format!("USE {}", quote_ident(driver, schema))),
DbDriver::Mysql => 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))),
}
@@ -1030,7 +1032,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 DB_NAME()"));
assert_eq!(current_schema(DbDriver::SqlServer), Some("SELECT SCHEMA_NAME()"));
assert_eq!(crate::conn::begin_statement(DbDriver::SqlServer), "BEGIN TRAN");
assert_eq!(
schemas(DbDriver::SqlServer, true),
@@ -1149,7 +1151,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, "app] data"), Some("USE [app]] data]".into()));
assert_eq!(use_schema(DbDriver::SqlServer, "dbo"), None);
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"));
+50
View File
@@ -0,0 +1,50 @@
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();
});
+75
View File
@@ -0,0 +1,75 @@
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();
});
+73 -1
View File
@@ -1,9 +1,11 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { EditorController, openFilePaths, useEditorStatus, useTabs } from "./controller";
import { EditorController, openFilePaths, useEditorStatus, useTabErrors, 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,
@@ -11,6 +13,7 @@ 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";
@@ -29,6 +32,75 @@ 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" }));
+48 -2
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
initialTabsState,
moveTabToNewSplit,
@@ -9,7 +9,15 @@ import {
togglePin,
type TabsState,
} from "./tabs";
import { loadSession, parseSession, restoreTabsState, serializeSession, slashPath } from "./session";
import {
loadSession,
parseSession,
restoreTabsState,
serializeSession,
slashPath,
storeSession,
type EditorSession,
} from "./session";
const file = (path: string) => ({ kind: "file", key: `file:${path}`, path });
const fileKey = (p: string) => `file:${p}`;
@@ -103,6 +111,44 @@ 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,7 +1,6 @@
.dialog [data-dialog-body] {
display: flex;
flex-direction: column;
overflow: hidden;
}
.body {
@@ -9,8 +8,8 @@
min-height: 0;
display: flex;
flex-direction: column;
gap: var(--space-3);
padding: 14px;
gap: var(--space-2);
padding: var(--space-3);
font-size: var(--fs-ui);
color: var(--fg);
}
@@ -18,54 +17,34 @@
.header {
flex: none;
display: grid;
grid-template-columns: 150px 1fr 1fr;
gap: var(--space-3);
grid-template-columns: minmax(0, 0.75fr) minmax(0, 1fr) minmax(0, 1.25fr);
align-items: end;
gap: var(--space-2);
}
.field {
flex: none;
display: flex;
flex-direction: column;
gap: var(--space-1-5);
gap: var(--space-1);
min-width: 0;
}
.parameters {
flex: 1 1 auto;
min-height: 0;
min-height: calc(var(--h-list-row) * 5);
display: flex;
flex-direction: column;
border: 1px solid var(--border);
border-radius: 4px;
border-radius: var(--radius-control);
overflow: hidden;
}
.toolbar {
flex: none;
display: flex;
gap: 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);
padding: var(--space-0-5) var(--space-1);
border-bottom: 1px solid var(--border);
}
@@ -73,6 +52,57 @@
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 {
@@ -84,14 +114,16 @@
}
.preview {
height: clamp(56px, 18vh, 128px);
margin: 0;
padding: 6px 8px;
padding: var(--space-1-5) var(--space-2);
border: 1px solid var(--border);
border-radius: 4px;
font-family: var(--font-mono);
font-size: var(--fs-code);
border-radius: var(--radius-control);
overflow: auto;
white-space: pre-wrap;
overflow-wrap: anywhere;
line-height: 1.5;
user-select: text;
color: var(--fg);
background: var(--bg-input);
}
+100 -54
View File
@@ -1,5 +1,5 @@
/** IDEA's Change Signature dialog for Java methods (`signature.ts`). */
import { useEffect, useRef, useState } from "react";
import { useEffect, useId, useLayoutEffect, useRef, useState, type CSSProperties } from "react";
import type { MethodSignature } from "@/bindings";
import { Checkbox, Dialog, IconButton, Input, Select, Spinner, T, Toolbar } from "@/ui";
import { useTx } from "@/platform/i18n";
@@ -34,6 +34,16 @@ 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,
@@ -45,6 +55,10 @@ 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);
@@ -93,7 +107,8 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
title="Change Signature"
className={styles.dialog}
width={640}
minHeight={380}
minWidth={360}
minHeight={360}
maxHeight={640}
resizable="both"
buttons={[
@@ -110,7 +125,7 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
) : undefined
}
>
<div className={styles.body}>
<div className={styles.body} style={codeStyle}>
<div className={styles.header}>
<label className={styles.field}>
<T>Visibility:</T>
@@ -123,11 +138,18 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
</label>
<label className={styles.field}>
<T>Return type:</T>
<Input mono value={returnType} onChange={(e) => setReturnType(e.target.value)} />
<Input className={styles.code} mono value={returnType} onChange={(e) => setReturnType(e.target.value)} />
</label>
<label className={styles.field}>
<T>Name:</T>
<Input mono autoFocus autoSelect value={methodName} onChange={(e) => setMethodName(e.target.value)} />
<Input
className={styles.code}
mono
data-autofocus
autoSelect
value={methodName}
onChange={(e) => setMethodName(e.target.value)}
/>
</label>
</div>
<div className={styles.parameters}>
@@ -142,59 +164,83 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
onClick={() => move(1)}
/>
</Toolbar>
<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 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>
</div>
<Checkbox checked={delegate} onChange={setDelegate} label={<T>Delegate via overloading method</T>} />
<div className={styles.field}>
<T>Signature Preview</T>
<pre className={styles.preview}>{signatureText(signature)}</pre>
<span id={previewLabel}>
<T>Signature Preview</T>
</span>
<pre className={styles.preview} role="region" aria-labelledby={previewLabel} tabIndex={0}>
{signatureText(signature)}
</pre>
</div>
{(error ?? (signatureChanged(info, signature) ? problem : null)) && (
<span className={styles.error} role="alert">
+1 -1
View File
@@ -16,7 +16,7 @@ const info: MethodSignature = {
describe("change signature", () => {
it("previews the signature like the declaration", () => {
expect(signatureText(info)).toBe("public int sum(int a, int b) throws java.io.IOException");
expect(signatureText(info)).toBe("public int sum(\n int a,\n int b\n) throws java.io.IOException");
expect(signatureText({ ...info, modifier: "", parameters: [], exceptions: [] })).toBe("int sum()");
});
+4 -3
View File
@@ -36,7 +36,7 @@ export const parameterRow = (p: SignatureParameter): ParameterRow => ({ ...p, ke
export const newParameter = (): ParameterRow =>
parameterRow({ type: "", name: "", defaultValue: "", originalIndex: -1 });
/** `public int sum(int a, int b) throws IOException`, as the dialog's preview shows it. */
/** Formats the declaration for the dialog's preview. */
export function signatureText(sig: {
modifier: string;
returnType: string;
@@ -44,8 +44,9 @@ export function signatureText(sig: {
parameters: readonly SignatureParameter[];
exceptions?: readonly { type: string }[];
}): string {
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 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 throws = sig.exceptions?.length ? ` throws ${sig.exceptions.map((e) => e.type).join(", ")}` : "";
return head + throws;
}
+2 -2
View File
@@ -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, driver) : null),
[editability, model, tab.schema, driver],
() => (editability.kind === "editable" ? resolveTarget(editability, model, tab.schema) : null),
[editability, model, tab.schema],
);
const detailsId = target ? detailsKey(tab.sourceId, target.schema ?? "", target.table) : null;
const details = useDatabase((s) => (detailsId ? s.details[detailsId] : undefined));
+129 -52
View File
@@ -55,7 +55,17 @@ import {
import { shortcutLabel } from "@/platform/keymap";
import { Icon, IconButton, Select, Toolbar, lazyComponent } from "@/ui";
import { useProject } from "@/platform/project";
import { activeSchema, schemaSwitchable, sourceIcon, sourceLabel, splitTarget, targetOf } from "./model";
import {
activeSchema,
parseSchemaTreeValue,
schemaSwitchable,
schemaTreeRows,
schemaTreeValue,
sourceIcon,
sourceLabel,
splitTarget,
targetOf,
} from "./model";
import { loadSavedCatalog, offerIntrospection } from "./introspection";
import { analyze, templateContexts, valuesSlot } from "./sql/analyze";
import {
@@ -90,7 +100,6 @@ import {
setConsoleSchema,
setManualCommit,
sourceById,
targetLabel,
useDatabase,
} from "./store";
import styles from "./Database.module.css";
@@ -586,7 +595,6 @@ 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);
@@ -594,7 +602,6 @@ 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]);
@@ -602,49 +609,35 @@ 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 && (sqlServer || listsDatabases(sourceById(boundId))) && !useDatabase.getState().databases[boundId])
if (boundId && listsDatabases(sourceById(boundId)) && !useDatabase.getState().databases[boundId])
void loadDatabases(boundId);
}, [boundId, sqlServer]);
}, [boundId]);
// Loads the list again after a refresh drops it.
const schemasMissing = !schemaList;
useEffect(() => {
if (bound && switchable && !sqlServer && !useDatabase.getState().schemas[bound]) void loadSchemas(bound);
}, [bound, switchable, sqlServer]);
if (bound && switchable && schemasMissing) void loadSchemas(bound);
}, [bound, switchable, schemasMissing]);
const schemaOptions = useMemo(() => {
if (!switchable) return [];
const databaseList = boundId ? databases[boundId] : undefined;
const names = sqlServer
? databaseList?.status === "ok"
? databaseList.value.names
: []
: schemaList?.status === "ok"
? schemaList.value
: [];
const 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, 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]);
}, [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],
);
useEffect(() => {
if (!loaded) void loadSources();
}, [loaded]);
@@ -731,23 +724,28 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
<Select
variant="ghost"
aria-label="Data source"
value={bound ?? null}
value={boundId}
placeholder={sources.length ? "<data source>" : "None configured"}
options={targets}
onChange={(id) => bindConsole(path, id)}
options={sourceOptions}
searchable
onChange={(id) => id !== boundId && bindConsole(path, id)}
disabled={!sources.length}
/>
{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}
/>
{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}
/>
)
)}
{driver === "sqlite" && (
<span className={styles.consoleSchema} title={tx("Schema")}>
@@ -759,6 +757,85 @@ 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, '""')}"`;
/**
+70
View File
@@ -484,3 +484,73 @@ 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;
}
+3 -5
View File
@@ -205,12 +205,10 @@ describe("resolveTarget", () => {
expect(resolveTarget(e, model)).toEqual({ schema: "nope", table: "missing", alias: null });
});
it("refuses unresolved defaults and SQL Server database/schema ambiguity", () => {
it("refuses an unresolved default and keeps an explicit schema over the console's", () => {
expect(resolveTarget(editable("SELECT * FROM users"), model, "")).toBeNull();
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({
expect(resolveTarget(editable("SELECT * FROM users"), model, "sales")?.schema).toBe("sales");
expect(resolveTarget(editable("SELECT * FROM dbo.users"), model, "sales")).toEqual({
schema: "dbo",
table: "users",
alias: null,
-3
View File
@@ -227,10 +227,7 @@ 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 };
}
+2 -6
View File
@@ -485,15 +485,11 @@ describe("read-only results with a reason", () => {
expect(backend.applyEdits).not.toHaveBeenCalled();
});
it("keeps an unresolved SQL Server table schema read-only", async () => {
it("resolves an unqualified SQL Server table in the console's schema", async () => {
backend.driver = "sqlServer";
show("SELECT * FROM users", [{ name: "id" }, { name: "name" }], [["1", "Ann"]]);
await act(async () => render(<ResultsView />));
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();
expect(backend.details).toHaveBeenCalledWith("pg", "public", "users");
});
it.each(["postgres", "sqlServer"] as const)("matches case-sensitive key columns exactly for %s", async (driver) => {
+37
View File
@@ -0,0 +1,37 @@
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,7 +24,10 @@ describe("the Breakpoints dialog", () => {
});
const dialog = () => screen.getByRole("dialog", { name: "Breakpoints" });
const row = (name: string) => within(within(dialog()).getByLabelText("All breakpoints")).getByText(name);
const row = (location: string) =>
within(within(dialog()).getByRole("listbox", { name: "All breakpoints" })).getByRole("option", {
name: (name) => name.includes(`Enable breakpoint at ${location}`),
});
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) => {
@@ -37,8 +40,8 @@ describe("the Breakpoints dialog", () => {
render(<DebuggerOverlays />);
clickRow("main.py:7", 1);
expect(openFile).not.toHaveBeenCalled();
// Its details show beside the list.
expect(within(dialog()).getAllByText("main.py:7")).toHaveLength(2);
expect(row("main.py:7").getAttribute("aria-selected")).toBe("true");
expect(condition().value).toBe("");
clickRow("main.py:3", 2);
expect(openFile).toHaveBeenCalledWith(path, { selection: { line: 2, col: 0 } });
});
@@ -1,7 +1,4 @@
.section {
flex: none;
max-height: 40%;
overflow: auto;
border-top: 1px solid var(--border-popup);
padding: 6px 12px 8px;
display: flex;
+66 -19
View File
@@ -88,36 +88,46 @@
}
/* breakpoints dialog */
.bpDialog {
display: flex;
height: 420px;
min-height: 0;
}
.bpListPane {
width: 360px;
flex: none;
.bpWindow [data-dialog-body] {
display: flex;
flex-direction: column;
border-right: 1px solid var(--border-popup);
min-height: 0;
overflow: hidden;
}
.bpDialog {
flex: 1 1 420px;
}
.bpListHeader {
height: var(--h-header);
min-height: var(--h-header);
flex: none;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: var(--space-1-5);
padding: 0 8px 0 12px;
padding: var(--space-0-5) var(--space-2);
border-bottom: 1px solid var(--border-popup);
}
.bpListActions {
display: flex;
gap: var(--space-1);
margin-inline-start: auto;
}
.bpList {
flex: 1;
flex: 1 0 calc(2 * var(--h-list-row));
min-height: 0;
}
.bpAuxiliary {
flex: 0 1 auto;
max-height: 42%;
min-height: 0;
overflow: auto;
}
.bpRow,
.chooserRow {
display: flex;
@@ -135,6 +145,31 @@
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;
@@ -156,14 +191,29 @@
.bpDetail {
flex: 1;
min-width: 0;
min-height: 0;
overflow: auto;
}
.detail {
padding: 12px 14px;
padding: var(--space-3);
display: flex;
flex-direction: column;
gap: 10px;
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);
}
.statusLine {
@@ -245,9 +295,6 @@
}
.exceptions {
flex: none;
max-height: 40%;
overflow: auto;
border-top: 1px solid var(--border-popup);
padding: 6px 12px 8px;
display: flex;
+89 -38
View File
@@ -3,6 +3,7 @@ import {
Fragment,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
@@ -13,7 +14,23 @@ 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, Toggle, T } from "@/ui";
import {
Button,
Checkbox,
Dialog,
Icon,
IconButton,
Input,
Kbd,
List,
Menu,
Popup,
SplitGroup,
SplitHandle,
SplitPanel,
Toggle,
T,
} from "@/ui";
import { isConditional, suspends, type BreakpointEntry } from "../breakpoints/model";
import {
removeAllBreakpoints,
@@ -373,6 +390,15 @@ 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);
@@ -407,6 +433,18 @@ 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?.();
@@ -430,28 +468,38 @@ 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 }]}
>
<div className={styles.bpDialog}>
<div className={styles.bpListPane}>
<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.bpListHeader}>
<Toggle checked={muted} onChange={setMuted} label="Mute breakpoints" />
<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 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>
<List
items={rows}
@@ -486,7 +534,9 @@ 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}>{specialTitle(r.bp)}</span>
<span className={styles.bpName} title={specialTitle(r.bp)}>
{specialTitle(r.bp)}
</span>
{r.bp.path && (
<span className={styles.bpDir}>
{basename(r.bp.path)}
@@ -520,9 +570,7 @@ function BreakpointsDialog() {
}
aria-hidden
/>
<span className={styles.bpName}>
{basename(r.path)}:{r.bp.line + 1}
</span>
<BreakpointLocation path={r.path} line={r.bp.line} />
<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 && (
@@ -534,17 +582,22 @@ function BreakpointsDialog() {
);
}}
/>
<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>
<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>
</Dialog>
);
}
@@ -610,10 +663,7 @@ function BreakpointDetail({
return (
<div className={styles.detail}>
<div className={styles.bpTitle}>
<span className={styles.bpFile}>
{basename(path)}:{bp.line + 1}
</span>
<div className={styles.spacer} />
<BreakpointLocation path={path} line={bp.line} />
<Button size="small" variant="ghost" onClick={onGo}>
<T>Go to Source</T>
</Button>
@@ -664,8 +714,9 @@ 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}>{specialTitle(bp)}</span>
<div className={styles.spacer} />
<span className={styles.bpFile} title={specialTitle(bp)}>
{specialTitle(bp)}
</span>
{bp.path && (
<Button size="small" variant="ghost" onClick={onGo}>
<T>Go to Source</T>
+4 -1
View File
@@ -2740,5 +2740,8 @@
"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"
"Resize right merge pane": "Resize right merge pane",
"Database and schema": "Database and schema",
"Loading…": "Loading…",
"<schema>": "<schema>"
}
+2 -1
View File
@@ -9110,5 +9110,6 @@
"Sorting Options": "排序选项",
"Sort by Duration": "按持续时间排序",
"Resize left merge pane": "调整左侧合并窗格宽度",
"Resize right merge pane": "调整右侧合并窗格宽度"
"Resize right merge pane": "调整右侧合并窗格宽度",
"Database and schema": "数据库和 schema"
}
+10
View File
@@ -159,6 +159,16 @@
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;
+26 -2
View File
@@ -1,4 +1,13 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import {
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
type CSSProperties,
type KeyboardEvent,
type ReactNode,
} from "react";
import clsx from "clsx";
import { Icon, type IconName } from "./icons";
import { Popup } from "./Popup";
@@ -19,6 +28,8 @@ 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> {
@@ -38,6 +49,8 @@ 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;
@@ -235,6 +248,7 @@ 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>}
@@ -263,6 +277,7 @@ 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)}
@@ -289,6 +304,14 @@ 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,
@@ -301,6 +324,7 @@ export function Select<V extends string = string>({
renderValue,
searchable = false,
onPreview,
keepOpen,
...aria
}: SelectProps<V>) {
const given = useGivenTx();
@@ -380,7 +404,7 @@ export function Select<V extends string = string>({
aria-label={aria["aria-label"]}
onChoose={(v) => {
onChange(v);
setOpen(false);
if (!keepOpen?.(v)) setOpen(false);
}}
/>
</Popup>
+24
View File
@@ -5,6 +5,7 @@ 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;
@@ -308,6 +309,29 @@ 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", () => {
+34 -14
View File
@@ -33,7 +33,7 @@ import { acquirePopup } from "./popupState";
import styles from "./Tree.module.css";
import { T } from "./T";
import { setContext } from "@/platform/context";
import { registerKeyClaim } from "@/platform/keymap";
import { isMacHost, registerKeyClaim } from "@/platform/keymap";
import { useGivenTx } from "@/platform/i18n";
import { useTreeReorder, type TreeReorder } from "./treeReorder";
import { startPointerDrag, type DragData } from "./pointerDrag";
@@ -287,6 +287,13 @@ 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);
@@ -386,7 +393,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 (!query) return;
if (!searching) return;
const release = acquirePopup();
const unclaim = registerKeyClaim(
(e) => e.key === "Backspace" && e.target instanceof Node && !!scrollRef.current?.contains(e.target),
@@ -395,7 +402,7 @@ export function Tree<T>(props: TreeProps<T>) {
release();
unclaim();
};
}, [query]);
}, [searching]);
const setExpanded = (row: Row<T>, open: boolean) => {
if (!row.expandable || row.expanded === open) return;
@@ -534,6 +541,18 @@ 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);
@@ -546,7 +565,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;
setQuery("");
endSearch();
if (onJumpToSource) {
if (!row.loading) onJumpToSource(row.node, selected);
} else activate(row, e);
@@ -556,8 +575,8 @@ export function Tree<T>(props: TreeProps<T>) {
}
switch (e.key) {
case "Escape":
if (!query) return;
setQuery("");
if (!searching) return;
endSearch();
break;
case "Backspace":
if (!query) return;
@@ -578,14 +597,14 @@ export function Tree<T>(props: TreeProps<T>) {
break;
}
case "ArrowRight":
setQuery("");
endSearch();
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":
setQuery("");
endSearch();
if (!row) return;
if (row.expanded) setExpanded(row, false);
else if (row.parentKey != null) {
@@ -603,16 +622,16 @@ export function Tree<T>(props: TreeProps<T>) {
break;
}
case "PageDown":
setQuery("");
endSearch();
selectIndex(Math.min(rows.length - 1, Math.max(0, leadIndex) + pageSize), range ? "range" : "single");
break;
case "PageUp":
setQuery("");
endSearch();
selectIndex(Math.max(0, leadIndex - pageSize), range ? "range" : "single");
break;
case "Enter":
if (!row) return;
setQuery("");
endSearch();
activate(row, e);
break;
case "a":
@@ -644,7 +663,7 @@ export function Tree<T>(props: TreeProps<T>) {
e.preventDefault();
return;
}
setQuery("");
endSearch();
if (e.shiftKey) selectIndex(i, "range");
else if (e.metaKey || e.ctrlKey) selectIndex(i, "toggle");
else selectIndex(i);
@@ -701,7 +720,8 @@ export function Tree<T>(props: TreeProps<T>) {
className={styles.tree}
onKeyDown={onKeyDown}
onBlur={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setQuery("");
if (e.currentTarget.contains(e.relatedTarget as Node | null)) return;
endSearch();
}}
onContextMenu={
onContextMenu
@@ -836,7 +856,7 @@ export function Tree<T>(props: TreeProps<T>) {
})}
</div>
</div>
{query &&
{searching &&
(speedSearchField ? (
// Typing stays in the tree: a press here must not take its focus, which would end the search.
<div