mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-22 19:49:35 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9b4358f046 |
No files matched your search
Generated
-1
@@ -5017,7 +5017,6 @@ dependencies = [
|
||||
"ignore",
|
||||
"notify",
|
||||
"parking_lot",
|
||||
"rayon",
|
||||
"rustix",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -217,8 +217,7 @@ impl ManageConnection for MssqlConnectionManager {
|
||||
let row = client.simple_query("SELECT DB_NAME()").await?.into_row().await?;
|
||||
let default = row
|
||||
.and_then(|r| r.get::<&str, _>(0).map(str::to_owned))
|
||||
// Statements that `USE` another database must not move the pooled connection for good.
|
||||
.map(|db| format!("USE {}", crate::sql::quote_ident(DbDriver::SqlServer, &db)));
|
||||
.and_then(|db| crate::sql::use_schema(DbDriver::SqlServer, &db));
|
||||
Ok(MssqlConnection(Some(client), Context::new(default)))
|
||||
}
|
||||
|
||||
|
||||
@@ -442,8 +442,7 @@ pub fn current_schema(driver: DbDriver) -> Option<&'static str> {
|
||||
DbDriver::Sqlite | DbDriver::Jdbc => None,
|
||||
DbDriver::Postgres => Some("SELECT current_schema()"),
|
||||
DbDriver::Mysql => Some("SELECT DATABASE()"),
|
||||
// The login's default schema; the database is the console's target (IDEA's `database.schema`).
|
||||
DbDriver::SqlServer => Some("SELECT SCHEMA_NAME()"),
|
||||
DbDriver::SqlServer => Some("SELECT DB_NAME()"),
|
||||
DbDriver::Oracle => Some("SELECT SYS_CONTEXT('USERENV', 'CURRENT_SCHEMA') FROM DUAL"),
|
||||
DbDriver::Snowflake => Some("SELECT CURRENT_SCHEMA()"),
|
||||
}
|
||||
@@ -451,13 +450,12 @@ pub fn current_schema(driver: DbDriver) -> Option<&'static str> {
|
||||
|
||||
/// The statement that makes unqualified names resolve in `schema` on the
|
||||
/// connection that runs it (a query console's active schema; `None`: the driver
|
||||
/// has no schema to switch — SQLite's `main`, ClickHouse's `USE` differs, and SQL Server
|
||||
/// cannot change a session's default schema, so its console schema only scopes resolution).
|
||||
/// has no schema to switch — SQLite's `main`, ClickHouse's `USE` differs).
|
||||
pub fn use_schema(driver: DbDriver, schema: &str) -> Option<String> {
|
||||
match driver {
|
||||
DbDriver::Sqlite | DbDriver::Clickhouse | DbDriver::Jdbc | DbDriver::SqlServer => None,
|
||||
DbDriver::Sqlite | DbDriver::Clickhouse | DbDriver::Jdbc => None,
|
||||
DbDriver::Postgres => Some(format!("SET search_path TO {}", quote_ident(driver, schema))),
|
||||
DbDriver::Mysql => Some(format!("USE {}", quote_ident(driver, schema))),
|
||||
DbDriver::Mysql | DbDriver::SqlServer => Some(format!("USE {}", quote_ident(driver, schema))),
|
||||
DbDriver::Oracle => Some(format!("ALTER SESSION SET CURRENT_SCHEMA = {}", quote_ident(driver, schema))),
|
||||
DbDriver::Snowflake => Some(format!("USE SCHEMA {}", quote_ident(driver, schema))),
|
||||
}
|
||||
@@ -1032,7 +1030,7 @@ mod tests {
|
||||
assert_eq!(quote_ident(DbDriver::SqlServer, "a]b"), "[a]]b]");
|
||||
assert_eq!(qualified(DbDriver::SqlServer, "dbo", "t"), "[dbo].[t]");
|
||||
assert_eq!(qualified(DbDriver::SqlServer, "", "t"), "[t]");
|
||||
assert_eq!(current_schema(DbDriver::SqlServer), Some("SELECT SCHEMA_NAME()"));
|
||||
assert_eq!(current_schema(DbDriver::SqlServer), Some("SELECT DB_NAME()"));
|
||||
assert_eq!(crate::conn::begin_statement(DbDriver::SqlServer), "BEGIN TRAN");
|
||||
assert_eq!(
|
||||
schemas(DbDriver::SqlServer, true),
|
||||
@@ -1151,7 +1149,7 @@ mod tests {
|
||||
fn schema_switch_statement_per_dialect() {
|
||||
assert_eq!(use_schema(DbDriver::Postgres, "app data"), Some("SET search_path TO \"app data\"".into()));
|
||||
assert_eq!(use_schema(DbDriver::Mysql, "a`b"), Some("USE `a``b`".into()));
|
||||
assert_eq!(use_schema(DbDriver::SqlServer, "dbo"), None);
|
||||
assert_eq!(use_schema(DbDriver::SqlServer, "app] data"), Some("USE [app]] data]".into()));
|
||||
assert_eq!(use_schema(DbDriver::Postgres, "a\"b"), Some("SET search_path TO \"a\"\"b\"".into()));
|
||||
assert_eq!(use_schema(DbDriver::Oracle, "a\"b"), Some("ALTER SESSION SET CURRENT_SCHEMA = \"a\"\"b\"".into()));
|
||||
assert!(sqlserver_databases().contains("state = 0 AND HAS_DBACCESS(name) = 1"));
|
||||
|
||||
@@ -22,7 +22,6 @@ parking_lot.workspace = true
|
||||
zip.workspace = true
|
||||
flate2.workspace = true
|
||||
tar.workspace = true
|
||||
rayon.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
+41
-48
@@ -10,7 +10,6 @@ mod rules;
|
||||
mod watch;
|
||||
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use rayon::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::cmp::Ordering;
|
||||
@@ -134,57 +133,51 @@ pub fn read_dir(dir: &Path, excludes: &[String]) -> IdeResult<Vec<FileEntry>> {
|
||||
let base = gitignore.repo_root().unwrap_or(dir).to_path_buf();
|
||||
let excludes = ExcludeMatcher::new(excludes);
|
||||
|
||||
let paths: Vec<PathBuf> = fs::read_dir(dir)?
|
||||
.filter_map(|entry| match entry {
|
||||
Ok(e) => Some(e.path()),
|
||||
let mut entries: Vec<(bool, FileEntry)> = Vec::new();
|
||||
for entry in fs::read_dir(dir)? {
|
||||
let entry = match entry {
|
||||
Ok(e) => e,
|
||||
Err(e) => {
|
||||
tracing::debug!("read_dir {}: {e}", dir.display());
|
||||
None
|
||||
continue;
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
// One stat per entry dominates a large folder (and every stat is a round trip on a network
|
||||
// share): stat in parallel; small folders stay on this thread.
|
||||
let mut entries: Vec<(bool, FileEntry)> = paths
|
||||
.into_par_iter()
|
||||
.with_min_len(256)
|
||||
.filter_map(|path| {
|
||||
let name = path.file_name()?.to_string_lossy().into_owned();
|
||||
let lmeta = fs::symlink_metadata(&path).ok()?;
|
||||
let (kind, meta, target_kind) = if lmeta.file_type().is_symlink() {
|
||||
match fs::metadata(&path) {
|
||||
Ok(m) => {
|
||||
let target = if m.is_dir() { EntryKind::Dir } else { EntryKind::File };
|
||||
(EntryKind::Symlink, m, Some(target))
|
||||
}
|
||||
Err(_) => (EntryKind::Symlink, lmeta, None),
|
||||
};
|
||||
let path = entry.path();
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
let Ok(lmeta) = fs::symlink_metadata(&path) else { continue };
|
||||
let (kind, meta, target_kind) = if lmeta.file_type().is_symlink() {
|
||||
match fs::metadata(&path) {
|
||||
Ok(m) => {
|
||||
let target = if m.is_dir() { EntryKind::Dir } else { EntryKind::File };
|
||||
(EntryKind::Symlink, m, Some(target))
|
||||
}
|
||||
} else if lmeta.is_dir() {
|
||||
(EntryKind::Dir, lmeta, None)
|
||||
} else {
|
||||
(EntryKind::File, lmeta, None)
|
||||
};
|
||||
let is_dir = meta.is_dir();
|
||||
let rel = path.strip_prefix(&base).unwrap_or(&path);
|
||||
let excluded = excludes.is_excluded(rel);
|
||||
let ignored = excluded || gitignore.is_ignored(&path, is_dir);
|
||||
Some((
|
||||
is_dir,
|
||||
FileEntry {
|
||||
hidden: name.starts_with('.'),
|
||||
size: if is_dir { 0 } else { meta.len() },
|
||||
mtime_ms: mtime_ms(&meta),
|
||||
name,
|
||||
path: path.into(),
|
||||
kind,
|
||||
ignored,
|
||||
excluded,
|
||||
target_kind,
|
||||
},
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
entries.par_sort_by(|(da, a), (db, b)| db.cmp(da).then_with(|| natural_cmp(&a.name, &b.name)));
|
||||
Err(_) => (EntryKind::Symlink, lmeta, None),
|
||||
}
|
||||
} else if lmeta.is_dir() {
|
||||
(EntryKind::Dir, lmeta, None)
|
||||
} else {
|
||||
(EntryKind::File, lmeta, None)
|
||||
};
|
||||
let is_dir = meta.is_dir();
|
||||
let rel = path.strip_prefix(&base).unwrap_or(&path);
|
||||
let excluded = excludes.is_excluded(rel);
|
||||
let ignored = excluded || gitignore.is_ignored(&path, is_dir);
|
||||
entries.push((
|
||||
is_dir,
|
||||
FileEntry {
|
||||
hidden: name.starts_with('.'),
|
||||
size: if is_dir { 0 } else { meta.len() },
|
||||
mtime_ms: mtime_ms(&meta),
|
||||
name,
|
||||
path: path.into(),
|
||||
kind,
|
||||
ignored,
|
||||
excluded,
|
||||
target_kind,
|
||||
},
|
||||
));
|
||||
}
|
||||
entries.sort_by(|(da, a), (db, b)| db.cmp(da).then_with(|| natural_cmp(&a.name, &b.name)));
|
||||
Ok(entries.into_iter().map(|(_, e)| e).collect())
|
||||
}
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ Conventions:
|
||||
| ---------- | --------------------------------------- | --------------------------------------------------------------------------------------- |
|
||||
| oxfmt | `pnpm format` (CI: `pnpm format:check`) | `.oxfmtrc.json`: print width 120, double quotes, semicolons, trailing commas everywhere |
|
||||
| oxlint | `pnpm lint` | `.oxlintrc.json`: TypeScript and React plugins |
|
||||
| Type check | `pnpm typecheck` | `tsconfig.json` and the configs of `e2e/`, `evals/`, `perf/`, `scripts/`, `smoke/` |
|
||||
| Type check | `pnpm typecheck` | `tsconfig.json` and the configs of `perf/`, `scripts/`, `smoke/` |
|
||||
| knip | `pnpm knip` | `knip.ts`: unused files, exports and dependencies |
|
||||
|
||||
`pnpm knip` fails on an export nobody imports, a file nobody reaches or a dependency nobody uses. Delete dead code rather than suppressing it; exports used only inside their own file are allowed.
|
||||
|
||||
@@ -206,7 +206,6 @@ 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.
|
||||
|
||||
@@ -25,12 +25,12 @@ description: "Rust 与 TypeScript 的格式化、lint 和死代码检查,以
|
||||
|
||||
## TypeScript 与 React
|
||||
|
||||
| 工具 | 命令 | 配置 |
|
||||
| -------- | ---------------------------------------- | --------------------------------------------------------------------------- |
|
||||
| oxfmt | `pnpm format`(CI:`pnpm format:check`) | `.oxfmtrc.json`:行宽 120、双引号、处处尾逗号 |
|
||||
| oxlint | `pnpm lint` | `.oxlintrc.json`:TypeScript 和 React 插件 |
|
||||
| 类型检查 | `pnpm typecheck` | `tsconfig.json` 以及 `e2e/`、`evals/`、`perf/`、`scripts/`、`smoke/` 的配置 |
|
||||
| knip | `pnpm knip` | `knip.ts`:未使用的文件、导出和依赖 |
|
||||
| 工具 | 命令 | 配置 |
|
||||
| -------- | ---------------------------------------- | --------------------------------------------------------- |
|
||||
| oxfmt | `pnpm format`(CI:`pnpm format:check`) | `.oxfmtrc.json`:行宽 120、双引号、分号、处处尾逗号 |
|
||||
| oxlint | `pnpm lint` | `.oxlintrc.json`:TypeScript 和 React 插件 |
|
||||
| 类型检查 | `pnpm typecheck` | `tsconfig.json` 以及 `perf/`、`scripts/`、`smoke/` 的配置 |
|
||||
| knip | `pnpm knip` | `knip.ts`:未使用的文件、导出和依赖 |
|
||||
|
||||
`pnpm knip` 发现没人 import 的导出、没人引用的文件或没人用的依赖时会失败。请删掉死代码,而不是屏蔽检查;只在本文件内使用的导出是允许的。
|
||||
|
||||
|
||||
@@ -204,7 +204,6 @@ Git 工具窗口的 **日志** 标签页显示提交图。
|
||||
|
||||
- **搁置更改…**:选择文件并命名,之后这些更改会被还原。
|
||||
- **取消搁置…**:以三方合并的方式把搁置(或其中某个文件)应用到你选择的更改列表。
|
||||
- **静默搁置**(`⇧⌘H` / `Ctrl+Shift+H`,也在更改工具栏上)不弹对话框,直接搁置选中的更改(未选中时为活动更改列表):每个更改列表一个搁置,以列表名命名。**静默取消搁置**(在搁置中按 `⌥⌘U` / `Ctrl+Alt+U`)把选中的搁置或文件应用到与搁置同名的更改列表,没有则应用到活动更改列表。
|
||||
- **搁置** 标签页列出所有搁置,支持查看差异、与本地比较、导出补丁、重命名和删除。
|
||||
|
||||
在 Git 设置中打开 **在同一个标签页中合并显示贮藏和搁置**,两者会显示在同一个标签页里。
|
||||
|
||||
@@ -26,7 +26,7 @@ const firstTask: AgentTask = {
|
||||
const secondTask: AgentTask = { ...firstTask, id: "focus-second", title: "Second focus task" };
|
||||
const draft = "draft keep this unsent";
|
||||
const reboundShortcut = "Control+Meta+Shift+J";
|
||||
const subagent: Extract<AgentEntry, { type: "subagent" }> = {
|
||||
const subagent: AgentEntry = {
|
||||
type: "subagent",
|
||||
id: "focus-child",
|
||||
title: "Inspect focus behavior",
|
||||
|
||||
@@ -149,7 +149,7 @@ test("opens slash-prefixed Windows Markdown links with preview content and hover
|
||||
for (const [label, path, heading] of [
|
||||
["Specification", spec, "Windows specification"],
|
||||
["Work skill", skill, "Work specification skill"],
|
||||
] as const) {
|
||||
]) {
|
||||
const link = reply.getByRole("link", { name: label, exact: true });
|
||||
await link.hover();
|
||||
await expect(link).toHaveAttribute("title", path);
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
import type { AgentQuestion, AgentTask } from "../src/bindings";
|
||||
import type * as AgentStore from "../src/features/agents/store";
|
||||
import type * as Ipc from "../src/platform/ipc";
|
||||
|
||||
const task: AgentTask = {
|
||||
id: "questions",
|
||||
@@ -51,12 +49,14 @@ for (const status of ["running", "ready"] as const) {
|
||||
const key = JSON.stringify(["request_user_input_async", "call-1", 0]);
|
||||
await page.evaluate(
|
||||
async ({ task, status, key }) => {
|
||||
// Keep the workbench imports in the browser's Vite realm.
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const ipcPath = "/src/platform/ipc.ts";
|
||||
const store: typeof AgentStore = await import(storePath);
|
||||
const { commands }: typeof Ipc = await import(ipcPath);
|
||||
commands.agentAnswerQuestion = async (id, question, answer) => {
|
||||
const store = await import(storePath);
|
||||
(await import(ipcPath)).commands.agentAnswerQuestion = async (
|
||||
id: string,
|
||||
question: string,
|
||||
answer: string | null,
|
||||
) => {
|
||||
document.documentElement.dataset.asyncAnswer = JSON.stringify({ id, question, answer });
|
||||
const entries = store.useAgents.getState().entries.get(id)!;
|
||||
store.useAgents.setState({
|
||||
@@ -111,7 +111,7 @@ for (const status of ["running", "ready"] as const) {
|
||||
if (status === "running") {
|
||||
await page.evaluate(async (id) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const { useAgents }: typeof AgentStore = await import(storePath);
|
||||
const { useAgents } = await import(storePath);
|
||||
useAgents.setState((s) => ({ tasks: new Map(s.tasks).set(id, { ...s.tasks.get(id)!, status: "ready" }) }));
|
||||
}, task.id);
|
||||
await expect(card.getByRole("radio", { name: /^Read latest content/ })).toBeChecked();
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type * as ProjectStore from "../src/platform/project";
|
||||
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test.use({ video: "on" });
|
||||
@@ -115,11 +114,9 @@ test("restricting an attached folder leaves the current project untouched", asyn
|
||||
test("restricted attachments can be trusted individually from the banner", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
// Load the running workbench's store in the browser.
|
||||
const projectPath = "/src/platform/project.ts";
|
||||
const { useProject }: typeof ProjectStore = await import(/* @vite-ignore */ projectPath);
|
||||
const m = "/src/platform/project.ts";
|
||||
const { useProject } = await import(/* @vite-ignore */ m);
|
||||
const primary = useProject.getState().project;
|
||||
if (!primary) throw new Error("Expected the sample project to be open");
|
||||
let current = {
|
||||
...primary,
|
||||
trusted: false,
|
||||
@@ -129,11 +126,11 @@ test("restricted attachments can be trusted individually from the banner", async
|
||||
const trusted = new Set([primary.root]);
|
||||
window.__ipc.handlers.project_trust_status = ({ path }) => ({
|
||||
root: path,
|
||||
trusted: typeof path === "string" && trusted.has(path),
|
||||
trusted: trusted.has(path),
|
||||
decided: true,
|
||||
});
|
||||
window.__ipc.handlers.project_trust_set = ({ path, trusted: allow }) => {
|
||||
if (allow && typeof path === "string") trusted.add(path);
|
||||
if (allow) trusted.add(path);
|
||||
current = { ...current, trusted: current.workspace.projects.every((path) => trusted.has(path)) };
|
||||
};
|
||||
window.__ipc.handlers.project_current = () => current;
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
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 });
|
||||
});
|
||||
@@ -1,50 +0,0 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("keeps breakpoint details editable when the dialog gets narrow", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 500, height: 480 });
|
||||
await page.evaluate(async () => {
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const storeModule = "/src/features/debugger/breakpoints/store.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
const { addBreakpoint } = await import(/* @vite-ignore */ storeModule);
|
||||
addBreakpoint("/dev/acme-api/CheckInternationalSettlementBeforeDispatch.java", 7, {
|
||||
condition: "amount > 100",
|
||||
});
|
||||
addBreakpoint("/dev/acme-api/Receipt.java", 4);
|
||||
await executeAction("debug.viewBreakpoints");
|
||||
});
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Breakpoints" });
|
||||
const list = dialog.getByRole("listbox", { name: "All breakpoints" });
|
||||
const condition = dialog.locator('input[aria-label="Condition"]');
|
||||
await expect(condition).toHaveValue("amount > 100");
|
||||
await expect.poll(async () => (await condition.boundingBox())?.width ?? 0).toBeGreaterThanOrEqual(240);
|
||||
await expect(dialog.getByRole("button", { name: "Done", exact: true })).toBeInViewport({ ratio: 1 });
|
||||
await condition.fill("amount > 250");
|
||||
await dialog.getByRole("checkbox", { name: "Evaluate and log", exact: true }).check();
|
||||
await dialog.getByRole("textbox", { name: "Evaluate and log", exact: true }).fill("total: {amount}");
|
||||
const first = list.getByRole("option", { name: /CheckInternationalSettlementBeforeDispatch\.java:8/ });
|
||||
await expect(first.getByText(":8", { exact: true })).toBeInViewport({ ratio: 1 });
|
||||
await list.getByRole("option", { name: /Receipt\.java:5/ }).click();
|
||||
await expect(condition).toHaveValue("");
|
||||
await first.click();
|
||||
await expect(condition).toHaveValue("amount > 250");
|
||||
await expect(dialog.getByRole("textbox", { name: "Evaluate and log", exact: true })).toHaveValue("total: {amount}");
|
||||
|
||||
await page.setViewportSize({ width: 1080, height: 760 });
|
||||
const divider = dialog.locator('[data-separator][aria-orientation="vertical"]');
|
||||
await expect(divider).toBeInViewport();
|
||||
const oldWidth = (await list.boundingBox())!.width;
|
||||
const handle = (await divider.boundingBox())!;
|
||||
await page.mouse.move(handle.x + handle.width / 2, handle.y + handle.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(handle.x + 60, handle.y + handle.height / 2, { steps: 4 });
|
||||
await page.mouse.up();
|
||||
await expect.poll(async () => (await list.boundingBox())?.width ?? 0).toBeGreaterThan(oldWidth + 20);
|
||||
await expect(condition).toHaveValue("amount > 250");
|
||||
const request = dialog.getByRole("textbox", { name: "Part of a request URL" });
|
||||
await request.scrollIntoViewIfNeeded();
|
||||
await expect(request).toBeInViewport({ ratio: 1 });
|
||||
await dialog.getByRole("button", { name: "Done", exact: true }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
});
|
||||
@@ -1,75 +0,0 @@
|
||||
import type { MethodSignature } from "../src/bindings";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const signature: MethodSignature = {
|
||||
methodIdentifier: "invoice",
|
||||
modifier: "",
|
||||
returnType: "Invoice",
|
||||
methodName: "prepareInvoiceForInternationalSettlement",
|
||||
parameters: [
|
||||
["Order", "order"],
|
||||
["String", "billingCurrency"],
|
||||
["BigDecimal", "amountBeforeDiscount"],
|
||||
["Map<String, BigDecimal>", "taxRatesByJurisdiction"],
|
||||
["List<Adjustment>", "settlementAdjustments"],
|
||||
["RoundingMode", "roundingMode"],
|
||||
["LocalDate", "scheduledSettlementDate"],
|
||||
["boolean", "includeTaxBreakdown"],
|
||||
].map(([type, name], originalIndex) => ({ type: type!, name: name!, originalIndex, defaultValue: "" })),
|
||||
exceptions: [],
|
||||
};
|
||||
|
||||
test("keeps parameter rows and a long signature preview usable in a short dialog", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 490, height: 520 });
|
||||
await page.evaluate(async () => {
|
||||
const workbench = "/src/workbench/contributions.ts";
|
||||
const { editorService } = await import(/* @vite-ignore */ workbench);
|
||||
await editorService().openFile("/dev/acme-api/InvoiceService.java");
|
||||
});
|
||||
const editor = page.locator(".cm-editor .cm-content");
|
||||
await expect(editor).toBeVisible();
|
||||
await stubDesktop(page);
|
||||
const fontSize = await editor.evaluate(async (content, signature) => {
|
||||
window.__ipc.handlers.lsp_signature_info = () => signature;
|
||||
const viewModule = "/node_modules/.vite/deps/@codemirror_view.js";
|
||||
const prefsModule = "/src/editor/core/cm/prefs.ts";
|
||||
const { EditorView } = await import(/* @vite-ignore */ viewModule);
|
||||
const { stepFontZoom } = await import(/* @vite-ignore */ prefsModule);
|
||||
const base = Number.parseFloat(getComputedStyle(content).fontSize);
|
||||
const view = EditorView.findFromDOM(content as HTMLElement)!;
|
||||
stepFontZoom(view, 4);
|
||||
view.focus();
|
||||
return `${base + 4}px`;
|
||||
}, signature);
|
||||
await expect(editor).toHaveCSS("font-size", fontSize);
|
||||
await page.keyboard.press("Meta+F6");
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Change Signature" });
|
||||
const table = dialog.getByRole("table", { name: "Parameters" });
|
||||
const names = table.getByRole("textbox", { name: "Name", exact: true });
|
||||
await expect(names.first()).toBeInViewport({ ratio: 1 });
|
||||
const defaults = table.getByRole("columnheader", { name: "Default value", exact: true });
|
||||
await expect(defaults).toHaveCount(0);
|
||||
const preview = dialog.locator("pre");
|
||||
await expect(preview).toBeInViewport({ ratio: 1 });
|
||||
await expect(preview).toHaveCSS("font-size", fontSize);
|
||||
await expect(names.first()).toHaveCSS("font-size", fontSize);
|
||||
expect(
|
||||
await preview.evaluate((el) => el.scrollHeight > el.clientHeight && el.scrollWidth <= el.clientWidth + 1),
|
||||
).toBe(true);
|
||||
await expect(dialog.getByRole("button", { name: "Cancel" })).toBeInViewport({ ratio: 1 });
|
||||
|
||||
await dialog.getByRole("button", { name: "Add", exact: true }).click();
|
||||
await expect(defaults).toBeInViewport({ ratio: 1 });
|
||||
const addedType = table.getByRole("textbox", { name: "Type", exact: true }).last();
|
||||
await expect(addedType).toBeInViewport({ ratio: 1 });
|
||||
await addedType.fill("boolean");
|
||||
await names.last().fill("attachReceipt");
|
||||
await table.getByRole("textbox", { name: "Default value", exact: true }).last().fill("false");
|
||||
await dialog.getByRole("button", { name: "Move Up", exact: true }).click();
|
||||
await expect(names.nth(7)).toHaveValue("attachReceipt");
|
||||
await expect(preview).toContainText("boolean attachReceipt");
|
||||
await expect(dialog.getByRole("button", { name: "Preview", exact: true })).toBeEnabled();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(dialog).toBeHidden();
|
||||
});
|
||||
@@ -1,62 +0,0 @@
|
||||
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 })]);
|
||||
});
|
||||
+1
-76
@@ -559,82 +559,7 @@ test("indexed single-file rename previews all anchors and applies only after con
|
||||
}
|
||||
await expect.poll(() => ipcCalls(page, "apply_workspace_edit")).toHaveLength(1);
|
||||
const [apply] = await ipcCalls(page, "apply_workspace_edit");
|
||||
expect(apply?.edit).toMatchObject({ preconditions: [{ path: FILE, hash: "indexed-snapshot" }] });
|
||||
});
|
||||
|
||||
test("rename keeps the typed name, uses the editor font and shows long preview names in a narrow dialog", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const editor = await openSample(page);
|
||||
await page.evaluate(
|
||||
async ({ file, prepared }) => {
|
||||
const projectModule = "/src/platform/project.ts";
|
||||
const schemaModule = "/src/features/settings/model/schema.ts";
|
||||
const [{ useProject }, { DEFAULT_SETTINGS }] = await Promise.all([
|
||||
import(/* @vite-ignore */ projectModule),
|
||||
import(/* @vite-ignore */ schemaModule),
|
||||
]);
|
||||
const base = useProject.getState().settings ?? DEFAULT_SETTINGS;
|
||||
useProject.setState({ settings: { ...base, editor: { ...base.editor, fontSize: 17 } } });
|
||||
window.__ipc.handlers.lsp_prepare_rename = () => prepared;
|
||||
window.__ipc.handlers.lsp_rename = (args) => ({
|
||||
preview: true,
|
||||
incomplete: null,
|
||||
edit: {
|
||||
files: [
|
||||
{
|
||||
kind: "edit",
|
||||
path: file,
|
||||
edits: [{ range: prepared, new_text: args.newName }],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
window.__ipc.handlers.apply_workspace_edit = () => null;
|
||||
},
|
||||
{ file: FILE, prepared: range(20, 12, 17) },
|
||||
);
|
||||
|
||||
await caretAt(editor, page, "val order: Order", "order");
|
||||
await page.keyboard.press("Shift+F6");
|
||||
await expect(page.getByText(/Press ⇧F6 to show dialog/)).toBeVisible();
|
||||
const name = "checkoutOrderWithDeliveryInstructionsAndInventoryReservation";
|
||||
await page.keyboard.insertText(name);
|
||||
await page.keyboard.press("Shift+F6");
|
||||
await page.setViewportSize({ width: 440, height: 520 });
|
||||
const dialog = page.getByRole("dialog", { name: "Rename 'order'", exact: true });
|
||||
const input = dialog.getByRole("textbox", { name: "New name" });
|
||||
await expect(input).toBeFocused();
|
||||
await expect(input).toHaveValue(name);
|
||||
await expect(input).toHaveCSS("font-size", "17px");
|
||||
const [label, field] = await Promise.all([
|
||||
dialog.getByText("New name", { exact: true }).boundingBox(),
|
||||
input.boundingBox(),
|
||||
]);
|
||||
expect(label!.x + label!.width).toBeLessThan(field!.x);
|
||||
const rename = dialog.getByRole("button", { name: "Rename", exact: true });
|
||||
|
||||
await input.fill("");
|
||||
await expect(rename).toBeDisabled();
|
||||
await input.press("Enter");
|
||||
await expect(dialog).toBeVisible();
|
||||
expect(await ipcCalls(page, "lsp_rename")).toHaveLength(0);
|
||||
await input.fill(name);
|
||||
await input.press("Enter");
|
||||
|
||||
const summary = `Rename 'order' to '${name}'`;
|
||||
const preview = page.getByRole("dialog", { name: summary, exact: true });
|
||||
const context = preview.getByText(summary, { exact: true });
|
||||
await expect(context).toBeVisible();
|
||||
const geometry = await context.evaluate((element) => ({
|
||||
client: element.clientWidth,
|
||||
content: element.scrollWidth,
|
||||
}));
|
||||
expect(geometry.content).toBeLessThanOrEqual(geometry.client + 1);
|
||||
await expect(preview.getByText("1 occurrence in 1 file")).toBeVisible();
|
||||
expect(await ipcCalls(page, "apply_workspace_edit")).toHaveLength(0);
|
||||
await preview.getByRole("button", { name: "Do Refactor" }).click();
|
||||
await expect.poll(() => ipcCalls(page, "apply_workspace_edit")).toHaveLength(1);
|
||||
expect(apply.edit).toMatchObject({ preconditions: [{ path: FILE, hash: "indexed-snapshot" }] });
|
||||
});
|
||||
|
||||
test("intention previews fit narrow windows and wrap long code lines", async ({ workbench: page }) => {
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
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();
|
||||
});
|
||||
@@ -6,7 +6,7 @@ for (const [id, selector] of [
|
||||
["keymap", "[class*='presetLabel']"],
|
||||
["editor.inspections", "[class*='profileRow'] > span:first-child"],
|
||||
["vcs.issueNavigation", "[class*='pageBody'] button:not([aria-label])"],
|
||||
] as const) {
|
||||
]) {
|
||||
test(`${id} keeps compact labels inside their controls`, async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog");
|
||||
@@ -41,7 +41,7 @@ for (const [id, selector] of [
|
||||
for (const [id, selector] of [
|
||||
["general", "[class*='fontRow'] > label"],
|
||||
["build.console", "[class*='inlineRow'] > label"],
|
||||
] as const) {
|
||||
]) {
|
||||
test(`${id} keeps a readable width for inline text`, async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
await expect(page.getByRole("dialog", { name: "Settings", exact: true })).toBeVisible();
|
||||
|
||||
@@ -49,7 +49,7 @@ commands.lspHover = async () => {
|
||||
};
|
||||
commands.lspDocumentLinks = async () => ({ status: "ok", data: [] });
|
||||
commands.lspDocumentHighlights = async () => ({ status: "ok", data: [] });
|
||||
commands.cancelRequest = async () => {};
|
||||
commands.cancelRequest = async () => ({ status: "ok", data: null });
|
||||
const java = new EditorView({
|
||||
parent: javaHost,
|
||||
state: EditorState.create({
|
||||
|
||||
@@ -10,7 +10,7 @@ test("data source tabs share a stable layout and scroll within a short window",
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "New Data Source" });
|
||||
const panel = dialog.getByRole("tabpanel");
|
||||
const dialogSize = () => dialog.evaluate((element: HTMLElement) => [element.offsetWidth, element.offsetHeight]);
|
||||
const dialogSize = () => dialog.evaluate((element) => [element.offsetWidth, element.offsetHeight]);
|
||||
await expect(panel.getByRole("textbox", { name: "Host:" })).toBeVisible();
|
||||
const size = await dialogSize();
|
||||
await dialog.getByRole("tab", { name: "SSH/SSL" }).click();
|
||||
|
||||
@@ -187,7 +187,7 @@ test("result context menu fits the viewport, responds to hover and keyboard, and
|
||||
for (const [theme, label] of [
|
||||
["solarized-light", "Solarized Light"],
|
||||
["solarized-dark", "Solarized Dark"],
|
||||
] as const) {
|
||||
]) {
|
||||
test(`${label}: retains the inactive context-menu target's hover until dismissal without selecting it`, async ({
|
||||
workbench: page,
|
||||
}, info) => {
|
||||
|
||||
@@ -113,60 +113,3 @@ test("stops at a breakpoint, shows frames and variables, steps and resumes", asy
|
||||
await expect.poll(() => ipcCalls(page, "debug_resume")).toHaveLength(1);
|
||||
await expect(debug.getByText("CreateOrderRequest(sku='A-1', qty=2)")).toBeHidden();
|
||||
});
|
||||
|
||||
test("Evaluate keeps a multiline expression and its result visible in a short dialog", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 580, height: 420 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async (session) => {
|
||||
const handlers = window.__ipc.handlers;
|
||||
handlers.debug_capabilities = () => ({});
|
||||
handlers.debug_completions = () => [];
|
||||
handlers.debug_evaluate_in = () => ({
|
||||
name: "orderSummary",
|
||||
typeName: "OrderSummary",
|
||||
value: "total = 36",
|
||||
variablesReference: 210,
|
||||
evaluateName: null,
|
||||
});
|
||||
handlers.debug_variables = () => [
|
||||
{ name: "tax", value: "4", typeName: "int", variablesReference: 0, evaluateName: null },
|
||||
];
|
||||
const stateModule = "/src/features/debugger/state.ts";
|
||||
const { adoptSession } = await import(/* @vite-ignore */ stateModule);
|
||||
adoptSession(session, { name: "Checkout", adapter: "debugpy", status: "paused", selectedFrame: 11 });
|
||||
}, SESSION);
|
||||
|
||||
await page.keyboard.press("Alt+F8");
|
||||
const dialog = page.getByRole("dialog", { name: "Evaluate expression" });
|
||||
const field = dialog.getByRole("textbox", { name: "Expression" });
|
||||
const expression = ["orderSummary(", ...Array.from({ length: 12 }, (_, i) => ` item${i},`), ")"].join("\n");
|
||||
await field.fill(expression);
|
||||
await field.press("Enter");
|
||||
const result = dialog.getByRole("tree", { name: "Evaluation result" });
|
||||
const row = result.getByRole("treeitem").first();
|
||||
await expect(row).toContainText("total = 36");
|
||||
await expect
|
||||
.poll(() =>
|
||||
dialog.locator("[data-dialog-body]").evaluate((body) => {
|
||||
const area = body.querySelector("textarea")!;
|
||||
const resultRow = body.querySelector('[role="treeitem"]')!.getBoundingClientRect();
|
||||
const bounds = body.getBoundingClientRect();
|
||||
return (
|
||||
body.scrollHeight <= body.clientHeight + 1 &&
|
||||
area.scrollHeight > area.clientHeight &&
|
||||
resultRow.top >= bounds.top &&
|
||||
resultRow.bottom <= bounds.bottom
|
||||
);
|
||||
}),
|
||||
)
|
||||
.toBe(true);
|
||||
await row.click();
|
||||
await row.press("ArrowRight");
|
||||
await expect(result.getByText("tax", { exact: true })).toBeVisible();
|
||||
|
||||
await field.fill("otherExpression");
|
||||
await dialog.getByRole("button", { name: "History", exact: true }).click();
|
||||
await page.getByRole("menuitem", { name: /orderSummary/ }).click();
|
||||
await expect(field).toHaveValue(expression);
|
||||
await expect(field).toBeFocused();
|
||||
});
|
||||
@@ -1,63 +0,0 @@
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const amountName = "regionalSettlementAmountFromExternalProcessorBeforeRounding";
|
||||
const routingName = "settlementRoutingReferenceForCrossBorderReconciliation";
|
||||
const routingValue = "'APR-2026 / eu-west / batch-701 / settlement complete'";
|
||||
|
||||
test("keeps values and their full-value action readable in a narrow debugger", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1220, height: 760 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ amountName, routingName, routingValue }) => {
|
||||
const debugModule = "/src/features/debugger/state.ts";
|
||||
const layoutModule = "/src/workbench/toolwindows/store.ts";
|
||||
const servicesModule = "/src/workbench/contributions.ts";
|
||||
const { adoptSession } = await import(/* @vite-ignore */ debugModule);
|
||||
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
|
||||
const { toolWindowService } = await import(/* @vite-ignore */ servicesModule);
|
||||
const h = window.__ipc.handlers;
|
||||
h.debug_scopes = () => [{ name: "Locals", variablesReference: 100, expensive: false }];
|
||||
h.debug_variables = () => [
|
||||
{ name: amountName, value: "47.74", typeName: "float", variablesReference: 0, evaluateName: amountName },
|
||||
{ name: routingName, value: routingValue, typeName: "str", variablesReference: 0, evaluateName: routingName },
|
||||
];
|
||||
adoptSession(91, {
|
||||
name: "Checkout",
|
||||
adapter: "debugpy",
|
||||
status: "paused",
|
||||
selectedFrame: 11,
|
||||
frames: [{ id: 11, name: "checkout", path: null, line: 0, column: 0, presentationHint: null }],
|
||||
});
|
||||
moveToolWindow("debug", "right");
|
||||
setToolWindowSize("right", 390);
|
||||
toolWindowService().show("debug", true);
|
||||
},
|
||||
{ amountName, routingName, routingValue },
|
||||
);
|
||||
|
||||
const debug = page.getByRole("region", { name: "Debug", exact: true });
|
||||
await debug.getByRole("tab", { name: "Threads & Variables", exact: true }).click();
|
||||
const amount = debug.getByText("47.74", { exact: true });
|
||||
await expect
|
||||
.poll(() => amount.evaluate((el) => el.clientWidth > 0 && el.scrollWidth <= el.clientWidth + 1))
|
||||
.toBe(true);
|
||||
const routing = debug.getByRole("treeitem").filter({ hasText: routingName });
|
||||
const show = routing.getByTitle("Show", { exact: true });
|
||||
await expect(show).toBeInViewport({ ratio: 1 });
|
||||
await show.click();
|
||||
const dialog = page.getByRole("dialog", { name: `Value of ${routingName}` });
|
||||
await expect(dialog.getByText(routingValue, { exact: true })).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(dialog).toBeHidden();
|
||||
|
||||
await page.setViewportSize({ width: 1640, height: 760 });
|
||||
await page.evaluate(async () => {
|
||||
const layoutModule = "/src/workbench/toolwindows/store.ts";
|
||||
const { moveToolWindow } = await import(/* @vite-ignore */ layoutModule);
|
||||
moveToolWindow("debug", "bottom");
|
||||
});
|
||||
await expect(show).toBeHidden();
|
||||
await expect
|
||||
.poll(() => routing.getByText(routingValue, { exact: true }).evaluate((el) => el.scrollWidth <= el.clientWidth + 1))
|
||||
.toBe(true);
|
||||
});
|
||||
@@ -232,48 +232,6 @@ test("⌘R replaces every match in the file", async ({ workbench: page }) => {
|
||||
await expect(editor.locator(".cm-line", { hasText: "OrderDto" })).toHaveCount(2);
|
||||
});
|
||||
|
||||
test("the inline find and replace controls stay inside a narrow editor pane", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1120, height: 760 });
|
||||
const editor = await openFromTree(page, "build.gradle.kts");
|
||||
await editor.locator(".cm-content").click();
|
||||
await page.keyboard.press("Meta+r");
|
||||
const bar = page.getByRole("search", { name: "Replace in file" });
|
||||
const find = bar.getByRole("textbox", { name: "Find" });
|
||||
const replace = bar.getByRole("textbox", { name: "Replace" });
|
||||
const next = bar.getByRole("button", { name: /Next Occurrence/ });
|
||||
await find.fill("OrderDto");
|
||||
await find.press("Tab");
|
||||
await expect(replace).toBeFocused();
|
||||
await replace.fill("OrderView");
|
||||
const navigationIsBelowFind = async () => {
|
||||
const [input, button] = await Promise.all([find.boundingBox(), next.boundingBox()]);
|
||||
return !!input && !!button && button.y >= input.y + input.height;
|
||||
};
|
||||
const controlsFit = () =>
|
||||
bar.evaluate((panel) => {
|
||||
const bounds = panel.getBoundingClientRect();
|
||||
return [...panel.querySelectorAll("button, textarea")].every((element) => {
|
||||
const control = element.getBoundingClientRect();
|
||||
return control.width > 0 && control.left >= bounds.left && control.right <= bounds.right;
|
||||
});
|
||||
});
|
||||
await expect.poll(navigationIsBelowFind).toBe(false);
|
||||
|
||||
await page.setViewportSize({ width: 590, height: 760 });
|
||||
await expect.poll(controlsFit).toBe(true);
|
||||
await expect.poll(navigationIsBelowFind).toBe(true);
|
||||
await page.setViewportSize({ width: 495, height: 760 });
|
||||
await expect.poll(controlsFit).toBe(true);
|
||||
await expect(find).toHaveValue("OrderDto");
|
||||
await expect(replace).toHaveValue("OrderView");
|
||||
await next.click();
|
||||
await expect(bar.getByText(/^[12]\/2$/)).toBeVisible();
|
||||
await bar.getByRole("button", { name: "Replace All" }).click();
|
||||
await expect(editor.locator(".cm-line", { hasText: "OrderView" })).toHaveCount(2);
|
||||
await bar.getByRole("button", { name: "Close", exact: true }).click();
|
||||
await expect(bar).toBeHidden();
|
||||
});
|
||||
|
||||
test("Markdown preview highlights ⌘F matches, selected words and scales diagrams with font zoom", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
@@ -638,15 +596,3 @@ test("dragging the Markdown split divider resizes and reflows editor and preview
|
||||
.poll(async () => Math.round((await reopenedEditor.boundingBox())!.width))
|
||||
.toBe(Math.round(initialEditor));
|
||||
});
|
||||
|
||||
test("Markdown Preview only leaves the Project view clickable", async ({ workbench: page }) => {
|
||||
await openFromTree(page, "README.md");
|
||||
await page.getByRole("button", { name: "Preview Only" }).click();
|
||||
await expect(page.getByRole("document", { name: "Markdown preview" })).toBeVisible();
|
||||
|
||||
const row = page.getByRole("treeitem", { name: "build.gradle.kts", exact: true });
|
||||
// A hidden editor panel used to leave an implicit resize region over everything left of the preview,
|
||||
// which swallowed the click.
|
||||
await row.click();
|
||||
await expect(row).toHaveAttribute("aria-selected", "true");
|
||||
});
|
||||
@@ -1,90 +0,0 @@
|
||||
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);
|
||||
});
|
||||
@@ -1,86 +0,0 @@
|
||||
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();
|
||||
});
|
||||
@@ -1,98 +0,0 @@
|
||||
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 });
|
||||
});
|
||||
@@ -45,10 +45,11 @@ POST https://example.test/messages
|
||||
const json = document.createElement("div");
|
||||
json.id = "json";
|
||||
document.body.append(json);
|
||||
const jsonSupport = await loadSupport(findLanguageDescription("JSON", "body.json")!);
|
||||
if (!jsonSupport) throw new Error("Failed to load JSON support for the highlighting fixture");
|
||||
new EditorView({
|
||||
parent: json,
|
||||
doc: '{"name": "World", "count": 12, "enabled": true, "ready": false, "empty": null, "items": [1]}',
|
||||
extensions: [jsonSupport, syntaxHighlighting(openideaHighlightStyle)],
|
||||
extensions: [
|
||||
await loadSupport(findLanguageDescription("JSON", "body.json")!),
|
||||
syntaxHighlighting(openideaHighlightStyle),
|
||||
],
|
||||
});
|
||||
@@ -1,5 +1,4 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import type * as EditorBackend from "../src/editor/core/backend";
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
const xml = readFileSync(
|
||||
@@ -11,14 +10,13 @@ test("imported PHP colours stay separate from Java and preserve regular text on
|
||||
workbench: page,
|
||||
}, info) => {
|
||||
await page.evaluate(async (xml) => {
|
||||
// Load the workbench modules in the browser's Vite realm.
|
||||
const iclsPath = "/src/platform/icls.ts";
|
||||
const projectPath = "/src/platform/project.ts";
|
||||
const backendPath = "/src/editor/core/backend.ts";
|
||||
const contributionsPath = "/src/workbench/contributions.ts";
|
||||
const { parseIcls } = await import(iclsPath);
|
||||
const { useProject } = await import(projectPath);
|
||||
const { docBackend }: typeof EditorBackend = await import(backendPath);
|
||||
const { docBackend } = await import(backendPath);
|
||||
const { editorService } = await import(contributionsPath);
|
||||
const previous = useProject.getState().settings ?? {};
|
||||
useProject.setState({
|
||||
@@ -33,11 +31,10 @@ test("imported PHP colours stay separate from Java and preserve regular text on
|
||||
},
|
||||
});
|
||||
const backend = docBackend();
|
||||
if (!("files" in backend) || !(backend.files instanceof Map)) throw new Error("Expected the in-memory backend");
|
||||
const open = backend.open.bind(backend);
|
||||
backend.open = async (path) => {
|
||||
const result = await open(path);
|
||||
return path.endsWith(".php") ? { ...result, language: "php", uiMode: "PHP" } : result;
|
||||
backend.open = async (...args: Parameters<typeof open>) => {
|
||||
const result = await open(...args);
|
||||
return args[0].endsWith(".php") ? { ...result, language: "php", uiMode: "PHP" } : result;
|
||||
};
|
||||
backend.files.set(
|
||||
"/dev/acme-api/palette.php",
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import type { InlayHint, Range } from "../src/bindings";
|
||||
import { commands } from "../src/platform/ipc";
|
||||
import { commands, type InlayHint, type Range } from "../src/platform/ipc";
|
||||
import { setInvokeRoute } from "../src/platform/tauriCore";
|
||||
import { lspDoc } from "../src/editor/lsp/lsp";
|
||||
import { inlayExtension } from "../src/editor/lsp/inlay";
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("Inspections keeps the selected rule and its controls usable as the pane changes width", 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 page.evaluate(async () => {
|
||||
const path = "/src/features/settings/model/staging.ts";
|
||||
(await import(/* @vite-ignore */ path)).selectPage("editor.inspections");
|
||||
});
|
||||
|
||||
const search = dialog.getByRole("textbox", { name: "Search inspections" });
|
||||
await search.fill("typo");
|
||||
const tree = dialog.getByRole("tree", { name: "Inspections" });
|
||||
const typo = tree.getByRole("treeitem", { name: /Typo/ });
|
||||
await typo.click();
|
||||
const body = dialog.locator("[class*='pageBody']");
|
||||
await expect.poll(() => body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
|
||||
const resize = dialog.getByRole("separator", { name: "Resize inspection panes" });
|
||||
const details = dialog.getByRole("region", { name: "Inspection details" });
|
||||
await expect(resize).toHaveAttribute("aria-orientation", "horizontal");
|
||||
await expect(details.getByRole("heading", { name: "Typo" })).toBeVisible();
|
||||
const narrowTree = await tree.boundingBox();
|
||||
const narrowDetails = await details.boundingBox();
|
||||
expect(narrowDetails!.y).toBeGreaterThan(narrowTree!.y + narrowTree!.height);
|
||||
|
||||
await expect(details.getByRole("separator", { name: "Resize inspection description" })).toHaveAttribute(
|
||||
"aria-orientation",
|
||||
"horizontal",
|
||||
);
|
||||
const severity = details.getByRole("button", { name: "Severity" });
|
||||
const severityBox = await severity.boundingBox();
|
||||
expect(severityBox!.y + severityBox!.height).toBeLessThan(narrowDetails!.y + narrowDetails!.height);
|
||||
await severity.click();
|
||||
await page.getByRole("option", { name: "Warning", exact: true }).click();
|
||||
const code = details.getByRole("checkbox", { name: "Process code" });
|
||||
await code.uncheck();
|
||||
await expect(severity).toHaveText("Warning");
|
||||
|
||||
await page.setViewportSize({ width: 1040, height: 740 });
|
||||
await expect(resize).toHaveAttribute("aria-orientation", "vertical");
|
||||
const width = (await tree.boundingBox())!.width;
|
||||
await resize.press("ArrowRight");
|
||||
await expect.poll(async () => (await tree.boundingBox())!.width).toBeGreaterThan(width + 5);
|
||||
await expect(typo).toHaveAttribute("aria-selected", "true");
|
||||
await expect(severity).toHaveText("Warning");
|
||||
await expect(code).not.toBeChecked();
|
||||
});
|
||||
+11
-16
@@ -1,4 +1,3 @@
|
||||
import type { DataSource_Deserialize, DbJdbcDriver } from "../src/bindings";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("configures a local JDBC profile and a source through mocked IPC", async ({ workbench: page }, info) => {
|
||||
@@ -103,25 +102,21 @@ test("configures a local JDBC profile and a source through mocked IPC", async ({
|
||||
await source.getByLabel("Property value", { exact: true }).fill("true");
|
||||
await test.click();
|
||||
await expect(source.getByRole("status")).toHaveText("Succeeded: Mock JDBC database");
|
||||
const [tested] = await ipcCalls(page, "db_test");
|
||||
const [{ source: tested, password }] = await ipcCalls(page, "db_test");
|
||||
expect(password).toBe("mock secret");
|
||||
expect(tested).toMatchObject({
|
||||
password: "mock secret",
|
||||
source: {
|
||||
driver: "jdbc",
|
||||
url,
|
||||
user: "example-user",
|
||||
readOnly: true,
|
||||
properties: [{ name: "ssl", value: "true" }],
|
||||
},
|
||||
driver: "jdbc",
|
||||
url,
|
||||
user: "example-user",
|
||||
readOnly: true,
|
||||
properties: [{ name: "ssl", value: "true" }],
|
||||
});
|
||||
await source.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await expect(source).not.toBeVisible();
|
||||
const [save] = await ipcCalls(page, "db_save_sources");
|
||||
const saved = (save?.sources as DataSource_Deserialize[] | undefined)?.[0];
|
||||
const [profile] = await ipcCalls(page, "db_save_jdbc_driver");
|
||||
const driver = profile?.driver as DbJdbcDriver | undefined;
|
||||
if (!saved || !driver) throw new Error("Expected the JDBC source and driver to be saved");
|
||||
const [{ sources }] = await ipcCalls(page, "db_save_sources");
|
||||
const [saved] = sources as Record<string, unknown>[];
|
||||
const [{ driver }] = await ipcCalls(page, "db_save_jdbc_driver");
|
||||
expect(saved.readOnly).toBe(true);
|
||||
expect(saved.jdbcDriver).toBe(driver.id);
|
||||
expect(saved.jdbcDriver).toBe((driver as Record<string, unknown>).id);
|
||||
for (const key of ["jars", "className", "classpath", "exec", "password"]) expect(saved).not.toHaveProperty(key);
|
||||
});
|
||||
@@ -1,56 +0,0 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("Keymap fits a narrow Settings pane and keeps shortcut editing reachable", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1080, height: 760 });
|
||||
await page.keyboard.press("Meta+,");
|
||||
const settings = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await settings.getByRole("treeitem", { name: "Keymap", exact: true }).click();
|
||||
|
||||
const search = settings.getByRole("textbox", { name: "Search actions" });
|
||||
const expand = settings.getByRole("button", { name: "Expand All", exact: true });
|
||||
await expect(search).toBeVisible();
|
||||
const wideSearch = (await search.boundingBox())!;
|
||||
const wideExpand = (await expand.boundingBox())!;
|
||||
expect(wideExpand.x).toBeLessThan(wideSearch.x);
|
||||
expect(Math.abs(wideExpand.y - wideSearch.y)).toBeLessThan(8);
|
||||
|
||||
await page.setViewportSize({ width: 520, height: 760 });
|
||||
const narrowSearch = (await search.boundingBox())!;
|
||||
const narrowExpand = (await expand.boundingBox())!;
|
||||
expect(narrowSearch.y).toBeGreaterThan(narrowExpand.y + narrowExpand.height);
|
||||
|
||||
const body = settings.locator("[class*='pageBody']");
|
||||
const fitPane = () =>
|
||||
expect.poll(() => body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
await fitPane();
|
||||
|
||||
await search.fill("Reformat Code");
|
||||
const tree = settings.getByRole("tree", { name: "Actions", exact: true });
|
||||
const action = tree
|
||||
.getByRole("treeitem")
|
||||
.filter({ hasText: /Reformat Code/ })
|
||||
.first();
|
||||
await action.click();
|
||||
await settings.getByRole("button", { name: "Add Keyboard Shortcut", exact: true }).click();
|
||||
const recorder = page.getByRole("dialog", { name: /Keyboard Shortcut: Reformat Code/ });
|
||||
await recorder.getByRole("textbox", { name: "First stroke" }).press("Control+Alt+Shift+F8");
|
||||
await expect(recorder.getByText("No conflicts")).toBeVisible();
|
||||
await recorder.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await expect(action.locator("kbd").filter({ hasText: "F8" })).toHaveCount(1);
|
||||
|
||||
const title = action.getByText(/Reformat Code/).first();
|
||||
await expect.poll(() => title.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
await tree.evaluate((el) => {
|
||||
el.scrollLeft = el.scrollWidth;
|
||||
});
|
||||
expect(await tree.evaluate((el) => el.scrollLeft)).toBeGreaterThan(0);
|
||||
await fitPane();
|
||||
|
||||
await settings.getByRole("button", { name: "Find Actions by Shortcut" }).click();
|
||||
await settings.getByRole("textbox", { name: "Find actions by shortcut" }).press("Control+Alt+Shift+F8");
|
||||
await expect(action).toBeVisible();
|
||||
await fitPane();
|
||||
|
||||
await settings.getByRole("button", { name: "Apply", exact: true }).click();
|
||||
await expect(settings.getByRole("button", { name: "Apply", exact: true })).toBeDisabled();
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
/** Linked Gradle builds use isolated native stubs; no real builds or files are touched. */
|
||||
import type { GradleModel, RunConfig_Deserialize } from "../src/bindings";
|
||||
import type { GradleModel, RunConfig } from "../src/platform/ipc";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const build = (dir: string): GradleModel => ({
|
||||
@@ -46,7 +46,7 @@ test("links independent Gradle roots, runs identical task paths in their own bui
|
||||
};
|
||||
h["plugin:dialog|open"] = () => ["/dev/acme-api/second/settings.gradle"];
|
||||
h.run_start = (args) => {
|
||||
const config = args.config as RunConfig_Deserialize;
|
||||
const config = args.config as RunConfig;
|
||||
const id = ++runId;
|
||||
setTimeout(() => window.__ipc.emit({ type: "runExited", run: id, code: 0 }), 50);
|
||||
return { id, configId: config.id, name: config.name, pid: 4242 + id, running: true, pty: false };
|
||||
@@ -89,7 +89,7 @@ test("links independent Gradle roots, runs identical task paths in their own bui
|
||||
await expect.poll(async () => (await ipcCalls(page, "run_start")).length).toBe(1);
|
||||
await tasks.nth(1).dblclick();
|
||||
await expect.poll(async () => (await ipcCalls(page, "run_start")).length).toBe(2);
|
||||
const runs = (await ipcCalls(page, "run_start")).map((args) => args.config as RunConfig_Deserialize);
|
||||
const runs = (await ipcCalls(page, "run_start")).map((args) => args.config as RunConfig);
|
||||
expect(runs[0]!.id).not.toBe(runs[1]!.id);
|
||||
for (const [index, dir] of ["first", "second"].entries()) {
|
||||
expect(runs[index]).toMatchObject({
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
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");
|
||||
});
|
||||
@@ -63,44 +63,6 @@ const result = (page: Page) => page.getByRole("region", { name: "Result" });
|
||||
const text = async (pane: Locator) => (await pane.locator(".cm-content").innerText()).replace(//g, "");
|
||||
const status = (page: Page) => page.locator("#merge-host [class*=status]").first();
|
||||
|
||||
test("merge controls and pane titles fit while resizing the result", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 400, height: 600 });
|
||||
await mountMerge(page);
|
||||
const host = page.locator("#merge-host");
|
||||
for (const name of ["Accept Yours", "Accept Theirs", "Cancel", "Apply"])
|
||||
await expect(host.getByRole("button", { name, exact: true })).toBeInViewport({ ratio: 1 });
|
||||
await expect(status(page)).toHaveText("3 changes left, 2 conflicts");
|
||||
await expect(status(page)).toBeInViewport({ ratio: 1 });
|
||||
|
||||
const ours = page.getByRole("region", { name: "Your version" });
|
||||
await expect(ours.getByText("Your version", { exact: true })).toBeVisible();
|
||||
await expect(
|
||||
page.getByRole("region", { name: "Their version" }).getByText("Their version", { exact: true }),
|
||||
).toBeVisible();
|
||||
await ours.locator(".cm-merge-accept").nth(1).focus();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect.poll(() => text(result(page))).toContain("\nmine\n");
|
||||
|
||||
await page.setViewportSize({ width: 980, height: 660 });
|
||||
const resultWidth = async () => (await result(page).boundingBox())!.width;
|
||||
const initial = await resultWidth();
|
||||
const left = host.getByRole("separator", { name: "Resize left merge pane" });
|
||||
await left.press("ArrowLeft");
|
||||
await expect.poll(resultWidth).toBeGreaterThan(initial + 1);
|
||||
|
||||
const right = host.getByRole("separator", { name: "Resize right merge pane" });
|
||||
const grip = (await right.boundingBox())!;
|
||||
const withLeftResized = await resultWidth();
|
||||
await page.mouse.move(grip.x + grip.width / 2, grip.y + grip.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(grip.x + grip.width / 2 + 36, grip.y + grip.height / 2, { steps: 4 });
|
||||
await page.mouse.up();
|
||||
await expect.poll(resultWidth).toBeGreaterThan(withLeftResized + 20);
|
||||
await expect(result(page).getByText("Result", { exact: true })).toBeVisible();
|
||||
await expect(ours.getByText("Changes from main", { exact: true })).toBeVisible();
|
||||
await expect.poll(() => text(result(page))).toContain("\nmine\n");
|
||||
});
|
||||
|
||||
/** Capture the save boundary, keeping real editor state, dialogs and Apply behavior. */
|
||||
async function captureWrites(page: Page) {
|
||||
await page.evaluate(async () => {
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
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: "" },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
});
|
||||
@@ -1,76 +0,0 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { SignatureHelp } from "../src/bindings";
|
||||
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
|
||||
|
||||
function signature(name: string, parameters: string[]) {
|
||||
let offset = name.length + 1;
|
||||
const ranges: [number, number][] = parameters.map((parameter) => {
|
||||
const range: [number, number] = [offset, offset + parameter.length];
|
||||
offset = range[1] + 2;
|
||||
return range;
|
||||
});
|
||||
return { label: `${name}(${parameters.join(", ")}): Invoice`, parameters: ranges, documentation: null };
|
||||
}
|
||||
|
||||
async function openParameterInfo(page: Page, help: SignatureHelp) {
|
||||
const editor = await openFromTree(page, "build.gradle.kts");
|
||||
await stubDesktop(page);
|
||||
await page.evaluate((help) => {
|
||||
window.__ipc.handlers.lsp_signature_help = () => help;
|
||||
}, help);
|
||||
await editor.locator(".cm-line", { hasText: "return order.toDto()" }).click();
|
||||
await page.keyboard.press("End");
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
await page.keyboard.press("Meta+p");
|
||||
const popup = page.locator(".cm-lsp-signature");
|
||||
await expect(popup).toBeVisible();
|
||||
return { editor, popup };
|
||||
}
|
||||
|
||||
test("parameter info wraps long parameters and follows the editor width", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1120, height: 700 });
|
||||
const parameter = "roundingPolicyForThirdPartyPaymentsWithMultipleSettlementCurrencies: RoundingPolicy";
|
||||
const { editor, popup } = await openParameterInfo(page, {
|
||||
signatures: [signature("formatInvoice", ["order: Cart", parameter, "currency: string"])],
|
||||
activeSignature: 0,
|
||||
activeParameter: 1,
|
||||
});
|
||||
await page.setViewportSize({ width: 560, height: 650 });
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const [pane, hint] = await Promise.all([editor.boundingBox(), popup.boundingBox()]);
|
||||
return !!pane && !!hint && hint.x >= pane.x - 1 && hint.x + hint.width <= pane.x + pane.width + 1;
|
||||
})
|
||||
.toBe(true);
|
||||
await expect.poll(() => popup.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
await expect(popup.locator("b")).toHaveText(parameter);
|
||||
const fontSize = await editor.locator(".cm-content").evaluate((el) => getComputedStyle(el).fontSize);
|
||||
await expect(popup).toHaveCSS("font-size", fontSize);
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(popup).toBeHidden();
|
||||
});
|
||||
|
||||
test("parameter info keeps the active overload visible and scrolls to the others", async ({ workbench: page }) => {
|
||||
const signatures = Array.from({ length: 20 }, (_, i) =>
|
||||
signature("formatInvoice", [`order: Cart${i}`, "currency: string"]),
|
||||
);
|
||||
const { popup } = await openParameterInfo(page, { signatures, activeSignature: 16, activeParameter: 1 });
|
||||
await expect(popup.locator(".cm-lsp-signature-row")).toHaveCount(signatures.length);
|
||||
const active = popup.locator(".cm-lsp-signature-active b");
|
||||
await expect(active).toHaveText("currency: string");
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const [frame, parameter] = await Promise.all([popup.boundingBox(), active.boundingBox()]);
|
||||
return (
|
||||
!!frame && !!parameter && parameter.y >= frame.y && parameter.y + parameter.height <= frame.y + frame.height
|
||||
);
|
||||
})
|
||||
.toBe(true);
|
||||
expect(await popup.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
|
||||
await popup.hover();
|
||||
await page.mouse.wheel(0, -1200);
|
||||
await expect.poll(() => popup.evaluate((el) => el.scrollTop)).toBe(0);
|
||||
await expect(
|
||||
popup.getByText("formatInvoice(order: Cart0, currency: string): Invoice", { exact: true }),
|
||||
).toBeInViewport();
|
||||
});
|
||||
@@ -1,47 +0,0 @@
|
||||
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);
|
||||
});
|
||||
@@ -1,86 +0,0 @@
|
||||
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 },
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
+42
-120
@@ -9,75 +9,50 @@ import { expect, stubDesktop, test } from "./fixtures";
|
||||
const ROOT = "/dev/acme-api";
|
||||
const HUGE = `feature/wrap-${"x".repeat(140)}`;
|
||||
|
||||
const OUTGOING = "Apply order-level discounts before calculating checkout taxes";
|
||||
|
||||
async function openPushDialog(page: Page, { outgoing = false, multi = false } = {}) {
|
||||
async function openPushDialog(page: Page) {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ root, outgoing, multi, subject }) => {
|
||||
const h = window.__ipc.handlers;
|
||||
const head = multi ? "feature/refine-checkout-pricing-and-order-summary-for-regional-release" : "main";
|
||||
const roots = multi ? [root, `${root}/billing-and-refunds`] : [root];
|
||||
h.vcs_roots = () => roots.map((root) => ({ root, operation: null, head, headCommit: "1111111" }));
|
||||
h.vcs_branch_info = () => ({
|
||||
head,
|
||||
headCommit: "1111111",
|
||||
upstream: `origin/${head}`,
|
||||
ahead: outgoing ? 1 : 0,
|
||||
behind: 0,
|
||||
operation: null,
|
||||
});
|
||||
h.vcs_status = () => [];
|
||||
h.vcs_log = () =>
|
||||
outgoing
|
||||
? [
|
||||
{
|
||||
id: "2222222",
|
||||
shortId: "2222222",
|
||||
parents: ["1111111"],
|
||||
summary: subject,
|
||||
message: subject + "\n\nKeep the new totals consistent with receipts.",
|
||||
author: "Sam Rivera",
|
||||
email: "[email protected]",
|
||||
timeMs: 1795100000000,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
h.vcs_commit_files = () => [{ path: "checkout.ts", oldPath: null, kind: "modified" }];
|
||||
h.vcs_has_hook = () => false;
|
||||
h.vcs_remotes = () => [{ name: "origin", url: "[email protected]:acme/api.git" }];
|
||||
const branch = (name: string, remote: boolean, upstream: string | null = null) => ({
|
||||
name,
|
||||
remote,
|
||||
current: !remote,
|
||||
upstream,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
lastCommitMs: 0,
|
||||
});
|
||||
h.vcs_branches = () => [
|
||||
branch("main", false, "origin/main"),
|
||||
branch("feature/login", false),
|
||||
branch("origin/main", true),
|
||||
branch("origin/feature/login", true),
|
||||
branch("origin/fix/error-auth", true),
|
||||
branch("origin/feature/PLATFORM-12345-order-history-export", true),
|
||||
branch(`origin/feature/wrap-${"x".repeat(140)}`, true),
|
||||
];
|
||||
const vcsModule = "/src/features/vcs/store.ts";
|
||||
const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsModule);
|
||||
useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false });
|
||||
await refreshNow();
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
void executeAction("vcs.push");
|
||||
},
|
||||
{ root: ROOT, outgoing, multi, subject: OUTGOING },
|
||||
);
|
||||
await page.evaluate(async (root) => {
|
||||
const h = window.__ipc.handlers;
|
||||
h.vcs_roots = () => [{ root, operation: null, head: "main", headCommit: "1111111" }];
|
||||
h.vcs_branch_info = () => ({
|
||||
head: "main",
|
||||
headCommit: "1111111",
|
||||
upstream: "origin/main",
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
operation: null,
|
||||
});
|
||||
h.vcs_status = () => [];
|
||||
h.vcs_log = () => [];
|
||||
h.vcs_remotes = () => [{ name: "origin", url: "[email protected]:acme/api.git" }];
|
||||
const branch = (name: string, remote: boolean, upstream: string | null = null) => ({
|
||||
name,
|
||||
remote,
|
||||
current: !remote,
|
||||
upstream,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
lastCommitMs: 0,
|
||||
});
|
||||
h.vcs_branches = () => [
|
||||
branch("main", false, "origin/main"),
|
||||
branch("feature/login", false),
|
||||
branch("origin/main", true),
|
||||
branch("origin/feature/login", true),
|
||||
branch("origin/fix/error-auth", true),
|
||||
branch("origin/feature/PLATFORM-12345-order-history-export", true),
|
||||
branch(`origin/feature/wrap-${"x".repeat(140)}`, true),
|
||||
];
|
||||
const vcsModule = "/src/features/vcs/store.ts";
|
||||
const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsModule);
|
||||
useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false });
|
||||
await refreshNow();
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
void executeAction("vcs.push");
|
||||
}, ROOT);
|
||||
const dialog = page.getByRole("dialog", { name: /Push/ });
|
||||
const input = multi
|
||||
? dialog.getByRole("textbox", { name: "Target branch of acme-api" })
|
||||
: dialog.getByRole("combobox", { name: "Target branch" });
|
||||
const input = dialog.getByRole("combobox", { name: "Target branch" });
|
||||
await expect(input).toBeVisible();
|
||||
return { dialog, input };
|
||||
}
|
||||
@@ -152,56 +127,3 @@ test("Escape closes the list but keeps the dialog", async ({ workbench: page })
|
||||
await expect(page.getByRole("listbox", { name: "Remote branches" })).toHaveCount(0);
|
||||
await expect(dialog).toBeVisible();
|
||||
});
|
||||
|
||||
test("Push keeps commit subjects and changed files readable in a narrow window", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 1140, height: 760 });
|
||||
const { dialog, input } = await openPushDialog(page, { outgoing: true });
|
||||
const outgoing = dialog.getByRole("listbox", { name: "Outgoing commits" });
|
||||
const files = dialog.getByRole("tree", { name: "Changed files" });
|
||||
const commit = outgoing.getByRole("option", { name: new RegExp(OUTGOING) });
|
||||
await commit.click();
|
||||
await expect(files.getByText("checkout.ts")).toBeVisible();
|
||||
const filesBelowCommits = async () => {
|
||||
const [list, tree] = await Promise.all([outgoing.boundingBox(), files.boundingBox()]);
|
||||
return !!list && !!tree && tree.y >= list.y + list.height;
|
||||
};
|
||||
await expect.poll(filesBelowCommits).toBe(false);
|
||||
|
||||
await page.setViewportSize({ width: 540, height: 630 });
|
||||
await expect.poll(filesBelowCommits).toBe(true);
|
||||
await expect(commit).toHaveAttribute("aria-selected", "true");
|
||||
const subject = commit.getByText(OUTGOING, { exact: true });
|
||||
await expect(subject).toHaveAttribute("title", /Sam Rivera/);
|
||||
await expect.poll(() => subject.evaluate((el) => el.scrollWidth <= el.clientWidth)).toBe(true);
|
||||
await expect(input).toHaveValue("main");
|
||||
await expect(dialog.getByRole("button", { name: "Push", exact: true })).toBeInViewport();
|
||||
const details = dialog.getByRole("region", { name: "Commit details" });
|
||||
await expect(details).toContainText("Keep the new totals consistent with receipts.");
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const [tree, message] = await Promise.all([files.boundingBox(), details.boundingBox()]);
|
||||
return !!tree && !!message && message.y >= tree.y + tree.height;
|
||||
})
|
||||
.toBe(true);
|
||||
});
|
||||
|
||||
test("Push keeps per-repository targets editable with long source branches", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 475, height: 620 });
|
||||
const { dialog, input } = await openPushDialog(page, { outgoing: true, multi: true });
|
||||
const other = dialog.getByRole("textbox", { name: "Target branch of billing-and-refunds" });
|
||||
for (const field of [input, other]) {
|
||||
await expect
|
||||
.poll(() =>
|
||||
field.evaluate((target) => {
|
||||
const row = target.closest('[role="treeitem"]')!.getBoundingClientRect();
|
||||
const bounds = target.getBoundingClientRect();
|
||||
return bounds.width >= 42 && bounds.left >= row.left && bounds.right <= row.right;
|
||||
}),
|
||||
)
|
||||
.toBe(true);
|
||||
}
|
||||
await input.fill("release/checkout");
|
||||
await expect(input).toHaveValue("release/checkout");
|
||||
await expect(other).toHaveValue(/^feature\//);
|
||||
await expect(dialog.getByRole("checkbox", { name: "acme-api" })).toBeChecked();
|
||||
});
|
||||
@@ -1,55 +0,0 @@
|
||||
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();
|
||||
});
|
||||
+3
-76
@@ -3,21 +3,15 @@
|
||||
* the process. Processes are stubbed at the IPC layer; `crates/ide-run` covers spawning them.
|
||||
*/
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { RunConfig } from "../src/bindings";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const RUN_ID = 7;
|
||||
|
||||
/** One saved `npm run dev` configuration; `run_start` prints `output` and exits with `exit` unless null. */
|
||||
async function stubRun(
|
||||
page: Page,
|
||||
output: { kind: string; text: string }[],
|
||||
exit: number | null,
|
||||
overrides: Partial<RunConfig> = {},
|
||||
) {
|
||||
async function stubRun(page: Page, output: { kind: string; text: string }[], exit: number | null) {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ output, exit, runId, overrides }) => {
|
||||
async ({ output, exit, runId }) => {
|
||||
const config = {
|
||||
id: "npm:dev",
|
||||
name: "dev",
|
||||
@@ -29,7 +23,6 @@ async function stubRun(
|
||||
detected: false,
|
||||
isTest: false,
|
||||
debugAdapter: null,
|
||||
...overrides,
|
||||
};
|
||||
const h = window.__ipc.handlers;
|
||||
h.run_configs = () => [config];
|
||||
@@ -50,7 +43,7 @@ async function stubRun(
|
||||
await loadConfigs();
|
||||
selectConfig(config.id);
|
||||
},
|
||||
{ output, exit, runId: RUN_ID, overrides },
|
||||
{ output, exit, runId: RUN_ID },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -184,72 +177,6 @@ test("Go reruns keep each package's exact failures and the original configuratio
|
||||
]);
|
||||
});
|
||||
|
||||
test("test results keep counts, actions and selected output visible as the pane narrows", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1060, height: 740 });
|
||||
const goPackage = "example.com/checkout";
|
||||
const name = "TestCheckoutTotalsWithDiscountsAndPendingInventoryReservations";
|
||||
const message = "expected subtotal 42, got 37";
|
||||
const records = [
|
||||
{ Action: "run", Test: name },
|
||||
{ Action: "output", Test: name, Output: message + "\n" },
|
||||
{ Action: "fail", Test: name, Elapsed: 0.125 },
|
||||
{ Action: "pass", Test: "TestPayment", Elapsed: 0.02 },
|
||||
{ Action: "skip", Test: "TestDelayedShipping" },
|
||||
{ Action: "fail", Elapsed: 0.17 },
|
||||
];
|
||||
await stubRun(
|
||||
page,
|
||||
records.map((record) => ({ kind: "stdout", text: JSON.stringify({ Package: goPackage, ...record }) + "\n" })),
|
||||
1,
|
||||
{
|
||||
id: "go:checkout-tests",
|
||||
name: "Checkout tests",
|
||||
kind: "go",
|
||||
command: "go",
|
||||
args: ["test", "-json"],
|
||||
isTest: true,
|
||||
},
|
||||
);
|
||||
await page.keyboard.press("Control+r");
|
||||
const run = page.getByRole("region", { name: "Run", exact: true });
|
||||
const tree = run.getByRole("tree", { name: "Test results" });
|
||||
const row = tree.getByRole("treeitem", { name: new RegExp(name) });
|
||||
await row.click();
|
||||
const output = run.getByRole("log");
|
||||
await expect(output).toContainText(message);
|
||||
await expect.poll(async () => (await output.boundingBox())!.x > (await tree.boundingBox())!.x).toBe(true);
|
||||
await page.setViewportSize({ width: 540, height: 740 });
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const [list, console] = await Promise.all([tree.boundingBox(), output.boundingBox()]);
|
||||
return !!list && !!console && console.y >= list.y + list.height - 1;
|
||||
})
|
||||
.toBe(true);
|
||||
const summary = run.getByRole("status").filter({ hasText: "1 failing" });
|
||||
for (const count of ["1 failing", "1 passed", "1 ignored"]) await expect(summary.getByText(count)).toBeVisible();
|
||||
await expect(row).toHaveAttribute("aria-selected", "true");
|
||||
await expect(row.getByText("125 ms")).toBeVisible();
|
||||
await expect(output).toContainText(message);
|
||||
const toolbar = run.getByRole("toolbar", { name: "Test results" });
|
||||
await toolbar.getByRole("button", { name: "More Actions" }).click();
|
||||
await expect(page.getByRole("menuitem", { name: "Collapse All" })).toBeVisible();
|
||||
await expect(page.getByRole("menuitem", { name: "Export Test Results…" })).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
const divider = run.getByRole("separator");
|
||||
const treeHeight = async () => (await tree.boundingBox())!.height;
|
||||
const beforeResize = await treeHeight();
|
||||
await divider.press("ArrowDown");
|
||||
await expect.poll(treeHeight).toBeGreaterThan(beforeResize + 1);
|
||||
const customizedHeight = await treeHeight();
|
||||
await page.setViewportSize({ width: 1060, height: 740 });
|
||||
await expect.poll(async () => (await output.boundingBox())!.x > (await tree.boundingBox())!.x).toBe(true);
|
||||
await page.setViewportSize({ width: 540, height: 740 });
|
||||
await expect.poll(async () => Math.abs((await treeHeight()) - customizedHeight)).toBeLessThan(2);
|
||||
await expect(output).toContainText(message);
|
||||
});
|
||||
|
||||
test("CMake builds the selected target in Build before starting only the application in Run", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
|
||||
+4
-8
@@ -1,4 +1,3 @@
|
||||
import type { SearchQuery } from "../src/bindings";
|
||||
import { doubleShift, expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("double Shift opens Search Everywhere with its tabs; Escape closes it", async ({ workbench: page }) => {
|
||||
@@ -101,14 +100,11 @@ test("Find in Files streams matches by file and opens the chosen one at its line
|
||||
await expect
|
||||
.poll(
|
||||
async () =>
|
||||
(await ipcCalls(page, "search_start"))
|
||||
.filter(({ query }) => {
|
||||
const pattern = query && typeof query === "object" && "pattern" in query ? query.pattern : undefined;
|
||||
return typeof pattern !== "string" || !/\bTODO\b/.test(pattern);
|
||||
})
|
||||
.at(-1)?.query,
|
||||
(await ipcCalls(page, "search_start")).filter((c) => !/\bTODO\b/.test(c.query?.pattern ?? "")).at(-1)?.query,
|
||||
)
|
||||
.toMatchObject({ pattern: "OrderService" } satisfies Pick<SearchQuery, "pattern">);
|
||||
.toMatchObject({
|
||||
pattern: "OrderService",
|
||||
});
|
||||
const preview = dialog.getByRole("region", { name: "Preview", exact: true }).locator(".cm-content");
|
||||
await expect(preview).toHaveAttribute("contenteditable", "true");
|
||||
// Matches take the editor scheme's search result background (IDEA's SEARCH_RESULT_ATTRIBUTES) and keep the syntax colours.
|
||||
|
||||
@@ -79,7 +79,7 @@ test.describe("search popups at the minimum window width", () => {
|
||||
[400, 500],
|
||||
[600, 700],
|
||||
[1120, 750],
|
||||
] as const) {
|
||||
]) {
|
||||
await page.setViewportSize({ width, height });
|
||||
await expectControlsFit(page);
|
||||
// Room enough for the title and the reporter's count: shown whole, on one line.
|
||||
|
||||
@@ -9,9 +9,9 @@ test("semantic roles honor all Color Scheme attributes and keep modifier styles"
|
||||
[".cm-sem-function:not(.cm-sem-static)", "rgb(102, 136, 170)"],
|
||||
[".cm-sem-parameter", "rgb(119, 153, 187)"],
|
||||
[".cm-sem-constant", "rgb(136, 170, 204)"],
|
||||
] as const) {
|
||||
]) {
|
||||
const role = page.locator(selector);
|
||||
await expect(role).toHaveCSS("color", color);
|
||||
await expect(role).toHaveCSS("color", color!);
|
||||
await expect(role).toHaveCSS("background-color", "rgb(221, 238, 255)");
|
||||
}
|
||||
await expect(page.locator(".cm-sem-namespace")).toHaveCSS("font-style", "italic");
|
||||
|
||||
@@ -6,7 +6,7 @@ for (const [id, selector] of [
|
||||
["languages.servers", "[class*='body'] > [class*='language'][aria-label]"],
|
||||
["plugins", "[class*='body'] > [class*='details']"],
|
||||
["agents.list", "section[aria-label='Codex']"],
|
||||
] as const) {
|
||||
]) {
|
||||
test(`${id} keeps its details usable beside the list`, async ({ workbench: page }) => {
|
||||
await page.keyboard.press("Meta+,");
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
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,
|
||||
},
|
||||
]);
|
||||
});
|
||||
+8
-4
@@ -1,8 +1,12 @@
|
||||
{
|
||||
"extends": "../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"lib": ["ES2024", "DOM", "DOM.Iterable"],
|
||||
"types": ["node", "vite/client"]
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"skipLibCheck": true,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": [".", "../playwright.config.ts", "../src/**/*.d.ts"]
|
||||
"include": ["./**/*.ts", "../playwright.config.ts"]
|
||||
}
|
||||
@@ -71,57 +71,3 @@ 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
-1
@@ -17,7 +17,7 @@
|
||||
"format": "oxfmt",
|
||||
"format:check": "oxfmt --check",
|
||||
"knip": "knip",
|
||||
"typecheck": "tsrs --noEmit && tsrs -p tsconfig.node.json --noEmit && tsrs -p perf --noEmit && tsrs -p evals --noEmit && tsrs -p scripts --noEmit && tsrs -p smoke --noEmit && tsrs -p e2e --noEmit",
|
||||
"typecheck": "tsrs --noEmit && tsrs -p tsconfig.node.json --noEmit && tsrs -p perf --noEmit && tsrs -p evals --noEmit && tsrs -p scripts --noEmit && tsrs -p smoke --noEmit",
|
||||
"gen:bindings": "cargo test -p openidea --test export_bindings",
|
||||
"gen:windows-icons": "node scripts/gen-windows-icons.ts",
|
||||
"gen:angular-grammar": "lezer-generator src/editor/core/cm/angular/angular.grammar --typeScript -o src/editor/core/cm/angular/parser.ts",
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
diff --git a/dist/index.cjs b/dist/index.cjs
|
||||
index b20aa9d84be6ff4b85b126bdd930065277668a26..e677ab06ca9668407e202979e14b75ab7641d6b1 100644
|
||||
--- a/dist/index.cjs
|
||||
+++ b/dist/index.cjs
|
||||
@@ -9675,7 +9675,9 @@ const hideNativeSelection = state.Prec.highest(EditorView.theme({
|
||||
"& :focus": {
|
||||
caretColor: "initial !important",
|
||||
...drawMainRange ? {
|
||||
- "&::selection, & ::selection": {
|
||||
+ // Not `& ::selection` too: a pseudo-class with a universal descendant restyles the
|
||||
+ // whole subtree of every element that gains or loses focus.
|
||||
+ "&::selection": {
|
||||
backgroundColor: "Highlight !important"
|
||||
}
|
||||
} : {}
|
||||
diff --git a/dist/index.js b/dist/index.js
|
||||
index 216f754db06f65f7f17f056b47d8f6fab45067bf..22282993239d836ea1da19af10ccfc61b6480cc5 100644
|
||||
--- a/dist/index.js
|
||||
+++ b/dist/index.js
|
||||
@@ -9670,7 +9670,9 @@ const hideNativeSelection = /*@__PURE__*/Prec.highest(/*@__PURE__*/EditorView.th
|
||||
"& :focus": {
|
||||
caretColor: "initial !important",
|
||||
...drawMainRange ? {
|
||||
- "&::selection, & ::selection": {
|
||||
+ // Not `& ::selection` too: a pseudo-class with a universal descendant restyles the
|
||||
+ // whole subtree of every element that gains or loses focus.
|
||||
+ "&::selection": {
|
||||
backgroundColor: "Highlight !important"
|
||||
}
|
||||
} : {}
|
||||
+25
-34
@@ -323,18 +323,6 @@ const scroll: Scenario = {
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Runs an action without a default shortcut from a key press: the press is the measured input,
|
||||
* and the action runs in its handler, as from a key binding. Pause is bound to nothing.
|
||||
*/
|
||||
async function runActionOnKey(h: Harness, id: string) {
|
||||
await h.page.evaluate((id) => {
|
||||
const probe = (window as never as { __openideaPerf: { runAction(id: string): Promise<boolean> } }).__openideaPerf;
|
||||
addEventListener("keydown", () => void probe.runAction(id), { capture: true, once: true });
|
||||
}, id);
|
||||
await h.page.keyboard.press("Pause");
|
||||
}
|
||||
|
||||
/**
|
||||
* Git Log with 20,000 commits on branching lanes, loaded page by page as the
|
||||
* backend does (150 ms a page, like `git log`): showing it, walking the
|
||||
@@ -351,7 +339,12 @@ const gitLog: Scenario = {
|
||||
).__openideaPerf.fakeGitLog(20_000, 150),
|
||||
);
|
||||
const showMs = await h.measure(
|
||||
() => runActionOnKey(h, "vcs.showLog"),
|
||||
() =>
|
||||
h.page.evaluate(() =>
|
||||
(window as never as { __openideaPerf: { runAction(id: string): Promise<boolean> } }).__openideaPerf.runAction(
|
||||
"vcs.showLog",
|
||||
),
|
||||
),
|
||||
'[role="listbox"][aria-label="Commits"]',
|
||||
"order flow step 0",
|
||||
);
|
||||
@@ -437,13 +430,16 @@ const resizePanels: Scenario = {
|
||||
await h.page.evaluate(() =>
|
||||
(window as never as { __openideaPerf: { fakeGitLog(n: number): void } }).__openideaPerf.fakeGitLog(2_000),
|
||||
);
|
||||
await h.page.evaluate(() =>
|
||||
(window as never as { __openideaPerf: { runAction(id: string): Promise<boolean> } }).__openideaPerf.runAction(
|
||||
"vcs.showLog",
|
||||
),
|
||||
await h.measure(
|
||||
() =>
|
||||
h.page.evaluate(() =>
|
||||
(window as never as { __openideaPerf: { runAction(id: string): Promise<boolean> } }).__openideaPerf.runAction(
|
||||
"vcs.showLog",
|
||||
),
|
||||
),
|
||||
'[role="listbox"][aria-label="Commits"]',
|
||||
"order flow step 0",
|
||||
);
|
||||
// Set-up, not measured: the splitters are dragged once the log is shown.
|
||||
await h.inPage((p) => p.waitShown('[role="listbox"][aria-label="Commits"]', "order flow step 0", 10_000));
|
||||
const refresh = await h.refreshMs();
|
||||
const drag = async (name: string, dx: number, dy: number) => {
|
||||
const box = (await h.page.getByRole("separator", { name }).boundingBox())!;
|
||||
@@ -564,9 +560,7 @@ const agentTabs: Scenario = {
|
||||
window as never as { __openideaPerf: { runAction(id: string, arg?: unknown): Promise<boolean> } }
|
||||
).__openideaPerf.runAction("agents.openSampleConversations", { tasks: 2, turns: 150 }),
|
||||
);
|
||||
// The conversation shown: its requests end with its task's title.
|
||||
const SHOWN = "[data-editor-focus] [data-message]";
|
||||
const title = (n: number) => `(Sample task ${n})`;
|
||||
const shown = (n: number) => `[data-editor-focus] span[title="Sample task ${n}"]`;
|
||||
// Both conversations get their earlier entries painted in background batches, also the
|
||||
// first one, hidden behind the second as soon as it opened.
|
||||
await h.page.waitForFunction(
|
||||
@@ -581,28 +575,25 @@ const agentTabs: Scenario = {
|
||||
// Rows painted while hidden are laid out the first time their conversation shows.
|
||||
for (const n of [1, 2]) {
|
||||
await h.page.getByRole("tab", { name: `Sample task ${n}` }).click();
|
||||
await h.page
|
||||
.locator(SHOWN, { hasText: title(n) })
|
||||
.first()
|
||||
.waitFor();
|
||||
await h.page.locator(shown(n)).waitFor();
|
||||
await h.page.waitForTimeout(300);
|
||||
}
|
||||
// WebKit restyles a hidden conversation in full when it is shown again (Chromium keeps its
|
||||
// style): what bounds that there is the history's DOM, and rows skipping rendering off screen.
|
||||
const { conversationNodes, rowsAlwaysRendered } = await h.page.evaluate((selector) => {
|
||||
const conversation = document.querySelector(selector)!;
|
||||
const conversation = document.querySelector(selector)!.closest("[data-editor-focus]")!;
|
||||
const rows = [...conversation.querySelector("[data-message]")!.parentElement!.children];
|
||||
return {
|
||||
conversationNodes: conversation.querySelectorAll("*").length,
|
||||
rowsAlwaysRendered: rows.filter((r) => getComputedStyle(r).contentVisibility !== "auto").length,
|
||||
};
|
||||
}, "[data-editor-focus]");
|
||||
}, shown(2));
|
||||
|
||||
const t0 = await h.now();
|
||||
const before = await h.counters();
|
||||
const switches: number[] = [];
|
||||
for (let i = 0; i < 10; i++) {
|
||||
switches.push(await h.measure(() => h.pressAction("navigate.switcher"), SHOWN, title(i % 2 ? 2 : 1)));
|
||||
switches.push(await h.measure(() => h.pressAction("navigate.switcher"), shown(i % 2 ? 2 : 1)));
|
||||
await h.page.waitForTimeout(150);
|
||||
}
|
||||
const work = Harness.delta(before, await h.counters());
|
||||
@@ -611,7 +602,10 @@ const agentTabs: Scenario = {
|
||||
// Scrolling up from the end, a step at a time: how far the text under the pointer moves
|
||||
// beyond the scroll itself.
|
||||
const scrollJumps = await h.page.evaluate(async (selector) => {
|
||||
const stream = document.querySelector(selector)!.parentElement!;
|
||||
const stream = document
|
||||
.querySelector(selector)!
|
||||
.closest("[data-editor-focus]")!
|
||||
.querySelector("[data-message]")!.parentElement!;
|
||||
const frame = () => new Promise(requestAnimationFrame);
|
||||
stream.scrollTop = stream.scrollHeight;
|
||||
await frame();
|
||||
@@ -632,7 +626,7 @@ const agentTabs: Scenario = {
|
||||
}
|
||||
stream.scrollTop = stream.scrollHeight;
|
||||
return jumps;
|
||||
}, SHOWN);
|
||||
}, shown(2));
|
||||
|
||||
const refresh = await h.refreshMs();
|
||||
const box = (await h.page.locator("[data-editor-focus]").boundingBox())!;
|
||||
@@ -738,9 +732,6 @@ const projectTree: Scenario = {
|
||||
async run(h) {
|
||||
const generated = h.page.locator('[role="treeitem"][aria-level="2"]', { hasText: "generated" }).first();
|
||||
await generated.click();
|
||||
// Measure from a settled selection: a key pressed in the click's own frame also pays for that frame.
|
||||
await generated.and(h.page.locator('[aria-selected="true"]')).waitFor();
|
||||
await h.page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
|
||||
const expandMs = await h.measure(
|
||||
() => h.page.keyboard.press("ArrowRight"),
|
||||
'[role="tree"][aria-label="Project"]',
|
||||
|
||||
Generated
+24
-20
@@ -7,9 +7,6 @@ settings:
|
||||
overrides:
|
||||
mermaid>katex: ^0.18.2
|
||||
|
||||
patchedDependencies:
|
||||
'@codemirror/view': 0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5
|
||||
|
||||
importers:
|
||||
|
||||
.:
|
||||
@@ -64,7 +61,7 @@ importers:
|
||||
version: 6.7.6
|
||||
'@codemirror/view':
|
||||
specifier: ^6.43.14
|
||||
version: 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
version: 6.43.14
|
||||
'@floating-ui/react-dom':
|
||||
specifier: ^2.1.9
|
||||
version: 2.1.9([email protected]([email protected]))([email protected])
|
||||
@@ -88,7 +85,7 @@ importers:
|
||||
version: 1.2.0
|
||||
'@replit/codemirror-vim':
|
||||
specifier: 6.4.0
|
||||
version: 6.4.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected](patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5))
|
||||
version: 6.4.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])
|
||||
'@tanstack/react-virtual':
|
||||
specifier: ^3.14.21
|
||||
version: 3.14.21([email protected]([email protected]))([email protected])
|
||||
@@ -594,6 +591,7 @@ packages:
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@oxc-parser/[email protected]':
|
||||
resolution: {integrity: sha512-JSlhgoK+/g1TGJI5NuADx2+6syhxnQNLCWLXyO5QLFyetomcr/vIxSdiNlmyAv963YXUzCuwAwRG6npZ5xyJ1A==}
|
||||
@@ -1071,6 +1069,7 @@ packages:
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@rolldown/[email protected]':
|
||||
resolution: {integrity: sha512-4+Kl8daPV8NDHaD7mfCcc1pRM+Qg7ab8DyMm5FG5WoZgv4h2i3KFN1CybYBNbQqmuYm7ftJLvmMI1eHYJ22S/Q==}
|
||||
@@ -1084,12 +1083,14 @@ packages:
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [s390x]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rolldown/[email protected]':
|
||||
resolution: {integrity: sha512-WxalXzgrLVpKC93xfpaJ3gCXUWzeCr+FRCbDVD2mUAy4L6Vo3lNVz0epUEUpxPWJkLNYUwM4OSIikv36OJ9mLg==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@rolldown/[email protected]':
|
||||
resolution: {integrity: sha512-3G3tnAmTpdk9jO3GQtyHXqeFD2SlecfTws/Y3M2mmj9nMBwwuLT4kur8sZKeu7ENUHSpVO3cIsm5A52LEWWwlg==}
|
||||
@@ -1863,6 +1864,7 @@ packages:
|
||||
engines: {node: '>= 12.0.0'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==}
|
||||
@@ -1876,12 +1878,14 @@ packages:
|
||||
engines: {node: '>= 12.0.0'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==}
|
||||
engines: {node: '>= 12.0.0'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==}
|
||||
@@ -2387,14 +2391,14 @@ snapshots:
|
||||
dependencies:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@codemirror/view': 6.43.14
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@codemirror/view': 6.43.14
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2434,7 +2438,7 @@ snapshots:
|
||||
'@codemirror/lang-javascript': 6.2.5
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@codemirror/view': 6.43.14
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/css': 1.3.9
|
||||
'@lezer/html': 1.3.13
|
||||
@@ -2450,7 +2454,7 @@ snapshots:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/lint': 6.9.7
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@codemirror/view': 6.43.14
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/javascript': 1.5.6
|
||||
|
||||
@@ -2460,7 +2464,7 @@ snapshots:
|
||||
'@codemirror/lang-html': 6.4.12
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@codemirror/view': 6.43.14
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
@@ -2484,7 +2488,7 @@ snapshots:
|
||||
'@codemirror/lang-html': 6.4.12
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@codemirror/view': 6.43.14
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
@@ -2495,7 +2499,7 @@ snapshots:
|
||||
'@codemirror/lang-html': 6.4.12
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@codemirror/view': 6.43.14
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/markdown': 1.8.0
|
||||
|
||||
@@ -2558,7 +2562,7 @@ snapshots:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@codemirror/view': 6.43.14
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/xml': 1.0.6
|
||||
|
||||
@@ -2602,7 +2606,7 @@ snapshots:
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/streamparser': 6.0.0
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@codemirror/view': 6.43.14
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.11
|
||||
@@ -2615,21 +2619,21 @@ snapshots:
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@codemirror/view': 6.43.14
|
||||
crelt: 1.0.7
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@codemirror/view': 6.43.14
|
||||
'@lezer/highlight': 1.2.5
|
||||
style-mod: 4.1.4
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@codemirror/view': 6.43.14
|
||||
crelt: 1.0.7
|
||||
|
||||
'@codemirror/[email protected]':
|
||||
@@ -2638,7 +2642,7 @@ snapshots:
|
||||
|
||||
'@codemirror/[email protected]': {}
|
||||
|
||||
'@codemirror/[email protected](patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)':
|
||||
'@codemirror/[email protected]':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
crelt: 1.0.7
|
||||
@@ -3101,13 +3105,13 @@ snapshots:
|
||||
|
||||
'@replit/[email protected]': {}
|
||||
|
||||
'@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected](patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5))':
|
||||
'@replit/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])':
|
||||
dependencies:
|
||||
'@codemirror/commands': 6.11.1
|
||||
'@codemirror/language': 6.13.1
|
||||
'@codemirror/search': 6.7.2
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.14(patch_hash=0ee18e0fe711bd749ccc9f89f3566c74b5e08910f2892e166d207f286b0da0c5)
|
||||
'@codemirror/view': 6.43.14
|
||||
'@replit/codemirror-vim-core': 0.1.0
|
||||
|
||||
'@rolldown/[email protected]':
|
||||
|
||||
@@ -3,5 +3,3 @@ allowBuilds:
|
||||
overrides:
|
||||
# GHSA-238p-pmpm-9mq7 (fixed in 0.18.2); mermaid 12.1 still asks for katex ^0.16.
|
||||
mermaid>katex: ^0.18.2
|
||||
patchedDependencies:
|
||||
"@codemirror/view": patches/@codemirror__view.patch
|
||||
@@ -51,9 +51,7 @@ class CornerInset {
|
||||
|
||||
private measure() {
|
||||
const corner = this.corner;
|
||||
// A hidden tab's view is detached and measures 0: keeping the inset spares every line
|
||||
// a restyle when the tab hides and another when it shows again.
|
||||
if (!corner || !this.view.dom.isConnected) return;
|
||||
if (!corner) return;
|
||||
const width = corner.getBoundingClientRect().width;
|
||||
let inset = width > 0 ? round(width) + CORNER_GAP : 0;
|
||||
// A narrow window or a wide corner: keep at least half of the width for text.
|
||||
|
||||
@@ -20,12 +20,16 @@ import { countColumn, Facet, RangeSetBuilder, type EditorState, type Extension }
|
||||
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
|
||||
import { getIndentUnit, matchBrackets, syntaxTree } from "@codemirror/language";
|
||||
import { LINE_INSET } from "./lineInset";
|
||||
import { SPACE, spaceWidth } from "./spaceWidth";
|
||||
import { BRACKET_COLORS, LONG_LINE, bracketScanner, type BracketScanner } from "./rainbowBrackets";
|
||||
|
||||
/** How far (px) a guide sits left of its column, so a caret in that column is right of it (IDEA's indent guide shift). */
|
||||
const GUIDE_SHIFT = 2;
|
||||
|
||||
/** One column of indentation: a space in the editor font, as measured by the guides plugin. */
|
||||
const SPACE = "var(--openidea-space, 1ch)";
|
||||
|
||||
const SPACE_SAMPLE = 64;
|
||||
|
||||
/** Number of `--openidea-guide-<n>` rainbow colours; deeper guides repeat them. */
|
||||
export const GUIDE_COLORS = 5;
|
||||
|
||||
@@ -321,20 +325,37 @@ function build(
|
||||
}
|
||||
|
||||
export const indentGuides: Extension = [
|
||||
spaceWidth,
|
||||
ViewPlugin.fromClass(
|
||||
class {
|
||||
decorations: DecorationSet;
|
||||
private probe: HTMLElement;
|
||||
private brackets: BracketCache[] = [];
|
||||
/** Guide variables of each decorated line, by its start: code lens rows above it repeat them. */
|
||||
private lineVars = new Map<number, { images: string; positions: string }>();
|
||||
private scanner: BracketScanner | null;
|
||||
constructor(readonly view: EditorView) {
|
||||
// Inherits the editor font from the scroller, outside the content CodeMirror observes;
|
||||
// the measured width goes on the scroller, where lines and code lens rows pick it up.
|
||||
this.probe = document.createElement("span");
|
||||
this.probe.setAttribute("aria-hidden", "true");
|
||||
this.probe.style.cssText = "position: absolute; top: 0; left: 0; visibility: hidden; white-space: pre";
|
||||
this.probe.textContent = " ".repeat(SPACE_SAMPLE);
|
||||
view.scrollDOM.appendChild(this.probe);
|
||||
const scanner = bracketScanner(view);
|
||||
this.scanner = scanner;
|
||||
this.decorations = build(view, scanner, this.brackets, this.lineVars);
|
||||
this.measure();
|
||||
this.syncLenses();
|
||||
}
|
||||
measure() {
|
||||
this.view.requestMeasure({
|
||||
key: this,
|
||||
read: (view) => this.probe.getBoundingClientRect().width / (view.scaleX || 1) / SPACE_SAMPLE,
|
||||
write: (width, view) => {
|
||||
if (width > 0) view.scrollDOM.style.setProperty("--openidea-space", `${+width.toFixed(3)}px`);
|
||||
},
|
||||
});
|
||||
}
|
||||
/** Gives code lens rows the guides of the line they annotate, once they are in the DOM. */
|
||||
syncLenses() {
|
||||
this.view.requestMeasure({
|
||||
@@ -358,12 +379,15 @@ export const indentGuides: Extension = [
|
||||
});
|
||||
}
|
||||
destroy() {
|
||||
this.probe.remove();
|
||||
this.view.scrollDOM.style.removeProperty("--openidea-space");
|
||||
for (const el of this.view.contentDOM.querySelectorAll<HTMLElement>(".cm-openidea-lens")) {
|
||||
el.style.removeProperty("--openidea-guide-images");
|
||||
el.style.removeProperty("--openidea-guide-positions");
|
||||
}
|
||||
}
|
||||
update(u: ViewUpdate) {
|
||||
if (u.geometryChanged) this.measure();
|
||||
const scanner = bracketScanner(u.view);
|
||||
// A new scanner (rainbow brackets toggled or reconfigured) may colour blocks differently.
|
||||
const bracketsChanged = scanner !== this.scanner;
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { registerEditorContribution } from "@/editor/api";
|
||||
import { prewarmEditor } from "./prewarm";
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
it("builds an off-screen editor with embedded contributions only, then removes it", () => {
|
||||
let frame: FrameRequestCallback | undefined;
|
||||
vi.stubGlobal("requestAnimationFrame", (f: FrameRequestCallback) => ((frame = f), 1));
|
||||
const seen: string[] = [];
|
||||
const offEmbedded = registerEditorContribution({
|
||||
id: "test.embedded",
|
||||
embedded: true,
|
||||
extensions: (ctx) => (seen.push(`embedded ${ctx.doc}`), []),
|
||||
});
|
||||
const offFile = registerEditorContribution({
|
||||
id: "test.file",
|
||||
extensions: () => (seen.push("file"), []),
|
||||
});
|
||||
try {
|
||||
prewarmEditor();
|
||||
expect(document.querySelectorAll(".cm-editor")).toHaveLength(1);
|
||||
expect(seen).toEqual(["embedded -1"]);
|
||||
frame!(0);
|
||||
expect(document.querySelector(".cm-editor")).toBeNull();
|
||||
expect(document.body.children).toHaveLength(0);
|
||||
} finally {
|
||||
offEmbedded();
|
||||
offFile();
|
||||
}
|
||||
});
|
||||
@@ -1,55 +0,0 @@
|
||||
import { EditorState, type Extension } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { editorContributions, type EditorDocContext } from "@/editor/api";
|
||||
import { baseExtensions } from "./setup";
|
||||
|
||||
/**
|
||||
* Builds and drops an off-screen editor with the file editors' setup, so the first file opened
|
||||
* does not also pay for compiling the editor code and mounting its stylesheets. The document is
|
||||
* virtual and empty, and only contributions that accept such editors (`embedded`) take part:
|
||||
* nothing reaches a language server or the file system.
|
||||
*/
|
||||
export function prewarmEditor(): void {
|
||||
const host = document.createElement("div");
|
||||
host.setAttribute("aria-hidden", "true");
|
||||
host.style.cssText = "position:fixed;left:-10000px;top:0;width:480px;height:240px;visibility:hidden;contain:strict";
|
||||
document.body.appendChild(host);
|
||||
const ctx: EditorDocContext = {
|
||||
doc: -1,
|
||||
path: "prewarm.txt",
|
||||
language: "plaintext",
|
||||
uiMode: null,
|
||||
readOnly: true,
|
||||
virtual: true,
|
||||
};
|
||||
const contributions: Extension[] = [];
|
||||
for (const c of editorContributions()) {
|
||||
if (!c.embedded) continue;
|
||||
try {
|
||||
contributions.push(c.extensions(ctx));
|
||||
} catch {
|
||||
// Warming is best effort: the real editor reports a failing contribution.
|
||||
}
|
||||
}
|
||||
const view = new EditorView({
|
||||
parent: host,
|
||||
state: EditorState.create({
|
||||
doc: "",
|
||||
extensions: baseExtensions({
|
||||
ctx,
|
||||
settings: undefined,
|
||||
info: undefined,
|
||||
language: null,
|
||||
docLength: 0,
|
||||
indent: { tabSize: 4, insertSpaces: true },
|
||||
wrapOverride: false,
|
||||
contributions,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
// One frame so its measure pass runs too, then nothing of it is left behind.
|
||||
requestAnimationFrame(() => {
|
||||
view.destroy();
|
||||
host.remove();
|
||||
});
|
||||
}
|
||||
@@ -189,7 +189,7 @@ it("indents by the code's character width, so a font size change keeps it in lin
|
||||
const v = open(true, ["class A {", "\t/**", "\t * Books.", "\t */", "\tvoid book() {}", "}"].join("\n"));
|
||||
const body = v.dom.querySelector<HTMLElement>(".cm-openidea-renderedDoc")!;
|
||||
// A tab is a tab size of columns, not one character.
|
||||
expect(body.style.marginLeft).toContain(`${v.state.tabSize} * var(--openidea-space`);
|
||||
expect(body.style.marginLeft).toContain(`${v.state.tabSize} * var(--openidea-doc-char`);
|
||||
});
|
||||
|
||||
it("forgets a flip whose comment is deleted, so the feature turns off again", async () => {
|
||||
|
||||
@@ -61,7 +61,6 @@ import { tx, useI18n } from "@/platform/i18n";
|
||||
import { loadMarkdown, markupToHtml } from "@/editor/lsp/markdown";
|
||||
import { hasContent, renderDoc, type DocComment, type DocStyle, type RenderedDoc } from "./docRender";
|
||||
import { LINE_INSET } from "./lineInset";
|
||||
import { SPACE, spaceWidth } from "./spaceWidth";
|
||||
|
||||
/** The file's default: render its doc comments or not. */
|
||||
export const renderDocComments = Facet.define<boolean, boolean>({
|
||||
@@ -321,9 +320,9 @@ class DocWidget extends WidgetType {
|
||||
const titles = doc.sections.map(sectionTitle);
|
||||
const dom = document.createElement("div");
|
||||
dom.className = "cm-openidea-renderedDoc";
|
||||
// In columns of the code's font (`spaceWidth`): the DOM stays right through a font
|
||||
// size change or zoom, which does not draw the widget again.
|
||||
const left = `(${this.indent} * ${SPACE} + ${LINE_INSET}px)`;
|
||||
// In the code's character width, which `docMetrics` keeps current: the DOM stays
|
||||
// right through a font size change or zoom, which does not draw the widget again.
|
||||
const left = `(${this.indent} * var(--openidea-doc-char, 1ch) + ${LINE_INSET}px)`;
|
||||
dom.style.marginLeft = `calc${left}`;
|
||||
// The content is as wide as its longest line; the comment wraps at the visible width instead.
|
||||
dom.style.maxWidth = `calc(var(--openidea-doc-width, 100%) - ${left} - ${DOC_RIGHT_GAP}px)`;
|
||||
@@ -828,10 +827,12 @@ export function toggleRenderedViewAtCaret(view: EditorView): boolean {
|
||||
const DOC_RIGHT_GAP = 24;
|
||||
|
||||
/**
|
||||
* Publishes on the content the visible width of the text area, `--openidea-doc-width`.
|
||||
* A block widget is as wide as the content, which without soft wraps is as wide as the
|
||||
* longest line, so a rendered comment needs it to wrap where the reader can see.
|
||||
* Scrolling leaves it unchanged, so lines are not restyled while scrolling.
|
||||
* Publishes on the content the visible width of the text area, `--openidea-doc-width`,
|
||||
* and the code's character width, `--openidea-doc-char`. A block widget is as wide as
|
||||
* the content, which without soft wraps is as wide as the longest line, so a rendered
|
||||
* comment needs the first to wrap where the reader can see, as IDEA's does; it indents
|
||||
* by the second, which a font size change or zoom changes. Horizontal scrolling leaves
|
||||
* both unchanged.
|
||||
*/
|
||||
const docMetrics = ViewPlugin.fromClass(
|
||||
class {
|
||||
@@ -844,12 +845,18 @@ const docMetrics = ViewPlugin.fromClass(
|
||||
measure() {
|
||||
this.view.requestMeasure({
|
||||
key: this,
|
||||
read: (view) => view.scrollDOM.clientWidth - view.contentDOM.offsetLeft,
|
||||
write: (width, view) => {
|
||||
read: (view) => ({
|
||||
width: view.scrollDOM.clientWidth - view.contentDOM.offsetLeft,
|
||||
char: view.defaultCharacterWidth,
|
||||
}),
|
||||
write: ({ width, char }, view) => {
|
||||
const style = view.contentDOM.style;
|
||||
const value = `${Math.max(0, Math.floor(width))}px`;
|
||||
if (style.getPropertyValue("--openidea-doc-width") !== value)
|
||||
style.setProperty("--openidea-doc-width", value);
|
||||
const widthValue = `${Math.max(0, Math.floor(width))}px`;
|
||||
if (style.getPropertyValue("--openidea-doc-width") !== widthValue)
|
||||
style.setProperty("--openidea-doc-width", widthValue);
|
||||
const charValue = `${char}px`;
|
||||
if (style.getPropertyValue("--openidea-doc-char") !== charValue)
|
||||
style.setProperty("--openidea-doc-char", charValue);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -940,6 +947,5 @@ export const renderedDocsExtension: Extension = [
|
||||
markdownReady,
|
||||
languageWatcher,
|
||||
docMetrics,
|
||||
spaceWidth,
|
||||
docsTheme,
|
||||
];
|
||||
@@ -1,51 +0,0 @@
|
||||
/**
|
||||
* The editor font's space width, published on the scroller as `--openidea-space`
|
||||
* for anything laid out in columns of indentation (indent guides, code lens rows,
|
||||
* rendered doc comments). A space is measured, not `ch`: in a proportional font it
|
||||
* is narrower than "0". The probe's text is fixed, so the value only changes with
|
||||
* the font, its size or zoom; `defaultCharacterWidth` is sampled from whichever
|
||||
* line is in view and drifts while scrolling, and an inherited variable that
|
||||
* changes restyles every line.
|
||||
*/
|
||||
import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
|
||||
|
||||
/** One column of indentation, as a CSS length. */
|
||||
export const SPACE = "var(--openidea-space, 1ch)";
|
||||
|
||||
const SAMPLE = 64;
|
||||
|
||||
/** Shared by every extension that lays out by `SPACE`; CodeMirror installs it once. */
|
||||
export const spaceWidth = ViewPlugin.fromClass(
|
||||
class {
|
||||
private probe: HTMLElement;
|
||||
private written = "";
|
||||
constructor(readonly view: EditorView) {
|
||||
// Inherits the editor font from the scroller, outside the content CodeMirror observes.
|
||||
this.probe = document.createElement("span");
|
||||
this.probe.setAttribute("aria-hidden", "true");
|
||||
this.probe.style.cssText = "position: absolute; top: 0; left: 0; visibility: hidden; white-space: pre";
|
||||
this.probe.textContent = " ".repeat(SAMPLE);
|
||||
view.scrollDOM.appendChild(this.probe);
|
||||
this.measure();
|
||||
}
|
||||
measure() {
|
||||
this.view.requestMeasure({
|
||||
key: this,
|
||||
read: (view) => this.probe.getBoundingClientRect().width / (view.scaleX || 1) / SAMPLE,
|
||||
write: (width, view) => {
|
||||
const value = `${+width.toFixed(3)}px`;
|
||||
if (width <= 0 || value === this.written) return;
|
||||
this.written = value;
|
||||
view.scrollDOM.style.setProperty("--openidea-space", value);
|
||||
},
|
||||
});
|
||||
}
|
||||
update(u: ViewUpdate) {
|
||||
if (u.geometryChanged) this.measure();
|
||||
}
|
||||
destroy() {
|
||||
this.probe.remove();
|
||||
this.view.scrollDOM.style.removeProperty("--openidea-space");
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -1,11 +1,9 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorController, openFilePaths, useEditorStatus, useTabErrors, useTabs } from "./controller";
|
||||
import { EditorController, openFilePaths, useEditorStatus, useTabs } from "./controller";
|
||||
import { createMemoryBackend } from "./backend";
|
||||
import { initialTabsState } from "./model/tabs";
|
||||
import { useDocMeta } from "./model/document";
|
||||
import { storeSession } from "./model/session";
|
||||
import { resetDistractionFree, setDistractionFree } from "@/workbench/distractionFree";
|
||||
import * as contributions from "@/workbench/contributions";
|
||||
import {
|
||||
registerEditorKind,
|
||||
registerTextEditorWrapper,
|
||||
@@ -13,7 +11,6 @@ import {
|
||||
useProjectViewLead,
|
||||
} from "@/workbench/contributions";
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { IpcError, type ErrorKind } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { useRemote } from "@/platform/remote";
|
||||
import { hideContextMenu, resolveMenuItems, useContextMenuStore } from "@/ui";
|
||||
@@ -32,75 +29,6 @@ afterEach(() => {
|
||||
useEditorStatus.setState({ status: null });
|
||||
});
|
||||
|
||||
describe("restoring an editor session", () => {
|
||||
const root = "/session-restore";
|
||||
const existing = `${root}/existing.txt`;
|
||||
const unavailable = `${root}/unavailable.txt`;
|
||||
const text = "first\nsecond";
|
||||
let controller: EditorController | undefined;
|
||||
|
||||
afterEach(() => {
|
||||
controller?.stop();
|
||||
controller = undefined;
|
||||
storeSession(root, null);
|
||||
useTabErrors.setState({}, true);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
async function restoreWithOpenError(kind: ErrorKind, message: string) {
|
||||
storeSession(root, {
|
||||
version: 1,
|
||||
layout: { kind: "pane", tabs: [{ path: existing }, { path: unavailable }], active: 1 },
|
||||
activePane: 0,
|
||||
files: { [existing]: { anchor: 6, head: 6 } },
|
||||
});
|
||||
const backend = createMemoryBackend({ [existing]: text });
|
||||
// For an absent path the memory backend serves sample text, not a disk error.
|
||||
const open = backend.open.bind(backend);
|
||||
vi.spyOn(backend, "open").mockImplementation(async (path) => {
|
||||
if (path === unavailable) throw new IpcError({ kind, message });
|
||||
return open(path);
|
||||
});
|
||||
const editor = (controller = new EditorController(backend));
|
||||
editor.start();
|
||||
|
||||
const restoring = editor.restoreSession(root);
|
||||
const state = useTabs.getState();
|
||||
const selected = state.panes[state.activePane]!.active!;
|
||||
// Restore opens the selected tab in the background. Join the same slot request.
|
||||
await Promise.all([restoring, editor.ensureSlot(selected)]);
|
||||
return { editor, selected };
|
||||
}
|
||||
|
||||
it("silently drops a deleted selected file and restores the remaining tab", async () => {
|
||||
const notify = vi.fn();
|
||||
vi.spyOn(contributions, "notifications").mockReturnValue({ notify });
|
||||
const { editor, selected } = await restoreWithOpenError("notFound", `No such file: ${unavailable}`);
|
||||
|
||||
expect(notify).not.toHaveBeenCalled();
|
||||
expect(useTabErrors.getState()).toEqual({});
|
||||
expect(openFilePaths(useTabs.getState())).toEqual([existing]);
|
||||
expect(editor.slotFor(selected)).toBeNull();
|
||||
expect(editor.activeInput()?.path).toBe(existing);
|
||||
|
||||
// In the app the visible tab's editor host requests this slot after selection changes.
|
||||
const state = useTabs.getState();
|
||||
const slot = await editor.ensureSlot(state.panes[state.activePane]!.active!);
|
||||
expect(slot?.model.path).toBe(existing);
|
||||
expect(slot?.state.doc.toString()).toBe(text);
|
||||
expect(slot?.caret()).toMatchObject({ line: 1, col: 0 });
|
||||
});
|
||||
|
||||
it("keeps a tab and reports its open error when access is denied", async () => {
|
||||
const message = `Permission denied: ${unavailable}`;
|
||||
const { editor, selected } = await restoreWithOpenError("permissionDenied", message);
|
||||
|
||||
expect(openFilePaths(useTabs.getState())).toEqual([existing, unavailable]);
|
||||
expect(editor.activeInput()?.path).toBe(unavailable);
|
||||
expect(useTabErrors.getState()).toEqual({ [selected]: message });
|
||||
});
|
||||
});
|
||||
|
||||
describe("EditorController", () => {
|
||||
it("returns navigation context to the editor when activating a non-text tab", async () => {
|
||||
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "one\n" }));
|
||||
|
||||
@@ -47,7 +47,7 @@ import { useDistractionFree } from "@/workbench/distractionFree";
|
||||
import { restoreMaximizedToolWindow } from "@/workbench/toolwindows/store";
|
||||
import { ask, confirm } from "@/workbench/messages";
|
||||
import { t, tx } from "@/platform/i18n";
|
||||
import { call, commands, isErrorKind, isTauri } from "@/platform/ipc";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { openLightweightEditor } from "./openLightweightEditor";
|
||||
import { windowBackgroundHex } from "@/workbench/theme";
|
||||
import { hoverActionsAt } from "@/platform/hoverActions";
|
||||
@@ -736,7 +736,7 @@ export class EditorController implements SlotHost {
|
||||
return this.slots.get(tabId) ?? this.createSlot(tabId, m, init);
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
if (this.restoredTabs.has(tabId) && isErrorKind(e, "notFound")) {
|
||||
if (this.restoredTabs.has(tabId) && (e as { kind?: string } | null)?.kind === "notFound") {
|
||||
// A file from the saved session no longer exists: drop its tab quietly.
|
||||
this.restoredTabs.delete(tabId);
|
||||
this.restoredViews.delete(path);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
initialTabsState,
|
||||
moveTabToNewSplit,
|
||||
@@ -9,15 +9,7 @@ import {
|
||||
togglePin,
|
||||
type TabsState,
|
||||
} from "./tabs";
|
||||
import {
|
||||
loadSession,
|
||||
parseSession,
|
||||
restoreTabsState,
|
||||
serializeSession,
|
||||
slashPath,
|
||||
storeSession,
|
||||
type EditorSession,
|
||||
} from "./session";
|
||||
import { loadSession, parseSession, restoreTabsState, serializeSession, slashPath } from "./session";
|
||||
|
||||
const file = (path: string) => ({ kind: "file", key: `file:${path}`, path });
|
||||
const fileKey = (p: string) => `file:${p}`;
|
||||
@@ -111,44 +103,6 @@ describe("editor session", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("loading a session with malformed JSON", () => {
|
||||
const root = "/malformed-session";
|
||||
const key = `openidea.editorSession.v1:${root}`;
|
||||
const malformed = '{"version":1,"layout":{"kind":"pane","tabs":[';
|
||||
|
||||
beforeEach(() => localStorage.setItem(key, malformed));
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
localStorage.removeItem(key);
|
||||
});
|
||||
|
||||
it("returns null without writing to storage or changing the saved bytes", () => {
|
||||
const before = localStorage.getItem(key);
|
||||
expect(before).toBe(malformed);
|
||||
const setItem = vi.spyOn(Storage.prototype, "setItem");
|
||||
|
||||
expect(loadSession(root)).toBeNull();
|
||||
expect(localStorage.getItem(key)).toBe(before);
|
||||
expect(setItem).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("loads a valid session after an explicit save replaces malformed JSON", () => {
|
||||
expect(loadSession(root)).toBeNull();
|
||||
const path = `${root}/recovered.ts`;
|
||||
const recovered: EditorSession = {
|
||||
version: 1,
|
||||
layout: { kind: "pane", tabs: [{ path }], active: 0 },
|
||||
activePane: 0,
|
||||
files: { [path]: { anchor: 1, head: 2 } },
|
||||
};
|
||||
|
||||
storeSession(root, recovered);
|
||||
|
||||
expect(JSON.parse(localStorage.getItem(key)!)).toEqual(recovered);
|
||||
expect(loadSession(root)).toEqual(recovered);
|
||||
});
|
||||
});
|
||||
|
||||
describe("moveTabToNewSplit", () => {
|
||||
it("moves a tab into a new pane on the given edge", () => {
|
||||
let s = initialTabsState();
|
||||
|
||||
@@ -61,20 +61,6 @@ export interface Reveal {
|
||||
const KEPT_VIEWS = 8;
|
||||
const keptSlots: EditorSlot[] = [];
|
||||
|
||||
/**
|
||||
* Holds the visible tabs' tooltip layers. A layer added to `document.body` itself on every
|
||||
* tab switch would change which element is the body's last child, and Chromium then
|
||||
* restyles the whole workbench (`:last-child` rules); inside this host it restyles nothing else.
|
||||
*/
|
||||
let tooltipHost: HTMLElement | null = null;
|
||||
function tooltipHostElement(): HTMLElement {
|
||||
if (!tooltipHost?.isConnected) {
|
||||
tooltipHost = document.createElement("div");
|
||||
document.body.appendChild(tooltipHost);
|
||||
}
|
||||
return tooltipHost;
|
||||
}
|
||||
|
||||
export class EditorSlot {
|
||||
private stored: EditorState;
|
||||
private historyTarget: WorkspaceHistoryTarget;
|
||||
@@ -84,7 +70,7 @@ export class EditorSlot {
|
||||
/** The view kept, detached from the document, while the tab is hidden. */
|
||||
private kept: EditorView | null = null;
|
||||
/**
|
||||
* The tab's tooltips (hints, hover, completion…). They live outside the view, under `document.body`,
|
||||
* The tab's tooltips (hints, hover, completion…). They live outside the view, in `document.body`,
|
||||
* so they leave the page with the view when the tab is hidden instead of floating over the next tab.
|
||||
*/
|
||||
private readonly tooltipLayer = typeof document === "undefined" ? null : document.createElement("div");
|
||||
@@ -221,7 +207,7 @@ export class EditorSlot {
|
||||
|
||||
mount(parent: HTMLElement): EditorView {
|
||||
if (this.view) return this.view;
|
||||
if (this.tooltipLayer && !this.tooltipLayer.isConnected) tooltipHostElement().appendChild(this.tooltipLayer);
|
||||
if (this.tooltipLayer && !this.tooltipLayer.isConnected) document.body.appendChild(this.tooltipLayer);
|
||||
const kept = this.kept;
|
||||
let view: EditorView;
|
||||
if (kept) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { ChangeSet, Text } from "@codemirror/state";
|
||||
import type { IdeError, TextChange } from "@/platform/ipc";
|
||||
import type { TextChange } from "@/platform/ipc";
|
||||
import { DocSync, toTextChanges } from "./DocSync";
|
||||
import { minimalChanges } from "./diff";
|
||||
|
||||
@@ -19,7 +19,7 @@ function numberedLines(count: number) {
|
||||
}
|
||||
|
||||
class OutOfSync extends Error {
|
||||
readonly kind: IdeError["kind"] = "outOfSync";
|
||||
kind = "outOfSync";
|
||||
}
|
||||
|
||||
/** Backend double: requests are queued and processed explicitly, in order. */
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
* the snapshot, selections mapped).
|
||||
*/
|
||||
import { ChangeSet, Text } from "@codemirror/state";
|
||||
import { isErrorKind, type TextChange } from "@/platform/ipc";
|
||||
import type { TextChange } from "@/platform/ipc";
|
||||
import { minimalChanges } from "./diff";
|
||||
|
||||
export interface SyncTransport {
|
||||
@@ -64,6 +64,10 @@ export const frameScheduler: Scheduler = (fn) => {
|
||||
setTimeout(once, 50);
|
||||
};
|
||||
|
||||
function isOutOfSync(e: unknown): boolean {
|
||||
return typeof e === "object" && e !== null && (e as { kind?: string }).kind === "outOfSync";
|
||||
}
|
||||
|
||||
export function toTextChanges(cs: ChangeSet): TextChange[] {
|
||||
const out: TextChange[] = [];
|
||||
cs.iterChanges((fromA, toA, _fromB, _toB, inserted) => {
|
||||
@@ -206,7 +210,7 @@ export class DocSync {
|
||||
}
|
||||
|
||||
private onReject(error: unknown) {
|
||||
if (!isErrorKind(error, "outOfSync")) {
|
||||
if (!isOutOfSync(error)) {
|
||||
this.host.onError?.(error);
|
||||
this.hardResync(error);
|
||||
return;
|
||||
|
||||
@@ -151,126 +151,52 @@
|
||||
}
|
||||
|
||||
/* Find / replace bar */
|
||||
.findContainer {
|
||||
.find {
|
||||
flex: none;
|
||||
min-width: 0;
|
||||
container: editor-find / inline-size;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(220px, 420px) auto 1fr;
|
||||
align-items: center;
|
||||
column-gap: var(--space-1-5);
|
||||
row-gap: var(--space-1-5);
|
||||
padding: 6px 8px 6px 10px;
|
||||
background: var(--bg-editor-inline, var(--bg-elev));
|
||||
border-bottom: 1px solid var(--border-editor-tabs, var(--border));
|
||||
}
|
||||
.find {
|
||||
display: grid;
|
||||
grid-template-columns: [mode] auto [field] minmax(0, 420px) [actions] fit-content(50%) [close] minmax(
|
||||
min-content,
|
||||
1fr
|
||||
);
|
||||
align-items: start;
|
||||
row-gap: var(--space-1);
|
||||
padding: var(--space-1-5) var(--space-2);
|
||||
.findExpandable {
|
||||
grid-template-columns: auto minmax(220px, 420px) auto 1fr;
|
||||
}
|
||||
.findExpand {
|
||||
grid-area: 1 / mode;
|
||||
margin-inline-end: var(--space-1);
|
||||
grid-column: 1;
|
||||
grid-row: 1;
|
||||
}
|
||||
.findExpandable .findField {
|
||||
grid-column: 2;
|
||||
}
|
||||
.findField {
|
||||
grid-area: 1 / field;
|
||||
}
|
||||
.replaceField {
|
||||
grid-area: 2 / field;
|
||||
}
|
||||
.findField,
|
||||
.replaceField {
|
||||
min-width: 0;
|
||||
}
|
||||
.findClose {
|
||||
grid-area: 1 / close;
|
||||
justify-self: end;
|
||||
margin-inline-start: var(--space-1);
|
||||
}
|
||||
.findExpand,
|
||||
.findClose {
|
||||
margin-block-start: var(--space-1);
|
||||
}
|
||||
.findButtons,
|
||||
.replaceButtons {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
min-height: var(--h-field);
|
||||
margin-inline-start: var(--space-1-5);
|
||||
}
|
||||
.findButtons {
|
||||
grid-area: 1 / actions;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5);
|
||||
}
|
||||
.replaceButtons {
|
||||
grid-area: 2 / actions;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
.findCount {
|
||||
min-inline-size: 5ch;
|
||||
padding-inline: var(--space-1);
|
||||
font-size: var(--fs-small);
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-size: var(--fs-ui);
|
||||
color: var(--fg-subtle);
|
||||
padding: 0 8px 0 4px;
|
||||
min-width: 56px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.findCountNone {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
@container editor-find (width < 500px) {
|
||||
.find {
|
||||
grid-template-columns: [mode] auto [field] minmax(0, 1fr) [close] auto;
|
||||
}
|
||||
.findButtons,
|
||||
.replaceButtons {
|
||||
grid-column: field / -1;
|
||||
min-height: 0;
|
||||
margin-inline-start: 0;
|
||||
}
|
||||
.findButtons {
|
||||
grid-row: 2;
|
||||
}
|
||||
.replaceField {
|
||||
grid-row: 3;
|
||||
}
|
||||
.replaceButtons {
|
||||
grid-row: 4;
|
||||
}
|
||||
.replaceButtons > button {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
min-height: var(--h-control);
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.findClose {
|
||||
justify-self: end;
|
||||
}
|
||||
|
||||
@container editor-find (width < 224px) {
|
||||
.findField,
|
||||
.replaceField,
|
||||
.replaceButtons {
|
||||
grid-column: mode / -1;
|
||||
}
|
||||
.findExpand,
|
||||
.findClose {
|
||||
grid-row: 2;
|
||||
margin-block-start: 0;
|
||||
}
|
||||
.findButtons {
|
||||
grid-column: field;
|
||||
}
|
||||
.findInput {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(20px, 1fr));
|
||||
height: auto;
|
||||
padding-block: var(--space-1);
|
||||
}
|
||||
.findInput textarea {
|
||||
grid-column: 2 / -1;
|
||||
}
|
||||
.replaceButtons {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
}
|
||||
|
||||
/* Go to line */
|
||||
|
||||
@@ -568,8 +568,7 @@ function EditorTabActions({ paneId, tab }: { paneId: string; tab: Tab }) {
|
||||
anchor={moreRef}
|
||||
placement="bottom-end"
|
||||
aria-label="Tab actions"
|
||||
// Built when shown: every tab render (each open and switch) would otherwise assemble the whole menu.
|
||||
items={open ? ctrl.tabMenu(paneId, tab) : []}
|
||||
items={ctrl.tabMenu(paneId, tab)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
+173
-176
@@ -608,185 +608,182 @@ export function FindPanel({ target, version, replace, seq, onReplaceShown, onClo
|
||||
const canReplace = !!opts.search && !invalid;
|
||||
|
||||
return (
|
||||
<div className={styles.findContainer}>
|
||||
<div
|
||||
ref={panelRef}
|
||||
onFocusCapture={() => {
|
||||
focusedTarget = target;
|
||||
setContext("findBarFocus", true);
|
||||
setContext(
|
||||
"findBarHasResults",
|
||||
!!target.results && !!opts.search && (!opts.regexp || regexValid(opts.search)) && !!count?.total,
|
||||
);
|
||||
}}
|
||||
onBlurCapture={(e) => {
|
||||
if (!panelRef.current?.contains(e.relatedTarget as Node | null)) setContext("findBarFocus", false);
|
||||
}}
|
||||
className={styles.find}
|
||||
role="search"
|
||||
aria-label={replace ? "Replace in file" : "Find in file"}
|
||||
>
|
||||
{onReplaceShown && (
|
||||
<IconButton
|
||||
icon={replace ? "chevron-down" : "chevron-right"}
|
||||
title={replace ? "Hide Replace" : "Show Replace"}
|
||||
size="small"
|
||||
className={styles.findExpand}
|
||||
aria-expanded={replace}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => {
|
||||
if (replaceBoxRef.current?.contains(document.activeElement)) inputRef.current?.focus();
|
||||
onReplaceShown(!replace);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<div ref={findBoxRef} className={styles.findField}>
|
||||
<SearchField
|
||||
ref={inputRef}
|
||||
value={opts.search}
|
||||
onChange={(search) => setOpts({ search })}
|
||||
placeholder="Find"
|
||||
aria-label="Find"
|
||||
invalid={invalid || none}
|
||||
multiline
|
||||
onHistory={() => setHistoryMenu("find")}
|
||||
onKeyDown={(e) => onKeyDown(e, "find")}
|
||||
className={styles.findInput}
|
||||
toggles={[
|
||||
{
|
||||
id: "case",
|
||||
icon: "case",
|
||||
title: "Match Case",
|
||||
shortcut: formatBinding("Alt+C"),
|
||||
pressed: opts.caseSensitive,
|
||||
onToggle: () => toggle("caseSensitive"),
|
||||
},
|
||||
{
|
||||
id: "word",
|
||||
icon: "word",
|
||||
title: "Words",
|
||||
shortcut: formatBinding("Alt+W"),
|
||||
pressed: opts.wholeWord,
|
||||
onToggle: () => toggle("wholeWord"),
|
||||
},
|
||||
{
|
||||
id: "regex",
|
||||
icon: "regex",
|
||||
title: "Regex",
|
||||
shortcut: formatBinding("Alt+X"),
|
||||
pressed: opts.regexp,
|
||||
onToggle: () => toggle("regexp"),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.findButtons}>
|
||||
<span className={clsx(styles.findCount, (none || invalid) && styles.findCountNone)} aria-live="polite">
|
||||
{counter}
|
||||
</span>
|
||||
<IconButton
|
||||
icon="arrow-up"
|
||||
title="Previous Occurrence"
|
||||
shortcut={formatBinding("Shift+Enter")}
|
||||
size="small"
|
||||
onClick={() => run(findPrevious)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="arrow-down"
|
||||
title="Next Occurrence"
|
||||
shortcut={formatBinding("Enter")}
|
||||
size="small"
|
||||
onClick={() => run(findNext)}
|
||||
/>
|
||||
<IconButton
|
||||
ref={filterRef}
|
||||
icon="filter"
|
||||
title="Filter Search Results"
|
||||
size="small"
|
||||
pressed={scoped || inChanges || opts.context !== "any"}
|
||||
onClick={() => setFilterMenu(true)}
|
||||
/>
|
||||
<IconButton ref={moreRef} icon="more" title="More" size="small" onClick={() => setMoreMenu(true)} />
|
||||
</div>
|
||||
<IconButton icon="close" title="Close" shortcut="⎋" size="small" className={styles.findClose} onClick={close} />
|
||||
{replace && (
|
||||
<>
|
||||
<div ref={replaceBoxRef} className={styles.replaceField}>
|
||||
<SearchField
|
||||
ref={replaceRef}
|
||||
value={opts.replace}
|
||||
onChange={(value) => setOpts({ replace: value })}
|
||||
placeholder="Replace"
|
||||
aria-label="Replace"
|
||||
multiline
|
||||
onHistory={() => setHistoryMenu("replace")}
|
||||
onKeyDown={(e) => onKeyDown(e, "replace")}
|
||||
toggles={[
|
||||
{
|
||||
id: "preserveCase",
|
||||
icon: "preserve-case",
|
||||
title: "Preserve Case",
|
||||
pressed: opts.preserveCase,
|
||||
onToggle: () => toggle("preserveCase"),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.replaceButtons}>
|
||||
<Button
|
||||
size="small"
|
||||
title={tx`Replace (${formatBinding("Alt+P")})`}
|
||||
onClick={doReplace}
|
||||
disabled={!canReplace}
|
||||
>
|
||||
<T>Replace</T>
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
title={tx`Replace All (${formatBinding("Alt+A")})`}
|
||||
onClick={doReplaceAll}
|
||||
disabled={!canReplace}
|
||||
>
|
||||
<T>Replace All</T>
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
title={
|
||||
count?.excluded ? tx`Include (${formatBinding("Alt+L")})` : tx`Exclude (${formatBinding("Alt+L")})`
|
||||
}
|
||||
onClick={() => run(excludeCurrent)}
|
||||
disabled={!canReplace || (!count?.total && !count?.excluded)}
|
||||
>
|
||||
{count?.excluded ? <T>Include</T> : <T>Exclude</T>}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<Menu
|
||||
open={historyMenu !== null}
|
||||
anchor={historyMenu === "replace" ? replaceBoxRef : findBoxRef}
|
||||
items={historyMenu ? historyItems(historyMenu) : []}
|
||||
placement="bottom-start"
|
||||
aria-label="Recent searches"
|
||||
onClose={() => setHistoryMenu(null)}
|
||||
<div
|
||||
ref={panelRef}
|
||||
onFocusCapture={() => {
|
||||
focusedTarget = target;
|
||||
setContext("findBarFocus", true);
|
||||
setContext(
|
||||
"findBarHasResults",
|
||||
!!target.results && !!opts.search && (!opts.regexp || regexValid(opts.search)) && !!count?.total,
|
||||
);
|
||||
}}
|
||||
onBlurCapture={(e) => {
|
||||
if (!panelRef.current?.contains(e.relatedTarget as Node | null)) setContext("findBarFocus", false);
|
||||
}}
|
||||
className={clsx(styles.find, onReplaceShown && styles.findExpandable)}
|
||||
role="search"
|
||||
aria-label={replace ? "Replace in file" : "Find in file"}
|
||||
>
|
||||
{onReplaceShown && (
|
||||
<IconButton
|
||||
icon={replace ? "chevron-down" : "chevron-right"}
|
||||
title={replace ? "Hide Replace" : "Show Replace"}
|
||||
size="small"
|
||||
className={styles.findExpand}
|
||||
aria-expanded={replace}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => {
|
||||
if (replaceBoxRef.current?.contains(document.activeElement)) inputRef.current?.focus();
|
||||
onReplaceShown(!replace);
|
||||
}}
|
||||
/>
|
||||
<Menu
|
||||
open={moreMenu}
|
||||
anchor={moreRef}
|
||||
items={moreItems}
|
||||
placement="bottom-end"
|
||||
aria-label="Find options"
|
||||
onClose={() => setMoreMenu(false)}
|
||||
/>
|
||||
<Menu
|
||||
open={filterMenu}
|
||||
anchor={filterRef}
|
||||
items={filterItems}
|
||||
placement="bottom-end"
|
||||
aria-label="Filter search results"
|
||||
onClose={() => setFilterMenu(false)}
|
||||
)}
|
||||
<div ref={findBoxRef} className={styles.findField}>
|
||||
<SearchField
|
||||
ref={inputRef}
|
||||
value={opts.search}
|
||||
onChange={(search) => setOpts({ search })}
|
||||
placeholder="Find"
|
||||
aria-label="Find"
|
||||
invalid={invalid || none}
|
||||
multiline
|
||||
onHistory={() => setHistoryMenu("find")}
|
||||
onKeyDown={(e) => onKeyDown(e, "find")}
|
||||
toggles={[
|
||||
{
|
||||
id: "case",
|
||||
icon: "case",
|
||||
title: "Match Case",
|
||||
shortcut: formatBinding("Alt+C"),
|
||||
pressed: opts.caseSensitive,
|
||||
onToggle: () => toggle("caseSensitive"),
|
||||
},
|
||||
{
|
||||
id: "word",
|
||||
icon: "word",
|
||||
title: "Words",
|
||||
shortcut: formatBinding("Alt+W"),
|
||||
pressed: opts.wholeWord,
|
||||
onToggle: () => toggle("wholeWord"),
|
||||
},
|
||||
{
|
||||
id: "regex",
|
||||
icon: "regex",
|
||||
title: "Regex",
|
||||
shortcut: formatBinding("Alt+X"),
|
||||
pressed: opts.regexp,
|
||||
onToggle: () => toggle("regexp"),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.findButtons}>
|
||||
<span className={clsx(styles.findCount, (none || invalid) && styles.findCountNone)} aria-live="polite">
|
||||
{counter}
|
||||
</span>
|
||||
<IconButton
|
||||
icon="arrow-up"
|
||||
title="Previous Occurrence"
|
||||
shortcut={formatBinding("Shift+Enter")}
|
||||
size="small"
|
||||
onClick={() => run(findPrevious)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="arrow-down"
|
||||
title="Next Occurrence"
|
||||
shortcut={formatBinding("Enter")}
|
||||
size="small"
|
||||
onClick={() => run(findNext)}
|
||||
/>
|
||||
<IconButton
|
||||
ref={filterRef}
|
||||
icon="filter"
|
||||
title="Filter Search Results"
|
||||
size="small"
|
||||
pressed={scoped || inChanges || opts.context !== "any"}
|
||||
onClick={() => setFilterMenu(true)}
|
||||
/>
|
||||
<IconButton ref={moreRef} icon="more" title="More" size="small" onClick={() => setMoreMenu(true)} />
|
||||
</div>
|
||||
<IconButton icon="close" title="Close" shortcut="⎋" size="small" className={styles.findClose} onClick={close} />
|
||||
{replace && (
|
||||
<>
|
||||
<div ref={replaceBoxRef} className={styles.findField}>
|
||||
<SearchField
|
||||
ref={replaceRef}
|
||||
value={opts.replace}
|
||||
onChange={(value) => setOpts({ replace: value })}
|
||||
placeholder="Replace"
|
||||
aria-label="Replace"
|
||||
multiline
|
||||
onHistory={() => setHistoryMenu("replace")}
|
||||
onKeyDown={(e) => onKeyDown(e, "replace")}
|
||||
toggles={[
|
||||
{
|
||||
id: "preserveCase",
|
||||
icon: "preserve-case",
|
||||
title: "Preserve Case",
|
||||
pressed: opts.preserveCase,
|
||||
onToggle: () => toggle("preserveCase"),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.replaceButtons}>
|
||||
<Button
|
||||
size="small"
|
||||
title={tx`Replace (${formatBinding("Alt+P")})`}
|
||||
onClick={doReplace}
|
||||
disabled={!canReplace}
|
||||
>
|
||||
<T>Replace</T>
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
title={tx`Replace All (${formatBinding("Alt+A")})`}
|
||||
onClick={doReplaceAll}
|
||||
disabled={!canReplace}
|
||||
>
|
||||
<T>Replace All</T>
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
title={
|
||||
count?.excluded ? tx`Include (${formatBinding("Alt+L")})` : tx`Exclude (${formatBinding("Alt+L")})`
|
||||
}
|
||||
onClick={() => run(excludeCurrent)}
|
||||
disabled={!canReplace || (!count?.total && !count?.excluded)}
|
||||
>
|
||||
{count?.excluded ? <T>Include</T> : <T>Exclude</T>}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<Menu
|
||||
open={historyMenu !== null}
|
||||
anchor={historyMenu === "replace" ? replaceBoxRef : findBoxRef}
|
||||
items={historyMenu ? historyItems(historyMenu) : []}
|
||||
placement="bottom-start"
|
||||
aria-label="Recent searches"
|
||||
onClose={() => setHistoryMenu(null)}
|
||||
/>
|
||||
<Menu
|
||||
open={moreMenu}
|
||||
anchor={moreRef}
|
||||
items={moreItems}
|
||||
placement="bottom-end"
|
||||
aria-label="Find options"
|
||||
onClose={() => setMoreMenu(false)}
|
||||
/>
|
||||
<Menu
|
||||
open={filterMenu}
|
||||
anchor={filterRef}
|
||||
items={filterItems}
|
||||
placement="bottom-end"
|
||||
aria-label="Filter search results"
|
||||
onClose={() => setFilterMenu(false)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -261,34 +261,6 @@
|
||||
font-size: var(--fs-tiny);
|
||||
color: var(--fg-faint);
|
||||
}
|
||||
.symbolRename {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
align-items: center;
|
||||
gap: var(--space-2) var(--space-3);
|
||||
padding: var(--space-3);
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
.renameContext,
|
||||
.symbolRenameNote {
|
||||
grid-column: 1 / -1;
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.renameContext {
|
||||
color: var(--fg-emphasis);
|
||||
}
|
||||
.symbolRename .renameField {
|
||||
width: 100%;
|
||||
height: max(var(--h-field), calc(var(--openidea-editor-font-size, var(--fs-code)) + var(--space-2)));
|
||||
font-family: var(--openidea-editor-font, var(--font-mono));
|
||||
font-size: var(--openidea-editor-font-size, var(--fs-code));
|
||||
}
|
||||
.symbolRenameNote {
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
|
||||
/* Fits its content up to a cap; resized (`data-resized`), it keeps that size and the body scrolls. */
|
||||
.docPopup {
|
||||
@@ -426,36 +398,6 @@
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
.renamePreview [data-dialog-body] {
|
||||
display: block;
|
||||
overflow: auto;
|
||||
}
|
||||
.previewContext {
|
||||
padding: var(--space-2) 14px 0;
|
||||
overflow-wrap: anywhere;
|
||||
color: var(--fg-emphasis);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
.renamePreview .previewList {
|
||||
overflow: visible;
|
||||
}
|
||||
.renamePreview .previewName {
|
||||
min-width: 0;
|
||||
max-width: 55%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.renamePreview .previewOp {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.renamePreview .previewWarning {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.previewSummary {
|
||||
flex: none;
|
||||
padding: 10px 14px 6px;
|
||||
@@ -527,18 +469,6 @@
|
||||
font-size: var(--fs-small);
|
||||
color: var(--fg-editor);
|
||||
}
|
||||
.renamePreview .previewOccurrences .previewRow {
|
||||
min-height: var(--h-row);
|
||||
height: auto;
|
||||
align-items: baseline;
|
||||
padding-block: var(--space-1);
|
||||
}
|
||||
.renamePreview .previewCode {
|
||||
font-family: var(--openidea-editor-font, var(--font-mono));
|
||||
font-size: var(--openidea-editor-font-size, var(--fs-code));
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.previewMatch {
|
||||
background: var(--bg-search-match);
|
||||
color: var(--fg-search-match, inherit);
|
||||
@@ -553,6 +483,33 @@
|
||||
}
|
||||
|
||||
/* 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, within } from "@testing-library/react";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import type { Location } from "@/bindings";
|
||||
|
||||
const openFile = vi.fn(async () => undefined);
|
||||
@@ -19,6 +19,7 @@ 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";
|
||||
@@ -351,7 +352,7 @@ describe("quick definition popup", () => {
|
||||
});
|
||||
|
||||
describe("reformat dialog", () => {
|
||||
it("offers only whole-file formatting when the editor has no selection", () => {
|
||||
it("wraps its content in the padded body", () => {
|
||||
const onRun = vi.fn();
|
||||
openPopup({
|
||||
kind: "reformat",
|
||||
@@ -362,10 +363,9 @@ describe("reformat dialog", () => {
|
||||
onRun,
|
||||
});
|
||||
render(<LspPopups />);
|
||||
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();
|
||||
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);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Run" }));
|
||||
expect(onRun).toHaveBeenCalledWith({ selectionOnly: false, optimizeImports: false });
|
||||
});
|
||||
|
||||
+30
-84
@@ -1,5 +1,5 @@
|
||||
/** React popups for LSP editor features, rendered as a workbench overlay. */
|
||||
import { useEffect, useId, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent } from "react";
|
||||
import { useEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
import {
|
||||
Checkbox,
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
List,
|
||||
MenuList,
|
||||
Popup,
|
||||
Radio,
|
||||
Select,
|
||||
Spinner,
|
||||
SymbolBadge,
|
||||
@@ -36,7 +35,6 @@ 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";
|
||||
|
||||
@@ -394,54 +392,6 @@ function RenamePopup({ popup }: { popup: Extract<LspPopup, { kind: "rename" }> }
|
||||
);
|
||||
}
|
||||
|
||||
function SymbolRenameDialog({ popup }: { popup: Extract<LspPopup, { kind: "symbolRename" }> }) {
|
||||
const [value, setValue] = useState(popup.initial);
|
||||
const field = useId();
|
||||
const name = value.trim();
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
title="Rename"
|
||||
aria-label={popup.title}
|
||||
onClose={closePopup}
|
||||
blockWorkbenchShortcuts
|
||||
width={440}
|
||||
buttons={[
|
||||
{
|
||||
label: "Rename",
|
||||
role: "default",
|
||||
disabled: !name,
|
||||
onClick: () => {
|
||||
closePopup();
|
||||
popup.onSubmit(name);
|
||||
},
|
||||
},
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
>
|
||||
<div className={popup.themeClasses}>
|
||||
<div className={styles.symbolRename}>
|
||||
<div className={styles.renameContext}>{popup.title}</div>
|
||||
<label htmlFor={field}>
|
||||
<T>New name</T>
|
||||
</label>
|
||||
<Input
|
||||
id={field}
|
||||
className={styles.renameField}
|
||||
mono
|
||||
data-autofocus
|
||||
autoSelect
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
invalid={!name}
|
||||
/>
|
||||
{popup.note && <div className={styles.symbolRenameNote}>{popup.note}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
|
||||
const focusSeq = useLspPopup((s) => s.focusSeq);
|
||||
const scope = useRef<HTMLDivElement>(null);
|
||||
@@ -586,7 +536,6 @@ function savePreviewSize(size: { w: number; h: number }) {
|
||||
}
|
||||
|
||||
function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }> }) {
|
||||
const rename = popup.renameThemeClasses !== undefined;
|
||||
const root = useProject((s) => s.project?.root ?? "");
|
||||
const { summary } = popup;
|
||||
const [initialSize] = useState(loadPreviewSize);
|
||||
@@ -594,9 +543,8 @@ function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }
|
||||
<Dialog
|
||||
open
|
||||
onClose={closePopup}
|
||||
title={rename ? "Rename" : popup.title}
|
||||
aria-label={popup.title}
|
||||
className={clsx(styles.previewDialog, rename && styles.renamePreview)}
|
||||
title={popup.title}
|
||||
className={styles.previewDialog}
|
||||
width={560}
|
||||
minWidth={400}
|
||||
minHeight={220}
|
||||
@@ -617,7 +565,6 @@ function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
>
|
||||
{rename && <div className={styles.previewContext}>{popup.title}</div>}
|
||||
{popup.warnings?.map((w) => (
|
||||
<div key={w} className={styles.previewWarning} role="note">
|
||||
<Icon name="warning" size={14} />
|
||||
@@ -626,10 +573,7 @@ function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }
|
||||
))}
|
||||
<div className={styles.previewSummary}>{describeSummary(summary)}</div>
|
||||
{popup.occurrences ? (
|
||||
<ul
|
||||
className={clsx(styles.previewList, styles.previewOccurrences, popup.renameThemeClasses)}
|
||||
aria-label={tx("Occurrences")}
|
||||
>
|
||||
<ul className={styles.previewList} aria-label={tx("Occurrences")}>
|
||||
{popup.occurrences.map((o, i) => {
|
||||
const lead = o.text.length - o.text.trimStart().length;
|
||||
const text = o.text.trim();
|
||||
@@ -652,9 +596,7 @@ function PreviewDialog({ popup }: { popup: Extract<LspPopup, { kind: "preview" }
|
||||
{summary.entries.map((e) => (
|
||||
<li key={e.path} className={styles.previewRow}>
|
||||
<Icon name={fileIconName(basename(e.path), e.path)} size={14} className={styles.itemIcon} />
|
||||
<span className={styles.previewName} title={relativePath(root, e.path)}>
|
||||
{basename(e.path)}
|
||||
</span>
|
||||
<span className={styles.previewName}>{basename(e.path)}</span>
|
||||
<span className={styles.previewPath} title={relativePath(root, e.path)}>
|
||||
{relativePath(root, e.path)}
|
||||
</span>
|
||||
@@ -683,7 +625,7 @@ function ReformatDialog({ popup }: { popup: Extract<LspPopup, { kind: "reformat"
|
||||
open
|
||||
onClose={closePopup}
|
||||
title={popup.title}
|
||||
width={400}
|
||||
width={380}
|
||||
buttons={[
|
||||
{
|
||||
label: "Run",
|
||||
@@ -697,27 +639,33 @@ function ReformatDialog({ popup }: { popup: Extract<LspPopup, { kind: "reformat"
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
>
|
||||
<div className={fieldsetStyles.body}>
|
||||
<fieldset className={fieldsetStyles.group}>
|
||||
<legend className={fieldsetStyles.legend}>
|
||||
<div className={styles.reformatBody}>
|
||||
<fieldset className={styles.reformatGroup}>
|
||||
<legend className={styles.reformatLegend}>
|
||||
<T>Scope</T>
|
||||
</legend>
|
||||
<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"
|
||||
/>
|
||||
<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>
|
||||
</fieldset>
|
||||
<fieldset className={fieldsetStyles.group}>
|
||||
<legend className={fieldsetStyles.legend}>
|
||||
<fieldset className={styles.reformatGroup}>
|
||||
<legend className={styles.reformatLegend}>
|
||||
<T>Options</T>
|
||||
</legend>
|
||||
<Checkbox
|
||||
@@ -794,8 +742,6 @@ export function LspPopups() {
|
||||
return <ListPopup key={seq} popup={popup} />;
|
||||
case "rename":
|
||||
return <RenamePopup key={seq} popup={popup} />;
|
||||
case "symbolRename":
|
||||
return <SymbolRenameDialog key={seq} popup={popup} />;
|
||||
case "doc":
|
||||
return <DocPopup key={seq} popup={popup} />;
|
||||
case "definition":
|
||||
|
||||
@@ -130,14 +130,6 @@ export type LspPopup =
|
||||
hint?: string;
|
||||
onSubmit: (name: string) => void;
|
||||
}
|
||||
| {
|
||||
kind: "symbolRename";
|
||||
title: string;
|
||||
initial: string;
|
||||
note?: string;
|
||||
themeClasses: string;
|
||||
onSubmit: (name: string) => void;
|
||||
}
|
||||
| {
|
||||
kind: "preview";
|
||||
title: string;
|
||||
@@ -148,8 +140,6 @@ export type LspPopup =
|
||||
warnings?: string[];
|
||||
/** Individual occurrences with line previews (single-file syntax-based renames). */
|
||||
occurrences?: PreviewOccurrence[];
|
||||
/** The editor theme for a symbol rename and its occurrence snippets. */
|
||||
renameThemeClasses?: string;
|
||||
};
|
||||
|
||||
export interface PreviewOccurrence {
|
||||
|
||||
@@ -27,9 +27,9 @@ import { executeAction } from "@/platform/actions";
|
||||
import { whenAllSynced, whenSynced, type EditorDocContext } from "@/editor/api";
|
||||
import { structure } from "@/editor/structure";
|
||||
import { docOf, incompleteNote, isUnavailable, lspRequest, reportLspError } from "./lsp";
|
||||
import { offsetToPos, rangeToOffsets } from "./positions";
|
||||
import { comparePos, offsetToPos, rangeToOffsets } from "./positions";
|
||||
import { showHint } from "./hint";
|
||||
import { openPopup, type PreviewOccurrence } from "./popupStore";
|
||||
import { caretAnchor, openPopup, type PreviewOccurrence } from "./popupStore";
|
||||
import { needsPreview, summarizeWorkspaceEdit } from "./workspaceEdit";
|
||||
import { endInplaceRename, inplaceSession, startInplaceRename, type Span } from "./inplaceRename";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
@@ -127,10 +127,10 @@ export async function startRename(view: EditorView) {
|
||||
const oldName = view.state.sliceDoc(from, to);
|
||||
const dialog = (initial: string) =>
|
||||
openPopup({
|
||||
kind: "symbolRename",
|
||||
kind: "rename",
|
||||
anchor: caretAnchor(view, from),
|
||||
title: tx`Rename '${oldName}'`,
|
||||
initial,
|
||||
themeClasses: view.themeClasses,
|
||||
onSubmit: (newName) => void finishRename(view, doc, pos, oldName, newName),
|
||||
});
|
||||
if (from === to) {
|
||||
@@ -304,7 +304,6 @@ async function finishRename(view: EditorView, doc: EditorDocContext, pos: Pos, o
|
||||
kind: "preview",
|
||||
title: tx`Rename '${oldName}' to '${newName}'`,
|
||||
summary,
|
||||
renameThemeClasses: view.themeClasses,
|
||||
...(note ? { warnings: [note] } : {}),
|
||||
confirmLabel: note ? "Rename Anyway" : "Do Refactor",
|
||||
onConfirm: () => void applyEdit(view, edit),
|
||||
@@ -351,12 +350,13 @@ async function startSyntaxRename(
|
||||
return true;
|
||||
}
|
||||
const { plan } = result;
|
||||
const at = plan.occurrences.find((o) => comparePos(o.range.start, pos) <= 0 && comparePos(pos, o.range.end) <= 0);
|
||||
openPopup({
|
||||
kind: "symbolRename",
|
||||
kind: "rename",
|
||||
anchor: caretAnchor(view, rangeToOffsets(view.state.doc, (at ?? plan.occurrences[0]!).range).from),
|
||||
title: tx`Rename '${plan.symbol.name}'`,
|
||||
initial: plan.symbol.name,
|
||||
note: `${SYNTAX_NOTE}: local occurrences only`,
|
||||
themeClasses: view.themeClasses,
|
||||
onSubmit: (newName) => void commitSyntaxRename(view, doc, plan, newName),
|
||||
});
|
||||
return true;
|
||||
@@ -418,7 +418,6 @@ export async function commitSyntaxRename(
|
||||
},
|
||||
warnings: [...risks, `${SYNTAX_NOTE}. Only the occurrences below will be renamed.`],
|
||||
occurrences,
|
||||
renameThemeClasses: view.themeClasses,
|
||||
confirmLabel: "Rename Anyway",
|
||||
onConfirm: apply,
|
||||
});
|
||||
|
||||
+10
-51
@@ -6,17 +6,8 @@
|
||||
*/
|
||||
import { EditorSelection, Prec, StateEffect, StateField, type Extension } from "@codemirror/state";
|
||||
import { completionStatus, hasNextSnippetField, hasPrevSnippetField } from "@codemirror/autocomplete";
|
||||
import {
|
||||
EditorView,
|
||||
ViewPlugin,
|
||||
keymap,
|
||||
repositionTooltips,
|
||||
showTooltip,
|
||||
type Tooltip,
|
||||
type ViewUpdate,
|
||||
} from "@codemirror/view";
|
||||
import { EditorView, ViewPlugin, keymap, showTooltip, type Tooltip, type ViewUpdate } from "@codemirror/view";
|
||||
import { commands, type SignatureHelp } from "@/platform/ipc";
|
||||
import { tooltipBounds } from "@/editor/core/cm/setup";
|
||||
import { docOf, lspRequest, reportLspError, debounce } from "./lsp";
|
||||
import { offsetToPos } from "./positions";
|
||||
import { showHint } from "./hint";
|
||||
@@ -49,6 +40,8 @@ export function splitSignature(label: string, params: ReadonlyArray<[number, num
|
||||
return { before: label.slice(0, s), param: label.slice(s, e), after: label.slice(e) };
|
||||
}
|
||||
|
||||
const MAX_ROWS = 12;
|
||||
|
||||
/** Whether an overload can take an argument at `index` (varargs take any number). */
|
||||
export function acceptsParameter(sig: { label: string; parameters: ReadonlyArray<[number, number]> }, index: number) {
|
||||
if (index < sig.parameters.length) return true;
|
||||
@@ -61,27 +54,23 @@ function signatureTooltip(s: SigState): Tooltip {
|
||||
pos: s.pos,
|
||||
above: true,
|
||||
strictSide: false,
|
||||
create: (view) => {
|
||||
create: () => {
|
||||
const dom = document.createElement("div");
|
||||
dom.className = "cm-lsp-signature";
|
||||
dom.setAttribute("role", "tooltip");
|
||||
const { signatures, activeSignature, activeParameter } = s.help;
|
||||
let active: HTMLElement | null = null;
|
||||
signatures.forEach((sig, i) => {
|
||||
const start = Math.max(0, Math.min(activeSignature - 6, signatures.length - MAX_ROWS));
|
||||
signatures.slice(start, start + MAX_ROWS).forEach((sig, j) => {
|
||||
const i = start + j;
|
||||
const row = document.createElement("div");
|
||||
row.className = "cm-lsp-signature-row";
|
||||
if (i === activeSignature) {
|
||||
row.classList.add("cm-lsp-signature-active");
|
||||
row.setAttribute("aria-current", "true");
|
||||
active = row;
|
||||
} else if (!acceptsParameter(sig, activeParameter)) row.classList.add("cm-lsp-signature-disabled");
|
||||
if (i === activeSignature) row.classList.add("cm-lsp-signature-active");
|
||||
else if (!acceptsParameter(sig, activeParameter)) row.classList.add("cm-lsp-signature-disabled");
|
||||
const parts = splitSignature(sig.label, sig.parameters, activeParameter);
|
||||
row.append(parts.before);
|
||||
if (parts.param) {
|
||||
const b = document.createElement("b");
|
||||
b.textContent = parts.param;
|
||||
row.appendChild(b);
|
||||
if (i === activeSignature) active = b;
|
||||
}
|
||||
row.append(parts.after);
|
||||
dom.appendChild(row);
|
||||
@@ -92,37 +81,7 @@ function signatureTooltip(s: SigState): Tooltip {
|
||||
d.classList.add("cm-lsp-signature-doc");
|
||||
dom.appendChild(d);
|
||||
}
|
||||
const fit = ({ left, right }: { left: number; right: number }) => {
|
||||
const width = `${Math.max(0, Math.floor(right - left))}px`;
|
||||
const fontSize = getComputedStyle(view.contentDOM).fontSize;
|
||||
const changed = dom.style.getPropertyValue("--cm-signature-width") !== width || dom.style.fontSize !== fontSize;
|
||||
if (changed) {
|
||||
dom.style.setProperty("--cm-signature-width", width);
|
||||
dom.style.fontSize = fontSize;
|
||||
}
|
||||
return changed;
|
||||
};
|
||||
// Reveal the current parameter after wrapping or a vertical clamp. Leave manual scrolling alone.
|
||||
let fittedWidth = 0;
|
||||
let fittedHeight = 0;
|
||||
return {
|
||||
dom,
|
||||
mount: () => void fit(tooltipBounds(view)),
|
||||
positioned: (space) => {
|
||||
if (fit(space)) {
|
||||
repositionTooltips(view);
|
||||
return;
|
||||
}
|
||||
if (!active || (fittedWidth === dom.clientWidth && fittedHeight === dom.clientHeight)) return;
|
||||
fittedWidth = dom.clientWidth;
|
||||
fittedHeight = dom.clientHeight;
|
||||
const top = dom.getBoundingClientRect().top + dom.clientTop;
|
||||
const parameter = active.getBoundingClientRect();
|
||||
const below = parameter.bottom - (top + fittedHeight);
|
||||
if (parameter.top < top || parameter.height >= fittedHeight) dom.scrollTop += parameter.top - top;
|
||||
else if (below > 0) dom.scrollTop += below;
|
||||
},
|
||||
};
|
||||
return { dom };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -646,8 +646,8 @@ describe("rename wiring", () => {
|
||||
const view = editor("const x = 1;\nf({ x });", "typescript", 6);
|
||||
await startRename(view);
|
||||
const popup = useLspPopup.getState().popup;
|
||||
expect(popup?.kind).toBe("symbolRename");
|
||||
if (popup?.kind !== "symbolRename") return;
|
||||
expect(popup?.kind).toBe("rename");
|
||||
if (popup?.kind !== "rename") return;
|
||||
expect(popup.note).toContain("Based on syntax");
|
||||
popup.onSubmit("y");
|
||||
await vi.waitFor(() => expect(view.state.doc.toString()).toBe("const y = 1;\nf({ x: y });"));
|
||||
@@ -661,7 +661,7 @@ describe("rename wiring", () => {
|
||||
const view = editor("const x = 1;\nx;\nvar x;", "typescript", 6);
|
||||
await startRename(view);
|
||||
const popup = useLspPopup.getState().popup;
|
||||
if (popup?.kind !== "symbolRename") throw new Error("no rename dialog");
|
||||
if (popup?.kind !== "rename") throw new Error("no rename popup");
|
||||
popup.onSubmit("y");
|
||||
await vi.waitFor(() => expect(useLspPopup.getState().popup?.kind).toBe("preview"));
|
||||
const preview = useLspPopup.getState().popup;
|
||||
@@ -860,12 +860,12 @@ describe("rename wiring", () => {
|
||||
await startRename(view);
|
||||
expect(inplaceSession(view.state)?.oldName).toBe("x");
|
||||
await startRename(view);
|
||||
expect(useLspPopup.getState().popup?.kind).toBe("symbolRename");
|
||||
expect(useLspPopup.getState().popup?.kind).toBe("rename");
|
||||
if (finish === "cancel") closePopup();
|
||||
release({ status: "ok", data: r(0, 6, 7) });
|
||||
await older;
|
||||
expect(inplaceSession(view.state)).toBeNull();
|
||||
expect(useLspPopup.getState().popup?.kind ?? null).toBe(finish === "dialog" ? "symbolRename" : null);
|
||||
expect(useLspPopup.getState().popup?.kind ?? null).toBe(finish === "dialog" ? "rename" : null);
|
||||
});
|
||||
|
||||
it.each(["text", "document"])("drops pending preparation when the editor %s changes", async (change) => {
|
||||
@@ -938,7 +938,7 @@ describe("rename wiring", () => {
|
||||
);
|
||||
cmd.syntaxLocals.mockReturnValueOnce(ok(local({ references: [] })));
|
||||
await startRename(view);
|
||||
expect(useLspPopup.getState().popup?.kind).toBe("symbolRename");
|
||||
expect(useLspPopup.getState().popup?.kind).toBe("rename");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+10
-17
@@ -270,35 +270,28 @@ export const lspTheme = EditorView.theme({
|
||||
cursor: "pointer",
|
||||
},
|
||||
".cm-lsp-link-button:hover": { color: "var(--link-hover)", textDecoration: "underline" },
|
||||
".cm-tooltip.cm-lsp-signature": {
|
||||
".cm-lsp-signature": {
|
||||
fontFamily: "var(--openidea-editor-font, var(--font-mono))",
|
||||
fontWeight: "var(--fw-code, 400)",
|
||||
fontSize: "var(--openidea-editor-font-size, var(--fs-code))",
|
||||
maxWidth: "min(640px, var(--cm-signature-width, 100%))",
|
||||
maxHeight: "min(380px, 65vh)",
|
||||
paddingBlock: "var(--space-0-5)",
|
||||
overflow: "auto",
|
||||
overscrollBehavior: "contain",
|
||||
},
|
||||
".cm-lsp-signature-row": {
|
||||
color: "var(--fg-secondary)",
|
||||
whiteSpace: "pre-wrap",
|
||||
overflowWrap: "anywhere",
|
||||
lineHeight: "1.5",
|
||||
padding: "var(--space-0-5) var(--space-2)",
|
||||
paddingInlineStart: "calc(var(--space-2) + 2ch)",
|
||||
textIndent: "-2ch",
|
||||
padding: "6px 10px",
|
||||
maxWidth: "640px",
|
||||
},
|
||||
".cm-lsp-signature-row": { color: "var(--fg-subtle)", whiteSpace: "pre-wrap", lineHeight: "max(20px, 1.5em)" },
|
||||
".cm-lsp-signature-active": {
|
||||
color: "var(--fg-strong)",
|
||||
backgroundColor: "var(--bg-identifier-under-caret, color-mix(in srgb, var(--accent) 14%, transparent))",
|
||||
margin: "0 -10px",
|
||||
padding: "0 10px",
|
||||
},
|
||||
".cm-lsp-signature-disabled": { opacity: "0.55" },
|
||||
".cm-lsp-signature b": { fontWeight: "var(--fw-code-bold, 700)", color: "var(--fg-strong)" },
|
||||
".cm-lsp-signature-doc": {
|
||||
borderTop: "1px solid var(--border-popup)",
|
||||
marginTop: "var(--space-1)",
|
||||
padding: "var(--space-2)",
|
||||
marginTop: "6px",
|
||||
paddingTop: "6px",
|
||||
maxHeight: "160px",
|
||||
overflow: "auto",
|
||||
},
|
||||
".cm-tooltip:has(> .cm-lsp-hint)": { background: "none", border: "none", boxShadow: "none" },
|
||||
".cm-lsp-hint": {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
.dialog [data-dialog-body] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.body {
|
||||
@@ -8,8 +9,8 @@
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-3);
|
||||
gap: var(--space-3);
|
||||
padding: 14px;
|
||||
font-size: var(--fs-ui);
|
||||
color: var(--fg);
|
||||
}
|
||||
@@ -17,34 +18,54 @@
|
||||
.header {
|
||||
flex: none;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 0.75fr) minmax(0, 1fr) minmax(0, 1.25fr);
|
||||
align-items: end;
|
||||
gap: var(--space-2);
|
||||
grid-template-columns: 150px 1fr 1fr;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.field {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
gap: var(--space-1-5);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.parameters {
|
||||
flex: 1 1 auto;
|
||||
min-height: calc(var(--h-list-row) * 5);
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-control);
|
||||
overflow: hidden;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
flex: none;
|
||||
display: flex;
|
||||
gap: var(--space-1);
|
||||
padding: var(--space-0-5) var(--space-1);
|
||||
padding: 2px 4px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.table {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.head,
|
||||
.row {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr 1fr;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: 0 8px;
|
||||
min-height: var(--h-list-row);
|
||||
}
|
||||
|
||||
.head {
|
||||
color: var(--fg-muted);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
@@ -52,57 +73,6 @@
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
scroll-padding-block-start: var(--h-list-row);
|
||||
}
|
||||
|
||||
.table {
|
||||
width: 100%;
|
||||
table-layout: fixed;
|
||||
border-spacing: 0;
|
||||
}
|
||||
|
||||
.table :is(th, td) {
|
||||
padding: 0 var(--space-2);
|
||||
}
|
||||
|
||||
.table th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
height: var(--h-list-row);
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--bg-dialog, var(--bg-elev));
|
||||
color: var(--fg-muted);
|
||||
text-align: start;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.table th:first-child {
|
||||
width: 42%;
|
||||
}
|
||||
|
||||
.table th:first-child:nth-last-child(3) {
|
||||
width: 36%;
|
||||
}
|
||||
|
||||
.table th:nth-child(3) {
|
||||
width: 28%;
|
||||
}
|
||||
|
||||
.body .code,
|
||||
.preview {
|
||||
font-family: var(--signature-font-family, var(--font-mono));
|
||||
font-size: var(--signature-font-size, var(--fs-code));
|
||||
font-weight: var(--signature-font-weight, var(--fw-code));
|
||||
}
|
||||
|
||||
.body .code {
|
||||
width: 100%;
|
||||
height: max(var(--h-field), calc(var(--signature-font-size, var(--fs-code)) + var(--space-2)));
|
||||
}
|
||||
|
||||
.row .code:focus-visible {
|
||||
box-shadow: inset 0 -1px var(--focus-ring);
|
||||
}
|
||||
|
||||
.row:hover {
|
||||
@@ -114,16 +84,14 @@
|
||||
}
|
||||
|
||||
.preview {
|
||||
height: clamp(56px, 18vh, 128px);
|
||||
margin: 0;
|
||||
padding: var(--space-1-5) var(--space-2);
|
||||
padding: 6px 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-control);
|
||||
overflow: auto;
|
||||
border-radius: 4px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-code);
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
line-height: 1.5;
|
||||
user-select: text;
|
||||
color: var(--fg);
|
||||
background: var(--bg-input);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** IDEA's Change Signature dialog for Java methods (`signature.ts`). */
|
||||
import { useEffect, useId, useLayoutEffect, useRef, useState, type CSSProperties } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { MethodSignature } from "@/bindings";
|
||||
import { Checkbox, Dialog, IconButton, Input, Select, Spinner, T, Toolbar } from "@/ui";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
@@ -34,16 +34,6 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
|
||||
const [delegate, setDelegate] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const previewLabel = useId();
|
||||
const selectedRow = useRef<HTMLTableRowElement>(null);
|
||||
const [codeStyle] = useState(() => {
|
||||
const { fontFamily, fontSize, fontWeight } = getComputedStyle(request.view.contentDOM);
|
||||
return {
|
||||
"--signature-font-family": fontFamily,
|
||||
"--signature-font-size": fontSize,
|
||||
"--signature-font-weight": fontWeight,
|
||||
} as CSSProperties;
|
||||
});
|
||||
|
||||
const signature: MethodSignature = {
|
||||
...info,
|
||||
@@ -55,10 +45,6 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
|
||||
const problem = signatureProblem(signature);
|
||||
const ready = !busy && !problem && signatureChanged(info, signature);
|
||||
const current = Math.min(selected, rows.length - 1);
|
||||
const hasNewParameters = rows.some((row) => row.originalIndex < 0);
|
||||
useLayoutEffect(() => {
|
||||
selectedRow.current?.scrollIntoView({ block: "nearest", inline: "nearest" });
|
||||
}, [current, rows.length]);
|
||||
|
||||
// Closing the dialog cancels a refactoring still being checked: it applies nothing.
|
||||
const running = useRef<AbortController | null>(null);
|
||||
@@ -107,8 +93,7 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
|
||||
title="Change Signature"
|
||||
className={styles.dialog}
|
||||
width={640}
|
||||
minWidth={360}
|
||||
minHeight={360}
|
||||
minHeight={380}
|
||||
maxHeight={640}
|
||||
resizable="both"
|
||||
buttons={[
|
||||
@@ -125,7 +110,7 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<div className={styles.body} style={codeStyle}>
|
||||
<div className={styles.body}>
|
||||
<div className={styles.header}>
|
||||
<label className={styles.field}>
|
||||
<T>Visibility:</T>
|
||||
@@ -138,18 +123,11 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
|
||||
</label>
|
||||
<label className={styles.field}>
|
||||
<T>Return type:</T>
|
||||
<Input className={styles.code} mono value={returnType} onChange={(e) => setReturnType(e.target.value)} />
|
||||
<Input mono value={returnType} onChange={(e) => setReturnType(e.target.value)} />
|
||||
</label>
|
||||
<label className={styles.field}>
|
||||
<T>Name:</T>
|
||||
<Input
|
||||
className={styles.code}
|
||||
mono
|
||||
data-autofocus
|
||||
autoSelect
|
||||
value={methodName}
|
||||
onChange={(e) => setMethodName(e.target.value)}
|
||||
/>
|
||||
<Input mono autoFocus autoSelect value={methodName} onChange={(e) => setMethodName(e.target.value)} />
|
||||
</label>
|
||||
</div>
|
||||
<div className={styles.parameters}>
|
||||
@@ -164,83 +142,59 @@ function ChangeSignatureDialogInner({ request }: { request: SignatureRequest })
|
||||
onClick={() => move(1)}
|
||||
/>
|
||||
</Toolbar>
|
||||
<div className={styles.rows}>
|
||||
<table className={styles.table} aria-label={tx("Parameters")}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">
|
||||
<T>Type</T>
|
||||
</th>
|
||||
<th scope="col">
|
||||
<T>Name</T>
|
||||
</th>
|
||||
{hasNewParameters && (
|
||||
<th scope="col">
|
||||
<T>Default value</T>
|
||||
</th>
|
||||
)}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row, i) => (
|
||||
<tr
|
||||
key={row.key}
|
||||
ref={i === current ? selectedRow : undefined}
|
||||
className={styles.row}
|
||||
aria-selected={i === current}
|
||||
onFocusCapture={() => setSelected(i)}
|
||||
>
|
||||
<td>
|
||||
<Input
|
||||
className={styles.code}
|
||||
mono
|
||||
variant="bare"
|
||||
aria-label={tx("Type")}
|
||||
value={row.type}
|
||||
title={row.type}
|
||||
autoFocus={row.originalIndex < 0 && !row.type}
|
||||
onChange={(e) => update(row.key, { type: e.target.value })}
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<Input
|
||||
className={styles.code}
|
||||
mono
|
||||
variant="bare"
|
||||
aria-label={tx("Name")}
|
||||
value={row.name}
|
||||
title={row.name}
|
||||
onChange={(e) => update(row.key, { name: e.target.value })}
|
||||
/>
|
||||
</td>
|
||||
{hasNewParameters && (
|
||||
<td>
|
||||
{row.originalIndex < 0 && (
|
||||
<Input
|
||||
className={styles.code}
|
||||
mono
|
||||
variant="bare"
|
||||
aria-label={tx("Default value")}
|
||||
value={row.defaultValue}
|
||||
onChange={(e) => update(row.key, { defaultValue: e.target.value })}
|
||||
/>
|
||||
)}
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<div className={styles.table} role="table" aria-label={tx("Parameters")}>
|
||||
<div className={styles.head} role="row">
|
||||
<span role="columnheader">
|
||||
<T>Type</T>
|
||||
</span>
|
||||
<span role="columnheader">
|
||||
<T>Name</T>
|
||||
</span>
|
||||
<span role="columnheader">
|
||||
<T>Default value</T>
|
||||
</span>
|
||||
</div>
|
||||
<div className={styles.rows}>
|
||||
{rows.map((row, i) => (
|
||||
<div
|
||||
key={row.key}
|
||||
className={styles.row}
|
||||
role="row"
|
||||
aria-selected={i === current}
|
||||
onFocusCapture={() => setSelected(i)}
|
||||
>
|
||||
<Input
|
||||
mono
|
||||
variant="bare"
|
||||
aria-label={tx("Type")}
|
||||
value={row.type}
|
||||
autoFocus={row.originalIndex < 0 && !row.type}
|
||||
onChange={(e) => update(row.key, { type: e.target.value })}
|
||||
/>
|
||||
<Input
|
||||
mono
|
||||
variant="bare"
|
||||
aria-label={tx("Name")}
|
||||
value={row.name}
|
||||
onChange={(e) => update(row.key, { name: e.target.value })}
|
||||
/>
|
||||
<Input
|
||||
mono
|
||||
variant="bare"
|
||||
aria-label={tx("Default value")}
|
||||
value={row.originalIndex < 0 ? row.defaultValue : ""}
|
||||
disabled={row.originalIndex >= 0}
|
||||
onChange={(e) => update(row.key, { defaultValue: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Checkbox checked={delegate} onChange={setDelegate} label={<T>Delegate via overloading method</T>} />
|
||||
<div className={styles.field}>
|
||||
<span id={previewLabel}>
|
||||
<T>Signature Preview</T>
|
||||
</span>
|
||||
<pre className={styles.preview} role="region" aria-labelledby={previewLabel} tabIndex={0}>
|
||||
{signatureText(signature)}
|
||||
</pre>
|
||||
<T>Signature Preview</T>
|
||||
<pre className={styles.preview}>{signatureText(signature)}</pre>
|
||||
</div>
|
||||
{(error ?? (signatureChanged(info, signature) ? problem : null)) && (
|
||||
<span className={styles.error} role="alert">
|
||||
|
||||
@@ -16,7 +16,7 @@ const info: MethodSignature = {
|
||||
|
||||
describe("change signature", () => {
|
||||
it("previews the signature like the declaration", () => {
|
||||
expect(signatureText(info)).toBe("public int sum(\n int a,\n int b\n) throws java.io.IOException");
|
||||
expect(signatureText(info)).toBe("public int sum(int a, int b) throws java.io.IOException");
|
||||
expect(signatureText({ ...info, modifier: "", parameters: [], exceptions: [] })).toBe("int sum()");
|
||||
});
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ export const parameterRow = (p: SignatureParameter): ParameterRow => ({ ...p, ke
|
||||
export const newParameter = (): ParameterRow =>
|
||||
parameterRow({ type: "", name: "", defaultValue: "", originalIndex: -1 });
|
||||
|
||||
/** Formats the declaration for the dialog's preview. */
|
||||
/** `public int sum(int a, int b) throws IOException`, as the dialog's preview shows it. */
|
||||
export function signatureText(sig: {
|
||||
modifier: string;
|
||||
returnType: string;
|
||||
@@ -44,9 +44,8 @@ export function signatureText(sig: {
|
||||
parameters: readonly SignatureParameter[];
|
||||
exceptions?: readonly { type: string }[];
|
||||
}): string {
|
||||
const params = sig.parameters.map((p) => `${p.type} ${p.name}`.trim());
|
||||
const args = params.length > 1 ? `\n ${params.join(",\n ")}\n` : (params[0] ?? "");
|
||||
const head = [sig.modifier, sig.returnType, `${sig.methodName}(${args})`].filter(Boolean).join(" ");
|
||||
const params = sig.parameters.map((p) => `${p.type} ${p.name}`.trim()).join(", ");
|
||||
const head = [sig.modifier, sig.returnType, `${sig.methodName}(${params})`].filter(Boolean).join(" ");
|
||||
const throws = sig.exceptions?.length ? ` throws ${sig.exceptions.map((e) => e.type).join(", ")}` : "";
|
||||
return head + throws;
|
||||
}
|
||||
|
||||
@@ -232,10 +232,8 @@
|
||||
.conversationRow[data-measured] {
|
||||
content-visibility: auto;
|
||||
}
|
||||
/* Keep turns distinct and the work within a turn close to its author. Not `* + *`: a
|
||||
universal adjacent-sibling rule makes Chromium restyle whole sibling subtrees on every
|
||||
DOM insertion anywhere in the window, which costs every editor scroll frame. */
|
||||
.stream > :where(:not(:first-child)) {
|
||||
/* Keep turns distinct and the work within a turn close to its author. */
|
||||
.stream > * + * {
|
||||
margin-top: var(--space-4);
|
||||
}
|
||||
.stream > [data-process] + [data-process] {
|
||||
@@ -338,7 +336,7 @@
|
||||
.agentAuthor > .role {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
:where(.conversationRow[data-author]) > :nth-child(2) {
|
||||
.agentAuthor + * {
|
||||
margin-top: calc(var(--space-2) / 2);
|
||||
}
|
||||
.conversationRow > .process,
|
||||
|
||||
@@ -29,7 +29,7 @@ function task(id: string, title: string, cwd: string): AgentTask {
|
||||
}
|
||||
|
||||
/** A turn as agents work: a request, reasoning, a run of tool calls, then a reply with code. */
|
||||
function turn(cwd: string, i: number, title: string): AgentEntry[] {
|
||||
function turn(cwd: string, i: number): AgentEntry[] {
|
||||
const file = (k: number) => `${cwd}/src/orders/Order${(i + k) % 40}.kt`;
|
||||
const tools: AgentEntry[] = Array.from({ length: 10 }, (_, k) => {
|
||||
// Tool titles as agents report them (commands and paths, not UI text).
|
||||
@@ -49,8 +49,7 @@ function turn(cwd: string, i: number, title: string): AgentEntry[] {
|
||||
};
|
||||
});
|
||||
// What a user and an agent wrote (conversation content, not UI text).
|
||||
// Ends with the task's title, so each conversation shown can be told apart.
|
||||
const request = `Turn ${i}: make the order service retry failed payments and cover it with tests (${title})`;
|
||||
const request = `Turn ${i}: make the order service retry failed payments and cover it with tests`;
|
||||
const reasoning = `The payment client throws on timeouts; retrying belongs in the service (turn ${i}).`;
|
||||
return [
|
||||
{
|
||||
@@ -95,14 +94,14 @@ function turn(cwd: string, i: number, title: string): AgentEntry[] {
|
||||
/** Opens `count` tasks of `turns` turns each (14 entries a turn), the last one shown. */
|
||||
export function openSampleConversations(count: number, turns: number) {
|
||||
const cwd = useProject.getState().project?.root ?? "/";
|
||||
const entries = Array.from({ length: turns }, (_, i) => turn(cwd, i)).flat();
|
||||
const s = useAgents.getState();
|
||||
const tasks = new Map(s.tasks);
|
||||
const all = new Map(s.entries);
|
||||
const ids = Array.from({ length: count }, (_, n) => `sample-${n + 1}`);
|
||||
ids.forEach((id, n) => {
|
||||
const title = `Sample task ${n + 1}`;
|
||||
tasks.set(id, task(id, title, cwd));
|
||||
all.set(id, Array.from({ length: turns }, (_, i) => turn(cwd, i, title)).flat());
|
||||
tasks.set(id, task(id, `Sample task ${n + 1}`, cwd));
|
||||
all.set(id, entries);
|
||||
});
|
||||
useAgents.setState({ tasks, entries: all });
|
||||
for (const id of ids) openTask(id);
|
||||
|
||||
@@ -559,7 +559,6 @@ export function Stream({
|
||||
(row.kind === "entry" && (row.entry.type === "user" || row.entry.type === "agent")) || undefined
|
||||
}
|
||||
data-process={row.kind !== "entry" || row.entry.type !== "user" || undefined}
|
||||
data-author={authorHeaders.has(row.index) || undefined}
|
||||
>
|
||||
{authorHeaders.has(row.index) && (
|
||||
<div className={styles.agentAuthor}>
|
||||
|
||||
@@ -199,21 +199,6 @@
|
||||
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,7 +29,6 @@ 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";
|
||||
|
||||
@@ -169,50 +168,40 @@ function ReformatCodeDialog({ targets, onClose }: { targets: readonly ReformatTa
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
>
|
||||
<div className={fieldsetStyles.body}>
|
||||
<div className={styles.reformatSubject}>{subject}</div>
|
||||
<fieldset className={fieldsetStyles.group}>
|
||||
<legend className={fieldsetStyles.legend}>
|
||||
<T>Options</T>
|
||||
</legend>
|
||||
<div className={styles.form}>
|
||||
<div className={styles.hint}>{subject}</div>
|
||||
{targets.some((t) => t.dir) && (
|
||||
<Checkbox
|
||||
checked={options.optimizeImports}
|
||||
onChange={(optimizeImports) => setOptions({ ...options, optimizeImports })}
|
||||
label="Optimize imports"
|
||||
checked={options.recursive}
|
||||
onChange={(recursive) => setOptions({ ...options, recursive })}
|
||||
label="Include subdirectories"
|
||||
/>
|
||||
)}
|
||||
<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.changedTextOnly}
|
||||
onChange={(changedTextOnly) => setOptions({ ...options, changedTextOnly })}
|
||||
label="Only VCS changed text"
|
||||
checked={options.useMask}
|
||||
onChange={(useMask) => setOptions({ ...options, useMask })}
|
||||
label="File mask:"
|
||||
/>
|
||||
{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>
|
||||
<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>
|
||||
<div className={styles.hint}>
|
||||
<T>Files are reformatted by their language's formatter and saved; files without one are skipped.</T>
|
||||
</div>
|
||||
|
||||
+78
-140
@@ -21,20 +21,7 @@ import {
|
||||
} from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { useTx, useTxTemplate } from "@/platform/i18n";
|
||||
import {
|
||||
Checkbox,
|
||||
Dialog,
|
||||
Icon,
|
||||
IconButton,
|
||||
Input,
|
||||
Select,
|
||||
SplitGroup,
|
||||
SplitHandle,
|
||||
SplitPanel,
|
||||
type SelectOption,
|
||||
T,
|
||||
hasIcon,
|
||||
} from "@/ui";
|
||||
import { Button, Checkbox, Dialog, Icon, Input, Select, 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";
|
||||
@@ -129,20 +116,6 @@ 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;
|
||||
@@ -292,19 +265,8 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
>
|
||||
<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}
|
||||
>
|
||||
<div className={styles.layout}>
|
||||
<div className={styles.sidebar}>
|
||||
<Input
|
||||
className={styles.search}
|
||||
value={query}
|
||||
@@ -324,7 +286,6 @@ 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"} />
|
||||
@@ -334,95 +295,82 @@ function NewProjectDialog({ onClose }: { onClose: () => void }) {
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</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)}
|
||||
/>
|
||||
<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
|
||||
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>
|
||||
{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>
|
||||
<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}
|
||||
/>
|
||||
))}
|
||||
</form>
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
{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>
|
||||
</div>
|
||||
))}
|
||||
</form>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -472,7 +420,6 @@ function FieldRow({
|
||||
control = (
|
||||
<Select
|
||||
id={id}
|
||||
className={styles.fieldSelect}
|
||||
value={value}
|
||||
options={kind.options.map((o) => ({ value: o.value, label: o.label }))}
|
||||
onChange={onChange}
|
||||
@@ -491,16 +438,7 @@ function FieldRow({
|
||||
})),
|
||||
];
|
||||
if (value && !options.some((o) => o.value === value)) options.push({ value, label: value, verbatim: true });
|
||||
control = (
|
||||
<Select
|
||||
id={id}
|
||||
className={styles.fieldSelect}
|
||||
value={value}
|
||||
options={options}
|
||||
onChange={onChange}
|
||||
aria-label={tx(field.label)}
|
||||
/>
|
||||
);
|
||||
control = <Select id={id} 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,42 +2,39 @@
|
||||
.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 {
|
||||
background: var(--bg-island);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
border-right: 1px solid var(--border);
|
||||
}
|
||||
.search {
|
||||
flex: none;
|
||||
margin: var(--space-2);
|
||||
margin: 8px;
|
||||
}
|
||||
.list {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: 0 var(--space-1) var(--space-2);
|
||||
padding: 0 4px 8px;
|
||||
}
|
||||
.groupLabel {
|
||||
padding: var(--space-2) var(--space-2) var(--space-1);
|
||||
padding: 8px 8px 4px;
|
||||
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: var(--h-list-row);
|
||||
padding: 0 var(--space-2);
|
||||
height: 26px;
|
||||
padding: 0 8px;
|
||||
border: 0;
|
||||
border-radius: var(--radius-control, 4px);
|
||||
background: transparent;
|
||||
@@ -45,12 +42,6 @@
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
}
|
||||
.entry > span {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.entry:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
@@ -63,50 +54,33 @@
|
||||
outline-offset: -2px;
|
||||
}
|
||||
.form {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
gap: 10px;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
padding: var(--space-4);
|
||||
font-size: var(--fs-ui);
|
||||
overflow-y: auto;
|
||||
padding: 16px;
|
||||
}
|
||||
.description {
|
||||
color: var(--fg-subtle);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: fit-content(38%) minmax(0, 1fr);
|
||||
grid-template-columns: max-content minmax(0, 1fr);
|
||||
align-items: center;
|
||||
gap: var(--space-2) var(--space-3);
|
||||
}
|
||||
.label {
|
||||
color: var(--fg);
|
||||
overflow-wrap: anywhere;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.location {
|
||||
.inline {
|
||||
display: flex;
|
||||
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);
|
||||
gap: var(--space-2);
|
||||
}
|
||||
.location:focus-within {
|
||||
box-shadow:
|
||||
inset 0 0 0 1px var(--focus-ring),
|
||||
0 0 0 1px var(--focus-ring);
|
||||
}
|
||||
.location .locationInput {
|
||||
.inline > :first-child {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding-inline: var(--space-2);
|
||||
}
|
||||
.fieldSelect {
|
||||
max-width: 100%;
|
||||
}
|
||||
.hint,
|
||||
.fieldHint {
|
||||
@@ -138,22 +112,17 @@
|
||||
}
|
||||
.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 {
|
||||
min-height: var(--h-field, 28px);
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
padding: var(--space-1) var(--space-3);
|
||||
height: var(--h-field, 28px);
|
||||
padding: 0 14px;
|
||||
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);
|
||||
@@ -178,18 +147,14 @@
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
min-height: 22px;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
padding: 0 var(--space-1-5) 0 var(--space-2);
|
||||
height: 22px;
|
||||
padding: 0 6px 0 8px;
|
||||
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 {
|
||||
min-height: var(--h-header);
|
||||
height: 32px;
|
||||
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,7 +29,6 @@
|
||||
font-size: var(--fs-small);
|
||||
font-style: italic;
|
||||
color: var(--fg-subtle);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.body {
|
||||
flex: 1;
|
||||
@@ -50,12 +49,17 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
.name {
|
||||
color: var(--fg-strong);
|
||||
color: var(--fg);
|
||||
}
|
||||
.detail {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.muted {
|
||||
flex: none;
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.error {
|
||||
flex: none;
|
||||
|
||||
@@ -106,37 +106,35 @@ function HierarchyToolbar() {
|
||||
const autoscroll = useHierarchyOptions((s) => s.autoscroll);
|
||||
return (
|
||||
<div className={styles.toolbar} role="toolbar" aria-label={tx("Hierarchy actions")}>
|
||||
<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="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} />
|
||||
<IconButton icon="refresh" size="small" iconSize={16} title="Refresh" onClick={refreshHierarchy} />
|
||||
<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>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -185,9 +183,13 @@ export function HierarchyView() {
|
||||
const renderNode = (n: Node, _state: TreeRowState) => {
|
||||
if (n.kind === "root") {
|
||||
return (
|
||||
<span className={styles.row} title={`${root.name}\n${relativePath(projectRoot, root.path)}:${root.line + 1}`}>
|
||||
<span className={styles.row}>
|
||||
<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}>
|
||||
@@ -197,42 +199,35 @@ 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={`${item.name}\n${relativePath(projectRoot, item.path)}:${item.selectionRange.start.line + 1}`}
|
||||
>
|
||||
<span className={styles.row} title={relativePath(projectRoot, item.path)}>
|
||||
<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>
|
||||
)}
|
||||
{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>
|
||||
)}
|
||||
{failed.has(n.id) && (
|
||||
<span className={styles.error}>
|
||||
<T>failed to load</T>
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
@@ -249,7 +244,6 @@ 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) : null),
|
||||
[editability, model, tab.schema],
|
||||
() => (editability.kind === "editable" ? resolveTarget(editability, model, tab.schema, driver) : null),
|
||||
[editability, model, tab.schema, driver],
|
||||
);
|
||||
const detailsId = target ? detailsKey(tab.sourceId, target.schema ?? "", target.table) : null;
|
||||
const details = useDatabase((s) => (detailsId ? s.details[detailsId] : undefined));
|
||||
|
||||
@@ -55,17 +55,7 @@ import {
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { Icon, IconButton, Select, Toolbar, lazyComponent } from "@/ui";
|
||||
import { useProject } from "@/platform/project";
|
||||
import {
|
||||
activeSchema,
|
||||
parseSchemaTreeValue,
|
||||
schemaSwitchable,
|
||||
schemaTreeRows,
|
||||
schemaTreeValue,
|
||||
sourceIcon,
|
||||
sourceLabel,
|
||||
splitTarget,
|
||||
targetOf,
|
||||
} from "./model";
|
||||
import { activeSchema, schemaSwitchable, sourceIcon, sourceLabel, splitTarget, targetOf } from "./model";
|
||||
import { loadSavedCatalog, offerIntrospection } from "./introspection";
|
||||
import { analyze, templateContexts, valuesSlot } from "./sql/analyze";
|
||||
import {
|
||||
@@ -100,6 +90,7 @@ import {
|
||||
setConsoleSchema,
|
||||
setManualCommit,
|
||||
sourceById,
|
||||
targetLabel,
|
||||
useDatabase,
|
||||
} from "./store";
|
||||
import styles from "./Database.module.css";
|
||||
@@ -595,6 +586,7 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
|
||||
const maxRows = useDatabase((s) => s.maxRows);
|
||||
const manual = useDatabase((s) => !!bound && s.manualCommit.has(bound));
|
||||
const pending = useDatabase((s) => !!bound && s.pendingTx.has(bound));
|
||||
const databases = useDatabase((s) => s.databases);
|
||||
const inEditor = useProject((s) => inEditorResults(s.settings));
|
||||
// SQL resolution scopes in the settings can move the console to another data source.
|
||||
useProject((s) => s.settings);
|
||||
@@ -602,6 +594,7 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
|
||||
const driver = sources.find((s) => s.id === boundId)?.driver;
|
||||
const jdbc = driver === "jdbc";
|
||||
const supportsTransactions = driver !== "clickhouse" && !jdbc;
|
||||
const sqlServer = driver === "sqlServer";
|
||||
const switchable = schemaSwitchable(driver);
|
||||
// The console's active schema: its pick, else the connection's default (`completion.defaultSchema`).
|
||||
const pickedSchema = useDatabase((s) => s.consoleSchemas[path]);
|
||||
@@ -609,35 +602,49 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
|
||||
const schemaList = useDatabase((s) => (bound ? s.schemas[bound] : undefined));
|
||||
const schema = activeSchema(pickedSchema, defaultSchema);
|
||||
useEffect(() => {
|
||||
if (boundId && listsDatabases(sourceById(boundId)) && !useDatabase.getState().databases[boundId])
|
||||
if (boundId && (sqlServer || listsDatabases(sourceById(boundId))) && !useDatabase.getState().databases[boundId])
|
||||
void loadDatabases(boundId);
|
||||
}, [boundId]);
|
||||
// Loads the list again after a refresh drops it.
|
||||
const schemasMissing = !schemaList;
|
||||
}, [boundId, sqlServer]);
|
||||
useEffect(() => {
|
||||
if (bound && switchable && schemasMissing) void loadSchemas(bound);
|
||||
}, [bound, switchable, schemasMissing]);
|
||||
if (bound && switchable && !sqlServer && !useDatabase.getState().schemas[bound]) void loadSchemas(bound);
|
||||
}, [bound, switchable, sqlServer]);
|
||||
const schemaOptions = useMemo(() => {
|
||||
if (!switchable) return [];
|
||||
const names = schemaList?.status === "ok" ? schemaList.value : [];
|
||||
const databaseList = boundId ? databases[boundId] : undefined;
|
||||
const names = sqlServer
|
||||
? databaseList?.status === "ok"
|
||||
? databaseList.value.names
|
||||
: []
|
||||
: schemaList?.status === "ok"
|
||||
? schemaList.value
|
||||
: [];
|
||||
const out = names.map((n) => ({ value: n, label: n, icon: "db-schema" }));
|
||||
// The connection's default is offered even before its schema list loads.
|
||||
if (defaultSchema && !names.includes(defaultSchema))
|
||||
out.unshift({ value: defaultSchema, label: defaultSchema, icon: "db-schema" });
|
||||
return out;
|
||||
}, [switchable, schemaList, defaultSchema]);
|
||||
// IDEA's order: pick the data source, then a database and a schema in it.
|
||||
const sourceOptions = useMemo(
|
||||
() =>
|
||||
sources.map((s) => ({
|
||||
value: s.id ?? "",
|
||||
label: s.name ?? "",
|
||||
verbatim: true,
|
||||
detail: sourceLabel(s).slice((s.name ?? "").length + 1),
|
||||
icon: sourceIcon(s),
|
||||
})),
|
||||
[sources],
|
||||
);
|
||||
}, [switchable, schemaList, defaultSchema, sqlServer, boundId, databases]);
|
||||
const targets = useMemo(() => {
|
||||
const out: Array<{ value: string; label: string; detail?: string; icon: string }> = [];
|
||||
for (const s of sources) {
|
||||
const id = s.id ?? "";
|
||||
const dbs = databases[id];
|
||||
const host = sourceLabel(s).slice((s.name ?? "").length + 1);
|
||||
if (listsDatabases(s) && dbs?.status === "ok") {
|
||||
for (const name of dbs.value.names)
|
||||
out.push({
|
||||
value: targetOf(id, name, dbs.value.current),
|
||||
label: `${s.name ?? ""}: ${name}`,
|
||||
detail: host,
|
||||
icon: sourceIcon(s),
|
||||
});
|
||||
} else out.push({ value: id, label: s.name ?? "", detail: host, icon: sourceIcon(s) });
|
||||
}
|
||||
// A console bound to a database whose list is not loaded yet still shows it.
|
||||
if (bound && !out.some((o) => o.value === bound))
|
||||
out.push({ value: bound, label: targetLabel(bound), icon: "database" });
|
||||
return out;
|
||||
}, [sources, databases, bound]);
|
||||
useEffect(() => {
|
||||
if (!loaded) void loadSources();
|
||||
}, [loaded]);
|
||||
@@ -724,28 +731,23 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label="Data source"
|
||||
value={boundId}
|
||||
value={bound ?? null}
|
||||
placeholder={sources.length ? "<data source>" : "None configured"}
|
||||
options={sourceOptions}
|
||||
searchable
|
||||
onChange={(id) => id !== boundId && bindConsole(path, id)}
|
||||
options={targets}
|
||||
onChange={(id) => bindConsole(path, id)}
|
||||
disabled={!sources.length}
|
||||
/>
|
||||
{bound && boundId && switchable && listsDatabases(sourceById(boundId)) ? (
|
||||
<DatabaseSchemaSwitcher path={path} bound={bound} sourceId={boundId} schema={schema} />
|
||||
) : (
|
||||
switchable && (
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label="Schema"
|
||||
value={schema || null}
|
||||
placeholder="<schema>"
|
||||
options={schemaOptions}
|
||||
searchable
|
||||
onChange={(v) => setConsoleSchema(path, v)}
|
||||
disabled={!bound}
|
||||
/>
|
||||
)
|
||||
{switchable && (
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label={sqlServer ? "Database" : "Schema"}
|
||||
value={schema || null}
|
||||
placeholder="<schema>"
|
||||
options={schemaOptions}
|
||||
searchable={schemaOptions.length > 10}
|
||||
onChange={(v) => setConsoleSchema(path, v)}
|
||||
disabled={!bound}
|
||||
/>
|
||||
)}
|
||||
{driver === "sqlite" && (
|
||||
<span className={styles.consoleSchema} title={tx("Schema")}>
|
||||
@@ -757,85 +759,6 @@ function ConsoleBar({ path, view }: { path: string; view: EditorView }) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The `database.schema` switcher of a data source that shows several databases (IDEA's): a tree of
|
||||
* its databases, expanding to their schemas. Choosing a schema in another database moves the console there.
|
||||
*/
|
||||
function DatabaseSchemaSwitcher({
|
||||
path,
|
||||
bound,
|
||||
sourceId,
|
||||
schema,
|
||||
}: {
|
||||
path: string;
|
||||
bound: string;
|
||||
sourceId: string;
|
||||
schema: string;
|
||||
}) {
|
||||
const listed = useDatabase((s) => s.databases[sourceId]);
|
||||
const schemas = useDatabase((s) => s.schemas);
|
||||
const read = useDatabase((s) => s.catalogs[sourceId]?.databases);
|
||||
const current = listed?.status === "ok" ? listed.value.current : null;
|
||||
const database = splitTarget(bound).database ?? current;
|
||||
// The console's database starts expanded, again whenever the console moves to another one.
|
||||
const [opened, setOpened] = useState<{ at: string | null; open: ReadonlySet<string> } | null>(null);
|
||||
const expanded = useMemo(
|
||||
() => (opened && opened.at === database ? opened.open : new Set(database ? [database] : [])),
|
||||
[opened, database],
|
||||
);
|
||||
const targetFor = (name: string) => (name === database ? bound : targetOf(sourceId, name, current));
|
||||
// Schemas of expanded databases that are not read yet, or were dropped by a refresh.
|
||||
const missing = [...expanded]
|
||||
.filter((name) => !read?.[name] && !schemas[targetFor(name)])
|
||||
.map(targetFor)
|
||||
.join("\n");
|
||||
useEffect(() => {
|
||||
for (const target of missing ? missing.split("\n") : []) void loadSchemas(target);
|
||||
}, [missing]);
|
||||
const rows = useMemo(() => {
|
||||
const names = listed?.status === "ok" ? [...listed.value.names] : [];
|
||||
// The console's database is offered even before the list loads.
|
||||
if (database && !names.includes(database)) names.unshift(database);
|
||||
return schemaTreeRows(names, expanded, (name) => {
|
||||
const target = name === database ? bound : targetOf(sourceId, name, current);
|
||||
const list = schemas[target];
|
||||
if (list?.status === "ok") return list.value;
|
||||
if (read?.[name]) return read[name].map((s) => s.name);
|
||||
return list?.status === "error" ? { error: list.message } : undefined;
|
||||
});
|
||||
}, [listed, database, expanded, schemas, read, bound, sourceId, current]);
|
||||
const value = database && schema ? schemaTreeValue(database, schema) : null;
|
||||
return (
|
||||
<Select
|
||||
variant="ghost"
|
||||
aria-label="Database and schema"
|
||||
value={value}
|
||||
placeholder="<schema>"
|
||||
options={rows}
|
||||
searchable
|
||||
renderValue={() => (database ? (schema ? `${database}.${schema}` : database) : tx("<schema>"))}
|
||||
keepOpen={(v) => parseSchemaTreeValue(v).schema === null}
|
||||
onChange={(v) => {
|
||||
const pick = parseSchemaTreeValue(v);
|
||||
if (pick.schema === null) {
|
||||
const next = new Set(expanded);
|
||||
if (!next.delete(pick.database)) {
|
||||
next.add(pick.database);
|
||||
// Expanding again retries a database whose schemas could not be read.
|
||||
const target = targetFor(pick.database);
|
||||
if (useDatabase.getState().schemas[target]?.status === "error") void loadSchemas(target);
|
||||
}
|
||||
setOpened({ at: database, open: next });
|
||||
return;
|
||||
}
|
||||
const target = targetFor(pick.database);
|
||||
if (target !== bound) bindConsole(path, target);
|
||||
setConsoleSchema(path, pick.schema);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const quoted = (name: string) => `"${name.replace(/"/g, '""')}"`;
|
||||
|
||||
/**
|
||||
|
||||
@@ -484,73 +484,3 @@ export function parseSourceUrl(raw: string): { source: Partial<DataSource>; pass
|
||||
if (properties.length) source.properties = properties;
|
||||
return { source, password };
|
||||
}
|
||||
|
||||
/** A row of the console's database › schema switcher. */
|
||||
export interface SchemaTreeRow {
|
||||
value: string;
|
||||
label: string;
|
||||
verbatim?: boolean;
|
||||
icon?: string;
|
||||
disabled?: boolean;
|
||||
/** Searching a database's name keeps its schemas visible. */
|
||||
keywords?: string;
|
||||
tree: { depth: number; expanded?: boolean };
|
||||
}
|
||||
|
||||
const TREE_SEP = "\u0000";
|
||||
|
||||
/** The switcher value of database `database`, or of its schema `schema`. */
|
||||
export function schemaTreeValue(database: string, schema?: string): string {
|
||||
return schema === undefined ? `d${TREE_SEP}${database}` : `s${TREE_SEP}${database}${TREE_SEP}${schema}`;
|
||||
}
|
||||
|
||||
/** The database (and schema, for a schema row) a switcher value names. */
|
||||
export function parseSchemaTreeValue(value: string): { database: string; schema: string | null } {
|
||||
const [kind, database = "", schema = ""] = value.split(TREE_SEP);
|
||||
return { database, schema: kind === "s" ? schema : null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Rows of the switcher (IDEA's `database.schema` popup): every database, each expanded one followed
|
||||
* by its schemas, a "Loading…" row while `schemasOf` has none for it yet, or the error reading them.
|
||||
*/
|
||||
export function schemaTreeRows(
|
||||
databases: readonly string[],
|
||||
expanded: ReadonlySet<string>,
|
||||
schemasOf: (database: string) => readonly string[] | { error: string } | undefined,
|
||||
): SchemaTreeRow[] {
|
||||
const out: SchemaTreeRow[] = [];
|
||||
for (const database of databases) {
|
||||
const open = expanded.has(database);
|
||||
out.push({
|
||||
value: schemaTreeValue(database),
|
||||
label: database,
|
||||
verbatim: true,
|
||||
icon: "database",
|
||||
tree: { depth: 0, expanded: open },
|
||||
});
|
||||
if (!open) continue;
|
||||
const schemas = schemasOf(database);
|
||||
if (!schemas || "error" in schemas) {
|
||||
out.push({
|
||||
value: `l${TREE_SEP}${database}`,
|
||||
label: schemas ? schemas.error : "Loading…",
|
||||
verbatim: !!schemas,
|
||||
disabled: true,
|
||||
keywords: database,
|
||||
tree: { depth: 1 },
|
||||
});
|
||||
continue;
|
||||
}
|
||||
for (const schema of schemas)
|
||||
out.push({
|
||||
value: schemaTreeValue(database, schema),
|
||||
label: schema,
|
||||
verbatim: true,
|
||||
icon: "db-schema",
|
||||
keywords: database,
|
||||
tree: { depth: 1 },
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -205,10 +205,12 @@ describe("resolveTarget", () => {
|
||||
expect(resolveTarget(e, model)).toEqual({ schema: "nope", table: "missing", alias: null });
|
||||
});
|
||||
|
||||
it("refuses an unresolved default and keeps an explicit schema over the console's", () => {
|
||||
it("refuses unresolved defaults and SQL Server database/schema ambiguity", () => {
|
||||
expect(resolveTarget(editable("SELECT * FROM users"), model, "")).toBeNull();
|
||||
expect(resolveTarget(editable("SELECT * FROM users"), model, "sales")?.schema).toBe("sales");
|
||||
expect(resolveTarget(editable("SELECT * FROM dbo.users"), model, "sales")).toEqual({
|
||||
expect(resolveTarget(editable("SELECT * FROM users"), model, "public", "sqlServer")).toBeNull();
|
||||
const explicit = editable("SELECT * FROM dbo.users");
|
||||
expect(resolveTarget(explicit, model, "other_database", "sqlServer")).toBeNull();
|
||||
expect(resolveTarget(explicit, model, "public", "sqlServer")).toEqual({
|
||||
schema: "dbo",
|
||||
table: "users",
|
||||
alias: null,
|
||||
|
||||
@@ -227,7 +227,10 @@ export function resolveTarget(
|
||||
e: Extract<ResultEditability, { kind: "editable" }>,
|
||||
model: DbCompletion | null,
|
||||
schema?: string,
|
||||
driver: DbDriver = "postgres",
|
||||
): { schema: string | null; table: string; alias: string | null } | null {
|
||||
// SQL Server switches databases, but table details and edits take a table schema.
|
||||
if (driver === "sqlServer" && (e.schema === null || (schema && schema !== model?.defaultSchema))) return null;
|
||||
if (e.schema === null && schema === "") return null;
|
||||
return { schema: e.schema ?? (schema || model?.defaultSchema || null), table: e.table, alias: e.alias };
|
||||
}
|
||||
|
||||
@@ -485,11 +485,15 @@ describe("read-only results with a reason", () => {
|
||||
expect(backend.applyEdits).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("resolves an unqualified SQL Server table in the console's schema", async () => {
|
||||
it("keeps an unresolved SQL Server table schema read-only", async () => {
|
||||
backend.driver = "sqlServer";
|
||||
show("SELECT * FROM users", [{ name: "id" }, { name: "name" }], [["1", "Ann"]]);
|
||||
await act(async () => render(<ResultsView />));
|
||||
expect(backend.details).toHaveBeenCalledWith("pg", "public", "users");
|
||||
expect(await screen.findByRole("note")).toHaveTextContent(
|
||||
"Read-only: the table schema could not be identified in the result database.",
|
||||
);
|
||||
expect(screen.queryByRole("button", { name: "Submit" })).toBeNull();
|
||||
expect(backend.details).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["postgres", "sqlServer"] as const)("matches case-sensitive key columns exactly for %s", async (driver) => {
|
||||
|
||||
Loaded 100 of 185 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user