Compare commits

..
27 changed files with 251 additions and 931 deletions

No files matched your search

+1 -2
View File
@@ -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)))
}
+6 -8
View File
@@ -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"));
-50
View File
@@ -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();
});
-75
View File
@@ -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();
});
+1 -73
View File
@@ -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" }));
+2 -48
View File
@@ -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,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);
}
+54 -100
View File
@@ -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">
+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(\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()");
});
+3 -4
View File
@@ -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;
}
+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) : 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));
+52 -129
View File
@@ -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, '""')}"`;
/**
-70
View File
@@ -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;
}
+5 -3
View File
@@ -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,
+3
View File
@@ -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 };
}
+6 -2
View File
@@ -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) => {
-37
View File
@@ -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;
+18 -65
View File
@@ -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;
+38 -89
View File
@@ -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>
+1 -4
View File
@@ -2740,8 +2740,5 @@
"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>"
"Resize right merge pane": "Resize right merge pane"
}
+1 -2
View File
@@ -9110,6 +9110,5 @@
"Sorting Options": "排序选项",
"Sort by Duration": "按持续时间排序",
"Resize left merge pane": "调整左侧合并窗格宽度",
"Resize right merge pane": "调整右侧合并窗格宽度",
"Database and schema": "数据库和 schema"
"Resize right merge pane": "调整右侧合并窗格宽度"
}
-10
View File
@@ -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
View File
@@ -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>
-24
View File
@@ -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
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 { 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