mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-22 23:56:05 -10:00
Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2b6798bf78 | ||
|
|
42fd0fa8e0 | ||
|
|
97a41ae983 | ||
|
|
f29903b698 | ||
|
|
610fe23f88 | ||
|
|
59376b9718 | ||
|
|
170fd735dd | ||
|
|
e0ae9e764c | ||
|
|
0a0b060144 | ||
|
|
19c1b72650 | ||
|
|
06ff2e51c3 | ||
|
|
6ae31b8148 | ||
|
|
3783b601b5 | ||
|
|
37044dcd89 | ||
|
|
1a2adab237 | ||
|
|
9ed87d77a7 | ||
|
|
9f4731189d | ||
|
|
92ccfac192 | ||
|
|
60d335eec0 | ||
|
|
a679e8086f | ||
|
|
4c20aa5c8d | ||
|
|
d19d74120b |
No files matched your search
@@ -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)))
|
||||
}
|
||||
|
||||
|
||||
@@ -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"));
|
||||
|
||||
@@ -206,6 +206,7 @@ Limits: interactive rebase doesn't support ranges with merge commits, and **Undo
|
||||
|
||||
- **Shelve Changes…** lets you pick files and a name; the changes are then reverted.
|
||||
- **Unshelve…** applies a shelf (or one file of it) with a three-way merge, into a changelist you choose.
|
||||
- **Shelve Silently** (`⇧⌘H` / `Ctrl+Shift+H`, also on the Changes toolbar) shelves the selected changes, or the active changelist, without the dialog: one shelf per changelist, named after it. **Unshelve Silently** (`⌥⌘U` / `Ctrl+Alt+U` in the Shelf) applies the selected shelf or file into the changelist with the shelf's name, else the active one.
|
||||
- The **Shelf** tab shows shelves with diff, compare with local, patch export, rename and delete.
|
||||
|
||||
Turn on **Combine stashes and shelves in one tab** in the Git settings to show both in one tab.
|
||||
|
||||
@@ -204,6 +204,7 @@ Git 工具窗口的 **日志** 标签页显示提交图。
|
||||
|
||||
- **搁置更改…**:选择文件并命名,之后这些更改会被还原。
|
||||
- **取消搁置…**:以三方合并的方式把搁置(或其中某个文件)应用到你选择的更改列表。
|
||||
- **静默搁置**(`⇧⌘H` / `Ctrl+Shift+H`,也在更改工具栏上)不弹对话框,直接搁置选中的更改(未选中时为活动更改列表):每个更改列表一个搁置,以列表名命名。**静默取消搁置**(在搁置中按 `⌥⌘U` / `Ctrl+Alt+U`)把选中的搁置或文件应用到与搁置同名的更改列表,没有则应用到活动更改列表。
|
||||
- **搁置** 标签页列出所有搁置,支持查看差异、与本地比较、导出补丁、重命名和删除。
|
||||
|
||||
在 Git 设置中打开 **在同一个标签页中合并显示贮藏和搁置**,两者会显示在同一个标签页里。
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("line bookmarks keep their code or description readable in the dock", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 880, height: 640 });
|
||||
const name = "QuarterlySettlementReconciliationCoordinator.ts";
|
||||
const path = `/dev/acme-api/${name}`;
|
||||
const code = "reconcileCheckoutOrders();";
|
||||
const description = "Review settlement totals";
|
||||
await page.evaluate(
|
||||
async ({ path, code }) => {
|
||||
const backendModule = "/src/editor/core/backend.ts";
|
||||
const { docBackend } = await import(/* @vite-ignore */ backendModule);
|
||||
docBackend().files.set(path, [...Array(27).fill("// Settlement rules"), code, "verifyTotals();", ""].join("\n"));
|
||||
const services = "/src/workbench/contributions.ts";
|
||||
const { editorService } = await import(/* @vite-ignore */ services);
|
||||
await editorService().openFile(path);
|
||||
},
|
||||
{ path, code },
|
||||
);
|
||||
await expect(page.locator(".cm-content")).toContainText(code);
|
||||
await page.evaluate(
|
||||
async ({ path, description }) => {
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
await executeAction("navigate.toggleBookmark", { path, line: 27 });
|
||||
await executeAction("navigate.toggleBookmark", { path, line: 29 });
|
||||
const bookmarkModule = "/src/features/search/bookmarks/store.ts";
|
||||
const { assignMnemonic, updateBookmarks } = await import(/* @vite-ignore */ bookmarkModule);
|
||||
updateBookmarks((items: unknown[]) => assignMnemonic(items, path, 28, "verifyTotals();", "4", description));
|
||||
await executeAction("toolwindow.bookmarks");
|
||||
const layoutModule = "/src/workbench/toolwindows/store.ts";
|
||||
const { setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
|
||||
setToolWindowSize("left", 240);
|
||||
},
|
||||
{ path, description },
|
||||
);
|
||||
|
||||
const tree = page.getByRole("tree", { name: "Bookmarks" });
|
||||
await expect(tree.getByText(name, { exact: true })).toBeVisible();
|
||||
const snippet = tree.getByText(code, { exact: true });
|
||||
await expect.poll(() => snippet.evaluate((el) => el.clientWidth)).toBeGreaterThanOrEqual(105);
|
||||
await expect(tree.getByText("28:", { exact: true })).toBeVisible();
|
||||
await expect(tree.getByText("29:", { exact: true })).toBeVisible();
|
||||
await expect(tree.getByText(description, { exact: true })).toBeVisible();
|
||||
await expect(tree.getByText("(empty line)", { exact: true })).toBeVisible();
|
||||
expect(await tree.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
|
||||
|
||||
const row = tree.getByRole("treeitem").filter({ hasText: code });
|
||||
await row.click();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect
|
||||
.poll(() =>
|
||||
page.evaluate(async () => {
|
||||
const module = "/src/workbench/contributions.ts";
|
||||
const { editorService } = await import(/* @vite-ignore */ module);
|
||||
const cursor = editorService().activeCursor();
|
||||
return { path: cursor?.path, line: cursor?.line };
|
||||
}),
|
||||
)
|
||||
.toEqual({ path, line: 27 });
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const REPO = "https://example.test/team/billing-service.git";
|
||||
|
||||
test("Clone Repository keeps URL, directory, and depth usable when the dialog narrows", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.setViewportSize({ width: 440, height: 620 });
|
||||
await page.evaluate(async (repo) => {
|
||||
window.__ipc.handlers["plugin:dialog|open"] = () => "/dev/workspaces";
|
||||
window.__ipc.handlers.vcs_clone = () => new Promise(() => {});
|
||||
const contributionsPath = "/src/workbench/contributions.ts";
|
||||
const { registerCloneSource } = await import(/* @vite-ignore */ contributionsPath);
|
||||
registerCloneSource({ id: "team", label: "Team repositories", icon: "branch", component: () => null });
|
||||
const actionsPath = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsPath);
|
||||
await executeAction("vcs.clone", repo);
|
||||
}, REPO);
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Clone Repository" });
|
||||
const sources = dialog.getByRole("complementary", { name: "Clone source" });
|
||||
const url = dialog.getByRole("textbox", { name: "URL:" });
|
||||
await expect(url).toHaveValue(REPO);
|
||||
await expect.poll(async () => (await url.boundingBox())!.width).toBeGreaterThan(180);
|
||||
|
||||
const form = dialog.locator("form");
|
||||
const position = () =>
|
||||
form.evaluate((el) => {
|
||||
const source = el.parentElement!.querySelector("aside")!.getBoundingClientRect();
|
||||
const body = el.getBoundingClientRect();
|
||||
return { below: body.top >= source.bottom, beside: body.left >= source.right };
|
||||
});
|
||||
await expect.poll(async () => (await position()).below).toBe(true);
|
||||
expect(await form.evaluate((el) => el.scrollWidth === el.clientWidth)).toBe(true);
|
||||
|
||||
await dialog.getByRole("button", { name: "Browse…" }).click();
|
||||
const directory = dialog.getByRole("textbox", { name: "Directory:" });
|
||||
await expect(directory).toHaveValue("/dev/workspaces/billing-service");
|
||||
|
||||
const shallow = dialog.getByRole("checkbox", { name: /^Shallow clone/ });
|
||||
const depth = dialog.getByRole("spinbutton", { name: "Clone depth" });
|
||||
await expect(depth).toBeDisabled();
|
||||
await shallow.check();
|
||||
await depth.fill("0");
|
||||
const clone = dialog.getByRole("button", { name: "Clone", exact: true });
|
||||
await expect(clone).toBeDisabled();
|
||||
await depth.fill("3");
|
||||
|
||||
await page.setViewportSize({ width: 1050, height: 750 });
|
||||
await expect.poll(async () => (await position()).beside).toBe(true);
|
||||
await sources.getByRole("button", { name: "Team repositories" }).click();
|
||||
await expect(url).toBeHidden();
|
||||
await sources.getByRole("button", { name: "Repository URL" }).click();
|
||||
await expect(url).toHaveValue(REPO);
|
||||
await expect(directory).toHaveValue("/dev/workspaces/billing-service");
|
||||
await expect(depth).toHaveValue("3");
|
||||
|
||||
await page.setViewportSize({ width: 440, height: 620 });
|
||||
await clone.click();
|
||||
await expect
|
||||
.poll(() => ipcCalls(page, "vcs_clone"))
|
||||
.toEqual([expect.objectContaining({ url: REPO, dest: "/dev/workspaces/billing-service", depth: 3 })]);
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Code Style keeps settings reachable by tab, keyboard, and search in a narrow pane", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 620, height: 720 });
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await expect(dialog).toBeVisible();
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
window.__ipc.handlers.languages = () => [
|
||||
{ id: "typescript", name: "TypeScript", indent: { tabSize: 2, insertSpaces: true }, lineComment: "//" },
|
||||
];
|
||||
const languageList = "/src/platform/languageList.ts";
|
||||
(await import(/* @vite-ignore */ languageList)).languageListChanged();
|
||||
});
|
||||
|
||||
const search = dialog.getByRole("textbox", { name: "Search settings" });
|
||||
await search.fill("typescript");
|
||||
await dialog.getByRole("treeitem", { name: "TypeScript", exact: true, level: 3 }).click();
|
||||
await search.clear();
|
||||
|
||||
const tabs = dialog.getByRole("tablist", { name: "Code Style" });
|
||||
const indents = tabs.getByRole("tab", { name: "Tabs and Indents" });
|
||||
const wrapping = tabs.getByRole("tab", { name: "Wrapping", exact: true });
|
||||
const comments = tabs.getByRole("tab", { name: "Comment Code" });
|
||||
await expect(indents).toHaveAttribute("aria-selected", "true");
|
||||
const size = dialog.getByRole("textbox", { name: "Tab size", exact: true });
|
||||
const indent = dialog.getByRole("textbox", { name: "Indent", exact: true });
|
||||
await expect(indent).toBeVisible();
|
||||
expect((await indent.boundingBox())!.x).toBeCloseTo((await size.boundingBox())!.x, 0);
|
||||
await size.fill("6");
|
||||
await indents.press("ArrowRight");
|
||||
await expect(wrapping).toBeFocused();
|
||||
await expect(dialog.getByRole("textbox", { name: "Hard wrap at", exact: true })).toBeVisible();
|
||||
await expect(size).toBeHidden();
|
||||
|
||||
await search.fill("TypeScript line comment at first column");
|
||||
await expect(comments).toHaveAttribute("aria-selected", "true");
|
||||
await expect(dialog.getByRole("checkbox", { name: "Line comment at first column" })).toBeVisible();
|
||||
await indents.click();
|
||||
await expect(size).toHaveValue("6");
|
||||
await page.setViewportSize({ width: 520, height: 720 });
|
||||
const body = dialog.locator("[class*='pageBody']");
|
||||
await expect.poll(() => body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
await expect(dialog.getByRole("button", { name: "Copy to Project", exact: true })).toBeVisible();
|
||||
|
||||
await search.fill("do not format");
|
||||
await dialog.getByRole("treeitem", { name: "Code Style", exact: true, level: 2 }).click();
|
||||
await expect(dialog.getByRole("tab", { name: "Formatter", exact: true })).toHaveAttribute("aria-selected", "true");
|
||||
await expect(dialog.getByRole("listbox", { name: "Do not format" })).toBeVisible();
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const amountName = "regionalSettlementAmountFromExternalProcessorBeforeRounding";
|
||||
const routingName = "settlementRoutingReferenceForCrossBorderReconciliation";
|
||||
const routingValue = "'APR-2026 / eu-west / batch-701 / settlement complete'";
|
||||
|
||||
test("keeps values and their full-value action readable in a narrow debugger", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1220, height: 760 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ amountName, routingName, routingValue }) => {
|
||||
const debugModule = "/src/features/debugger/state.ts";
|
||||
const layoutModule = "/src/workbench/toolwindows/store.ts";
|
||||
const servicesModule = "/src/workbench/contributions.ts";
|
||||
const { adoptSession } = await import(/* @vite-ignore */ debugModule);
|
||||
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
|
||||
const { toolWindowService } = await import(/* @vite-ignore */ servicesModule);
|
||||
const h = window.__ipc.handlers;
|
||||
h.debug_scopes = () => [{ name: "Locals", variablesReference: 100, expensive: false }];
|
||||
h.debug_variables = () => [
|
||||
{ name: amountName, value: "47.74", typeName: "float", variablesReference: 0, evaluateName: amountName },
|
||||
{ name: routingName, value: routingValue, typeName: "str", variablesReference: 0, evaluateName: routingName },
|
||||
];
|
||||
adoptSession(91, {
|
||||
name: "Checkout",
|
||||
adapter: "debugpy",
|
||||
status: "paused",
|
||||
selectedFrame: 11,
|
||||
frames: [{ id: 11, name: "checkout", path: null, line: 0, column: 0, presentationHint: null }],
|
||||
});
|
||||
moveToolWindow("debug", "right");
|
||||
setToolWindowSize("right", 390);
|
||||
toolWindowService().show("debug", true);
|
||||
},
|
||||
{ amountName, routingName, routingValue },
|
||||
);
|
||||
|
||||
const debug = page.getByRole("region", { name: "Debug", exact: true });
|
||||
await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click();
|
||||
const amount = debug.getByText("47.74", { exact: true });
|
||||
await expect
|
||||
.poll(() => amount.evaluate((el) => el.clientWidth > 0 && el.scrollWidth <= el.clientWidth + 1))
|
||||
.toBe(true);
|
||||
const routing = debug.getByRole("treeitem").filter({ hasText: routingName });
|
||||
const show = routing.getByTitle("Show", { exact: true });
|
||||
await expect(show).toBeInViewport({ ratio: 1 });
|
||||
await show.click();
|
||||
const dialog = page.getByRole("dialog", { name: `Value of ${routingName}` });
|
||||
await expect(dialog.getByText(routingValue, { exact: true })).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(dialog).toBeHidden();
|
||||
|
||||
await page.setViewportSize({ width: 1640, height: 760 });
|
||||
await page.evaluate(async () => {
|
||||
const layoutModule = "/src/workbench/toolwindows/store.ts";
|
||||
const { moveToolWindow } = await import(/* @vite-ignore */ layoutModule);
|
||||
moveToolWindow("debug", "bottom");
|
||||
});
|
||||
await expect(show).toBeHidden();
|
||||
await expect
|
||||
.poll(() => routing.getByText(routingValue, { exact: true }).evaluate((el) => el.scrollWidth <= el.clientWidth + 1))
|
||||
.toBe(true);
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import type { Locator, Page } from "@playwright/test";
|
||||
import { expect, openFromTree, test } from "./fixtures";
|
||||
|
||||
async function setTabs(page: Page, tabs: Record<string, unknown>) {
|
||||
await page.evaluate(async (tabs) => {
|
||||
const projectModule = "/src/platform/project.ts";
|
||||
const { useProject } = await import(/* @vite-ignore */ projectModule);
|
||||
const { settings } = useProject.getState();
|
||||
useProject.setState({
|
||||
settings: { ...settings, editor: { ...settings?.editor, tabs: { ...settings?.editor?.tabs, ...tabs } } },
|
||||
});
|
||||
}, tabs);
|
||||
}
|
||||
|
||||
const box = async (locator: Locator) => (await locator.boundingBox())!;
|
||||
const closeOf = (tab: Locator) => tab.locator("..").getByRole("button", { name: "Close Tab", exact: true });
|
||||
|
||||
test("a close button on the right keeps a narrow slot on every tab", async ({ workbench: page }) => {
|
||||
await openFromTree(page, "README.md");
|
||||
await openFromTree(page, "build.gradle.kts");
|
||||
const strip = page.getByRole("tablist", { name: "Editor tabs" });
|
||||
const idle = strip.getByRole("tab", { name: "README.md" });
|
||||
const label = await box(idle.locator(":scope > span"));
|
||||
const idleTab = await box(idle.locator(".."));
|
||||
expect(idleTab.x + idleTab.width - (label.x + label.width)).toBeCloseTo(18, 0);
|
||||
|
||||
const selected = strip.getByRole("tab", { name: "build.gradle.kts" });
|
||||
const close = await box(closeOf(selected));
|
||||
const tab = await box(selected.locator(".."));
|
||||
const text = await box(selected.locator(":scope > span"));
|
||||
expect(close.x).toBeGreaterThanOrEqual(text.x + text.width - 0.5);
|
||||
expect(close.x + close.width).toBeLessThanOrEqual(tab.x + tab.width + 0.5);
|
||||
expect(tab.x - (idleTab.x + idleTab.width)).toBeCloseTo(4, 0);
|
||||
});
|
||||
|
||||
for (const closeButtonPosition of ["right", "left"]) {
|
||||
test(`a dragged tab's ghost keeps the tab's layout, close button ${closeButtonPosition}`, async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await openFromTree(page, "README.md");
|
||||
await openFromTree(page, "build.gradle.kts");
|
||||
await setTabs(page, { closeButtonPosition });
|
||||
const selected = page.getByRole("tablist", { name: "Editor tabs" }).getByRole("tab", { name: "build.gradle.kts" });
|
||||
const tab = await box(selected.locator(".."));
|
||||
const close = await box(closeOf(selected));
|
||||
await page.mouse.move(tab.x + tab.width / 2, tab.y + tab.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(tab.x + tab.width / 2, tab.y + tab.height / 2 + 40, { steps: 4 });
|
||||
const ghost = page.locator('[aria-hidden="true"]:has([data-tab-close])');
|
||||
const copy = await box(ghost);
|
||||
const copyClose = await box(ghost.locator("[data-tab-close] button"));
|
||||
expect(copy.width).toBeCloseTo(tab.width, 0);
|
||||
expect(copyClose.x - copy.x).toBeCloseTo(close.x - tab.x, 0);
|
||||
expect(copyClose.x + copyClose.width).toBeLessThanOrEqual(copy.x + copy.width + 0.5);
|
||||
await page.keyboard.press("Escape");
|
||||
await page.mouse.up();
|
||||
await expect(ghost).toHaveCount(0);
|
||||
});
|
||||
}
|
||||
|
||||
test("a close button on the left keeps a narrow slot before the icon", async ({ workbench: page }) => {
|
||||
await openFromTree(page, "README.md");
|
||||
await openFromTree(page, "build.gradle.kts");
|
||||
await setTabs(page, { closeButtonPosition: "left" });
|
||||
const strip = page.getByRole("tablist", { name: "Editor tabs" });
|
||||
|
||||
// The selected and the hovered tab show their button in an 18px slot before the icon, which stays visible.
|
||||
const selected = strip.getByRole("tab", { name: "build.gradle.kts" });
|
||||
const other = strip.getByRole("tab", { name: "README.md" });
|
||||
await other.hover();
|
||||
for (const tab of [selected, other]) {
|
||||
const icon = tab.locator(":scope > :first-child");
|
||||
await expect(icon).toHaveCSS("opacity", "1");
|
||||
await expect(closeOf(tab)).toHaveCSS("opacity", "1");
|
||||
const slot = await box(tab.locator(".."));
|
||||
const close = await box(closeOf(tab));
|
||||
const glyph = await box(icon);
|
||||
const label = await box(tab.locator(":scope > span"));
|
||||
expect(close.x + close.width).toBeLessThanOrEqual(glyph.x + 0.5);
|
||||
expect(glyph.x - slot.x).toBeCloseTo(18, 0);
|
||||
expect(slot.x + slot.width - (label.x + label.width)).toBeCloseTo(8, 0);
|
||||
}
|
||||
|
||||
// Without file icons the close button keeps its own place before the label.
|
||||
await setTabs(page, { showFileIcon: false });
|
||||
await expect(selected.locator("svg, img")).toHaveCount(0);
|
||||
const label = await box(selected.locator(":scope > span"));
|
||||
const slot = await box(closeOf(selected));
|
||||
expect(slot.x + slot.width).toBeLessThanOrEqual(label.x + 0.5);
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const root = "/dev/acme-api";
|
||||
const name = `InternationalSettlement${"Reconciliation".repeat(10)}.txt`;
|
||||
const destination = `archive/Approved${"Settlement".repeat(11)}`;
|
||||
|
||||
test("keeps a long source name and destination readable while moving a file", async ({ workbench: page }) => {
|
||||
await page.evaluate(
|
||||
async ({ root, name, destination }) => {
|
||||
const fsModule = "/src/features/project-tree/fs.ts";
|
||||
const { projectFs } = await import(/* @vite-ignore */ fsModule);
|
||||
const storeModule = "/src/features/project-tree/store.ts";
|
||||
const { loadDir } = await import(/* @vite-ignore */ storeModule);
|
||||
const fs = projectFs(root);
|
||||
await fs.createFile(`${root}/${name}`);
|
||||
await fs.createDir(`${root}/archive`);
|
||||
await fs.createDir(`${root}/${destination}`);
|
||||
await loadDir(root, true);
|
||||
},
|
||||
{ root, name, destination },
|
||||
);
|
||||
await page.getByRole("treeitem", { name, exact: true }).click();
|
||||
await page.keyboard.press("F6");
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Move", exact: true });
|
||||
const field = dialog.getByRole("textbox", { name: "Target directory" });
|
||||
await expect(field).toBeFocused();
|
||||
await page.setViewportSize({ width: 470, height: 480 });
|
||||
await expect
|
||||
.poll(() => dialog.locator("[data-dialog-body]").evaluate((el) => el.scrollWidth - el.clientWidth))
|
||||
.toBeLessThanOrEqual(1);
|
||||
expect(
|
||||
await field.evaluate((el: HTMLInputElement) => el.value.slice(el.selectionStart ?? 0, el.selectionEnd ?? 0)),
|
||||
).toBe("acme-api");
|
||||
const submit = dialog.getByRole("button", { name: "Refactor", exact: true });
|
||||
await expect(submit).toBeDisabled();
|
||||
await field.fill(destination);
|
||||
await expect(dialog.getByText(destination, { exact: true })).toBeVisible();
|
||||
await expect(submit).toBeInViewport({ ratio: 1 });
|
||||
await dialog.getByRole("checkbox", { name: "Search for references" }).uncheck();
|
||||
await dialog.getByRole("checkbox", { name: "Search in comments and strings" }).uncheck();
|
||||
await submit.click();
|
||||
await expect(dialog).toBeHidden();
|
||||
await expect
|
||||
.poll(() =>
|
||||
page.evaluate(
|
||||
async ({ root, destination }) => {
|
||||
const fsModule = "/src/features/project-tree/fs.ts";
|
||||
const { projectFs } = await import(/* @vite-ignore */ fsModule);
|
||||
return (await projectFs(root).readDir(`${root}/${destination}`)).map((entry: { name: string }) => entry.name);
|
||||
},
|
||||
{ root, destination },
|
||||
),
|
||||
)
|
||||
.toEqual([name]);
|
||||
});
|
||||
|
||||
test("browses for a destination and keeps the current path on cancel", async ({ workbench: page }) => {
|
||||
await page.getByRole("treeitem", { name: "README.md", exact: true }).click();
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(() => {
|
||||
window.__ipc.handlers.file_dialog_needs_gtk = () => false;
|
||||
let chosen: string | null = null;
|
||||
window.__ipc.handlers["plugin:dialog|open"] = () => {
|
||||
const result = chosen;
|
||||
chosen = "C:\\Projects\\Invoice Archive";
|
||||
return result;
|
||||
};
|
||||
});
|
||||
await page.keyboard.press("F6");
|
||||
const dialog = page.getByRole("dialog", { name: "Move", exact: true });
|
||||
const field = dialog.getByRole("textbox", { name: "Target directory" });
|
||||
const browse = dialog.getByRole("button", { name: "Browse for target directory", exact: true });
|
||||
await browse.click();
|
||||
await expect.poll(() => ipcCalls(page, "plugin:dialog|open")).toHaveLength(1);
|
||||
await expect(field).toHaveValue(root);
|
||||
await browse.click();
|
||||
await expect(field).toHaveValue("C:/Projects/Invoice Archive");
|
||||
await expect(dialog.getByRole("button", { name: "Refactor", exact: true })).toBeEnabled();
|
||||
await field.fill("C:/");
|
||||
await expect(dialog.getByText("C:/", { exact: true })).toBeVisible();
|
||||
await field.fill("/");
|
||||
await expect(dialog.getByText("/", { exact: true })).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(dialog).toBeHidden();
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Hierarchy keeps source context and controls reachable in a narrow dock", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 940, height: 680 });
|
||||
const path = "/dev/acme-api/QuarterlySettlementReconciliationCoordinator.ts";
|
||||
const caller = "reconcileQuarterlySettlementForMerchantOrders";
|
||||
const context = "Checkout and settlement coordinator";
|
||||
await page.evaluate(
|
||||
async ({ path, caller }) => {
|
||||
const backend = "/src/editor/core/backend.ts";
|
||||
const { docBackend } = await import(/* @vite-ignore */ backend);
|
||||
docBackend().files.set(
|
||||
path,
|
||||
[
|
||||
"function settleOrder() {}",
|
||||
"",
|
||||
`function ${caller}() {`,
|
||||
" settleOrder();",
|
||||
" settleOrder();",
|
||||
"}",
|
||||
`function flushSettlementQueue() { ${caller}(); }`,
|
||||
].join("\n"),
|
||||
);
|
||||
const service = "/src/workbench/contributions.ts";
|
||||
await (await import(/* @vite-ignore */ service)).editorService().openFile(path);
|
||||
},
|
||||
{ path, caller },
|
||||
);
|
||||
const editor = page.locator(".cm-content");
|
||||
await expect(editor).toContainText("settleOrder");
|
||||
await editor.evaluate((el) => {
|
||||
const view = (el as HTMLElement & { cmTile: { view: EditorView } }).cmTile.view;
|
||||
view.dispatch({ selection: { anchor: 11 } });
|
||||
view.focus();
|
||||
});
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ path, caller, context }) => {
|
||||
const range = (line: number, col: number) => ({ start: { line, col }, end: { line, col: col + 5 } });
|
||||
const item = (name: string, line: number, detail: string, fromRanges: ReturnType<typeof range>[]) => ({
|
||||
name,
|
||||
path,
|
||||
detail,
|
||||
kind: "function",
|
||||
range: range(line, 0),
|
||||
selectionRange: range(line, 9),
|
||||
fromRanges,
|
||||
});
|
||||
window.__ipc.handlers.lsp_call_hierarchy = ({ pos }) => {
|
||||
const line = (pos as { line: number }).line;
|
||||
return {
|
||||
items:
|
||||
line === 0
|
||||
? [item(caller, 2, context, [range(3, 2), range(4, 2)])]
|
||||
: [item("flushSettlementQueue", 6, "Queue processing", [range(6, 34)])],
|
||||
incomplete: null,
|
||||
};
|
||||
};
|
||||
const actions = "/src/platform/actions.ts";
|
||||
await (await import(/* @vite-ignore */ actions)).executeAction("navigate.callHierarchy");
|
||||
const dock = "/src/workbench/toolwindows/store.ts";
|
||||
(await import(/* @vite-ignore */ dock)).setToolWindowSize("right", 136);
|
||||
},
|
||||
{ path, caller, context },
|
||||
);
|
||||
|
||||
const tree = page.getByRole("tree", { name: "Call hierarchy" });
|
||||
const row = tree.getByRole("treeitem").filter({ hasText: caller });
|
||||
await expect(row).toBeVisible();
|
||||
const detail = row.getByText(context, { exact: true });
|
||||
await expect.poll(() => detail.evaluate((el) => el.clientWidth)).toBeGreaterThan(100);
|
||||
expect((await row.getByText("(2 calls)", { exact: true }).boundingBox())!.x).toBeLessThan(
|
||||
(await detail.boundingBox())!.x,
|
||||
);
|
||||
const toolbar = page.getByRole("toolbar", { name: "Hierarchy actions" });
|
||||
expect(await toolbar.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
await tree.evaluate((el) => {
|
||||
el.scrollLeft = el.scrollWidth;
|
||||
});
|
||||
expect(await tree.evaluate((el) => el.scrollLeft)).toBeGreaterThan(100);
|
||||
await tree.evaluate((el) => {
|
||||
el.scrollLeft = 0;
|
||||
});
|
||||
await row.click({ position: { x: 90, y: 12 } });
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await expect(tree.getByRole("treeitem").filter({ hasText: "flushSettlementQueue" })).toBeVisible();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect
|
||||
.poll(() =>
|
||||
page.evaluate(async () => {
|
||||
const service = "/src/workbench/contributions.ts";
|
||||
const cursor = (await import(/* @vite-ignore */ service)).editorService().activeCursor();
|
||||
return { path: cursor?.path, line: cursor?.line, col: cursor?.col };
|
||||
}),
|
||||
)
|
||||
.toEqual({ path, line: 3, col: 2 });
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Local History gives the diff room and keeps revision selection across layouts", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1180, height: 700 });
|
||||
await openFromTree(page, "build.gradle.kts");
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const file = "/dev/acme-api/build.gradle.kts";
|
||||
const entries = [
|
||||
{ id: "after", path: file, timestampMs: 2000, label: "Saved", size: 31, kind: "snapshot" },
|
||||
{ id: "before", path: file, timestampMs: 1000, label: "Original", size: 34, kind: "snapshot" },
|
||||
];
|
||||
window.__ipc.handlers.history_list_dir = () => ({ entries, deleted: [] });
|
||||
window.__ipc.handlers.history_content = ({ id }) =>
|
||||
id === "before" ? 'val reportMode = "summary"\n' : 'val reportMode = "detailed"\n';
|
||||
window.__ipc.handlers.vcs_file_mode = () => null;
|
||||
window.__ipc.handlers.fs_probe = () => ({ size: 32, binary: false, tooLarge: false });
|
||||
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
await executeAction("vcs.localHistory", file);
|
||||
});
|
||||
|
||||
const revisions = page.getByRole("listbox", { name: "Revisions" });
|
||||
await expect(revisions.getByRole("option", { name: /Saved/ })).toBeVisible();
|
||||
const separator = page.getByRole("separator", { name: "Revisions" });
|
||||
await expect(separator).toHaveAttribute("aria-orientation", "vertical");
|
||||
const initialWidth = (await revisions.boundingBox())!.width;
|
||||
await separator.press("ArrowLeft");
|
||||
await expect.poll(async () => (await revisions.boundingBox())!.width).toBeLessThan(initialWidth);
|
||||
|
||||
const original = revisions.getByRole("option", { name: /^Original/ });
|
||||
await original.click();
|
||||
await expect(original).toHaveAttribute("aria-selected", "true");
|
||||
await expect.poll(async () => ipcCalls(page, "history_content")).toContainEqual({ id: "before" });
|
||||
|
||||
await page.setViewportSize({ width: 480, height: 620 });
|
||||
await expect(separator).toHaveAttribute("aria-orientation", "horizontal");
|
||||
await expect(original).toHaveAttribute("aria-selected", "true");
|
||||
const diff = page.locator(".cm-mergeView").filter({ hasText: "summary" });
|
||||
await expect(diff).toBeVisible();
|
||||
const listBox = (await revisions.boundingBox())!;
|
||||
const diffBox = (await diff.boundingBox())!;
|
||||
expect(diffBox.y).toBeGreaterThanOrEqual(listBox.y + listBox.height);
|
||||
expect(diffBox.width).toBeGreaterThanOrEqual(listBox.width - 2);
|
||||
|
||||
await page.setViewportSize({ width: 1180, height: 700 });
|
||||
await expect(separator).toHaveAttribute("aria-orientation", "vertical");
|
||||
await expect(original).toHaveAttribute("aria-selected", "true");
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
import type { GeneratorInfo } from "../src/bindings";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const java: GeneratorInfo = {
|
||||
id: "java",
|
||||
name: "Java",
|
||||
group: "Java",
|
||||
icon: "project-java",
|
||||
order: 1,
|
||||
description: "A plain Java application built with Maven or Gradle.",
|
||||
git: true,
|
||||
dynamic: false,
|
||||
fields: [
|
||||
{
|
||||
id: "build",
|
||||
label: "Build system:",
|
||||
default: "maven",
|
||||
hint: "",
|
||||
visible: {},
|
||||
kind: {
|
||||
type: "choice",
|
||||
segmented: true,
|
||||
options: [
|
||||
{ value: "maven", label: "Maven" },
|
||||
{ value: "gradle", label: "Gradle" },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "jdk",
|
||||
label: "JDK:",
|
||||
default: "",
|
||||
hint: "",
|
||||
visible: {},
|
||||
kind: { type: "sdk", sdk: "jdk" },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const empty: GeneratorInfo = {
|
||||
...java,
|
||||
id: "empty",
|
||||
name: "Empty Project",
|
||||
group: "Project",
|
||||
description: "",
|
||||
fields: [],
|
||||
};
|
||||
|
||||
test("New Project fits the template form in a narrow window and preserves edits when resized", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubDesktop(page);
|
||||
await page.setViewportSize({ width: 490, height: 570 });
|
||||
await page.evaluate(
|
||||
async (catalog) => {
|
||||
const handlers = window.__ipc.handlers;
|
||||
handlers.scaffold_catalog = () => catalog;
|
||||
handlers.sdk_detect = () => [];
|
||||
handlers.scaffold_requirements = () => [];
|
||||
handlers.scaffold_create = () => new Promise(() => {});
|
||||
handlers["plugin:dialog|open"] = () => "/dev/workspaces";
|
||||
const actionsPath = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsPath);
|
||||
await executeAction("file.newProject");
|
||||
},
|
||||
[empty, java],
|
||||
);
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "New Project" });
|
||||
const generators = dialog.getByRole("listbox", { name: "Generators" });
|
||||
await generators.getByRole("option", { name: "Java", exact: true }).click();
|
||||
|
||||
const form = dialog.locator("form");
|
||||
const hasNoHorizontalOverflow = (el: Element) => el.scrollWidth === el.clientWidth;
|
||||
expect(await form.evaluate(hasNoHorizontalOverflow)).toBe(true);
|
||||
await expect(dialog.getByRole("separator", { name: "Generators" })).toHaveAttribute("aria-orientation", "horizontal");
|
||||
|
||||
await dialog.getByRole("textbox", { name: "Name:" }).fill("Billing Service");
|
||||
await dialog.getByRole("button", { name: "Browse…" }).click();
|
||||
await expect(dialog.getByRole("textbox", { name: "Location:" })).toHaveValue("/dev/workspaces");
|
||||
const gradle = dialog.getByRole("button", { name: "Gradle" });
|
||||
await gradle.click();
|
||||
await expect(gradle).toHaveAttribute("aria-pressed", "true");
|
||||
|
||||
await page.setViewportSize({ width: 1040, height: 750 });
|
||||
const handle = dialog.getByRole("separator", { name: "Generators" });
|
||||
await expect(handle).toHaveAttribute("aria-orientation", "vertical");
|
||||
const originalWidth = (await generators.boundingBox())!.width;
|
||||
await handle.press("ArrowRight");
|
||||
await expect.poll(async () => (await generators.boundingBox())!.width).toBeGreaterThan(originalWidth);
|
||||
await expect(generators.getByRole("option", { name: "Java", exact: true })).toHaveAttribute("aria-selected", "true");
|
||||
await expect(dialog.getByRole("textbox", { name: "Name:" })).toHaveValue("Billing Service");
|
||||
await expect(gradle).toHaveAttribute("aria-pressed", "true");
|
||||
|
||||
await page.setViewportSize({ width: 490, height: 570 });
|
||||
await dialog.getByRole("button", { name: "Create", exact: true }).click();
|
||||
await expect
|
||||
.poll(() => ipcCalls(page, "scaffold_create"))
|
||||
.toEqual([
|
||||
expect.objectContaining({
|
||||
req: {
|
||||
generator: "java",
|
||||
location: "/dev/workspaces",
|
||||
name: "Billing Service",
|
||||
git: true,
|
||||
values: { build: "gradle", jdk: "" },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const JDK_PATH = "/opt/jdks/corretto-21.0.8";
|
||||
const LONG_NAME = "AmazonCorretto21".repeat(6);
|
||||
|
||||
test("Project Structure SDKs keeps selection and selected details usable in a compact dialog", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubDesktop(page);
|
||||
await page.setViewportSize({ width: 520, height: 720 });
|
||||
await page.evaluate(
|
||||
async ({ path, name }) => {
|
||||
const sdk = { path, name, version: "21.0.8", source: "system", home: path, extra: null };
|
||||
window.__ipc.handlers.sdk_detect = ({ kind }) =>
|
||||
kind === "jdk"
|
||||
? [sdk]
|
||||
: kind === "python"
|
||||
? [{ ...sdk, path: "/usr/bin/python3", home: "/usr/bin", name: "Python 3.12", version: "3.12.2" }]
|
||||
: [];
|
||||
const actions = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actions);
|
||||
await executeAction("file.projectStructure", "sdks");
|
||||
},
|
||||
{ path: JDK_PATH, name: LONG_NAME },
|
||||
);
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Project Structure" });
|
||||
const list = dialog.getByRole("listbox", { name: "SDKs" });
|
||||
const details = dialog.getByRole("region", { name: "SDK Details" });
|
||||
await expect(list.getByRole("option", { name: /Python 3.12/ })).toBeVisible();
|
||||
await expect(details.getByText(LONG_NAME, { exact: true })).toBeVisible();
|
||||
const content = dialog.locator("[class*='psDialogBody']");
|
||||
expect(await content.evaluate((el) => el.scrollWidth)).toBe(await content.evaluate((el) => el.clientWidth));
|
||||
|
||||
const path = details.getByRole("textbox", { name: "SDK home path" });
|
||||
await expect(path).toHaveValue(JDK_PATH);
|
||||
await expect(details.getByText("21.0.8", { exact: true })).toBeVisible();
|
||||
const useSdk = details.getByRole("button", { name: "Use as Project SDK" });
|
||||
await useSdk.click();
|
||||
await expect(useSdk).toBeDisabled();
|
||||
await expect(dialog.getByRole("button", { name: "Apply", exact: true })).toBeEnabled();
|
||||
|
||||
await list.getByRole("option", { name: /Python 3.12/ }).click();
|
||||
await expect(path).toHaveValue("/usr/bin/python3");
|
||||
await expect(details.getByText("3.12.2", { exact: true })).toBeVisible();
|
||||
await expect(useSdk).toHaveCount(0);
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Pull fits the remote branch picker and keeps flags accessible in a narrow window", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 380, height: 580 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const root = "/dev/checkout-reconciliation";
|
||||
const second = `${root}/billing-and-transaction-settlement`;
|
||||
const branch = {
|
||||
head: "main",
|
||||
upstream: "origin/main",
|
||||
headCommit: "c1",
|
||||
behind: 1,
|
||||
ahead: 0,
|
||||
operation: null,
|
||||
};
|
||||
const h = window.__ipc.handlers;
|
||||
h.vcs_roots = () => [root, second].map((root) => ({ root, ...branch }));
|
||||
h.vcs_branch_info = () => branch;
|
||||
h.vcs_status = () => [];
|
||||
h.vcs_log = () => [];
|
||||
h.vcs_remotes = () => [
|
||||
{ name: "origin", url: "/git/checkout-reconciliation.git" },
|
||||
{ name: "settlement-integration", url: "/git/settlement.git" },
|
||||
];
|
||||
h.vcs_branches = () =>
|
||||
["origin/main", "origin/release/month-end-international-settlement-reconciliation"].map((name) => ({
|
||||
name,
|
||||
commit: "c1",
|
||||
current: false,
|
||||
remote: true,
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
lastCommitMs: 0,
|
||||
}));
|
||||
h.vcs_remote = () => new Promise(() => {});
|
||||
const storeModule = "/src/features/vcs/store.ts";
|
||||
const { useVcs } = await import(/* @vite-ignore */ storeModule);
|
||||
useVcs.setState({ available: true, root, repo: second, roots: [root, second], branch });
|
||||
const contextModule = "/src/platform/context.ts";
|
||||
const { setContext } = await import(/* @vite-ignore */ contextModule);
|
||||
setContext("vcsAvailable", true);
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
await executeAction("vcs.pull");
|
||||
});
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Pull to main" });
|
||||
const branch = dialog.getByRole("button", { name: "Remote branch" });
|
||||
await expect(branch).toHaveText("main");
|
||||
const body = dialog.locator("[data-dialog-body]");
|
||||
await expect.poll(() => branch.evaluate((el) => el.getBoundingClientRect().width)).toBeGreaterThanOrEqual(250);
|
||||
expect(await body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
|
||||
|
||||
await branch.press("s");
|
||||
await page.getByRole("option", { name: "release/month-end-international-settlement-reconciliation" }).click();
|
||||
await expect(branch).toContainText("month-end-international-settlement-reconciliation");
|
||||
|
||||
const modify = dialog.getByRole("button", { name: "Modify options" });
|
||||
await modify.press("Enter");
|
||||
await page.getByRole("menuitemcheckbox", { name: "--ff-only" }).click();
|
||||
await expect(dialog.locator("code", { hasText: "--ff-only" })).toBeVisible();
|
||||
await modify.press("Enter");
|
||||
await expect(page.getByRole("menuitemcheckbox", { name: "--ff-only" })).toBeChecked();
|
||||
await expect(page.getByRole("menuitemcheckbox", { name: "--no-commit" })).toBeDisabled();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(modify).toBeFocused();
|
||||
await dialog.getByRole("button", { name: "Pull", exact: true }).click();
|
||||
await expect
|
||||
.poll(() => ipcCalls(page, "vcs_remote"))
|
||||
.toMatchObject([
|
||||
{
|
||||
repo: "/dev/checkout-reconciliation/billing-and-transaction-settlement",
|
||||
op: {
|
||||
op: "pullFrom",
|
||||
remote: "origin",
|
||||
branches: ["release/month-end-international-settlement-reconciliation"],
|
||||
rebase: false,
|
||||
options: { ffOnly: true },
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { expect, openFromTree, test } from "./fixtures";
|
||||
|
||||
test("Reformat File aligns scope and option controls and supports arrow-key scope changes", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const editor = await openFromTree(page, "build.gradle.kts");
|
||||
await editor.locator(".cm-line").first().click();
|
||||
await page.keyboard.press("Home");
|
||||
await page.keyboard.press("Shift+End");
|
||||
await page.evaluate(async () => {
|
||||
const path = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ path);
|
||||
await executeAction("code.reformatDialog");
|
||||
});
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: /Reformat File/ });
|
||||
const scope = dialog.getByRole("group", { name: "Scope" });
|
||||
const selected = scope.getByRole("radio", { name: "Selected text" });
|
||||
await expect(selected).toBeChecked();
|
||||
await expect(scope.getByRole("radio").first()).toHaveAccessibleName("Selected text");
|
||||
await selected.press("ArrowDown");
|
||||
await expect(scope.getByRole("radio", { name: "Whole file" })).toBeChecked();
|
||||
|
||||
const optimize = dialog.getByRole("group", { name: "Options" }).getByRole("checkbox", { name: "Optimize imports" });
|
||||
expect((await selected.boundingBox())!.x).toBeCloseTo((await optimize.boundingBox())!.x, 0);
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(dialog).toBeHidden();
|
||||
});
|
||||
|
||||
test("Reformat Code keeps long targets and the file mask usable in a narrow window", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 340, height: 460 });
|
||||
const target = "InternationalSettlementReconciliation".repeat(4);
|
||||
await page.evaluate(async (target) => {
|
||||
const path = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ path);
|
||||
await executeAction("code.reformatFiles", { directories: [`/dev/acme-api/${target}`] });
|
||||
}, target);
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Reformat Code", exact: true });
|
||||
await expect(dialog.getByText(target, { exact: true })).toBeVisible();
|
||||
const body = dialog.locator("[data-dialog-body]");
|
||||
expect(await body.evaluate((el) => el.scrollWidth)).toBe(await body.evaluate((el) => el.clientWidth));
|
||||
|
||||
await expect(
|
||||
dialog.getByRole("group", { name: "Options" }).getByRole("checkbox", { name: "Include subdirectories" }),
|
||||
).toBeChecked();
|
||||
const filters = dialog.getByRole("group", { name: "Filters" });
|
||||
const mask = filters.getByRole("textbox", { name: "File mask" });
|
||||
await expect(mask).toBeDisabled();
|
||||
await filters.getByText("File mask:", { exact: true }).click();
|
||||
await mask.fill("*.java");
|
||||
await expect(mask).toHaveValue("*.java");
|
||||
await dialog.getByRole("button", { name: "Cancel" }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Stash wraps the current branch and accepts a multiline message in a narrow window", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 380, height: 590 });
|
||||
await stubDesktop(page);
|
||||
const root = "/dev/settlement-engine";
|
||||
const head = "release/QuarterlyInternationalSettlementReconciliationAndAuthorizationForMerchantOperations";
|
||||
await page.evaluate(
|
||||
async ({ root, head }) => {
|
||||
const branch = { head, headCommit: "c1", upstream: null, ahead: 0, behind: 0, operation: null };
|
||||
const h = window.__ipc.handlers;
|
||||
h.vcs_branch_info = () => branch;
|
||||
h.vcs_roots = () => [{ root, ...branch }];
|
||||
h.vcs_status = () => [];
|
||||
h.vcs_stashes = () => [];
|
||||
h.vcs_stash_push = () => null;
|
||||
const storeModule = "/src/features/vcs/store.ts";
|
||||
const { useVcs } = await import(/* @vite-ignore */ storeModule);
|
||||
useVcs.setState({ available: true, root, repo: root, roots: [root], branch });
|
||||
const contextModule = "/src/platform/context.ts";
|
||||
const { setContext } = await import(/* @vite-ignore */ contextModule);
|
||||
setContext("vcsAvailable", true);
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
await executeAction("vcs.stash");
|
||||
},
|
||||
{ root, head },
|
||||
);
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Stash", exact: true });
|
||||
await expect(dialog.getByText(`Current branch: ${head}`)).toBeVisible();
|
||||
const body = dialog.locator("[data-dialog-body]");
|
||||
expect(await body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
|
||||
const message = dialog.getByRole("textbox", { name: "Message", exact: true });
|
||||
await expect(message).toBeFocused();
|
||||
await message.fill("Set aside settlement work");
|
||||
await message.press("End");
|
||||
await message.press("Enter");
|
||||
await expect(message).toHaveValue("Set aside settlement work\n");
|
||||
await message.pressSequentially("Continue after the release.");
|
||||
expect(await ipcCalls(page, "vcs_stash_push")).toEqual([]);
|
||||
|
||||
await dialog.getByRole("checkbox", { name: "Keep index" }).check();
|
||||
await dialog.getByRole("checkbox", { name: "Include untracked files" }).check();
|
||||
await message.press("Control+Enter");
|
||||
await expect(dialog).toBeHidden();
|
||||
await expect
|
||||
.poll(() => ipcCalls(page, "vcs_stash_push"))
|
||||
.toEqual([
|
||||
{
|
||||
repo: root,
|
||||
message: "Set aside settlement work\nContinue after the release.",
|
||||
keepIndex: true,
|
||||
includeUntracked: true,
|
||||
paths: null,
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -71,3 +71,57 @@ test("shows Update failures from the branch menu even when VCS notifications are
|
||||
await expect(page.getByText(/untracked working tree files would be overwritten by merge/)).toBeVisible();
|
||||
expect(await ipcCalls(page, "vcs_remote")).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("Update Project wraps long tracking branches and keeps its options reachable", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.setViewportSize({ width: 360, height: 580 });
|
||||
const local = "release/" + "InternationalSettlementReconciliation".repeat(3);
|
||||
await page.evaluate(async (head) => {
|
||||
const root = "/dev/acme-api";
|
||||
const branch = { head, upstream: `origin/${head}`, behind: 1, ahead: 1, operation: null, headCommit: "c1" };
|
||||
const h = window.__ipc.handlers;
|
||||
h.vcs_branch_info = () => branch;
|
||||
h.vcs_roots = () => [{ root, head, headCommit: "c1", operation: null }];
|
||||
h.settings_set = () => null;
|
||||
h.vcs_remote = () => new Promise(() => {});
|
||||
const storeModule = "/src/features/vcs/store.ts";
|
||||
const { useVcs } = await import(/* @vite-ignore */ storeModule);
|
||||
useVcs.setState({ available: true, root, repo: root, roots: [root], branch });
|
||||
const contextModule = "/src/platform/context.ts";
|
||||
const { setContext } = await import(/* @vite-ignore */ contextModule);
|
||||
setContext("vcsAvailable", true);
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
await executeAction("vcs.update");
|
||||
}, local);
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Update Project", exact: true });
|
||||
await expect(dialog.getByText(`Update ${local} from origin/${local} (1 incoming)`)).toBeVisible();
|
||||
const body = dialog.locator("[data-dialog-body]");
|
||||
const width = await body.evaluate((el) => ({ scroll: el.scrollWidth, available: el.clientWidth }));
|
||||
expect(width.scroll).toBe(width.available);
|
||||
|
||||
const reset = dialog.getByRole("button", { name: "Reset to the Remote Branch" });
|
||||
await expect(reset).toBeVisible();
|
||||
expect(
|
||||
await reset.evaluate(
|
||||
(el) => el.getBoundingClientRect().right <= el.closest('[role="dialog"]')!.getBoundingClientRect().right,
|
||||
),
|
||||
).toBe(true);
|
||||
const merge = dialog.getByRole("radio", { name: /^Merge incoming changes/ });
|
||||
const rebase = dialog.getByRole("radio", { name: /^Rebase the current branch/ });
|
||||
await expect(merge).toBeChecked();
|
||||
await merge.press("ArrowDown");
|
||||
await expect(rebase).toBeChecked();
|
||||
await dialog.getByRole("checkbox", { name: "Don't show again" }).check();
|
||||
await dialog.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await expect
|
||||
.poll(() => ipcCalls(page, "vcs_remote"))
|
||||
.toEqual([expect.objectContaining({ op: { op: "pull", rebase: true } })]);
|
||||
expect(await ipcCalls(page, "settings_set")).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ key: "vcs.git.updateMethod", value: '"rebase"' }),
|
||||
expect.objectContaining({ key: "vcs.confirmation.showUpdateOptions", value: "false" }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
@@ -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" }));
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -553,33 +553,6 @@
|
||||
}
|
||||
|
||||
/* Dialog bodies get no padding of their own; wrap the groups like Analysis dialogs' .form. */
|
||||
.reformatBody {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
padding: 14px;
|
||||
}
|
||||
.reformatGroup {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1-5);
|
||||
}
|
||||
.reformatLegend {
|
||||
margin-bottom: 6px;
|
||||
padding: 0;
|
||||
font-size: var(--fs-small);
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.reformatOption {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
|
||||
.pasteImports {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { act, fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import type { Location } from "@/bindings";
|
||||
|
||||
const openFile = vi.fn(async () => undefined);
|
||||
@@ -19,7 +19,6 @@ const { closePopup, openPopup, useLspPopup } = await import("./popupStore");
|
||||
const { useDocWindow, hoverDoc, pushHistory, stepHistory, hoverCandidates } = await import("./docs");
|
||||
const { mountHoverDoc } = await import("./DocView");
|
||||
const { hoverSource } = await import("./hover");
|
||||
import popupStyles from "./Popups.module.css";
|
||||
import { registerImportsOnPasteActions } from "./importsOnPaste";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
@@ -352,7 +351,7 @@ describe("quick definition popup", () => {
|
||||
});
|
||||
|
||||
describe("reformat dialog", () => {
|
||||
it("wraps its content in the padded body", () => {
|
||||
it("offers only whole-file formatting when the editor has no selection", () => {
|
||||
const onRun = vi.fn();
|
||||
openPopup({
|
||||
kind: "reformat",
|
||||
@@ -363,9 +362,10 @@ describe("reformat dialog", () => {
|
||||
onRun,
|
||||
});
|
||||
render(<LspPopups />);
|
||||
const body = screen.getByRole("dialog", { name: "Reformat File" }).querySelector("[data-dialog-body]")!;
|
||||
expect(body.firstElementChild).toHaveClass(popupStyles.reformatBody!);
|
||||
expect(body.firstElementChild!.querySelectorAll("fieldset")).toHaveLength(2);
|
||||
const scope = within(screen.getByRole("group", { name: "Scope" }));
|
||||
expect(scope.getByRole("radio", { name: "Selected text" })).toBeDisabled();
|
||||
expect(scope.getByRole("radio", { name: "Whole file" })).toBeChecked();
|
||||
expect(within(screen.getByRole("group", { name: "Options" })).getByRole("checkbox")).not.toBeChecked();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Run" }));
|
||||
expect(onRun).toHaveBeenCalledWith({ selectionOnly: false, optimizeImports: false });
|
||||
});
|
||||
|
||||
+21
-25
@@ -11,6 +11,7 @@ import {
|
||||
List,
|
||||
MenuList,
|
||||
Popup,
|
||||
Radio,
|
||||
Select,
|
||||
Spinner,
|
||||
SymbolBadge,
|
||||
@@ -35,6 +36,7 @@ import { renderCode } from "./markdown";
|
||||
import { describeSummary } from "./workspaceEdit";
|
||||
import { useUsagesStatus } from "./navigation";
|
||||
import styles from "./Popups.module.css";
|
||||
import fieldsetStyles from "@/ui/DialogFieldset.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
|
||||
@@ -681,7 +683,7 @@ function ReformatDialog({ popup }: { popup: Extract<LspPopup, { kind: "reformat"
|
||||
open
|
||||
onClose={closePopup}
|
||||
title={popup.title}
|
||||
width={380}
|
||||
width={400}
|
||||
buttons={[
|
||||
{
|
||||
label: "Run",
|
||||
@@ -695,33 +697,27 @@ function ReformatDialog({ popup }: { popup: Extract<LspPopup, { kind: "reformat"
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
>
|
||||
<div className={styles.reformatBody}>
|
||||
<fieldset className={styles.reformatGroup}>
|
||||
<legend className={styles.reformatLegend}>
|
||||
<div className={fieldsetStyles.body}>
|
||||
<fieldset className={fieldsetStyles.group}>
|
||||
<legend className={fieldsetStyles.legend}>
|
||||
<T>Scope</T>
|
||||
</legend>
|
||||
<label className={styles.reformatOption}>
|
||||
<input
|
||||
type="radio"
|
||||
name="reformat-scope"
|
||||
checked={!selectionOnly}
|
||||
onChange={() => setSelectionOnly(false)}
|
||||
/>
|
||||
<T>Whole file</T>
|
||||
</label>
|
||||
<label className={clsx(styles.reformatOption, !popup.hasSelection && styles.disabled)}>
|
||||
<input
|
||||
type="radio"
|
||||
name="reformat-scope"
|
||||
checked={selectionOnly}
|
||||
disabled={!popup.hasSelection}
|
||||
onChange={() => setSelectionOnly(true)}
|
||||
/>
|
||||
<T>Selected text</T>
|
||||
</label>
|
||||
<Radio
|
||||
name="reformat-scope"
|
||||
checked={selectionOnly}
|
||||
disabled={!popup.hasSelection}
|
||||
onChange={() => setSelectionOnly(true)}
|
||||
label="Selected text"
|
||||
/>
|
||||
<Radio
|
||||
name="reformat-scope"
|
||||
checked={!selectionOnly}
|
||||
onChange={() => setSelectionOnly(false)}
|
||||
label="Whole file"
|
||||
/>
|
||||
</fieldset>
|
||||
<fieldset className={styles.reformatGroup}>
|
||||
<legend className={styles.reformatLegend}>
|
||||
<fieldset className={fieldsetStyles.group}>
|
||||
<legend className={fieldsetStyles.legend}>
|
||||
<T>Options</T>
|
||||
</legend>
|
||||
<Checkbox
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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()");
|
||||
});
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -199,6 +199,21 @@
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
.reformatSubject {
|
||||
overflow-wrap: anywhere;
|
||||
font-size: var(--fs-ui);
|
||||
font-weight: 600;
|
||||
}
|
||||
.reformatMask {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
.reformatMaskInput {
|
||||
flex: 1 1 12ch;
|
||||
min-width: 0;
|
||||
}
|
||||
.languageSelect {
|
||||
min-width: 180px;
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
type StructuralForm,
|
||||
} from "./structural";
|
||||
import styles from "./Analysis.module.css";
|
||||
import fieldsetStyles from "@/ui/DialogFieldset.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
|
||||
@@ -168,40 +169,50 @@ function ReformatCodeDialog({ targets, onClose }: { targets: readonly ReformatTa
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
>
|
||||
<div className={styles.form}>
|
||||
<div className={styles.hint}>{subject}</div>
|
||||
{targets.some((t) => t.dir) && (
|
||||
<div className={fieldsetStyles.body}>
|
||||
<div className={styles.reformatSubject}>{subject}</div>
|
||||
<fieldset className={fieldsetStyles.group}>
|
||||
<legend className={fieldsetStyles.legend}>
|
||||
<T>Options</T>
|
||||
</legend>
|
||||
<Checkbox
|
||||
checked={options.recursive}
|
||||
onChange={(recursive) => setOptions({ ...options, recursive })}
|
||||
label="Include subdirectories"
|
||||
checked={options.optimizeImports}
|
||||
onChange={(optimizeImports) => setOptions({ ...options, optimizeImports })}
|
||||
label="Optimize imports"
|
||||
/>
|
||||
)}
|
||||
<Checkbox
|
||||
checked={options.optimizeImports}
|
||||
onChange={(optimizeImports) => setOptions({ ...options, optimizeImports })}
|
||||
label="Optimize imports"
|
||||
/>
|
||||
<Checkbox
|
||||
checked={options.changedTextOnly}
|
||||
onChange={(changedTextOnly) => setOptions({ ...options, changedTextOnly })}
|
||||
label="Only VCS changed text"
|
||||
/>
|
||||
<div className={styles.fieldRow}>
|
||||
<Checkbox
|
||||
checked={options.useMask}
|
||||
onChange={(useMask) => setOptions({ ...options, useMask })}
|
||||
label="File mask:"
|
||||
checked={options.changedTextOnly}
|
||||
onChange={(changedTextOnly) => setOptions({ ...options, changedTextOnly })}
|
||||
label="Only VCS changed text"
|
||||
/>
|
||||
<Input
|
||||
className={styles.grow}
|
||||
value={options.mask}
|
||||
disabled={!options.useMask}
|
||||
placeholder="*.sh, *.py"
|
||||
onChange={(e) => setOptions({ ...options, mask: e.target.value })}
|
||||
aria-label="File mask"
|
||||
/>
|
||||
</div>
|
||||
{targets.some((t) => t.dir) && (
|
||||
<Checkbox
|
||||
checked={options.recursive}
|
||||
onChange={(recursive) => setOptions({ ...options, recursive })}
|
||||
label="Include subdirectories"
|
||||
/>
|
||||
)}
|
||||
</fieldset>
|
||||
<fieldset className={fieldsetStyles.group}>
|
||||
<legend className={fieldsetStyles.legend}>
|
||||
<T>Filters</T>
|
||||
</legend>
|
||||
<div className={styles.reformatMask}>
|
||||
<Checkbox
|
||||
checked={options.useMask}
|
||||
onChange={(useMask) => setOptions({ ...options, useMask })}
|
||||
label="File mask:"
|
||||
/>
|
||||
<Input
|
||||
className={styles.reformatMaskInput}
|
||||
value={options.mask}
|
||||
disabled={!options.useMask}
|
||||
placeholder="*.sh, *.py"
|
||||
onChange={(e) => setOptions({ ...options, mask: e.target.value })}
|
||||
aria-label="File mask"
|
||||
/>
|
||||
</div>
|
||||
</fieldset>
|
||||
<div className={styles.hint}>
|
||||
<T>Files are reformatted by their language's formatter and saved; files without one are skipped.</T>
|
||||
</div>
|
||||
|
||||
+140
-78
@@ -21,7 +21,20 @@ import {
|
||||
} from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { useTx, useTxTemplate } from "@/platform/i18n";
|
||||
import { Button, Checkbox, Dialog, Icon, Input, Select, type SelectOption, T, hasIcon } from "@/ui";
|
||||
import {
|
||||
Checkbox,
|
||||
Dialog,
|
||||
Icon,
|
||||
IconButton,
|
||||
Input,
|
||||
Select,
|
||||
SplitGroup,
|
||||
SplitHandle,
|
||||
SplitPanel,
|
||||
type SelectOption,
|
||||
T,
|
||||
hasIcon,
|
||||
} from "@/ui";
|
||||
import { effectiveValues, fieldError, isVisible, type Values } from "./newProjectTemplate";
|
||||
import { defaultProjectDirectory, openProjectInWindow } from "./windows";
|
||||
import styles from "./newProject.module.css";
|
||||
@@ -116,6 +129,20 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
|
||||
const [requirements, setRequirements] = useState<Requirement[]>([]);
|
||||
const [jdks, setJdks] = useState<Sdk[] | null>(null);
|
||||
const [job, setJob] = useState<Job | null>(null);
|
||||
const layout = useRef<HTMLDivElement>(null);
|
||||
const [stacked, setStacked] = useState(false);
|
||||
const configuring = job === null;
|
||||
|
||||
useEffect(() => {
|
||||
const el = layout.current;
|
||||
if (!configuring || !el || typeof ResizeObserver === "undefined") return;
|
||||
const observer = new ResizeObserver(([entry]) => {
|
||||
const width = entry?.contentRect.width;
|
||||
if (width) setStacked(width < 580);
|
||||
});
|
||||
observer.observe(el);
|
||||
return () => observer.disconnect();
|
||||
}, [configuring]);
|
||||
|
||||
useEffect(() => {
|
||||
if (initialLocation()) return;
|
||||
@@ -265,8 +292,19 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
>
|
||||
<div className={styles.layout}>
|
||||
<div className={styles.sidebar}>
|
||||
<SplitGroup
|
||||
className={styles.layout}
|
||||
elementRef={layout}
|
||||
orientation={stacked ? "vertical" : "horizontal"}
|
||||
storageKey="openidea.newProject.layout"
|
||||
>
|
||||
<SplitPanel
|
||||
id="new-project-generators"
|
||||
defaultSize="25%"
|
||||
minSize={stacked ? "28%" : "148px"}
|
||||
maxSize="45%"
|
||||
className={styles.sidebar}
|
||||
>
|
||||
<Input
|
||||
className={styles.search}
|
||||
value={query}
|
||||
@@ -286,6 +324,7 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
|
||||
role="option"
|
||||
aria-selected={g.id === selected}
|
||||
className={styles.entry}
|
||||
title={tx(g.name)}
|
||||
onClick={() => setSelected(g.id)}
|
||||
>
|
||||
<Icon name={hasIcon(g.icon) ? g.icon : "folder"} />
|
||||
@@ -295,82 +334,95 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<form
|
||||
className={styles.form}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void createProject();
|
||||
}}
|
||||
>
|
||||
{generator?.description && <div className={styles.description}>{tx(generator.description)}</div>}
|
||||
<div className={styles.grid}>
|
||||
<label className={styles.label} htmlFor="np-name">
|
||||
<T>Name:</T>
|
||||
</label>
|
||||
<Input
|
||||
id="np-name"
|
||||
data-autofocus
|
||||
value={name}
|
||||
invalid={!!nameError}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
<label className={styles.label} htmlFor="np-location">
|
||||
<T>Location:</T>
|
||||
</label>
|
||||
<div className={styles.inline}>
|
||||
<Input id="np-location" value={location} onChange={(e) => setLocation(e.target.value)} />
|
||||
<Button onClick={() => void browse()} disabled={!isTauri()}>
|
||||
<T>Browse…</T>
|
||||
</Button>
|
||||
</div>
|
||||
<span />
|
||||
<div className={styles.hint}>
|
||||
{nameError ? txTemplate(nameError) : path && txTemplate(`Project will be created in: ${path}`)}
|
||||
</div>
|
||||
{generator?.git && (
|
||||
<>
|
||||
<span />
|
||||
<Checkbox checked={git} onChange={setGit} label="Create Git repository" />
|
||||
</>
|
||||
)}
|
||||
{visibleFields.map((f) => (
|
||||
<FieldRow
|
||||
key={f.id}
|
||||
field={f}
|
||||
value={values[f.id] ?? ""}
|
||||
onChange={(v) => setValue(f.id, v)}
|
||||
jdks={jdks}
|
||||
</SplitPanel>
|
||||
<SplitHandle aria-label={tx("Generators")} />
|
||||
<SplitPanel id="new-project-form" defaultSize="75%">
|
||||
<form
|
||||
className={styles.form}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void createProject();
|
||||
}}
|
||||
>
|
||||
{generator?.description && <div className={styles.description}>{tx(generator.description)}</div>}
|
||||
<div className={styles.grid}>
|
||||
<label className={styles.label} htmlFor="np-name">
|
||||
<T>Name:</T>
|
||||
</label>
|
||||
<Input
|
||||
id="np-name"
|
||||
data-autofocus
|
||||
value={name}
|
||||
invalid={!!nameError}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
))}
|
||||
{loadingDynamic && (
|
||||
<>
|
||||
<span />
|
||||
<div className={styles.hint}>
|
||||
<T>Loading options…</T>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{dynamicError && (
|
||||
<>
|
||||
<span />
|
||||
<div className={styles.error}>{txTemplate(dynamicError)}</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{missing.map((r) => (
|
||||
<div key={r.program} className={styles.missing}>
|
||||
<Icon name="warning" />
|
||||
<span>
|
||||
{r.found
|
||||
? tx`${r.program} ${r.found} is installed, but this project needs ${r.min ?? ""} or later.`
|
||||
: tx`${r.program} is not installed.`}{" "}
|
||||
{r.hint && tx(r.hint)}
|
||||
</span>
|
||||
<label className={styles.label} htmlFor="np-location">
|
||||
<T>Location:</T>
|
||||
</label>
|
||||
<div className={styles.location}>
|
||||
<Input
|
||||
id="np-location"
|
||||
variant="bare"
|
||||
className={styles.locationInput}
|
||||
value={location}
|
||||
onChange={(e) => setLocation(e.target.value)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
title="Browse…"
|
||||
size="small"
|
||||
onClick={() => void browse()}
|
||||
disabled={!isTauri()}
|
||||
/>
|
||||
</div>
|
||||
<span />
|
||||
<div className={styles.hint}>
|
||||
{nameError ? txTemplate(nameError) : path && txTemplate(`Project will be created in: ${path}`)}
|
||||
</div>
|
||||
{generator?.git && (
|
||||
<>
|
||||
<span />
|
||||
<Checkbox checked={git} onChange={setGit} label="Create Git repository" />
|
||||
</>
|
||||
)}
|
||||
{visibleFields.map((f) => (
|
||||
<FieldRow
|
||||
key={f.id}
|
||||
field={f}
|
||||
value={values[f.id] ?? ""}
|
||||
onChange={(v) => setValue(f.id, v)}
|
||||
jdks={jdks}
|
||||
/>
|
||||
))}
|
||||
{loadingDynamic && (
|
||||
<>
|
||||
<span />
|
||||
<div className={styles.hint}>
|
||||
<T>Loading options…</T>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{dynamicError && (
|
||||
<>
|
||||
<span />
|
||||
<div className={styles.error}>{txTemplate(dynamicError)}</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</form>
|
||||
</div>
|
||||
{missing.map((r) => (
|
||||
<div key={r.program} className={styles.missing}>
|
||||
<Icon name="warning" />
|
||||
<span>
|
||||
{r.found
|
||||
? tx`${r.program} ${r.found} is installed, but this project needs ${r.min ?? ""} or later.`
|
||||
: tx`${r.program} is not installed.`}{" "}
|
||||
{r.hint && tx(r.hint)}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</form>
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -420,6 +472,7 @@ function FieldRow({
|
||||
control = (
|
||||
<Select
|
||||
id={id}
|
||||
className={styles.fieldSelect}
|
||||
value={value}
|
||||
options={kind.options.map((o) => ({ value: o.value, label: o.label }))}
|
||||
onChange={onChange}
|
||||
@@ -438,7 +491,16 @@ function FieldRow({
|
||||
})),
|
||||
];
|
||||
if (value && !options.some((o) => o.value === value)) options.push({ value, label: value, verbatim: true });
|
||||
control = <Select id={id} value={value} options={options} onChange={onChange} aria-label={tx(field.label)} />;
|
||||
control = (
|
||||
<Select
|
||||
id={id}
|
||||
className={styles.fieldSelect}
|
||||
value={value}
|
||||
options={options}
|
||||
onChange={onChange}
|
||||
aria-label={tx(field.label)}
|
||||
/>
|
||||
);
|
||||
} else if (kind.type === "dependencies")
|
||||
control = <DependencyPicker id={id} groups={kind.groups} value={value} onChange={onChange} />;
|
||||
else
|
||||
|
||||
@@ -2,39 +2,42 @@
|
||||
.dialog {
|
||||
height: min(602px, calc(100vh - 48px));
|
||||
}
|
||||
.dialog [data-dialog-body] {
|
||||
overflow: hidden;
|
||||
}
|
||||
.dialog [data-dialog-footer] {
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
.layout {
|
||||
display: grid;
|
||||
grid-template-columns: 220px 1fr;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
.sidebar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
border-right: 1px solid var(--border);
|
||||
background: var(--bg-island);
|
||||
}
|
||||
.search {
|
||||
margin: 8px;
|
||||
flex: none;
|
||||
margin: var(--space-2);
|
||||
}
|
||||
.list {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: 0 4px 8px;
|
||||
padding: 0 var(--space-1) var(--space-2);
|
||||
}
|
||||
.groupLabel {
|
||||
padding: 8px 8px 4px;
|
||||
padding: var(--space-2) var(--space-2) var(--space-1);
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
font-weight: 600;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.entry {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
width: 100%;
|
||||
height: 26px;
|
||||
padding: 0 8px;
|
||||
height: var(--h-list-row);
|
||||
padding: 0 var(--space-2);
|
||||
border: 0;
|
||||
border-radius: var(--radius-control, 4px);
|
||||
background: transparent;
|
||||
@@ -42,6 +45,12 @@
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
}
|
||||
.entry > span {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.entry:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
@@ -54,33 +63,50 @@
|
||||
outline-offset: -2px;
|
||||
}
|
||||
.form {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: 16px;
|
||||
overflow: auto;
|
||||
padding: var(--space-4);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
.description {
|
||||
color: var(--fg-subtle);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: max-content minmax(0, 1fr);
|
||||
grid-template-columns: fit-content(38%) minmax(0, 1fr);
|
||||
align-items: center;
|
||||
gap: var(--space-2) var(--space-3);
|
||||
}
|
||||
.label {
|
||||
color: var(--fg);
|
||||
white-space: nowrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.inline {
|
||||
.location {
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
align-items: center;
|
||||
padding-inline-end: var(--space-1);
|
||||
border-radius: var(--radius-control);
|
||||
background: var(--bg-field, var(--bg-button));
|
||||
box-shadow: inset 0 0 0 1px var(--border-button);
|
||||
}
|
||||
.inline > :first-child {
|
||||
.location:focus-within {
|
||||
box-shadow:
|
||||
inset 0 0 0 1px var(--focus-ring),
|
||||
0 0 0 1px var(--focus-ring);
|
||||
}
|
||||
.location .locationInput {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding-inline: var(--space-2);
|
||||
}
|
||||
.fieldSelect {
|
||||
max-width: 100%;
|
||||
}
|
||||
.hint,
|
||||
.fieldHint {
|
||||
@@ -112,17 +138,22 @@
|
||||
}
|
||||
.segmented {
|
||||
display: inline-flex;
|
||||
flex-wrap: wrap;
|
||||
max-width: 100%;
|
||||
border-radius: var(--radius-control, 4px);
|
||||
box-shadow: inset 0 0 0 1px var(--border-button);
|
||||
}
|
||||
.segmented button {
|
||||
height: var(--h-field, 28px);
|
||||
padding: 0 14px;
|
||||
min-height: var(--h-field, 28px);
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
padding: var(--space-1) var(--space-3);
|
||||
border: 0;
|
||||
border-radius: inherit;
|
||||
background: transparent;
|
||||
color: var(--fg);
|
||||
font: inherit;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.segmented button[aria-pressed="true"] {
|
||||
background: var(--bg-tab-selected);
|
||||
@@ -147,14 +178,18 @@
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
height: 22px;
|
||||
padding: 0 6px 0 8px;
|
||||
min-height: 22px;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
padding: 0 var(--space-1-5) 0 var(--space-2);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 11px;
|
||||
background: var(--bg-control);
|
||||
color: var(--fg);
|
||||
font: inherit;
|
||||
font-size: var(--fs-small);
|
||||
overflow-wrap: anywhere;
|
||||
text-align: left;
|
||||
}
|
||||
.chip:hover {
|
||||
background: var(--bg-control-hover);
|
||||
|
||||
@@ -10,18 +10,18 @@
|
||||
background: none;
|
||||
}
|
||||
.toolbar {
|
||||
height: 32px;
|
||||
min-height: var(--h-header);
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5) var(--space-2);
|
||||
padding: var(--space-0-5) var(--space-1-5);
|
||||
}
|
||||
.toolbarGroup {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5);
|
||||
padding: 0 6px;
|
||||
}
|
||||
.sep {
|
||||
width: 1px;
|
||||
height: 16px;
|
||||
margin: 0 4px;
|
||||
background: var(--border);
|
||||
}
|
||||
.note {
|
||||
flex: none;
|
||||
@@ -29,6 +29,7 @@
|
||||
font-size: var(--fs-small);
|
||||
font-style: italic;
|
||||
color: var(--fg-subtle);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.body {
|
||||
flex: 1;
|
||||
@@ -49,17 +50,12 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
.name {
|
||||
color: var(--fg);
|
||||
}
|
||||
.detail {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--fg-subtle);
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
.muted {
|
||||
flex: none;
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.error {
|
||||
flex: none;
|
||||
|
||||
@@ -106,35 +106,37 @@ function HierarchyToolbar() {
|
||||
const autoscroll = useHierarchyOptions((s) => s.autoscroll);
|
||||
return (
|
||||
<div className={styles.toolbar} role="toolbar" aria-label={tx("Hierarchy actions")}>
|
||||
<IconButton
|
||||
icon="arrow-up"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title={tx`${directionLabel(mode, "incoming")} Hierarchy`}
|
||||
pressed={direction === "incoming"}
|
||||
onClick={() => setDirection("incoming")}
|
||||
/>
|
||||
<IconButton
|
||||
icon="arrow-down"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title={tx`${directionLabel(mode, "outgoing")} Hierarchy`}
|
||||
pressed={direction === "outgoing"}
|
||||
onClick={() => setDirection("outgoing")}
|
||||
/>
|
||||
<span className={styles.sep} />
|
||||
<div className={styles.toolbarGroup}>
|
||||
<IconButton
|
||||
icon="arrow-up"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title={tx`${directionLabel(mode, "incoming")} Hierarchy`}
|
||||
pressed={direction === "incoming"}
|
||||
onClick={() => setDirection("incoming")}
|
||||
/>
|
||||
<IconButton
|
||||
icon="arrow-down"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title={tx`${directionLabel(mode, "outgoing")} Hierarchy`}
|
||||
pressed={direction === "outgoing"}
|
||||
onClick={() => setDirection("outgoing")}
|
||||
/>
|
||||
</div>
|
||||
<IconButton icon="refresh" size="small" iconSize={16} title="Refresh" onClick={refreshHierarchy} />
|
||||
<span className={styles.sep} />
|
||||
<IconButton icon="arrow-up" action="navigate.prevOccurrence" size="small" iconSize={16} />
|
||||
<IconButton icon="arrow-down" action="navigate.nextOccurrence" size="small" iconSize={16} />
|
||||
<IconButton
|
||||
icon="autoscroll-to-source"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title="Autoscroll to Source"
|
||||
pressed={autoscroll}
|
||||
onClick={() => useHierarchyOptions.setState({ autoscroll: !autoscroll })}
|
||||
/>
|
||||
<div className={styles.toolbarGroup}>
|
||||
<IconButton icon="arrow-up" action="navigate.prevOccurrence" size="small" iconSize={16} />
|
||||
<IconButton icon="arrow-down" action="navigate.nextOccurrence" size="small" iconSize={16} />
|
||||
<IconButton
|
||||
icon="autoscroll-to-source"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title="Autoscroll to Source"
|
||||
pressed={autoscroll}
|
||||
onClick={() => useHierarchyOptions.setState({ autoscroll: !autoscroll })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -183,13 +185,9 @@ export function HierarchyView() {
|
||||
const renderNode = (n: Node, _state: TreeRowState) => {
|
||||
if (n.kind === "root") {
|
||||
return (
|
||||
<span className={styles.row}>
|
||||
<span className={styles.row} title={`${root.name}\n${relativePath(projectRoot, root.path)}:${root.line + 1}`}>
|
||||
<SymbolBadge kind={mode === "call" ? "function" : "class"} />
|
||||
<span className={styles.name}>{root.name}</span>
|
||||
{root.detail && <span className={styles.detail}>{root.detail}</span>}
|
||||
<span className={styles.muted}>
|
||||
{basename(root.path)}:{root.line + 1}
|
||||
</span>
|
||||
{loading && <Spinner size={12} />}
|
||||
{failed.has(ROOT_ID) && (
|
||||
<span className={styles.error}>
|
||||
@@ -199,35 +197,42 @@ export function HierarchyView() {
|
||||
{!loading && !failed.has(ROOT_ID) && children.get(ROOT_ID)?.length === 0 && (
|
||||
<span className={styles.muted}>{noneFoundLabel(mode, direction)}</span>
|
||||
)}
|
||||
{root.detail && <span className={styles.muted}>{root.detail}</span>}
|
||||
<span className={styles.muted}>
|
||||
{basename(root.path)}:{root.line + 1}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
const { item } = n.node;
|
||||
const calls = item.fromRanges.length;
|
||||
return (
|
||||
<span className={styles.row} title={relativePath(projectRoot, item.path)}>
|
||||
<span
|
||||
className={styles.row}
|
||||
title={`${item.name}\n${relativePath(projectRoot, item.path)}:${item.selectionRange.start.line + 1}`}
|
||||
>
|
||||
<SymbolBadge kind={badgeKind(item.kind)} />
|
||||
<span className={styles.name}>{item.name}</span>
|
||||
{item.detail && <span className={styles.detail}>{item.detail}</span>}
|
||||
<span className={styles.muted}>
|
||||
{basename(item.path)}:{item.selectionRange.start.line + 1}
|
||||
</span>
|
||||
{calls > 1 && <span className={styles.muted}>{tx`(${calls} calls)`}</span>}
|
||||
{n.node.recursion && (
|
||||
<span className={styles.muted}>
|
||||
<T>recursive</T>
|
||||
</span>
|
||||
)}
|
||||
{notes.has(n.id) && (
|
||||
<span className={styles.muted} title={notes.get(n.id)}>
|
||||
{notes.get(n.id)}
|
||||
</span>
|
||||
)}
|
||||
{failed.has(n.id) && (
|
||||
<span className={styles.error}>
|
||||
<T>failed to load</T>
|
||||
</span>
|
||||
)}
|
||||
{item.detail && <span className={styles.muted}>{item.detail}</span>}
|
||||
<span className={styles.muted}>
|
||||
{basename(item.path)}:{item.selectionRange.start.line + 1}
|
||||
</span>
|
||||
{notes.has(n.id) && (
|
||||
<span className={styles.muted} title={notes.get(n.id)}>
|
||||
{notes.get(n.id)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
@@ -244,6 +249,7 @@ export function HierarchyView() {
|
||||
<Tree<Node>
|
||||
key={generation}
|
||||
aria-label={mode === "call" ? "Call hierarchy" : "Type hierarchy"}
|
||||
horizontalScroll
|
||||
roots={roots}
|
||||
getKey={(n) => n.id}
|
||||
getLabel={(n) => (n.kind === "root" ? root.name : n.node.item.name)}
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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, '""')}"`;
|
||||
|
||||
/**
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -10,12 +10,12 @@
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
gap: var(--space-1);
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
box-sizing: border-box;
|
||||
font-family: var(--font-mono);
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--fs-ui);
|
||||
white-space: pre;
|
||||
color: var(--fg);
|
||||
@@ -23,7 +23,10 @@
|
||||
}
|
||||
|
||||
.name {
|
||||
flex: none;
|
||||
min-width: 0;
|
||||
max-width: 45%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
@@ -41,7 +44,6 @@
|
||||
|
||||
.nodeIcon {
|
||||
flex: none;
|
||||
margin-right: 1px;
|
||||
}
|
||||
|
||||
.eq {
|
||||
@@ -49,15 +51,28 @@
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
|
||||
.valueGroup {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
min-width: min(8ch, 45%);
|
||||
flex: 1 1 0;
|
||||
}
|
||||
|
||||
.value {
|
||||
min-width: 0;
|
||||
flex: 1 1 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
|
||||
.showValue {
|
||||
flex: none;
|
||||
flex: 0 0 auto;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
@@ -112,6 +127,7 @@
|
||||
|
||||
.type {
|
||||
min-width: 0;
|
||||
max-width: 25%;
|
||||
flex: 0 1 auto;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
@@ -136,7 +152,7 @@
|
||||
|
||||
.editInput {
|
||||
flex: 1;
|
||||
min-width: 80px;
|
||||
min-width: min(80px, 40%);
|
||||
height: 18px;
|
||||
padding: 0 4px;
|
||||
font: inherit;
|
||||
|
||||
@@ -415,7 +415,9 @@ function VarEditRow({
|
||||
useEffect(() => acquirePopup(), []);
|
||||
return (
|
||||
<span className={styles.row}>
|
||||
<span className={styles.name}>{node.name}</span>
|
||||
<span className={styles.name} title={node.name}>
|
||||
{node.name}
|
||||
</span>
|
||||
<span className={styles.eq}>=</span>
|
||||
<input
|
||||
className={clsx(styles.editInput, error && styles.editInvalid)}
|
||||
@@ -465,18 +467,21 @@ function VarRow({
|
||||
const valueRef = useRef<HTMLSpanElement>(null);
|
||||
const [overflow, setOverflow] = useState(false);
|
||||
useLayoutEffect(() => {
|
||||
const el = valueRef.current;
|
||||
if (!el) {
|
||||
const text = valueRef.current;
|
||||
const group = text?.parentElement;
|
||||
if (!text || !group) {
|
||||
setOverflow(false);
|
||||
return;
|
||||
}
|
||||
const update = () => setOverflow(el.scrollWidth > el.clientWidth + 1);
|
||||
// The group measures the space available before the Show button takes any of it.
|
||||
const update = () => setOverflow(text.scrollWidth > group.clientWidth + 1);
|
||||
update();
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
const observer = new ResizeObserver(update);
|
||||
observer.observe(el);
|
||||
observer.observe(group);
|
||||
observer.observe(text);
|
||||
return () => observer.disconnect();
|
||||
}, [node.value]);
|
||||
}, [node.value, node.typeName, node.error]);
|
||||
if (node.kind === "message") return <span className={styles.message}>{node.name}</span>;
|
||||
if (node.kind === "scope")
|
||||
return (
|
||||
@@ -489,7 +494,7 @@ function VarRow({
|
||||
const shown = shownValue(node.value, node.typeName);
|
||||
const evaluation = node.kind === "eval";
|
||||
return (
|
||||
<span className={styles.row}>
|
||||
<span className={styles.row} title={node.name}>
|
||||
<Icon name={nodeIcon(node)} size={16} className={styles.nodeIcon} />
|
||||
{!shown.entry && (
|
||||
<>
|
||||
@@ -511,23 +516,29 @@ function VarRow({
|
||||
<span className={styles.error}>{oneLine(node.error)}</span>
|
||||
) : (
|
||||
<>
|
||||
{shown.label && <span className={styles.type}>{shown.label}</span>}
|
||||
<span ref={valueRef} className={clsx(styles.value, kind && styles[kind])} title={node.value}>
|
||||
{oneLine(shown.text)}
|
||||
</span>
|
||||
{overflow && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.showValue}
|
||||
title={tx("Show")}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onShowValue(node);
|
||||
}}
|
||||
>
|
||||
…{tx("Show")}
|
||||
</button>
|
||||
{shown.label && (
|
||||
<span className={styles.type} title={shown.label}>
|
||||
{shown.label}
|
||||
</span>
|
||||
)}
|
||||
<span className={styles.valueGroup}>
|
||||
<span ref={valueRef} className={clsx(styles.value, kind && styles[kind])} title={node.value}>
|
||||
{oneLine(shown.text)}
|
||||
</span>
|
||||
{overflow && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.showValue}
|
||||
title={tx("Show")}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onShowValue(node);
|
||||
}}
|
||||
>
|
||||
…{tx("Show")}
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
|
||||
@@ -10,6 +10,60 @@
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
|
||||
.moveForm {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
}
|
||||
|
||||
.moveSubject {
|
||||
color: var(--fg-emphasis);
|
||||
font-size: var(--fs-ui);
|
||||
font-weight: 600;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.moveDestination {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-1) var(--space-2);
|
||||
}
|
||||
|
||||
.moveDestination > .fieldLabel {
|
||||
line-height: var(--h-field);
|
||||
}
|
||||
|
||||
.moveControls {
|
||||
display: flex;
|
||||
flex: 1 1 244px;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.moveField {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.moveField input {
|
||||
flex: 1 1 0;
|
||||
}
|
||||
|
||||
.moveField button {
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.movePath {
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
font-family: var(--font-mono);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.fieldLabel {
|
||||
color: var(--fg);
|
||||
font-size: var(--fs-ui);
|
||||
|
||||
@@ -6,7 +6,10 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { create } from "zustand";
|
||||
import type { FileMove } from "@/bindings";
|
||||
import { Checkbox, Dialog, Input, Spinner, T } from "@/ui";
|
||||
import { Checkbox, Dialog, IconButton, Input, Spinner, T } from "@/ui";
|
||||
import { choosePath } from "@/platform/choosePath";
|
||||
import { isTauri } from "@/platform/ipc";
|
||||
import { ipcPath } from "@/platform/paths";
|
||||
import { runFileRefactoring, type FileRefactorOptions } from "./fileRefactor";
|
||||
import {
|
||||
isSameOrInside,
|
||||
@@ -253,31 +256,59 @@ function RenameDialog({ request }: { request: Extract<FileRefactorRequest, { kin
|
||||
|
||||
/** Folder `typed` (absolute, or relative to the project root). */
|
||||
function resolveTarget(typed: string, root: string): string {
|
||||
const t = typed.trim().replace(/\/+$/, "");
|
||||
if (!t) return root;
|
||||
return t.startsWith("/") || /^[A-Za-z]:[\\/]/.test(t) ? t : joinPath(root, t);
|
||||
const value = ipcPath(typed.trim());
|
||||
if (!value) return root;
|
||||
const absolute = value.startsWith("/") || /^[A-Za-z]:\//.test(value);
|
||||
const isRoot = /^(?:[A-Za-z]:)?\/+$/.test(value);
|
||||
const path = value.replace(/\/+$/, isRoot ? "/" : "");
|
||||
return absolute ? path : joinPath(root, path);
|
||||
}
|
||||
|
||||
function MoveDialog({ request }: { request: Extract<FileRefactorRequest, { kind: "move" }> }) {
|
||||
const root = useProjectTree((s) => s.root) ?? "";
|
||||
const [target, setTarget] = useState(request.target);
|
||||
const [options, setOptions] = useState(() => loadOptions("move"));
|
||||
const [browsing, setBrowsing] = useState(false);
|
||||
const [browseError, setBrowseError] = useState<string | null>(null);
|
||||
const field = useRef<HTMLInputElement>(null);
|
||||
const { busy, run, cancel } = useSearch();
|
||||
useEffect(() => {
|
||||
const input = field.current;
|
||||
const path = request.target.replace(/[\\/]+$/, "");
|
||||
if (!input || !path || /^[A-Za-z]:$/.test(path)) return;
|
||||
const start = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1;
|
||||
input.setSelectionRange(start, path.length);
|
||||
input.scrollLeft = input.scrollWidth;
|
||||
}, [request.target]);
|
||||
const dest = resolveTarget(target, root);
|
||||
const moves: FileMove[] = request.paths
|
||||
.filter((p) => parentOf(p) !== dest)
|
||||
.map((p) => ({ from: p, to: joinPath(dest, nameOf(p)) }));
|
||||
.map((from) => ({ from, to: joinPath(dest, nameOf(from)) }))
|
||||
.filter((move) => move.from !== move.to);
|
||||
const error = request.paths.some((p) => isSameOrInside(dest, p))
|
||||
? "Cannot move a folder into itself"
|
||||
? tx("Cannot move a folder into itself")
|
||||
: !moves.length
|
||||
? "Already in this directory"
|
||||
? tx("Already in this directory")
|
||||
: null;
|
||||
const subject =
|
||||
request.paths.length === 1
|
||||
? `Move ${request.dir || useProjectTree.getState().listings.has(request.paths[0]!) ? "directory" : "file"} '${nameOf(request.paths[0]!)}'`
|
||||
: `Move ${request.paths.length} items`;
|
||||
const single = request.paths.length === 1 ? request.paths[0]! : null;
|
||||
const subject = single
|
||||
? request.dir || useProjectTree.getState().listings.has(single)
|
||||
? tx`Move directory '${nameOf(single)}'`
|
||||
: tx`Move file '${nameOf(single)}'`
|
||||
: tx`Move ${request.paths.length} items`;
|
||||
const browse = async () => {
|
||||
setBrowsing(true);
|
||||
setBrowseError(null);
|
||||
try {
|
||||
const picked = await choosePath({ directory: true, title: tx("Select Target Directory"), defaultPath: dest });
|
||||
if (picked !== null) setTarget(ipcPath(picked));
|
||||
} catch (e) {
|
||||
setBrowseError(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
setBrowsing(false);
|
||||
}
|
||||
};
|
||||
const submit = async () => {
|
||||
if (busy || error) return;
|
||||
if (busy || browsing || error) return;
|
||||
saveOptions("move", options);
|
||||
const status = await run(moves, options, "Move");
|
||||
if (status !== "done") return;
|
||||
@@ -291,38 +322,59 @@ function MoveDialog({ request }: { request: Extract<FileRefactorRequest, { kind:
|
||||
width={520}
|
||||
footerStart={busy ? <Busy /> : undefined}
|
||||
buttons={[
|
||||
{ label: "Refactor", role: "default", disabled: busy || !!error, onClick: () => void submit() },
|
||||
{ label: "Refactor", role: "default", disabled: busy || browsing || !!error, onClick: () => void submit() },
|
||||
{ label: "Cancel", role: "cancel", onClick: cancel },
|
||||
]}
|
||||
>
|
||||
<form
|
||||
className={styles.form}
|
||||
className={styles.moveForm}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
void submit();
|
||||
}}
|
||||
>
|
||||
<div className={styles.subject}>{subject}</div>
|
||||
<label className={styles.fieldLabel} htmlFor="file-move-target">
|
||||
<T>To directory:</T>
|
||||
</label>
|
||||
<Input
|
||||
id="file-move-target"
|
||||
autoFocus
|
||||
mono
|
||||
value={target}
|
||||
disabled={busy}
|
||||
invalid={!!error}
|
||||
aria-label="Target directory"
|
||||
onChange={(e) => setTarget(e.target.value)}
|
||||
/>
|
||||
<div className={styles.hint}>{relativeTo(root, dest) || (dest === root ? tx("Project root") : dest)}</div>
|
||||
{error && (
|
||||
<div className={styles.error} role="alert">
|
||||
{error}
|
||||
<div className={styles.moveSubject}>{subject}</div>
|
||||
<div className={styles.moveDestination}>
|
||||
<label className={styles.fieldLabel} htmlFor="file-move-target">
|
||||
<T>To directory:</T>
|
||||
</label>
|
||||
<div className={styles.moveControls}>
|
||||
<div className={styles.moveField}>
|
||||
<Input
|
||||
id="file-move-target"
|
||||
ref={field}
|
||||
data-autofocus
|
||||
mono
|
||||
value={target}
|
||||
disabled={busy}
|
||||
invalid={!!error}
|
||||
aria-label="Target directory"
|
||||
aria-describedby="file-move-preview"
|
||||
onChange={(e) => {
|
||||
setBrowseError(null);
|
||||
setTarget(e.target.value);
|
||||
}}
|
||||
/>
|
||||
{isTauri() && (
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
title={tx("Browse for target directory")}
|
||||
disabled={busy || browsing}
|
||||
onClick={() => void browse()}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className={styles.movePath} id="file-move-preview" title={dest}>
|
||||
{relativeTo(root, dest) || (dest === root ? tx("Project root") : dest)}
|
||||
</div>
|
||||
{(browseError ?? error) && (
|
||||
<div className={styles.error} role="alert">
|
||||
{browseError ?? error}
|
||||
</div>
|
||||
)}
|
||||
<Options value={options} onChange={setOptions} move disabled={busy} />
|
||||
</div>
|
||||
)}
|
||||
<Options value={options} onChange={setOptions} move disabled={busy} />
|
||||
</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
flex: none;
|
||||
}
|
||||
.label {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
@@ -38,6 +39,11 @@
|
||||
white-space: pre;
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.lineNumber {
|
||||
flex: none;
|
||||
color: var(--fg-subtle);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.mnemonic {
|
||||
flex: none;
|
||||
display: inline-flex;
|
||||
|
||||
@@ -286,7 +286,9 @@ export function BookmarksView() {
|
||||
return (
|
||||
<span className={styles.node}>
|
||||
<Icon name="toolwindow-bookmarks" size={16} className={styles.icon} />
|
||||
<span className={clsx(styles.label, n.isDefault && styles.defaultList)}>{n.list.name}</span>
|
||||
<span className={clsx(styles.label, n.isDefault && styles.defaultList)} title={n.list.name}>
|
||||
{n.list.name}
|
||||
</span>
|
||||
<span className={styles.meta}>
|
||||
{t("search.bookmarks.count", { count: n.count })}
|
||||
{n.isDefault ? tx(" · default") : ""}
|
||||
@@ -297,7 +299,9 @@ export function BookmarksView() {
|
||||
return (
|
||||
<span className={styles.node}>
|
||||
<Icon name="folder" size={16} className={styles.icon} />
|
||||
<span className={styles.label}>{n.name}</span>
|
||||
<span className={styles.label} title={n.path}>
|
||||
{n.name}
|
||||
</span>
|
||||
<span className={styles.meta}>{n.dir}</span>
|
||||
</span>
|
||||
);
|
||||
@@ -305,38 +309,49 @@ export function BookmarksView() {
|
||||
return (
|
||||
<span className={styles.node}>
|
||||
<Icon name={fileIconName(n.name)} size={16} className={styles.icon} />
|
||||
<span className={styles.label}>{n.name}</span>
|
||||
<span className={styles.label} title={n.path}>
|
||||
{n.name}
|
||||
</span>
|
||||
{n.bookmarked && <Icon name="bookmark" size={12} className={styles.icon} label="Bookmarked file" />}
|
||||
<span className={styles.meta}>{n.dir}</span>
|
||||
</span>
|
||||
);
|
||||
case "mark":
|
||||
case "mark": {
|
||||
const { bookmark } = n;
|
||||
const line = bookmark.line + 1;
|
||||
const label = bookmarkLabel(bookmark) || tx("(empty line)");
|
||||
const isCommit = bookmark.path.startsWith("git-log:");
|
||||
const fileAndLine = `${basename(bookmark.path)}:${line}`;
|
||||
return (
|
||||
<span className={styles.node}>
|
||||
{n.bookmark.mnemonic ? (
|
||||
<span className={styles.mnemonic} aria-label={`Mnemonic ${n.bookmark.mnemonic}`}>
|
||||
{n.bookmark.mnemonic}
|
||||
{bookmark.mnemonic ? (
|
||||
<span className={styles.mnemonic} aria-label={`Mnemonic ${bookmark.mnemonic}`}>
|
||||
{bookmark.mnemonic}
|
||||
</span>
|
||||
) : (
|
||||
<Icon name="bookmark" size={16} className={styles.icon} />
|
||||
)}
|
||||
{n.bookmark.description ? (
|
||||
{isCommit && !bookmark.description ? (
|
||||
<>
|
||||
<span className={styles.label}>{n.bookmark.description}</span>
|
||||
<span className={styles.meta}>
|
||||
{basename(n.bookmark.path)}:{n.bookmark.line + 1}
|
||||
</span>
|
||||
<span className={styles.label}>{fileAndLine}</span>
|
||||
<span className={styles.code}>{label}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className={styles.label}>
|
||||
{basename(n.bookmark.path)}:{n.bookmark.line + 1}
|
||||
{!isCommit && (
|
||||
<span className={styles.lineNumber} title={`${bookmark.path}:${line}`}>
|
||||
{line}:
|
||||
</span>
|
||||
)}
|
||||
<span className={styles.label} title={label}>
|
||||
{label}
|
||||
</span>
|
||||
<span className={styles.code}>{n.bookmark.text.trim() || tx("(empty line)")}</span>
|
||||
{isCommit && <span className={styles.meta}>{fileAndLine}</span>}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -1790,6 +1790,7 @@ function ArtifactsSection() {
|
||||
|
||||
function SdksSection() {
|
||||
const byKind = useSdks((s) => s.byKind);
|
||||
const homeId = useId();
|
||||
const [downloading, setDownloading] = useState(false);
|
||||
const [selectedKey, setSelectedKey] = useState<string>("");
|
||||
const [projectJdk, setProjectJdk] = useProjectSetting<string>("languages.java.jdk");
|
||||
@@ -1860,7 +1861,7 @@ function SdksSection() {
|
||||
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<div className={styles.splitLayout}>
|
||||
<div className={clsx(styles.splitLayout, styles.sdkLayout)}>
|
||||
<div className={styles.sideList}>
|
||||
<div className={styles.tableToolbar}>
|
||||
<IconButton
|
||||
@@ -1902,6 +1903,7 @@ function SdksSection() {
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={activeSdk?.key === r.key}
|
||||
title={`${r.name}\n${tildify(r.path)}`}
|
||||
className={clsx(styles.sideItem, activeSdk?.key === r.key && styles.sideItemActive)}
|
||||
onClick={() => setSelectedKey(r.key)}
|
||||
>
|
||||
@@ -1914,73 +1916,49 @@ function SdksSection() {
|
||||
</div>
|
||||
|
||||
<div className={styles.detailPane}>
|
||||
{activeSdk ? (
|
||||
{activeSdk && (
|
||||
<Section title="SDK Details">
|
||||
<div className={styles.psModuleHeader}>
|
||||
<span className={styles.badge}>{activeSdk.kindLabel}</span>
|
||||
<span className={styles.psModuleTitle}>{activeSdk.name}</span>
|
||||
{activeSdk.version && <span className={styles.versionCell}>{activeSdk.version}</span>}
|
||||
<span className={styles.spacer} />
|
||||
{activeSdk.kind === "jdk" && (
|
||||
<Button
|
||||
size="small"
|
||||
variant="secondary"
|
||||
disabled={projectJdk === activeSdk.path}
|
||||
onClick={() => setProjectJdk(activeSdk.path)}
|
||||
>
|
||||
<T>Use as Project SDK</T>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<Row label="SDK home path">
|
||||
<Input readOnly value={tildify(activeSdk.path)} title={activeSdk.path} />
|
||||
</Row>
|
||||
<dl className={styles.sdkProperties}>
|
||||
<dt>
|
||||
<T>Name</T>
|
||||
</dt>
|
||||
<dd className={styles.sdkName}>{activeSdk.name}</dd>
|
||||
<dt>
|
||||
<T>Type</T>
|
||||
</dt>
|
||||
<dd>{activeSdk.kindLabel}</dd>
|
||||
<dt>
|
||||
<T>Version</T>
|
||||
</dt>
|
||||
<dd className={styles.versionCell}>{activeSdk.version || "—"}</dd>
|
||||
<dt>
|
||||
<label htmlFor={homeId}>
|
||||
<T>SDK home path</T>
|
||||
</label>
|
||||
</dt>
|
||||
<dd>
|
||||
<Input
|
||||
id={homeId}
|
||||
className={styles.sdkHome}
|
||||
readOnly
|
||||
value={tildify(activeSdk.path)}
|
||||
title={activeSdk.path}
|
||||
/>
|
||||
</dd>
|
||||
</dl>
|
||||
{activeSdk.kind === "jdk" && (
|
||||
<Button
|
||||
className={styles.sdkAction}
|
||||
size="small"
|
||||
variant="secondary"
|
||||
disabled={projectJdk === activeSdk.path}
|
||||
onClick={() => setProjectJdk(activeSdk.path)}
|
||||
>
|
||||
<T>Use as Project SDK</T>
|
||||
</Button>
|
||||
)}
|
||||
</Section>
|
||||
) : null}
|
||||
|
||||
<div className={styles.tablePanel}>
|
||||
<div className={styles.tableScroll}>
|
||||
<table className={styles.table}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>
|
||||
<T>Type</T>
|
||||
</th>
|
||||
<th>
|
||||
<T>Name</T>
|
||||
</th>
|
||||
<th>
|
||||
<T>Version</T>
|
||||
</th>
|
||||
<th>
|
||||
<T>Home Path</T>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={4} className={styles.empty}>
|
||||
<T>No SDK installations detected yet.</T>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{rows.map((r) => (
|
||||
<tr key={r.key} onClick={() => setSelectedKey(r.key)}>
|
||||
<td>
|
||||
<span className={styles.badge}>{r.kindLabel}</span>
|
||||
</td>
|
||||
<td>{r.name}</td>
|
||||
<td className={styles.versionCell}>{r.version || "—"}</td>
|
||||
<td className={styles.path} title={r.path}>
|
||||
{tildify(r.path)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{downloading && (
|
||||
|
||||
@@ -519,6 +519,55 @@
|
||||
gap: 10px;
|
||||
min-width: 0;
|
||||
}
|
||||
.sdkLayout {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-start;
|
||||
min-height: 0;
|
||||
}
|
||||
.sdkLayout > .sideList {
|
||||
flex: 1 1 160px;
|
||||
min-width: 0;
|
||||
}
|
||||
.sdkLayout > .detailPane {
|
||||
flex: 3 1 280px;
|
||||
}
|
||||
.sdkLayout .sideItems {
|
||||
max-height: min(360px, 42vh);
|
||||
}
|
||||
.sdkLayout .error {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.sdkProperties {
|
||||
display: grid;
|
||||
grid-template-columns: fit-content(40%) minmax(0, 1fr);
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
margin: 0;
|
||||
font-size: var(--fs-ui);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.sdkProperties dd {
|
||||
margin: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
.sdkName {
|
||||
color: var(--fg-strong);
|
||||
font-weight: 600;
|
||||
}
|
||||
.sdkHome {
|
||||
width: 100%;
|
||||
}
|
||||
.sdkLayout .sdkAction {
|
||||
justify-self: start;
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
min-height: var(--h-control);
|
||||
margin-top: var(--space-3);
|
||||
padding-block: var(--space-1);
|
||||
line-height: 1.3;
|
||||
white-space: normal;
|
||||
}
|
||||
.entryList {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -1,40 +1,26 @@
|
||||
.page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
max-width: 760px;
|
||||
}
|
||||
|
||||
.scheme {
|
||||
display: inline-flex;
|
||||
display: flex;
|
||||
flex: 1 1 100%;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: var(--space-1);
|
||||
margin: 8px 0 4px;
|
||||
margin: var(--space-2) 0 var(--space-2);
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
|
||||
.tab {
|
||||
height: 26px;
|
||||
padding: 0 10px;
|
||||
border: none;
|
||||
border-bottom: 2px solid transparent;
|
||||
background: none;
|
||||
color: var(--fg-secondary);
|
||||
font: inherit;
|
||||
cursor: default;
|
||||
}
|
||||
.tab:hover {
|
||||
color: var(--fg);
|
||||
}
|
||||
.tabOn {
|
||||
color: var(--fg);
|
||||
border-bottom-color: var(--accent);
|
||||
}
|
||||
.tab:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: inset 0 0 0 1px var(--accent);
|
||||
.panel {
|
||||
min-width: 0;
|
||||
padding-bottom: var(--space-3);
|
||||
}
|
||||
@@ -12,10 +12,17 @@ import { Button, Checkbox, Input, type SelectOption, T } from "@/ui";
|
||||
import { commands, isTauri, type LanguageInfo_Serialize as LanguageInfo } from "@/platform/ipc";
|
||||
import { ENCODING_CHOICES, lineCommentDefaults, type LanguageCodeStyle } from "@/platform/editorSettings";
|
||||
import { NATIVE_TO_ASCII_ACTION } from "../../nativeToAscii";
|
||||
import { NumberInput, Row, Select } from "../../components/Form";
|
||||
import { FormGroup, NumberInput, Row, Select, Toggle } from "../../components/Form";
|
||||
import { useSetting } from "../../components/context";
|
||||
import type { PageSpec } from "../spec";
|
||||
import { CODE_STYLE_SCOPE, CodeStyleMain, SchemeRow, formatterLabels } from "./codeStyleScheme";
|
||||
import {
|
||||
CODE_STYLE_SCOPE,
|
||||
CodeStyleMain,
|
||||
CodeStyleTabs,
|
||||
SchemeRow,
|
||||
formatterLabels,
|
||||
type CodeStyleTab,
|
||||
} from "./codeStyleScheme";
|
||||
import { editorPage, sectionLabels, type EditorSection } from "./kit";
|
||||
import styles from "./Editor.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
@@ -131,7 +138,19 @@ const OTHER = {
|
||||
...SCHEME_SCOPE,
|
||||
};
|
||||
|
||||
/** Tabs and Indents of one language: overrides on top of the language definition. */
|
||||
const INDENTS = {
|
||||
id: "indents",
|
||||
label: "Tabs and Indents",
|
||||
keywords: ["Tab size", "Indent", "Use tab character"],
|
||||
};
|
||||
const WRAPPING = { id: "wrapping", label: "Wrapping", keywords: ["Hard wrap at"] };
|
||||
const COMMENTS = {
|
||||
id: "comments",
|
||||
label: "Comment Code",
|
||||
keywords: ["Line comment at first column", "Add a space at line comment start"],
|
||||
};
|
||||
|
||||
/** Code Style overrides on top of the language definition. */
|
||||
function LanguageStyle({ lang }: { lang: LanguageInfo }) {
|
||||
const [all, setAll] = useSetting<Record<string, LanguageCodeStyle>>("editor.codeStyle.languages");
|
||||
const [tabSize] = useSetting<number>("editor.tabSize");
|
||||
@@ -156,42 +175,38 @@ function LanguageStyle({ lang }: { lang: LanguageInfo }) {
|
||||
delete next[lang.id];
|
||||
setAll(next);
|
||||
};
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<SchemeRow />
|
||||
{lang.id === "java" && <JavaFormatter style={own} onChange={set} />}
|
||||
<section aria-label={tx("Tabs and Indents")}>
|
||||
<div className={styles.previewTitle}>
|
||||
<T>Tabs and Indents</T>
|
||||
</div>
|
||||
<div className={styles.check}>
|
||||
<Checkbox checked={eff.useTab} onChange={(v) => set({ useTab: v })} label="Use tab character" />
|
||||
</div>
|
||||
<Row label="Tab size">
|
||||
<NumberInput
|
||||
value={eff.tabSize}
|
||||
onChange={(n) => set({ tabSize: n })}
|
||||
min={1}
|
||||
max={16}
|
||||
integer
|
||||
aria-label="Tab size"
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Indent">
|
||||
<NumberInput
|
||||
value={eff.indent}
|
||||
onChange={(n) => set({ indent: n })}
|
||||
min={1}
|
||||
max={16}
|
||||
integer
|
||||
aria-label="Indent"
|
||||
/>
|
||||
</Row>
|
||||
</section>
|
||||
<section aria-label={tx("Wrapping")}>
|
||||
<div className={styles.previewTitle}>
|
||||
<T>Wrapping</T>
|
||||
</div>
|
||||
const tabs: CodeStyleTab[] = [
|
||||
{
|
||||
...INDENTS,
|
||||
content: (
|
||||
<FormGroup>
|
||||
<Toggle checked={eff.useTab} onChange={(v) => set({ useTab: v })} label="Use tab character" />
|
||||
<Row label="Tab size">
|
||||
<NumberInput
|
||||
value={eff.tabSize}
|
||||
onChange={(n) => set({ tabSize: n })}
|
||||
min={1}
|
||||
max={16}
|
||||
integer
|
||||
aria-label="Tab size"
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Indent">
|
||||
<NumberInput
|
||||
value={eff.indent}
|
||||
onChange={(n) => set({ indent: n })}
|
||||
min={1}
|
||||
max={16}
|
||||
integer
|
||||
aria-label="Indent"
|
||||
/>
|
||||
</Row>
|
||||
</FormGroup>
|
||||
),
|
||||
},
|
||||
{
|
||||
...WRAPPING,
|
||||
content: (
|
||||
<Row label="Hard wrap at" hint="Shown as the right margin guide in the editor.">
|
||||
<NumberInput
|
||||
value={eff.hardWrapAt}
|
||||
@@ -203,7 +218,33 @@ function LanguageStyle({ lang }: { lang: LanguageInfo }) {
|
||||
unit="columns"
|
||||
/>
|
||||
</Row>
|
||||
</section>
|
||||
),
|
||||
},
|
||||
];
|
||||
if (lang.lineComment) {
|
||||
tabs.push({
|
||||
...COMMENTS,
|
||||
content: (
|
||||
<>
|
||||
<Toggle
|
||||
checked={eff.lineCommentAtFirstColumn}
|
||||
onChange={(v) => set({ lineCommentAtFirstColumn: v })}
|
||||
label="Line comment at first column"
|
||||
/>
|
||||
<Toggle
|
||||
checked={eff.lineCommentAddSpace}
|
||||
onChange={(v) => set({ lineCommentAddSpace: v })}
|
||||
label="Add a space at line comment start"
|
||||
/>
|
||||
</>
|
||||
),
|
||||
});
|
||||
}
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<SchemeRow />
|
||||
{lang.id === "java" && <JavaFormatter style={own} onChange={set} />}
|
||||
<CodeStyleTabs tabs={tabs} />
|
||||
{lang.id === "php" && (
|
||||
<section aria-label={tx("Alignment")}>
|
||||
<div className={styles.previewTitle}>
|
||||
@@ -230,27 +271,6 @@ function LanguageStyle({ lang }: { lang: LanguageInfo }) {
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
{lang.lineComment && (
|
||||
<section aria-label={tx("Comment Code")}>
|
||||
<div className={styles.previewTitle}>
|
||||
<T>Comment Code</T>
|
||||
</div>
|
||||
<div className={styles.check}>
|
||||
<Checkbox
|
||||
checked={eff.lineCommentAtFirstColumn}
|
||||
onChange={(v) => set({ lineCommentAtFirstColumn: v })}
|
||||
label="Line comment at first column"
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.check}>
|
||||
<Checkbox
|
||||
checked={eff.lineCommentAddSpace}
|
||||
onChange={(v) => set({ lineCommentAddSpace: v })}
|
||||
label="Add a space at line comment start"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
<div className={styles.schemeRow}>
|
||||
<Button size="small" disabled={!all?.[lang.id]} onClick={reset}>
|
||||
<T>Reset to Language Defaults</T>
|
||||
@@ -337,13 +357,10 @@ export async function codeStyleLanguagePages(): Promise<PageSpec[]> {
|
||||
...SCHEME_SCOPE,
|
||||
keywords: [
|
||||
"Scheme",
|
||||
"Tabs and Indents",
|
||||
"Tab size",
|
||||
"Indent",
|
||||
"Use tab character",
|
||||
"Hard wrap at",
|
||||
"Comment Code",
|
||||
"Line comment at first column",
|
||||
...[INDENTS, WRAPPING, ...(lang.lineComment ? [COMMENTS] : [])].flatMap(({ label, keywords }) => [
|
||||
label,
|
||||
...keywords,
|
||||
]),
|
||||
...(lang.id === "java"
|
||||
? ["Formatting profile", "IntelliJ IDEA", "Custom Eclipse formatter XML", "Eclipse formatter XML"]
|
||||
: []),
|
||||
|
||||
@@ -4,17 +4,16 @@
|
||||
* and its language pages (`scopeGroup`); "Copy to Project" / "Copy to IDE"
|
||||
* stage every Code Style value in the other scope.
|
||||
*/
|
||||
import { useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { Button, T, type SelectOption } from "@/ui";
|
||||
import { useId, useState, type ReactNode } from "react";
|
||||
import { Button, T, Tabs, type SelectOption } from "@/ui";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { GlobListEditor, Row, Select } from "../../components/Form";
|
||||
import { usePageContext, useSetting } from "../../components/context";
|
||||
import { usePageContext, useSearchQuery, useSetting } from "../../components/context";
|
||||
import { labelMatches, queryTerms } from "../../model/pages";
|
||||
import { setPageScope, stage, stagedValue, useSettingsDialog, type Scope } from "../../model/staging";
|
||||
import { EditorSections, sectionLabels, type EditorSection } from "./kit";
|
||||
import { PluginFormattersSection } from "./pluginFormatters";
|
||||
import styles from "./CodeStyle.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
export const CODE_STYLE_SCOPE = "editor.codeStyle";
|
||||
|
||||
@@ -115,39 +114,88 @@ export const FORMATTER_SECTIONS: EditorSection[] = [
|
||||
],
|
||||
},
|
||||
];
|
||||
const FORMATTER_LABELS = [...sectionLabels(FORMATTER_SECTIONS), "Plugin Formatters"];
|
||||
|
||||
type Tab = "general" | "formatter";
|
||||
export interface CodeStyleTab {
|
||||
id: string;
|
||||
label: string;
|
||||
keywords: readonly string[];
|
||||
content: ReactNode;
|
||||
}
|
||||
|
||||
export function CodeStyleTabs({ tabs }: { tabs: CodeStyleTab[] }) {
|
||||
const query = useSearchQuery();
|
||||
const prefix = useId();
|
||||
const [selection, select] = useState({ id: tabs[0]!.id, query: "" });
|
||||
let active = tabs.find((tab) => tab.id === selection.id)?.id ?? tabs[0]!.id;
|
||||
if (query !== selection.query) {
|
||||
const terms = queryTerms(query);
|
||||
let best = 0;
|
||||
for (const tab of tabs) {
|
||||
const labels = [tab.label, ...tab.keywords];
|
||||
const score = terms.filter((term) => labels.some((label) => labelMatches(label, term))).length;
|
||||
if (score > best) {
|
||||
active = tab.id;
|
||||
best = score;
|
||||
}
|
||||
}
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<Tabs
|
||||
aria-label="Code Style"
|
||||
variant="compact"
|
||||
layout="wrap"
|
||||
className={styles.tabs}
|
||||
items={tabs.map(({ id, label }) => ({ id, label }))}
|
||||
activeId={active}
|
||||
panelIdPrefix={prefix}
|
||||
onSelect={(id) => select({ id, query })}
|
||||
/>
|
||||
{tabs.map(({ id, content }) => (
|
||||
<div
|
||||
key={id}
|
||||
role="tabpanel"
|
||||
id={`${prefix}-panel-${id}`}
|
||||
aria-labelledby={`${prefix}-tab-${id}`}
|
||||
className={styles.panel}
|
||||
hidden={id !== active}
|
||||
>
|
||||
{id === active && content}
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Code Style: Scheme, then the General / Formatter tabs. */
|
||||
export function CodeStyleMain({ general }: { general: EditorSection[] }) {
|
||||
const [tab, setTab] = useState<Tab>("general");
|
||||
const tabs: Array<[Tab, string]> = [
|
||||
["general", "General"],
|
||||
["formatter", "Formatter"],
|
||||
];
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<SchemeRow />
|
||||
<div className={styles.tabs} role="tablist" aria-label={tx("Code Style")}>
|
||||
{tabs.map(([id, label]) => (
|
||||
<button
|
||||
key={id}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={tab === id}
|
||||
className={clsx(styles.tab, tab === id && styles.tabOn)}
|
||||
onClick={() => setTab(id)}
|
||||
>
|
||||
<T>{label}</T>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div role="tabpanel">
|
||||
<EditorSections sections={tab === "general" ? general : FORMATTER_SECTIONS} />
|
||||
{tab === "formatter" && <PluginFormattersSection />}
|
||||
</div>
|
||||
<CodeStyleTabs
|
||||
tabs={[
|
||||
{
|
||||
id: "general",
|
||||
label: "General",
|
||||
keywords: sectionLabels(general),
|
||||
content: <EditorSections sections={general} />,
|
||||
},
|
||||
{
|
||||
id: "formatter",
|
||||
label: "Formatter",
|
||||
keywords: FORMATTER_LABELS,
|
||||
content: (
|
||||
<>
|
||||
<EditorSections sections={FORMATTER_SECTIONS} />
|
||||
<PluginFormattersSection />
|
||||
</>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const formatterLabels = () => ["Scheme", "Formatter", ...sectionLabels(FORMATTER_SECTIONS), "Plugin Formatters"];
|
||||
export const formatterLabels = () => ["Scheme", "Formatter", ...FORMATTER_LABELS];
|
||||
@@ -772,6 +772,7 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
|
||||
{mode === "local" && <IconButton icon="commit" action="vcs.commit" size="small" />}
|
||||
<IconButton icon="undo" action="vcs.rollback" size="small" />
|
||||
{mode === "local" && <IconButton icon="changelist" action="vcs.changelist.new" size="small" />}
|
||||
{mode !== "dialog" && <IconButton icon="shelve" action="vcs.shelveSilently" size="small" />}
|
||||
{mode !== "dialog" && <IconButton icon="git-pull" action="vcs.update" size="small" />}
|
||||
<IconButton
|
||||
ref={viewRef}
|
||||
|
||||
@@ -5,6 +5,9 @@
|
||||
display: flex;
|
||||
background: var(--bg-app);
|
||||
}
|
||||
.resizable {
|
||||
min-width: 0;
|
||||
}
|
||||
.sidebar {
|
||||
flex: none;
|
||||
width: 260px;
|
||||
@@ -18,7 +21,7 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: 0 8px 0 12px;
|
||||
padding: 0 var(--space-2) 0 var(--space-3);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.title {
|
||||
@@ -26,6 +29,14 @@
|
||||
color: var(--fg-emphasis);
|
||||
font-weight: 500;
|
||||
}
|
||||
.resizable .title {
|
||||
min-width: 0;
|
||||
font-size: var(--fs-ui);
|
||||
font-weight: 600;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.list {
|
||||
flex: 1;
|
||||
}
|
||||
@@ -35,14 +46,36 @@
|
||||
min-width: 0;
|
||||
gap: var(--space-0-5);
|
||||
}
|
||||
.time {
|
||||
color: var(--fg-emphasis);
|
||||
.resizable .entry {
|
||||
width: 100%;
|
||||
line-height: 1.2;
|
||||
}
|
||||
.label {
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
.primaryRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
color: var(--fg-strong);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
.primary,
|
||||
.meta,
|
||||
.path,
|
||||
.deletedPath {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.meta,
|
||||
.path,
|
||||
.deletedPath {
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.meta {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.deletedPath {
|
||||
text-decoration: line-through;
|
||||
}
|
||||
.diff {
|
||||
flex: 1;
|
||||
@@ -51,33 +84,11 @@
|
||||
flex-direction: column;
|
||||
}
|
||||
.message {
|
||||
padding: 16px;
|
||||
padding: var(--space-4);
|
||||
color: var(--fg-faint);
|
||||
text-align: center;
|
||||
}
|
||||
.path,
|
||||
.deletedPath {
|
||||
color: var(--fg);
|
||||
font-size: var(--fs-small);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.deletedPath {
|
||||
color: var(--fg-muted);
|
||||
text-decoration: line-through;
|
||||
}
|
||||
.labelRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
min-width: 0;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.labelName {
|
||||
font-size: var(--fs-small);
|
||||
font-weight: 500;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
.resizable .message {
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import type { HistoryEntry } from "@/bindings";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { relativePath, useProject } from "@/platform/project";
|
||||
import { Button, Icon, List, Spinner, T } from "@/ui";
|
||||
import { Button, Icon, List, Spinner, SplitGroup, SplitHandle, SplitPanel, T } from "@/ui";
|
||||
import { notifications, type EditorInput } from "@/workbench/contributions";
|
||||
import { DiffEditor } from "./DiffEditor";
|
||||
import { confirmDialog } from "./dialogs";
|
||||
@@ -70,6 +70,19 @@ export function LocalHistoryEditor({ input }: { input: EditorInput }) {
|
||||
const anchor = useRef(0);
|
||||
const previous = useRef(0);
|
||||
const pointer = useRef(false);
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const [stacked, setStacked] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const el = container.current;
|
||||
if (!el || typeof ResizeObserver === "undefined") return;
|
||||
const observer = new ResizeObserver(([entry]) => {
|
||||
const width = entry?.contentRect.width;
|
||||
if (width) setStacked(width < 620);
|
||||
});
|
||||
observer.observe(el);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
const load = useCallback(() => {
|
||||
call(commands.historyListDir(path))
|
||||
@@ -197,9 +210,17 @@ export function LocalHistoryEditor({ input }: { input: EditorInput }) {
|
||||
const revertLabel = current && !isLabel(current) && view?.deleted.has(current.path) ? "Restore" : "Revert";
|
||||
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<div
|
||||
className={styles.sidebar}
|
||||
<SplitGroup
|
||||
elementRef={container}
|
||||
className={`${styles.root} ${styles.resizable}`}
|
||||
orientation={stacked ? "vertical" : "horizontal"}
|
||||
storageKey="openidea.localHistory.layout"
|
||||
>
|
||||
<SplitPanel
|
||||
id="revisions"
|
||||
defaultSize="28%"
|
||||
minSize={stacked ? "24%" : "160px"}
|
||||
maxSize="52%"
|
||||
onMouseDownCapture={(e) => {
|
||||
pointer.current = e.button === 0 && !!(e.target as Element).closest('[role="option"]');
|
||||
}}
|
||||
@@ -253,7 +274,7 @@ export function LocalHistoryEditor({ input }: { input: EditorInput }) {
|
||||
setExtra(new Set());
|
||||
}
|
||||
}}
|
||||
rowHeight={view.folder ? 52 : 38}
|
||||
rowHeight={view.folder ? 56 : 44}
|
||||
aria-label="Revisions"
|
||||
className={styles.list}
|
||||
empty={
|
||||
@@ -261,33 +282,36 @@ export function LocalHistoryEditor({ input }: { input: EditorInput }) {
|
||||
{view.folder ? tx`No local history for this folder yet` : tx`No local history for this path yet`}
|
||||
</span>
|
||||
}
|
||||
renderItem={(e) =>
|
||||
isLabel(e) ? (
|
||||
renderItem={(e) => {
|
||||
const label = isLabel(e);
|
||||
const pathText = !label && view.folder ? relativePath(root, e.path) || baseName(e.path) : null;
|
||||
return (
|
||||
<span className={styles.entry}>
|
||||
<span className={styles.time}>{formatTime(e.timestampMs)}</span>
|
||||
<span className={styles.labelRow}>
|
||||
<Icon name="bookmark" size={12} />
|
||||
<span className={styles.labelName}>{e.label}</span>
|
||||
<span className={styles.primaryRow}>
|
||||
{label && <Icon name="bookmark" size={12} />}
|
||||
<span className={styles.primary} title={e.label}>
|
||||
{e.label}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
) : (
|
||||
<span className={styles.entry}>
|
||||
<span className={styles.time}>{formatTime(e.timestampMs)}</span>
|
||||
{view.folder && (
|
||||
<span className={view.deleted.has(e.path) ? styles.deletedPath : styles.path}>
|
||||
{relativePath(root, e.path) || baseName(e.path)}
|
||||
{pathText && (
|
||||
<span className={view.deleted.has(e.path) ? styles.deletedPath : styles.path} title={pathText}>
|
||||
{pathText}
|
||||
</span>
|
||||
)}
|
||||
<span className={styles.label}>
|
||||
{e.label} · {formatSize(e.size)}
|
||||
<span className={styles.meta}>
|
||||
{formatTime(e.timestampMs)}
|
||||
{!label && ` · ${formatSize(e.size)}`}
|
||||
</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className={styles.diff}>{detail}</div>
|
||||
</div>
|
||||
</SplitPanel>
|
||||
<SplitHandle aria-label={tx("Revisions")} />
|
||||
<SplitPanel id="preview" defaultSize="72%">
|
||||
{detail}
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
.form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-4);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
|
||||
.source,
|
||||
.command {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.source > .repository {
|
||||
flex: 1 1 124px;
|
||||
}
|
||||
|
||||
.command,
|
||||
.noRemotes {
|
||||
flex: 4 1 352px;
|
||||
}
|
||||
|
||||
.verb {
|
||||
flex: none;
|
||||
color: var(--fg-secondary);
|
||||
font-family: var(--font-mono);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.command > .remote {
|
||||
flex: 1 1 104px;
|
||||
}
|
||||
|
||||
.command > .branch {
|
||||
flex: 3 1 208px;
|
||||
}
|
||||
|
||||
.flags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.flags > code {
|
||||
padding: var(--space-0-5) var(--space-1-5);
|
||||
border-radius: var(--radius-control);
|
||||
background: var(--bg-field);
|
||||
color: var(--fg-secondary);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { registerAction, registerActions } from "@/platform/actions";
|
||||
import { clearContext, setContext } from "@/platform/context";
|
||||
import { menuGroupItems, provideNotificationService } from "@/workbench/contributions";
|
||||
import type { MenuItem } from "@/ui";
|
||||
import { copyRepositoryPathActions, registerCopyRepositoryPath } from "../copyRepositoryPath";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
const writeText = vi.fn(async (_text: string) => undefined);
|
||||
const hint = vi.fn();
|
||||
const notify = vi.fn();
|
||||
const disposers: Array<() => void> = [];
|
||||
|
||||
type Item = Extract<MenuItem, { kind?: "item" }>;
|
||||
const items = (paths: string[]) =>
|
||||
menuGroupItems("copyPath", { paths }).filter(
|
||||
(i): i is Item => i.kind !== "separator" && "run" in i && i.id === "vcs.copyRepositoryPath",
|
||||
);
|
||||
const preview = (paths: string[]) => items(paths)[0]?.preview;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.stubGlobal("navigator", { clipboard: { writeText }, userAgent: navigator.userAgent });
|
||||
provideNotificationService({ notify });
|
||||
setContext("vcsAvailable", true);
|
||||
useVcs.setState({ roots: ["/w/api", "/w/web", "/w/api/third_party/lib"] });
|
||||
disposers.push(
|
||||
registerActions(copyRepositoryPathActions),
|
||||
registerCopyRepositoryPath(),
|
||||
registerAction({ id: "editor.showHint", title: "Hint", run: ({ arg }) => hint(arg) }),
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
disposers
|
||||
.splice(0)
|
||||
.reverse()
|
||||
.forEach((dispose) => dispose());
|
||||
useVcs.setState({ roots: [] });
|
||||
clearContext("vcsAvailable");
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("Copy Path/Reference… › Path From Repository Root", () => {
|
||||
it("offers the file's path from its repository's root and copies it", async () => {
|
||||
const [item] = items(["/w/api/internal/server.go"]);
|
||||
expect(item).toMatchObject({
|
||||
id: "vcs.copyRepositoryPath",
|
||||
label: "Path From Repository Root",
|
||||
preview: "internal/server.go",
|
||||
});
|
||||
item!.run!();
|
||||
await vi.waitFor(() => expect(hint).toHaveBeenCalledWith({ text: "Copied internal/server.go" }));
|
||||
expect(writeText).toHaveBeenCalledExactlyOnceWith("internal/server.go");
|
||||
});
|
||||
|
||||
it("uses the innermost repository and gives each path its own repository, one per line", () => {
|
||||
expect(preview(["/w/api/third_party/lib/a.go"])).toBe("a.go");
|
||||
expect(preview(["/w/api/main.go", "/w/web/src/app.ts"])).toBe("main.go\nsrc/app.ts");
|
||||
});
|
||||
|
||||
it("copies a repository's root as '.' and ignores a trailing slash", () => {
|
||||
expect(preview(["/w/api"])).toBe(".");
|
||||
expect(preview(["/w/api/"])).toBe(".");
|
||||
expect(preview(["/w/api/third_party/lib"])).toBe(".");
|
||||
expect(preview(["/w/web/src/"])).toBe("src");
|
||||
});
|
||||
|
||||
it("leaves out paths outside every repository, and offers nothing when none is inside one", () => {
|
||||
expect(preview(["/w/api/a.go", "/w/notes.md", "/w/web/b.ts"])).toBe("a.go\nb.ts");
|
||||
expect(items(["/w/notes.md"])).toEqual([]);
|
||||
expect(items(["/w/api2/a.go"])).toEqual([]);
|
||||
expect(items(["/w/notes.md", "/w/api2/a.go"])).toEqual([]);
|
||||
expect(items([])).toEqual([]);
|
||||
useVcs.setState({ roots: [] });
|
||||
expect(items(["/w/api/a.go"])).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports a clipboard it cannot write to", async () => {
|
||||
writeText.mockRejectedValueOnce(new Error("denied"));
|
||||
items(["/w/api/a.go"])[0]!.run!();
|
||||
await vi.waitFor(() =>
|
||||
expect(notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ level: "error", title: "Cannot access the clipboard", body: "denied" }),
|
||||
),
|
||||
);
|
||||
expect(hint).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,7 @@ const mocks = vi.hoisted(() => ({
|
||||
patch: vi.fn(),
|
||||
probe: vi.fn(),
|
||||
unshelve: vi.fn(),
|
||||
shelve: vi.fn(),
|
||||
}));
|
||||
vi.mock("../diffInput", async (original) => ({
|
||||
...(await original<typeof import("../diffInput")>()),
|
||||
@@ -30,18 +31,32 @@ vi.mock("@/platform/ipc", async (original) => ({
|
||||
fsProbe: mocks.probe,
|
||||
vcsShelfPatch: mocks.patch,
|
||||
vcsUnshelve: mocks.unshelve,
|
||||
vcsShelve: mocks.shelve,
|
||||
},
|
||||
}));
|
||||
import { ShelfPanel, copyShelfPatch, shelfDiffs, shelfTarget, showShelfDiff, unshelve, useShelf } from "../shelf";
|
||||
import {
|
||||
ShelfPanel,
|
||||
copyShelfPatch,
|
||||
shelfDiffs,
|
||||
shelfTarget,
|
||||
shelveSilently,
|
||||
showShelfDiff,
|
||||
unshelve,
|
||||
unshelveSilently,
|
||||
useShelf,
|
||||
} from "../shelf";
|
||||
import { useCommit } from "../commitStore";
|
||||
import { useVcs } from "../store";
|
||||
import { useChangelists } from "../changelists";
|
||||
import { VcsDialogHost } from "../dialogs";
|
||||
import { ContextMenuHost } from "@/ui";
|
||||
import { registerVcsActions } from "../actions";
|
||||
import { registerHistoryActions } from "../historyActions";
|
||||
import { getAction, isActionKeyEnabled } from "@/platform/actions";
|
||||
import { intellijWindows } from "@/platform/keymaps/intellij-windows";
|
||||
import { intellijMacos } from "@/platform/keymaps/intellij-macos";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { setContext } from "@/platform/context";
|
||||
|
||||
const entry: ShelvedChangeList = {
|
||||
id: "work",
|
||||
@@ -255,3 +270,154 @@ describe("shelf scope and diffs", () => {
|
||||
expect(mocks.execute).toHaveBeenCalledWith("vcs.shelf.copyPatch", { id: "work", path: "a.txt" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Shelve Silently / Unshelve Silently", () => {
|
||||
const change = (path: string) => ({
|
||||
path,
|
||||
relPath: path,
|
||||
staged: null,
|
||||
unstaged: "modified" as const,
|
||||
renamedFrom: null,
|
||||
});
|
||||
const lists = (files: Record<string, string> = {}, active = "default") =>
|
||||
useChangelists.setState({
|
||||
loaded: false,
|
||||
state: {
|
||||
lists: [
|
||||
{ id: "default", name: "Changes", comment: "" },
|
||||
{ id: "work", name: "Work", comment: "" },
|
||||
],
|
||||
active,
|
||||
files,
|
||||
},
|
||||
});
|
||||
beforeEach(() => {
|
||||
mocks.ipc.mockReset().mockImplementation(async (value: unknown) => (await value) ?? []);
|
||||
mocks.shelve.mockImplementation(async (name: string, paths: string[]) => ({
|
||||
...entry,
|
||||
id: name,
|
||||
name,
|
||||
files: paths.map((path) => ({ path, kind: "modified", oldPath: null })),
|
||||
}));
|
||||
mocks.unshelve.mockResolvedValue({ applied: ["a.txt"], conflicts: [] });
|
||||
useVcs.setState({
|
||||
root: "/repo",
|
||||
roots: ["/repo"],
|
||||
available: true,
|
||||
status: [change("/repo/a.txt"), change("/repo/b.txt"), change("/repo/c.txt")],
|
||||
});
|
||||
useProject.setState({ settings: {} });
|
||||
});
|
||||
|
||||
it("shelves the selected changes without a dialog, one shelf per changelist named after it", async () => {
|
||||
lists({ "b.txt": "work" });
|
||||
render(<VcsDialogHost />);
|
||||
await act(() => shelveSilently(["/repo/a.txt", "/repo/b.txt"]));
|
||||
expect(mocks.shelve.mock.calls).toEqual([
|
||||
["Changes", ["/repo/a.txt"]],
|
||||
["Work", ["/repo/b.txt"]],
|
||||
]);
|
||||
expect(screen.queryByRole("dialog")).toBeNull();
|
||||
});
|
||||
|
||||
it("shelves the active changelist's changes when nothing is selected", async () => {
|
||||
lists({ "a.txt": "default", "b.txt": "work", "c.txt": "work" }, "work");
|
||||
await shelveSilently();
|
||||
expect(mocks.shelve.mock.calls).toEqual([["Work", ["/repo/b.txt", "/repo/c.txt"]]]);
|
||||
});
|
||||
|
||||
it("names the shelf like the Shelve dialog when the project has one changelist", async () => {
|
||||
useChangelists.setState({
|
||||
loaded: false,
|
||||
state: { lists: [{ id: "default", name: "Changes", comment: "" }], active: "default", files: {} },
|
||||
});
|
||||
await shelveSilently(["/repo/a.txt"]);
|
||||
expect(mocks.shelve.mock.calls).toEqual([["Uncommitted changes", ["/repo/a.txt"]]]);
|
||||
});
|
||||
|
||||
it("shelves nothing when there are no changes", async () => {
|
||||
lists();
|
||||
useVcs.setState({ status: [] });
|
||||
await shelveSilently();
|
||||
await shelveSilently(["/repo/missing.txt"]);
|
||||
expect(mocks.shelve).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stops after a shelf fails so later changelists stay in the working tree", async () => {
|
||||
lists({ "b.txt": "work" });
|
||||
mocks.shelve.mockRejectedValueOnce(new Error("disk full"));
|
||||
await shelveSilently(["/repo/a.txt", "/repo/b.txt"]);
|
||||
expect(mocks.shelve).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("ignores the Changes tab's selection while another Commit tab is shown", async () => {
|
||||
lists();
|
||||
const off = registerHistoryActions();
|
||||
setContext("activeToolWindow", "commit");
|
||||
useCommit.setState({ tab: "stashes", selection: ["/repo/b.txt"] });
|
||||
try {
|
||||
await getAction("vcs.shelveSilently")!.run({ ctx: {} });
|
||||
expect(mocks.shelve).not.toHaveBeenCalled();
|
||||
useCommit.setState({ tab: "changes" });
|
||||
await getAction("vcs.shelveSilently")!.run({ ctx: {} });
|
||||
expect(mocks.shelve.mock.calls).toEqual([["Changes", ["/repo/b.txt"]]]);
|
||||
} finally {
|
||||
off();
|
||||
setContext("activeToolWindow", null);
|
||||
useCommit.setState({ tab: "changes", selection: [] });
|
||||
}
|
||||
});
|
||||
|
||||
it("does nothing for a shelf without files", async () => {
|
||||
lists();
|
||||
await unshelveSilently({ ...entry, files: [] });
|
||||
expect(mocks.unshelve).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("unshelves into the changelist named like the shelf, without a dialog", async () => {
|
||||
lists();
|
||||
render(<VcsDialogHost />);
|
||||
await act(() => unshelveSilently(entry));
|
||||
expect(mocks.unshelve).toHaveBeenCalledWith("work", false, null);
|
||||
expect(screen.queryByRole("dialog")).toBeNull();
|
||||
expect(useChangelists.getState().state.files).toEqual({ "a.txt": "work" });
|
||||
});
|
||||
|
||||
it("unshelves into the active changelist when no changelist has the shelf's name", async () => {
|
||||
lists({}, "default");
|
||||
await unshelveSilently({ ...entry, name: "Experiment" });
|
||||
expect(useChangelists.getState().state.files).toEqual({ "a.txt": "default" });
|
||||
});
|
||||
|
||||
it("unshelves only the selected file and follows the remove-applied setting", async () => {
|
||||
lists();
|
||||
useProject.setState({ settings: { vcs: { shelf: { removeApplied: true } } } });
|
||||
await unshelveSilently(entry, "b.txt");
|
||||
expect(mocks.unshelve.mock.calls).toEqual([["work", true, "b.txt"]]);
|
||||
});
|
||||
|
||||
it("binds IDEA's shortcuts to the Commit tool window and the focused Shelf", async () => {
|
||||
const off = registerHistoryActions();
|
||||
try {
|
||||
const shelve = getAction("vcs.shelveSilently")!;
|
||||
const unshelveAction = getAction("vcs.unshelveSilently")!;
|
||||
expect(intellijWindows[shelve.id]).toEqual(["Ctrl+Shift+H"]);
|
||||
expect(intellijMacos[shelve.id]).toEqual(["Meta+Shift+H"]);
|
||||
expect(intellijWindows[unshelveAction.id]).toEqual(["Ctrl+Alt+U"]);
|
||||
expect(intellijMacos[unshelveAction.id]).toEqual(["Meta+Alt+U"]);
|
||||
expect(isActionKeyEnabled(shelve, { vcsAvailable: true, activeToolWindow: "commit" })).toBe(true);
|
||||
expect(isActionKeyEnabled(shelve, { vcsAvailable: true, activeToolWindow: "git" })).toBe(true);
|
||||
expect(isActionKeyEnabled(shelve, { vcsAvailable: true, activeToolWindow: "commit", shelfFocus: true })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(isActionKeyEnabled(shelve, { vcsAvailable: true, editorTextFocus: true })).toBe(false);
|
||||
expect(isActionKeyEnabled(unshelveAction, { vcsAvailable: true, shelfFocus: true })).toBe(true);
|
||||
expect(isActionKeyEnabled(unshelveAction, { vcsAvailable: true, editorTextFocus: true })).toBe(false);
|
||||
lists();
|
||||
await unshelveAction.run({ ctx: {}, arg: { id: "work", path: "a.txt" } });
|
||||
expect(mocks.unshelve).toHaveBeenCalledWith("work", false, "a.txt");
|
||||
} finally {
|
||||
off();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
/** Local change operations: commit, rollback, add, stash. */
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useId, useState } from "react";
|
||||
import type { FileStatus, Stash } from "@/bindings";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { Checkbox, Dialog, Icon, IconButton, Input, T, fileIconName } from "@/ui";
|
||||
@@ -367,7 +367,9 @@ function StashDialog({
|
||||
const [message, setMessage] = useState("");
|
||||
const [keepIndex, setKeepIndex] = useState(false);
|
||||
const [includeUntracked, setIncludeUntracked] = useState(false);
|
||||
const showRepo = useVcs((s) => pickRepo && s.roots.length > 1);
|
||||
const branch = useBranchInfo(repo)?.head ?? null;
|
||||
const messageId = useId();
|
||||
const submit = () => onDone({ repo, message: message.trim(), keepIndex, includeUntracked });
|
||||
return (
|
||||
<Dialog
|
||||
@@ -381,26 +383,38 @@ function StashDialog({
|
||||
]}
|
||||
>
|
||||
<form
|
||||
className={styles.form}
|
||||
className={`${styles.form} ${styles.stashForm}`}
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
submit();
|
||||
}}
|
||||
>
|
||||
{pickRepo && <RepoPicker repo={repo} onChange={setRepo} />}
|
||||
{branch && <div className={styles.hint}>{tx`Current branch: ${branch}`}</div>}
|
||||
<label className={styles.fieldLabel}>
|
||||
<T>Message:</T>
|
||||
</label>
|
||||
<Input
|
||||
data-autofocus
|
||||
aria-label="Message"
|
||||
placeholder="WIP"
|
||||
value={message}
|
||||
onChange={(e) => setMessage(e.target.value)}
|
||||
/>
|
||||
<Checkbox checked={keepIndex} onChange={setKeepIndex} label="Keep index" />
|
||||
<Checkbox checked={includeUntracked} onChange={setIncludeUntracked} label="Include untracked files" />
|
||||
{showRepo && (
|
||||
<div className={styles.stashRepo}>
|
||||
<T>Repository:</T>
|
||||
<RepoPicker repo={repo} onChange={setRepo} />
|
||||
</div>
|
||||
)}
|
||||
{branch && <div className={styles.stashBranch}>{tx`Current branch: ${branch}`}</div>}
|
||||
<div className={styles.stashMessage}>
|
||||
<label htmlFor={messageId}>
|
||||
<T>Message:</T>
|
||||
</label>
|
||||
<textarea
|
||||
id={messageId}
|
||||
className={styles.textarea}
|
||||
data-autofocus
|
||||
aria-label={tx("Message")}
|
||||
placeholder={tx("WIP")}
|
||||
rows={3}
|
||||
value={message}
|
||||
onChange={(e) => setMessage(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.stashOptions}>
|
||||
<Checkbox checked={keepIndex} onChange={setKeepIndex} label="Keep index" />
|
||||
<Checkbox checked={includeUntracked} onChange={setIncludeUntracked} label="Include untracked files" />
|
||||
</div>
|
||||
</form>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
@@ -25,52 +25,61 @@
|
||||
display: flex;
|
||||
}
|
||||
.sidebar {
|
||||
flex: 0 0 224px;
|
||||
padding: 8px 0;
|
||||
flex: 0 0 200px;
|
||||
padding: var(--space-2) 0;
|
||||
border-right: 1px solid var(--border);
|
||||
background: color-mix(in srgb, var(--bg-dialog, var(--bg-elev)) 96%, var(--fg-strong));
|
||||
overflow: auto;
|
||||
}
|
||||
.sourceItem {
|
||||
min-height: 44px;
|
||||
min-height: var(--h-row);
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
padding: 9px 14px;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-1) var(--space-3);
|
||||
width: 100%;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--fg-strong);
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: default;
|
||||
}
|
||||
.sourceItem[data-selected] {
|
||||
background: var(--bg-tree-selected);
|
||||
}
|
||||
.sourceName {
|
||||
font-weight: 600;
|
||||
line-height: 22px;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
font-weight: 500;
|
||||
font-size: var(--fs-ui);
|
||||
line-height: 1.4;
|
||||
}
|
||||
.form {
|
||||
--clone-label-width: 112px;
|
||||
--clone-field-gap: var(--space-3);
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-4);
|
||||
padding: 28px 24px;
|
||||
gap: var(--space-3);
|
||||
overflow: auto;
|
||||
padding: var(--space-4);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
.versionRow,
|
||||
.fieldRow {
|
||||
display: grid;
|
||||
grid-template-columns: 112px minmax(0, 1fr);
|
||||
grid-template-columns: var(--clone-label-width) minmax(0, 1fr);
|
||||
align-items: center;
|
||||
gap: 10px var(--space-3);
|
||||
gap: var(--clone-field-gap);
|
||||
}
|
||||
.versionRow {
|
||||
grid-template-columns: 112px 138px minmax(0, 1fr);
|
||||
}
|
||||
.versionRow > label,
|
||||
.fieldRow > label {
|
||||
color: var(--fg-strong);
|
||||
text-align: right;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.versionSelect {
|
||||
width: 138px;
|
||||
width: min(138px, 100%);
|
||||
}
|
||||
.comboField {
|
||||
min-width: 0;
|
||||
@@ -89,7 +98,7 @@
|
||||
.fieldInput {
|
||||
flex: 1;
|
||||
height: 100%;
|
||||
padding: 0 8px;
|
||||
padding-inline: var(--space-2);
|
||||
background: transparent;
|
||||
}
|
||||
.fieldButton {
|
||||
@@ -101,16 +110,27 @@
|
||||
.shallowRow {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding-left: 124px;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
.shallowRow,
|
||||
.feedback {
|
||||
padding-inline-start: calc(var(--clone-label-width) + var(--clone-field-gap));
|
||||
}
|
||||
.depthGroup {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.depthInput {
|
||||
width: 84px;
|
||||
}
|
||||
.feedback {
|
||||
min-width: 0;
|
||||
padding-left: 124px;
|
||||
}
|
||||
.progress {
|
||||
display: flex;
|
||||
@@ -127,44 +147,38 @@
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
line-height: 1.5;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.error {
|
||||
color: var(--danger);
|
||||
font-size: var(--fs-small);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.sidebar {
|
||||
flex-basis: 172px;
|
||||
}
|
||||
.form {
|
||||
padding-inline: 16px;
|
||||
}
|
||||
.versionRow,
|
||||
.fieldRow {
|
||||
grid-template-columns: 86px minmax(0, 1fr);
|
||||
}
|
||||
.versionRow {
|
||||
grid-template-columns: 86px 118px minmax(0, 1fr);
|
||||
}
|
||||
.versionSelect {
|
||||
width: 118px;
|
||||
}
|
||||
.shallowRow,
|
||||
.feedback {
|
||||
padding-left: 98px;
|
||||
}
|
||||
.layout[data-compact] {
|
||||
flex-direction: column;
|
||||
}
|
||||
.sidebar .sourceItem {
|
||||
width: 100%;
|
||||
border: 0;
|
||||
background: none;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: default;
|
||||
.layout[data-compact] .sidebar {
|
||||
flex: 0 1 auto;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-content: flex-start;
|
||||
gap: var(--space-1);
|
||||
max-height: min(120px, 32%);
|
||||
padding: var(--space-1);
|
||||
border-right: 0;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.sidebar .sourceItem[data-selected] {
|
||||
background: var(--bg-tree-selected);
|
||||
.layout[data-compact] .sourceItem {
|
||||
width: auto;
|
||||
max-width: 100%;
|
||||
border-radius: var(--radius-row);
|
||||
}
|
||||
.layout[data-compact] .form {
|
||||
--clone-label-width: 104px;
|
||||
}
|
||||
.layout[data-compact] .shallowRow {
|
||||
padding-inline-start: 0;
|
||||
}
|
||||
.sidebar .sourceItem:focus-visible {
|
||||
outline: 2px solid var(--focus-ring);
|
||||
|
||||
+33
-17
@@ -130,6 +130,8 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const request = useRef<number | null>(null);
|
||||
const urlField = useRef<HTMLDivElement>(null);
|
||||
const layout = useRef<HTMLDivElement>(null);
|
||||
const [compact, setCompact] = useState(false);
|
||||
const [recentUrls] = useState(readRecentUrls);
|
||||
const sources = cloneSourceList(useCloneSources((s) => s.sources));
|
||||
const source = sources.find((s) => s.id === sourceId);
|
||||
@@ -142,6 +144,17 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const el = layout.current;
|
||||
if (!el || typeof ResizeObserver === "undefined") return;
|
||||
const observer = new ResizeObserver(([entry]) => {
|
||||
const width = entry?.contentRect.width;
|
||||
if (width) setCompact(width < 580);
|
||||
});
|
||||
observer.observe(el);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
const dir = customDir ?? joinPath(parent, cloneDirName(url));
|
||||
const depth = shallow ? parseCloneDepth(depthInput) : null;
|
||||
const invalid = validateClone(url, dir) ?? (shallow && depth === null ? "Enter a positive number of commits" : null);
|
||||
@@ -231,7 +244,7 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
|
||||
{ label: "Cancel", role: "cancel", onClick: cancel },
|
||||
]}
|
||||
>
|
||||
<div className={styles.layout}>
|
||||
<div ref={layout} className={styles.layout} data-compact={compact || undefined}>
|
||||
<aside className={styles.sidebar} aria-label={tx("Clone source")}>
|
||||
{[{ id: "url", label: "Repository URL", icon: "branch" }, ...sources].map((s) => (
|
||||
<button
|
||||
@@ -243,7 +256,7 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
|
||||
disabled={busy}
|
||||
onClick={() => setSourceId(s.id)}
|
||||
>
|
||||
<Icon name={s.icon} size={22} />
|
||||
<Icon name={s.icon} size={16} />
|
||||
<span className={styles.sourceName}>
|
||||
<T>{s.label}</T>
|
||||
</span>
|
||||
@@ -264,11 +277,12 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className={styles.versionRow}>
|
||||
<label id="vcs-clone-version-label">
|
||||
<div className={styles.fieldRow}>
|
||||
<label htmlFor="vcs-clone-version">
|
||||
<T>Version control:</T>
|
||||
</label>
|
||||
<Select
|
||||
id="vcs-clone-version"
|
||||
aria-label="Version control"
|
||||
className={styles.versionSelect}
|
||||
value="git"
|
||||
@@ -337,19 +351,21 @@ function CloneDialog({ onClose, initialUrl }: { onClose: () => void; initialUrl:
|
||||
onChange={setShallow}
|
||||
label={<T>Shallow clone with a history truncated to</T>}
|
||||
/>
|
||||
<Input
|
||||
aria-label="Clone depth"
|
||||
className={styles.depthInput}
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
min={1}
|
||||
step={1}
|
||||
value={depthInput}
|
||||
disabled={busy || !shallow}
|
||||
invalid={shallow && depth === null}
|
||||
onChange={(e) => setDepthInput(e.target.value)}
|
||||
/>
|
||||
<T>commits</T>
|
||||
<div className={styles.depthGroup}>
|
||||
<Input
|
||||
aria-label="Clone depth"
|
||||
className={styles.depthInput}
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
min={1}
|
||||
step={1}
|
||||
value={depthInput}
|
||||
disabled={busy || !shallow}
|
||||
invalid={shallow && depth === null}
|
||||
onChange={(e) => setDepthInput(e.target.value)}
|
||||
/>
|
||||
<T>commits</T>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles.feedback}>
|
||||
|
||||
@@ -48,6 +48,51 @@
|
||||
flex-direction: column;
|
||||
gap: var(--space-0-5);
|
||||
}
|
||||
.updateForm {
|
||||
min-width: 0;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-4);
|
||||
font-size: var(--fs-ui);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.updateOptions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
min-inline-size: 0;
|
||||
margin: 0;
|
||||
padding: var(--space-2) 0 0;
|
||||
border: 0;
|
||||
border-top: 1px solid var(--border-popup);
|
||||
}
|
||||
.updateOptions > legend {
|
||||
padding: 0 var(--space-2) 0 0;
|
||||
color: var(--fg-strong);
|
||||
font-weight: 600;
|
||||
}
|
||||
.updateOptions .updateRadio {
|
||||
align-items: flex-start;
|
||||
}
|
||||
.updateCommand {
|
||||
color: var(--fg-subtle);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.updateActions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-2) var(--space-3);
|
||||
min-width: 0;
|
||||
}
|
||||
.updateActions .updateReset {
|
||||
max-width: 100%;
|
||||
min-height: var(--h-button);
|
||||
height: auto;
|
||||
padding-block: var(--space-1);
|
||||
line-height: 1.3;
|
||||
white-space: normal;
|
||||
}
|
||||
.fileList {
|
||||
max-height: 260px;
|
||||
overflow: auto;
|
||||
@@ -357,6 +402,44 @@
|
||||
outline: none;
|
||||
border-color: var(--focus-ring);
|
||||
}
|
||||
.stashForm {
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-4);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
.stashRepo {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
.stashRepo > button {
|
||||
flex: 1;
|
||||
}
|
||||
.stashBranch {
|
||||
color: var(--fg-secondary);
|
||||
line-height: 1.5;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.stashMessage {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1-5);
|
||||
}
|
||||
.stashMessage > label {
|
||||
color: var(--fg-strong);
|
||||
font-weight: 600;
|
||||
}
|
||||
.stashMessage > textarea {
|
||||
min-width: 0;
|
||||
padding: var(--space-2);
|
||||
line-height: 1.5;
|
||||
}
|
||||
.stashOptions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2) var(--space-4);
|
||||
}
|
||||
/* Interactive rebase dialog. */
|
||||
.rebaseList {
|
||||
max-height: 360px;
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* Copy Path/Reference… › Path From Repository Root: each path relative to the root of the
|
||||
* Git repository holding it, one per line.
|
||||
*/
|
||||
import { executeAction, type Action } from "@/platform/actions";
|
||||
import { writeClipboardText } from "@/platform/clipboard";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { notifications, registerMenuGroup } from "@/workbench/contributions";
|
||||
import { rootOf, stripSlash } from "./model";
|
||||
import { useVcs } from "./store";
|
||||
|
||||
/** The paths inside a repository, each from its root; null when none is. */
|
||||
function repositoryPaths(paths: readonly string[]): string | null {
|
||||
const { roots } = useVcs.getState();
|
||||
const relative: string[] = [];
|
||||
for (const path of paths.map(stripSlash)) {
|
||||
// A nested repository's own root is its root, not a folder of the outer one.
|
||||
const root = roots.includes(path) ? path : rootOf(path, roots);
|
||||
if (root) relative.push(path.slice(root.length + 1) || ".");
|
||||
}
|
||||
return relative.length ? relative.join("\n") : null;
|
||||
}
|
||||
|
||||
async function copy(text: string) {
|
||||
try {
|
||||
await writeClipboardText(text);
|
||||
void executeAction("editor.showHint", { text: tx`Copied ${text}` });
|
||||
} catch (error) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: tx("Cannot access the clipboard"),
|
||||
body: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const copyRepositoryPathActions: Action[] = [
|
||||
{
|
||||
id: "vcs.copyRepositoryPath",
|
||||
title: "Copy Path From Repository Root",
|
||||
category: "Git",
|
||||
icon: "copy",
|
||||
when: "vcsAvailable",
|
||||
hidden: true,
|
||||
run: ({ arg }) => {
|
||||
const text = Array.isArray(arg) ? repositoryPaths(arg as string[]) : null;
|
||||
if (text) void copy(text);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export function registerCopyRepositoryPath(): () => void {
|
||||
return registerMenuGroup({
|
||||
id: "vcs.copyRepositoryPath",
|
||||
menus: ["copyPath"],
|
||||
items: (_menu, { paths }) => {
|
||||
const text = repositoryPaths(paths);
|
||||
if (!text) return [];
|
||||
return [
|
||||
{
|
||||
id: "vcs.copyRepositoryPath",
|
||||
label: "Path From Repository Root",
|
||||
preview: text,
|
||||
run: () => void executeAction("vcs.copyRepositoryPath", paths),
|
||||
},
|
||||
];
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -6,18 +6,21 @@ import { executeAction } from "@/platform/actions";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import {
|
||||
Button,
|
||||
Checkbox,
|
||||
Dialog,
|
||||
HighlightedText,
|
||||
Icon,
|
||||
IconButton,
|
||||
Input,
|
||||
Menu,
|
||||
Select,
|
||||
T,
|
||||
Tree,
|
||||
useSanitizedField,
|
||||
type SelectOption,
|
||||
type SelectProps,
|
||||
type MenuItem,
|
||||
} from "@/ui";
|
||||
import { sortLocal, sortRemote } from "./branches";
|
||||
import { conflictActions, openConflictsInstead, validateBranchName } from "./branchOps";
|
||||
@@ -33,6 +36,7 @@ import {
|
||||
type RepoWorktrees,
|
||||
} from "./worktrees";
|
||||
import styles from "./common.module.css";
|
||||
import pullStyles from "./PullDialog.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
@@ -73,16 +77,8 @@ const FLAG_LABELS: Array<[MergeFlag, string]> = [
|
||||
["noCommit", "--no-commit"],
|
||||
];
|
||||
|
||||
function MergeFlags({
|
||||
on,
|
||||
setOn,
|
||||
rebase = false,
|
||||
}: {
|
||||
on: Set<MergeFlag>;
|
||||
setOn: (next: Set<MergeFlag>) => void;
|
||||
rebase?: boolean;
|
||||
}) {
|
||||
const disabled = disabledMergeFlags(on, rebase);
|
||||
function MergeFlags({ on, setOn }: { on: Set<MergeFlag>; setOn: (next: Set<MergeFlag>) => void }) {
|
||||
const disabled = disabledMergeFlags(on);
|
||||
return (
|
||||
<div className={styles.optionGrid} role="group" aria-label={tx("Merge options")}>
|
||||
{FLAG_LABELS.map(([flag, label]) => (
|
||||
@@ -141,12 +137,21 @@ export function showPullDialog(repo?: string | null) {
|
||||
}
|
||||
|
||||
/** IDEA's Git Root choice: shown only when the project holds several repositories. */
|
||||
export function RepoPicker({ repo, onChange }: { repo: string | null; onChange: (root: string) => void }) {
|
||||
export function RepoPicker({
|
||||
repo,
|
||||
onChange,
|
||||
className,
|
||||
}: {
|
||||
repo: string | null;
|
||||
onChange: (root: string) => void;
|
||||
className?: string;
|
||||
}) {
|
||||
const [roots] = useState(() => useVcs.getState().roots);
|
||||
if (roots.length < 2) return null;
|
||||
return (
|
||||
<Select
|
||||
aria-label="Repository"
|
||||
className={className}
|
||||
value={repo ?? roots[0] ?? null}
|
||||
options={roots.map((root) => ({ value: root, label: repoName(root), verbatim: true }))}
|
||||
onChange={onChange}
|
||||
@@ -181,6 +186,8 @@ function PullDialog({ initialRepo, onClose }: { initialRepo?: string | null; onC
|
||||
const [chosenBranch, setBranch] = useState<string | null>(null);
|
||||
const [rebase, setRebase] = useState(false);
|
||||
const [flags, setFlags] = useState<Set<MergeFlag>>(() => new Set());
|
||||
const [optionsOpen, setOptionsOpen] = useState(false);
|
||||
const optionsRef = useRef<HTMLButtonElement>(null);
|
||||
|
||||
const chooseRepo = (root: string) => {
|
||||
if (root === repo) return;
|
||||
@@ -215,6 +222,25 @@ function PullDialog({ initialRepo, onClose }: { initialRepo?: string | null; onC
|
||||
: preferred && remoteBranches.includes(preferred)
|
||||
? preferred
|
||||
: (remoteBranches[0] ?? null);
|
||||
const disabledFlags = disabledMergeFlags(flags, rebase);
|
||||
const selectedFlags = rebase
|
||||
? ["--rebase"]
|
||||
: FLAG_LABELS.filter(([flag]) => flags.has(flag)).map(([, label]) => label);
|
||||
const options: MenuItem[] = [
|
||||
{ label: "--rebase", verbatim: true, checked: rebase, run: () => setRebase(!rebase) },
|
||||
...FLAG_LABELS.map(([flag, label]) => ({
|
||||
label,
|
||||
verbatim: true,
|
||||
checked: flags.has(flag),
|
||||
disabled: disabledFlags.has(flag) && !flags.has(flag),
|
||||
run: () => {
|
||||
const next = new Set(flags);
|
||||
if (next.has(flag)) next.delete(flag);
|
||||
else next.add(flag);
|
||||
setFlags(next);
|
||||
},
|
||||
})),
|
||||
];
|
||||
|
||||
const run = async () => {
|
||||
if (!remote) return;
|
||||
@@ -238,44 +264,69 @@ function PullDialog({ initialRepo, onClose }: { initialRepo?: string | null; onC
|
||||
open
|
||||
title={tx`Pull to ${info?.head ?? "HEAD"}`}
|
||||
onClose={onClose}
|
||||
width={460}
|
||||
width={640}
|
||||
footerStart={
|
||||
<>
|
||||
<Button
|
||||
ref={optionsRef}
|
||||
variant="ghost"
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={optionsOpen}
|
||||
onClick={() => setOptionsOpen(!optionsOpen)}
|
||||
>
|
||||
<T>Modify options</T>
|
||||
<Icon name="chevron-down" size={12} />
|
||||
</Button>
|
||||
<Menu
|
||||
open={optionsOpen}
|
||||
onClose={() => setOptionsOpen(false)}
|
||||
anchor={optionsRef}
|
||||
placement="top-start"
|
||||
aria-label="Modify options"
|
||||
items={options}
|
||||
/>
|
||||
</>
|
||||
}
|
||||
buttons={[
|
||||
{ label: "Pull", role: "default", disabled: !remote, onClick: () => void run() },
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
>
|
||||
<div className={styles.form}>
|
||||
{remotes && !remotes.length ? (
|
||||
<>
|
||||
<RepoPicker repo={repo} onChange={chooseRepo} />
|
||||
<div className={styles.hint}>
|
||||
<div className={pullStyles.form}>
|
||||
<div className={pullStyles.source}>
|
||||
<RepoPicker repo={repo} onChange={chooseRepo} className={pullStyles.repository} />
|
||||
{remotes && !remotes.length ? (
|
||||
<div className={clsx(styles.hint, pullStyles.noRemotes)}>
|
||||
<T>No remotes are configured. Add one with Git › Manage Remotes….</T>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className={styles.fieldRow}>
|
||||
<RepoPicker repo={repo} onChange={chooseRepo} />
|
||||
<Select
|
||||
aria-label="Remote"
|
||||
value={remote}
|
||||
options={(remotes ?? []).map((r) => ({ value: r.name, label: r.name, detail: r.url }))}
|
||||
onChange={setRemote}
|
||||
/>
|
||||
<BranchSelect
|
||||
aria-label="Remote branch"
|
||||
className={styles.grow}
|
||||
value={branch}
|
||||
placeholder="Branch"
|
||||
options={remoteBranches.map((b) => ({ value: b, label: b, icon: "branch" }))}
|
||||
onChange={setBranch}
|
||||
/>
|
||||
) : (
|
||||
<div className={pullStyles.command}>
|
||||
<code className={pullStyles.verb}>git pull</code>
|
||||
<Select
|
||||
aria-label="Remote"
|
||||
className={pullStyles.remote}
|
||||
value={remote}
|
||||
options={(remotes ?? []).map((r) => ({ value: r.name, label: r.name, verbatim: true, detail: r.url }))}
|
||||
onChange={setRemote}
|
||||
/>
|
||||
<BranchSelect
|
||||
aria-label="Remote branch"
|
||||
className={pullStyles.branch}
|
||||
value={branch}
|
||||
renderValue={(option) => (option ? <span title={option.label}>{option.label}</span> : <T>Branch</T>)}
|
||||
options={remoteBranches.map((b) => ({ value: b, label: b, icon: "branch", verbatim: true }))}
|
||||
onChange={setBranch}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{selectedFlags.length > 0 && (
|
||||
<div className={pullStyles.flags} role="group" aria-label={tx("Options:")}>
|
||||
{selectedFlags.map((label) => (
|
||||
<code key={label}>{label}</code>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className={styles.fieldLabel}>
|
||||
<T>Options:</T>
|
||||
</div>
|
||||
<Checkbox label="--rebase" checked={rebase} onChange={setRebase} />
|
||||
<MergeFlags on={flags} setOn={setFlags} rebase={rebase} />
|
||||
<div className={styles.hint}>
|
||||
<T>Uncommitted changes are stashed before the pull and restored afterwards.</T>
|
||||
</div>
|
||||
|
||||
@@ -6,7 +6,7 @@ import { commitKey, commitRepo } from "./multiRoot";
|
||||
* and patches (ids are bound in keymaps/intellij-macos.ts where IDEA binds them).
|
||||
*/
|
||||
import type { Commit } from "@/bindings";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { getContext, setContext } from "@/platform/context";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { notifications, toolWindowService } from "@/workbench/contributions";
|
||||
import { executeAction, registerActions, type Action } from "@/platform/actions";
|
||||
@@ -57,10 +57,12 @@ import {
|
||||
loadShelves,
|
||||
renameShelf,
|
||||
shelveChanges,
|
||||
shelveSilently,
|
||||
shelfTarget,
|
||||
showShelf,
|
||||
showShelfDiff,
|
||||
unshelve,
|
||||
unshelveSilently,
|
||||
} from "./shelf";
|
||||
import { currentRepo, focusRepo, useVcs } from "./store";
|
||||
|
||||
@@ -622,6 +624,20 @@ export function registerHistoryActions(): () => void {
|
||||
when: VCS,
|
||||
run: ({ arg }) => shelveChanges(changePaths(arg)),
|
||||
},
|
||||
{
|
||||
id: "vcs.shelveSilently",
|
||||
title: "Shelve Silently",
|
||||
category: "Git",
|
||||
icon: "shelve",
|
||||
when: VCS,
|
||||
keyWhen: "vcsAvailable && (activeToolWindow == commit || activeToolWindow == git) && !shelfFocus",
|
||||
run: ({ arg }) => {
|
||||
// The Changes tab's selection is stale while the Shelf or Stash tab is shown.
|
||||
if (arg === undefined && getContext().activeToolWindow === "commit" && useCommit.getState().tab !== "changes")
|
||||
return;
|
||||
return shelveSilently(changePaths(arg));
|
||||
},
|
||||
},
|
||||
{ id: "vcs.showShelf", title: "Show Shelf", category: "Git", icon: "shelve", when: VCS, run: showShelf },
|
||||
{
|
||||
id: "vcs.unshelve",
|
||||
@@ -635,6 +651,19 @@ export function registerHistoryActions(): () => void {
|
||||
else showShelf();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "vcs.unshelveSilently",
|
||||
title: "Unshelve Silently",
|
||||
category: "Git",
|
||||
icon: "unshelve",
|
||||
when: VCS,
|
||||
keyWhen: "vcsAvailable && shelfFocus",
|
||||
run: ({ arg }) => {
|
||||
const target = shelfTarget(arg);
|
||||
if (target) return unshelveSilently(target.entry, target.path);
|
||||
showShelf();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "vcs.shelf.delete",
|
||||
title: "Delete Shelved Changes",
|
||||
|
||||
@@ -54,6 +54,7 @@ import { existsOnDisk, installVcsStore, onConflictsAppeared, onConflictsCleared,
|
||||
import { installRootSync } from "./rootSync";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { openOnRemoteActions, registerOpenOnRemote } from "./openOnRemote";
|
||||
import { copyRepositoryPathActions, registerCopyRepositoryPath } from "./copyRepositoryPath";
|
||||
import { activateSettingsPages } from "./settingsPages";
|
||||
|
||||
/** The Resolve/Continue/Abort buttons exist in the title bar only while there is something to resolve. */
|
||||
@@ -230,6 +231,8 @@ export function activate(): () => void {
|
||||
registerVcsActions(),
|
||||
registerActions(openOnRemoteActions),
|
||||
registerOpenOnRemote(),
|
||||
registerActions(copyRepositoryPathActions),
|
||||
registerCopyRepositoryPath(),
|
||||
registerHistoryActions(),
|
||||
registerLogPaneActions(),
|
||||
activateSettingsPages(),
|
||||
|
||||
@@ -5,7 +5,7 @@ import { call, commands } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { workflowSettings, type UpdateMethod } from "@/platform/workflowSettings";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { Button, Checkbox, Dialog, Input, List, Select, Spinner, T, Tree } from "@/ui";
|
||||
import { Button, Checkbox, Dialog, Input, List, Radio, Select, Spinner, T, Tree } from "@/ui";
|
||||
import { ask } from "@/workbench/messages";
|
||||
import { openDialog } from "./dialogs";
|
||||
import { saveVcsSetting } from "./settingsUi";
|
||||
@@ -94,9 +94,10 @@ function UpdateDialog({ repos, onClose }: UpdateDialogProps) {
|
||||
onClose={onClose}
|
||||
width={single ? 540 : 420}
|
||||
footerStart={
|
||||
<>
|
||||
<div className={styles.updateActions}>
|
||||
{single && (
|
||||
<Button
|
||||
className={styles.updateReset}
|
||||
onClick={() => {
|
||||
onClose();
|
||||
void resetToRemoteBranch();
|
||||
@@ -106,40 +107,52 @@ function UpdateDialog({ repos, onClose }: UpdateDialogProps) {
|
||||
</Button>
|
||||
)}
|
||||
<Checkbox checked={hide} onChange={setHide} label="Don't show again" />
|
||||
</>
|
||||
</div>
|
||||
}
|
||||
buttons={[
|
||||
{ label: "OK", role: "default", autoFocus: true, onClick: () => void run() },
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
>
|
||||
<div className={styles.form} role="radiogroup" aria-label={tx("Update type")}>
|
||||
<div className={`${styles.form} ${styles.updateForm}`}>
|
||||
<div className={styles.hint}>
|
||||
{branch?.upstream
|
||||
? `Update ${branch.head ?? "HEAD"} from ${branch.upstream}${branch.behind ? ` (${branch.behind} incoming)` : ""}`
|
||||
: tx("The current branch has no tracked branch; git pull may fail.")}
|
||||
</div>
|
||||
<div className={styles.fieldLabel}>
|
||||
<T>Update type:</T>
|
||||
</div>
|
||||
<label className={styles.radioRow}>
|
||||
<input type="radio" name="update" checked={!rebase} onChange={() => setRebase(false)} />
|
||||
<span className={styles.radioText}>
|
||||
<T>Merge incoming changes into the current branch</T>
|
||||
<span className={styles.hint}>
|
||||
<T>git pull --no-rebase --ff</T>
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
<label className={styles.radioRow}>
|
||||
<input type="radio" name="update" checked={rebase} onChange={() => setRebase(true)} />
|
||||
<span className={styles.radioText}>
|
||||
<T>Rebase the current branch on top of incoming changes</T>
|
||||
<span className={styles.hint}>
|
||||
<T>git pull --rebase</T>
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
<fieldset className={styles.updateOptions} aria-label={tx("Update type")}>
|
||||
<legend>
|
||||
<T>Update type:</T>
|
||||
</legend>
|
||||
<Radio
|
||||
className={styles.updateRadio}
|
||||
name="update"
|
||||
checked={!rebase}
|
||||
onChange={() => setRebase(false)}
|
||||
label={
|
||||
<span className={styles.radioText}>
|
||||
<T>Merge incoming changes into the current branch</T>
|
||||
<code className={styles.updateCommand}>
|
||||
<T>git pull --no-rebase --ff</T>
|
||||
</code>
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<Radio
|
||||
className={styles.updateRadio}
|
||||
name="update"
|
||||
checked={rebase}
|
||||
onChange={() => setRebase(true)}
|
||||
label={
|
||||
<span className={styles.radioText}>
|
||||
<T>Rebase the current branch on top of incoming changes</T>
|
||||
<code className={styles.updateCommand}>
|
||||
<T>git pull --rebase</T>
|
||||
</code>
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
</fieldset>
|
||||
<div className={styles.hint}>
|
||||
<T>Uncommitted changes are stashed before the update and restored afterwards.</T>
|
||||
</div>
|
||||
|
||||
+80
-22
@@ -6,7 +6,14 @@
|
||||
import { writeClipboardText } from "@/platform/clipboard";
|
||||
import { useEffect, useMemo, useState, type MouseEvent } from "react";
|
||||
import { create } from "zustand";
|
||||
import type { ApplyOutcome, ChangedFile, FileStatus, ShelvedChangeList, ShelfDiffFile } from "@/bindings";
|
||||
import type {
|
||||
ApplyOutcome,
|
||||
ChangedFile,
|
||||
ChangelistState,
|
||||
FileStatus,
|
||||
ShelvedChangeList,
|
||||
ShelfDiffFile,
|
||||
} from "@/bindings";
|
||||
import { setContext } from "@/platform/context";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { openDiff, openVcsDiff, withChain, type DiffData } from "./diffInput";
|
||||
@@ -88,6 +95,13 @@ export function defaultChangeFiles(paths?: readonly string[]): FileStatus[] {
|
||||
);
|
||||
}
|
||||
|
||||
/** Name a shelf of `list`'s changes gets by default: the list's name once the project has several. */
|
||||
function shelfName(state: ChangelistState, list: string): string {
|
||||
return state.lists.length > 1
|
||||
? (state.lists.find((l) => l.id === list) ?? activeList(state)).name
|
||||
: "Uncommitted changes";
|
||||
}
|
||||
|
||||
export function shelveChanges(paths?: readonly string[]) {
|
||||
const files = defaultChangeFiles(paths);
|
||||
if (!files.length) {
|
||||
@@ -95,8 +109,42 @@ export function shelveChanges(paths?: readonly string[]) {
|
||||
return;
|
||||
}
|
||||
const state = useChangelists.getState().state;
|
||||
const name = state.lists.length > 1 ? activeList(state).name : "Uncommitted changes";
|
||||
openDialog((close) => <ShelveDialog files={files} initialName={name} onClose={close} />);
|
||||
openDialog((close) => <ShelveDialog files={files} initialName={shelfName(state, state.active)} onClose={close} />);
|
||||
}
|
||||
|
||||
/** IDEA's Shelve Silently: no dialog, one shelf per changelist the changes belong to, named after it. */
|
||||
export async function shelveSilently(paths?: readonly string[]) {
|
||||
// Without a dialog to review the files, pick them after unsaved edits reach the disk.
|
||||
await saveAll();
|
||||
await refreshNow();
|
||||
const files = defaultChangeFiles(paths);
|
||||
if (!files.length) {
|
||||
notifications().notify({ group: "vcs", level: "info", title: "No changes to shelve" });
|
||||
return;
|
||||
}
|
||||
const state = useChangelists.getState().state;
|
||||
const byList = new Map<string, string[]>();
|
||||
for (const f of files) {
|
||||
const list = listOf(state, relOf(f.path));
|
||||
const own = byList.get(list);
|
||||
if (own) own.push(stripSlash(f.path));
|
||||
else byList.set(list, [stripSlash(f.path)]);
|
||||
}
|
||||
for (const [list, chosen] of byList) if (!(await shelveFiles(shelfName(state, list), chosen))) return;
|
||||
}
|
||||
|
||||
async function shelveFiles(name: string, paths: string[]): Promise<ShelvedChangeList | undefined> {
|
||||
const entry = await runOp(tx`Shelve changes “${name}”`, () => call(commands.vcsShelve(name, paths)));
|
||||
if (!entry) return undefined;
|
||||
void loadShelves().catch(() => undefined);
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
level: "info",
|
||||
title: `Shelved ${entry.files.length} file${entry.files.length === 1 ? "" : "s"}`,
|
||||
body: entry.name,
|
||||
actions: [{ label: "Show Shelf", run: showShelf }],
|
||||
});
|
||||
return entry;
|
||||
}
|
||||
|
||||
/** Files of `node` and everything below it. */
|
||||
@@ -227,16 +275,7 @@ function ShelveDialog({
|
||||
if (!chosen.length || !name.trim()) return;
|
||||
onClose();
|
||||
await saveAll();
|
||||
const entry = await runOp(tx`Shelve changes “${name.trim()}”`, () => call(commands.vcsShelve(name.trim(), chosen)));
|
||||
if (!entry) return;
|
||||
void loadShelves().catch(() => undefined);
|
||||
notifications().notify({
|
||||
group: "vcs",
|
||||
level: "info",
|
||||
title: `Shelved ${entry.files.length} file${entry.files.length === 1 ? "" : "s"}`,
|
||||
body: entry.name,
|
||||
actions: [{ label: "Show Shelf", run: showShelf }],
|
||||
});
|
||||
await shelveFiles(name.trim(), chosen);
|
||||
};
|
||||
return (
|
||||
<Dialog
|
||||
@@ -304,6 +343,33 @@ async function unshelveFiles(entry: ShelvedChangeList, paths: readonly string[],
|
||||
return outcome;
|
||||
}
|
||||
|
||||
/** Unshelves `paths` of `entry` into the `target` changelist. */
|
||||
async function applyShelf(entry: ShelvedChangeList, paths: readonly string[], remove: boolean, target: string) {
|
||||
const outcome = await runOp(tx`Unshelve “${entry.name}”`, () => unshelveFiles(entry, paths, remove), {
|
||||
refresh: false,
|
||||
});
|
||||
if (!outcome) return;
|
||||
await refreshNow();
|
||||
const repo = shelfRepository(entry);
|
||||
const rels = [...outcome.applied, ...outcome.conflicts].map((p) => relOf(repositoryPath(repo, p)));
|
||||
updateChangelists((s) => moveFiles(s, rels, target));
|
||||
void loadShelves().catch(() => undefined);
|
||||
await reportApply(outcome, `Unshelved “${entry.name}”`);
|
||||
}
|
||||
|
||||
/**
|
||||
* IDEA's Unshelve Silently: no dialog; into the changelist named like the shelf, else the active one,
|
||||
* removing applied files from the shelf as the Shelf setting says.
|
||||
*/
|
||||
export async function unshelveSilently(entry: ShelvedChangeList, path?: string) {
|
||||
const paths = path === undefined ? entry.files.map((f) => f.path) : [path];
|
||||
if (!paths.length) return;
|
||||
const state = useChangelists.getState().state;
|
||||
const target = state.lists.find((l) => l.name === entry.name)?.id ?? state.active;
|
||||
await saveAll();
|
||||
await applyShelf(entry, paths, workflowSettings().vcs.shelf.removeApplied, target);
|
||||
}
|
||||
|
||||
function UnshelveDialog({ entry, path, onClose }: { entry: ShelvedChangeList; path?: string; onClose: () => void }) {
|
||||
const lists = useChangelists((s) => s.state);
|
||||
const [target, setTarget] = useState(lists.active);
|
||||
@@ -322,15 +388,7 @@ function UnshelveDialog({ entry, path, onClose }: { entry: ShelvedChangeList; pa
|
||||
if (!chosen.length) return;
|
||||
onClose();
|
||||
await saveAll();
|
||||
const outcome = await runOp(tx`Unshelve “${entry.name}”`, () => unshelveFiles(entry, chosen, remove), {
|
||||
refresh: false,
|
||||
});
|
||||
if (!outcome) return;
|
||||
await refreshNow();
|
||||
const rels = [...outcome.applied, ...outcome.conflicts].map((p) => relOf(repositoryPath(repo, p)));
|
||||
updateChangelists((s) => moveFiles(s, rels, target));
|
||||
void loadShelves().catch(() => undefined);
|
||||
await reportApply(outcome, `Unshelved “${entry.name}”`);
|
||||
await applyShelf(entry, chosen, remove, target);
|
||||
};
|
||||
return (
|
||||
<Dialog
|
||||
|
||||
@@ -99,4 +99,6 @@ export const IDEA_ACTIONS: Readonly<Record<string, string>> = {
|
||||
VcsShowNextChangeMarker: "vcs.nextChange",
|
||||
VcsShowPrevChangeMarker: "vcs.prevChange",
|
||||
"Compare.SameVersion": "vcs.showDiff",
|
||||
"ChangesView.ShelveSilently": "vcs.shelveSilently",
|
||||
"ChangesView.UnshelveSilently": "vcs.unshelveSilently",
|
||||
};
|
||||
@@ -160,6 +160,8 @@ export const eclipseWindows: Record<string, string[]> = {
|
||||
"vcs.changelist.edit": ["Shift+Alt+R"],
|
||||
"toolwindow.services": ["Shift+Alt+H"],
|
||||
"vcs.changelist.move": [],
|
||||
"vcs.shelveSilently": [],
|
||||
"vcs.unshelveSilently": [],
|
||||
"navigate.gotoBookmark1": [],
|
||||
"toolwindow.resizeLeft": [],
|
||||
"toolwindow.resizeRight": [],
|
||||
|
||||
@@ -324,6 +324,8 @@ export const intellijMacos: Record<string, string[]> = {
|
||||
"view.quickSwitchScheme": ["Ctrl+`"],
|
||||
// Commit tool window (change lists) and Git log; keyWhen limits them to those tool windows.
|
||||
"vcs.changelist.move": ["Meta+Shift+M"],
|
||||
"vcs.shelveSilently": ["Meta+Shift+H"],
|
||||
"vcs.unshelveSilently": ["Meta+Alt+U"],
|
||||
"vcs.changelist.edit": ["F2", "Shift+F6"],
|
||||
"vcs.log.copyRevision": ["Meta+Alt+Shift+C"],
|
||||
"vcs.log.goToRef": ["Meta+F"],
|
||||
|
||||
@@ -322,6 +322,8 @@ export const intellijWindows: Record<string, string[]> = {
|
||||
"runAnything.show": ["Ctrl Ctrl"],
|
||||
"view.quickSwitchScheme": ["Ctrl+`"],
|
||||
"vcs.changelist.move": ["Alt+Shift+M"],
|
||||
"vcs.shelveSilently": ["Ctrl+Shift+H"],
|
||||
"vcs.unshelveSilently": ["Ctrl+Alt+U"],
|
||||
"vcs.changelist.edit": ["F2", "Shift+F6"],
|
||||
"vcs.log.copyRevision": ["Ctrl+Alt+Shift+C"],
|
||||
"vcs.log.goToRef": ["Ctrl+F"],
|
||||
|
||||
@@ -332,6 +332,8 @@ export const vscodeMacos: Record<string, string[]> = {
|
||||
"view.quickSwitchScheme": [],
|
||||
// Commit tool window (change lists) and Git log; keyWhen limits them to those tool windows.
|
||||
"vcs.changelist.move": [],
|
||||
"vcs.shelveSilently": [],
|
||||
"vcs.unshelveSilently": [],
|
||||
"vcs.changelist.edit": [],
|
||||
"vcs.log.copyRevision": [],
|
||||
"vcs.log.goToRef": [],
|
||||
|
||||
@@ -721,7 +721,6 @@
|
||||
"Packaging Artifacts": "Packaging Artifacts",
|
||||
"Configure JAR, WAR, or exploded WAR artifacts for packaging and application server deployment.": "Configure JAR, WAR, or exploded WAR artifacts for packaging and application server deployment.",
|
||||
"Detected Build Web Artifacts": "Detected Build Web Artifacts",
|
||||
"Home Path": "Home Path",
|
||||
"No SDK installations detected yet.": "No SDK installations detected yet.",
|
||||
"SDK Details": "SDK Details",
|
||||
"Use as Project SDK": "Use as Project SDK",
|
||||
@@ -885,6 +884,7 @@
|
||||
"Start Fresh": "Start Fresh",
|
||||
"This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.": "This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.",
|
||||
"Copy Path From Source Root": "Copy Path From Source Root",
|
||||
"Copy Path From Repository Root": "Copy Path From Repository Root",
|
||||
"Escape text on paste in string literals": "Escape text on paste in string literals",
|
||||
"Always": "Always",
|
||||
"Never": "Never",
|
||||
@@ -900,6 +900,7 @@
|
||||
"Copy Path with Line Number": "Copy Path with Line Number",
|
||||
"1 line": "1 line",
|
||||
"Path From Source Root": "Path From Source Root",
|
||||
"Path From Repository Root": "Path From Repository Root",
|
||||
"Paste preview": "Paste preview",
|
||||
"Add Imports on Paste": "Add Imports on Paste",
|
||||
"Select imports to add to the pasted code:": "Select imports to add to the pasted code:",
|
||||
@@ -2486,6 +2487,8 @@
|
||||
"{length} selected items": "{length} selected items",
|
||||
"Include subdirectories": "Include subdirectories",
|
||||
"Only VCS changed text": "Only VCS changed text",
|
||||
"Options": "Options",
|
||||
"Filters": "Filters",
|
||||
"Files are reformatted by their language's formatter and saved; files without one are skipped.": "Files are reformatted by their language's formatter and saved; files without one are skipped.",
|
||||
"No changed files to reformat": "No changed files to reformat",
|
||||
"No files to reformat": "No files to reformat",
|
||||
@@ -2739,6 +2742,18 @@
|
||||
"{description}; JVM options: {flags}": "{description}; JVM options: {flags}",
|
||||
"Sorting Options": "Sorting Options",
|
||||
"Sort by Duration": "Sort by Duration",
|
||||
"Move file '{name}'": "Move file '{name}'",
|
||||
"Move directory '{name}'": "Move directory '{name}'",
|
||||
"Move {count} items": "Move {count} items",
|
||||
"Browse for target directory": "Browse for target directory",
|
||||
"Select Target Directory": "Select Target Directory",
|
||||
"Cannot move a folder into itself": "Cannot move a folder into itself",
|
||||
"Already in this directory": "Already in this directory",
|
||||
"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>",
|
||||
"Shelve Silently": "Shelve Silently",
|
||||
"Unshelve Silently": "Unshelve Silently"
|
||||
}
|
||||
@@ -2282,7 +2282,6 @@
|
||||
"Packaging Artifacts": "打包构件",
|
||||
"Configure JAR, WAR, or exploded WAR artifacts for packaging and application server deployment.": "配置用于打包和应用服务器部署的 JAR、WAR 或展开式 WAR 构件。",
|
||||
"Detected Build Web Artifacts": "检测到的构建 Web 构件",
|
||||
"Home Path": "主目录路径",
|
||||
"No SDK installations detected yet.": "尚未检测到已安装的 SDK。",
|
||||
"SDK Details": "SDK 详情",
|
||||
"Use as Project SDK": "设为项目 SDK",
|
||||
@@ -7312,6 +7311,7 @@
|
||||
"Start Fresh": "重新开始",
|
||||
"This clears the entire conversation and starts a fresh agent session with this message. Files the agent changed stay as they are.": "这会清空整个对话,并使用此消息启动全新的智能体会话。智能体已修改的文件保持不变。",
|
||||
"Path From Source Root": "相对于源根的路径",
|
||||
"Path From Repository Root": "相对于仓库根的路径",
|
||||
"Paste preview": "粘贴预览",
|
||||
"Filter clipboard history": "筛选剪贴板历史",
|
||||
"Add Imports": "添加导入",
|
||||
@@ -7326,6 +7326,7 @@
|
||||
"Clipboard history": "剪贴板历史",
|
||||
"Select imports to add to the pasted code:": "选择要为粘贴的代码添加的导入:",
|
||||
"Copy Path From Source Root": "复制相对于源根的路径",
|
||||
"Copy Path From Repository Root": "复制相对于仓库根的路径",
|
||||
"Copied {text}": "已复制 {text}",
|
||||
"Reference": "引用",
|
||||
"Insert imports on paste": "粘贴时插入导入",
|
||||
@@ -8875,6 +8876,7 @@
|
||||
"{length} selected items": "已选择 {length} 项",
|
||||
"Include subdirectories": "包含子目录",
|
||||
"Only VCS changed text": "仅 VCS 更改的文本",
|
||||
"Filters": "筛选条件",
|
||||
"Files are reformatted by their language's formatter and saved; files without one are skipped.": "文件由各自语言的格式化程序重新格式化并保存;没有格式化程序的文件将被跳过。",
|
||||
"No changed files to reformat": "没有需要重新格式化的已更改文件",
|
||||
"No files to reformat": "没有需要重新格式化的文件",
|
||||
@@ -9109,6 +9111,16 @@
|
||||
"{description}; JVM options: {flags}": "{description};JVM 选项:{flags}",
|
||||
"Sorting Options": "排序选项",
|
||||
"Sort by Duration": "按持续时间排序",
|
||||
"Move file '{name}'": "移动文件「{name}」",
|
||||
"Move directory '{name}'": "移动目录「{name}」",
|
||||
"Move {count} items": "移动 {count} 个项目",
|
||||
"Browse for target directory": "浏览目标目录",
|
||||
"Select Target Directory": "选择目标目录",
|
||||
"Cannot move a folder into itself": "不能将文件夹移动到自身目录中",
|
||||
"Already in this directory": "已在此目录中",
|
||||
"Resize left merge pane": "调整左侧合并窗格宽度",
|
||||
"Resize right merge pane": "调整右侧合并窗格宽度"
|
||||
"Resize right merge pane": "调整右侧合并窗格宽度",
|
||||
"Database and schema": "数据库和 schema",
|
||||
"Shelve Silently": "静默搁置",
|
||||
"Unshelve Silently": "静默取消搁置"
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
.body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-4);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
|
||||
.group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
min-inline-size: 0;
|
||||
margin: 0;
|
||||
padding: var(--space-2) 0 0;
|
||||
border: 0;
|
||||
border-block-start: 1px solid var(--border-popup);
|
||||
}
|
||||
|
||||
.legend {
|
||||
padding: 0 var(--space-2) 0 0;
|
||||
color: var(--fg-strong);
|
||||
font-weight: 600;
|
||||
}
|
||||
@@ -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
@@ -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>
|
||||
|
||||
@@ -277,6 +277,37 @@
|
||||
padding: 0 var(--tab-inline-padding, 10px) 0 2px;
|
||||
}
|
||||
|
||||
/* Editor tabs in a row sit 4px apart; wrapped rows keep their row gap. */
|
||||
.editor:not(.vertical) .scroller {
|
||||
column-gap: var(--space-1);
|
||||
}
|
||||
/* Every closable tab keeps a close slot at one edge (IDEA), cut to what the close glyph needs: 18px, a 2px
|
||||
inset and the 16px button. The label side keeps the 8px inset, so the side doesn't change a tab's width. */
|
||||
.editor:not(.vertical) .closeSlot {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
right: 2px;
|
||||
width: auto;
|
||||
margin: 0;
|
||||
}
|
||||
.editor:not(.vertical) .close {
|
||||
width: 16px;
|
||||
}
|
||||
.editor:not(.vertical) .closeSlot .modified {
|
||||
left: 5px;
|
||||
}
|
||||
.editor:not(.vertical, .closeLeft) .closable .tabButton {
|
||||
padding-right: 18px;
|
||||
}
|
||||
.editor.closeLeft:not(.vertical) .closeSlot {
|
||||
right: auto;
|
||||
left: 2px;
|
||||
}
|
||||
.editor.closeLeft:not(.vertical) .closable .tabButton {
|
||||
padding-left: 18px;
|
||||
}
|
||||
|
||||
/* drag & drop: the dragged tab is an empty slot the other tabs make room for (IDEA) */
|
||||
.tab.dragging,
|
||||
.tab.dragging:hover {
|
||||
|
||||
@@ -358,7 +358,10 @@ describe("Tabs drag & drop", () => {
|
||||
hit = strip("Terminal sessions");
|
||||
pointer(window, "pointermove", 60);
|
||||
expect(dragged).toHaveClass(styles.dragging!);
|
||||
const ghost = document.body.lastElementChild as HTMLElement;
|
||||
// The ghost sits in a copy of the strip's classes, so the strip's tab rules still lay it out.
|
||||
const context = document.body.lastElementChild as HTMLElement;
|
||||
expect(context.className).toBe(strip("Terminal sessions").parentElement!.className);
|
||||
const ghost = context.firstElementChild as HTMLElement;
|
||||
expect(ghost).toHaveAttribute("aria-hidden", "true");
|
||||
expect(ghost.style.position).toBe("fixed");
|
||||
expect(shown("Terminal sessions")).toEqual(["Local", "Local (2)", "Local (3)"]);
|
||||
@@ -378,7 +381,7 @@ describe("Tabs drag & drop", () => {
|
||||
.map((b) => b.textContent),
|
||||
).toEqual(["Local (2)", "Local", "Local (3)"]);
|
||||
expect(tab("Terminal sessions", "Local")).not.toHaveClass(styles.dragging!);
|
||||
expect(document.body.lastElementChild).not.toBe(ghost);
|
||||
expect(context.isConnected).toBe(false);
|
||||
});
|
||||
|
||||
it("puts the slot back when the pointer leaves the strip and drops nothing on Escape", () => {
|
||||
|
||||
+10
-10
@@ -362,18 +362,16 @@ export function Tabs({
|
||||
)
|
||||
: null;
|
||||
const marker = dragging === null ? drop : null;
|
||||
const stripClass = clsx(
|
||||
styles.strip,
|
||||
styles[variant],
|
||||
vertical ? styles.vertical : layout !== "scroll" && styles[layout],
|
||||
closePosition === "left" && styles.closeLeft,
|
||||
className,
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={clsx(
|
||||
styles.strip,
|
||||
styles[variant],
|
||||
vertical ? styles.vertical : layout !== "scroll" && styles[layout],
|
||||
closePosition === "left" && styles.closeLeft,
|
||||
className,
|
||||
)}
|
||||
ref={stripRef}
|
||||
>
|
||||
<div className={stripClass} ref={stripRef}>
|
||||
{vertical && trailing && <div className={styles.trailing}>{trailing}</div>}
|
||||
<div
|
||||
ref={scrollRef}
|
||||
@@ -422,6 +420,8 @@ export function Tabs({
|
||||
e.currentTarget,
|
||||
{ type: dnd.type, payload: dnd.payload(item.id) },
|
||||
{
|
||||
// The ghost keeps the strip's layout rules (close slot, insets).
|
||||
ghostContext: stripClass,
|
||||
onStart: () => {
|
||||
draggingRef.current = item.id;
|
||||
setDragging(item.id);
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -48,6 +48,37 @@ describe("startPointerDrag with a reordered macOS tap", () => {
|
||||
expect(onEnd).toHaveBeenCalledWith(true, expect.objectContaining({ x: 60 }));
|
||||
});
|
||||
|
||||
it.each([
|
||||
["dropped", () => fire("pointerup", 0, 40, 0)],
|
||||
["cancelled with Escape", () => window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }))],
|
||||
])("wraps the ghost in its source's context and removes both when %s", (_, end) => {
|
||||
const source = document.body.appendChild(document.createElement("div"));
|
||||
startPointerDrag(
|
||||
{ button: 0, clientX: 0, clientY: 0, altKey: false },
|
||||
source,
|
||||
{ type: "t", payload: "" },
|
||||
{ ghostContext: "strip editor" },
|
||||
);
|
||||
fire("pointermove", 1, 40, 0);
|
||||
const ghost = document.querySelector<HTMLElement>("[aria-hidden]")!;
|
||||
const context = ghost.parentElement!;
|
||||
expect(context.parentElement).toBe(document.body);
|
||||
expect([...context.classList]).toEqual(["strip", "editor"]);
|
||||
expect(context.style.display).toBe("contents");
|
||||
expect(ghost.style.position).toBe("fixed");
|
||||
end();
|
||||
expect(context.isConnected).toBe(false);
|
||||
expect(document.body.children).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("puts the ghost straight into the body without a context", () => {
|
||||
start();
|
||||
fire("pointermove", 1, 40, 0);
|
||||
expect(document.querySelector("[aria-hidden]")!.parentElement).toBe(document.body);
|
||||
fire("pointerup", 0, 40, 0);
|
||||
expect(document.querySelector("[aria-hidden]")).toBeNull();
|
||||
});
|
||||
|
||||
it("clears a text selection that began before the drag threshold (#3334)", () => {
|
||||
const text = document.body.appendChild(document.createElement("p"));
|
||||
text.textContent = "dragging a file must not select this";
|
||||
|
||||
+14
-2
@@ -158,11 +158,17 @@ export function startPointerDrag(
|
||||
onEnd?: (dragged: boolean, drop?: PointerDrop) => void;
|
||||
/** Not subject to "Drag-and-drop with Alt pressed only" (tabs and stripe buttons). */
|
||||
always?: boolean;
|
||||
/**
|
||||
* Classes of the container `source` is styled by (a tab strip's): the ghost is wrapped in a
|
||||
* `display: contents` element carrying them, so the container's descendant rules still match it.
|
||||
*/
|
||||
ghostContext?: string;
|
||||
} = {},
|
||||
) {
|
||||
if (e.button !== 0 || (!opts.always && requiresAlt() && !e.altKey)) return;
|
||||
const start = { x: e.clientX, y: e.clientY };
|
||||
let ghost: HTMLElement | null = null;
|
||||
let context: HTMLElement | null = null;
|
||||
let endDrag: (() => void) | null = null;
|
||||
const session = dragSession(data);
|
||||
const onMove = (ev: PointerEvent) => {
|
||||
@@ -185,7 +191,13 @@ export function startPointerDrag(
|
||||
width: `${r.width}px`,
|
||||
height: `${r.height}px`,
|
||||
});
|
||||
document.body.appendChild(ghost);
|
||||
if (opts.ghostContext) {
|
||||
context = document.createElement("div");
|
||||
context.className = opts.ghostContext;
|
||||
context.style.display = "contents";
|
||||
context.appendChild(ghost);
|
||||
}
|
||||
document.body.appendChild(context ?? ghost);
|
||||
endDrag = beginDrag();
|
||||
opts.onStart?.();
|
||||
}
|
||||
@@ -217,7 +229,7 @@ export function startPointerDrag(
|
||||
window.removeEventListener("pointerup", onUp);
|
||||
window.removeEventListener("pointercancel", onCancel);
|
||||
window.removeEventListener("keydown", onKey, true);
|
||||
ghost?.remove();
|
||||
(context ?? ghost)?.remove();
|
||||
endDrag?.();
|
||||
};
|
||||
const onCancel = () => {
|
||||
|
||||
Reference in new issue
Block a user