Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-aiтаCursor 57cf4c9967 fix(agents): align session composer and asset pills with Islands style
Co-authored-by: Cursor <[email protected]>
2026-11-25 17:44:41 +08:00
31 змінених файлів з 62 додано та 430 видалено

No files matched your search

+1 -2
Переглянути файл
@@ -23,7 +23,6 @@ on:
- "Cargo.lock"
- "src/features/run/**"
- "src/features/debugger/**"
- "src/features/build/**"
- "src/features/build-tools/**"
- "src/platform/**"
- "src/workbench/**"
@@ -106,7 +105,7 @@ jobs:
# ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
# The workflow's paths, less those handled per language below.
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
+13 -24
Переглянути файл
@@ -95,8 +95,6 @@ const DEPENDENCY_TREE_JAR: &str =
/// The goals that read the effective POM into `effective` and the verbose dependency trees;
/// `repo` is the local repository the build resolves from. Both goals name their plugin by
/// coordinates: offline, a prefix resolves only from group metadata the repository may lack.
/// Offline without a cached 3.x `maven-help-plugin`, `effective-pom` is skipped so `mvn -o`
/// still resolves the dependency tree instead of failing to download the help plugin.
fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec<String> {
let pinned = !offline || repo.is_some_and(|repo| repo.join(DEPENDENCY_TREE_JAR).is_file());
let tree = if pinned {
@@ -107,16 +105,12 @@ fn maven_sync_goals(effective: &Path, offline: bool, repo: Option<&Path>) -> Vec
|v| format!("org.apache.maven.plugins:maven-dependency-plugin:{v}:tree"),
)
};
let has_help =
!offline || repo.is_some_and(|repo| maven::newest_local_plugin(repo, "maven-help-plugin", 3).is_some());
let mut goals = Vec::with_capacity(4);
if has_help {
goals.push(maven::plugin_goal("help:effective-pom", repo));
goals.push(format!("-Doutput={}", effective.to_string_lossy()));
}
goals.push(tree);
goals.push("-Dverbose".into());
goals
vec![
maven::plugin_goal("help:effective-pom", repo),
format!("-Doutput={}", effective.to_string_lossy()),
tree,
"-Dverbose".into(),
]
}
/// The settings' Maven options for the sync runs: the thread count (`-T`, also
@@ -953,24 +947,19 @@ mod tests {
let help = "org.apache.maven.plugins:maven-help-plugin:3.5.1:effective-pom";
let online = maven_sync_goals(Path::new("e.xml"), false, Some(tmp.path()));
assert_eq!(online, [help, "-Doutput=e.xml", DEPENDENCY_TREE, "-Dverbose"]);
// Offline with neither plugin cached: `effective-pom` is skipped so `mvn -o` does not fail
// on an uncached `maven-help-plugin`, and the tree falls back to the project's own version.
// Offline with neither plugin cached: the tree falls back to the project's own version.
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
assert_eq!(offline, ["dependency:tree", "-Dverbose"]);
// #5757 / #5844: offline, plugins in the local repository are named by their coordinates,
// since the prefix needs group metadata a repository filled from a private mirror may lack;
// a repository with `maven-dependency-plugin` but no 3.x `maven-help-plugin` runs only the tree.
for (artifact, version) in [("maven-help-plugin", "2.2"), ("maven-dependency-plugin", "3.6.1")] {
assert_eq!(offline, [help, "-Doutput=e.xml", "dependency:tree", "-Dverbose"]);
// #5757: offline, plugins in the local repository are named by their coordinates, since
// the prefix needs group metadata a repository filled from a private mirror may lack.
for (artifact, version) in
[("maven-help-plugin", "3.4.0"), ("maven-help-plugin", "2.2"), ("maven-dependency-plugin", "3.6.1")]
{
let jar =
tmp.path().join(format!("org/apache/maven/plugins/{artifact}/{version}/{artifact}-{version}.jar"));
std::fs::create_dir_all(jar.parent().unwrap()).unwrap();
std::fs::write(&jar, "").unwrap();
}
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
assert_eq!(offline, ["org.apache.maven.plugins:maven-dependency-plugin:3.6.1:tree", "-Dverbose"]);
let help_jar = tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.4.0/maven-help-plugin-3.4.0.jar");
std::fs::create_dir_all(help_jar.parent().unwrap()).unwrap();
std::fs::write(&help_jar, "").unwrap();
// A version folder without its jar (only the POM was fetched) doesn't count.
std::fs::create_dir_all(tmp.path().join("org/apache/maven/plugins/maven-help-plugin/3.10.0")).unwrap();
let offline = maven_sync_goals(Path::new("e.xml"), true, Some(tmp.path()));
+1 -1
Переглянути файл
@@ -213,7 +213,7 @@ impl FlutterDaemon {
Self(Arc::new(Shared { root, sink, executable, state: Mutex::default() }))
}
#[cfg(all(test, unix))]
#[cfg(test)]
fn with_executable(root: PathBuf, sink: SharedSink, executable: Option<PathBuf>) -> Self {
Self::new(root, sink, Box::new(move || executable.clone()))
}
+1 -1
Переглянути файл
@@ -146,7 +146,7 @@ impl ToolServer {
self.0.changed.notify_all();
}
#[cfg(all(test, unix))]
#[cfg(test)]
pub(crate) fn is_stopped(&self) -> bool {
matches!(self.0.state.lock().status, Status::Stopped)
}
+6 -20
Переглянути файл
@@ -391,10 +391,8 @@ async fn start_inner(
if config.command.is_empty() {
return Err(IdeError::invalid("run configuration has no command"));
}
// A JVM on a run target gets no plugin agents; a local one gets them once its JDK is resolved.
if config.extras.target.as_deref().is_some_and(|t| !t.is_empty()) {
add_java_agents(&mut config, &on_output, None);
}
let on_target = config.extras.target.as_deref().is_some_and(|t| !t.is_empty());
add_java_agents(&mut config, &on_output, !on_target);
// Settings › Run Targets: over SSH, or in a container.
if config.kind == "tomcat" && config.extras.target.as_deref().is_some_and(|t| !t.is_empty()) {
return Err(IdeError::invalid("Tomcat Local requires the local machine"));
@@ -485,8 +483,6 @@ async fn start_inner(
);
ide_sdk::go::apply_to_run(&mut config, &settings.languages.go.build_tags);
}
let run_dir = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
add_java_agents(&mut config, &on_output, Some(&run_dir));
if config.command == ide_sdk::godot::COMMAND {
return Err(IdeError::unavailable(ide_sdk::godot::NOT_FOUND));
}
@@ -559,24 +555,14 @@ async fn start_inner(
/// Plugins' Java agents (`[[contributes.javaAgents]]`, granted `java.agent`) for the JVM of an
/// Application, Spring Boot or JAR Application configuration started on this machine. A JVM on a
/// run target gets none; the console says so, and why an approved agent was left out.
fn add_java_agents(config: &mut RunConfig, on_output: &Emit<OutputChunk>, run_dir: Option<&Path>) {
fn add_java_agents(config: &mut RunConfig, on_output: &Emit<OutputChunk>, local: bool) {
if !ide_run::java_agent::applies(&config.kind) {
return;
}
// The JVM the launch starts: a bare `java` (what generated configurations name) is looked
// up the way the process start finds it, so the `jdk` filter of `vmOptions` sees that JDK.
let java = run_dir.and_then(|dir| {
let search = ide_run::wrap::search_path_in(config, dir);
let home = config
.env
.get("JAVA_HOME")
.map(std::path::PathBuf::from)
.or_else(|| std::env::var_os("JAVA_HOME").map(std::path::PathBuf::from));
ide_run::java_agent::launched_java(&config.command, &search, home.as_deref())
});
let agents = ide_run::java_agent::current_for(java.as_deref());
let java = std::path::Path::new(&config.command);
let agents = ide_run::java_agent::current_for(Some(java));
let say = |text: &str| on_output(OutputChunk::System { text: format!("{text}\n") });
if run_dir.is_none() {
if !local {
if !agents.options.is_empty() {
say(
"Plugin Java agents were not added: they load only into JVMs started on this machine, not on a run target.",
+1 -1
Переглянути файл
@@ -320,7 +320,7 @@ mod tests {
})
.unwrap();
assert_eq!(json, "{\"threadDump\":{}}");
let prefix = format!("Thread.dump_to_file -format=json \"{}", dir.join("threads-42-").display());
let prefix = format!("Thread.dump_to_file -format=json \"{}/threads-42-", dir.display());
assert!(sent.starts_with(&prefix) && sent.ends_with(".json\""), "{sent}");
assert!(is_empty(&dir));
}
-57
Переглянути файл
@@ -123,27 +123,6 @@ fn is_jetbrains_jdk(java: &Path) -> bool {
release_field(java, "IMPLEMENTOR").is_some_and(|v| v.to_ascii_lowercase().contains("jetbrains"))
}
/// The JVM a configuration whose command is `command` starts, for the JDK filter. A path is
/// itself. A bare `java` is the first one on `search`, as the launch finds it; when that is
/// no JDK's own launcher (macOS's `/usr/bin/java` stub, which runs `JAVA_HOME`'s), it is
/// `java_home`'s. `None` when neither is found.
pub fn launched_java(command: &str, search: &std::ffi::OsStr, java_home: Option<&Path>) -> Option<PathBuf> {
let path = Path::new(command);
if path.components().count() > 1 {
return Some(path.to_path_buf());
}
let windows = cfg!(windows);
let found =
ide_core::process::find_executable_in(command, search, windows, std::env::var("PATHEXT").ok().as_deref());
if let Some(java) = &found
&& release_field(java, "JAVA_VERSION").is_some()
{
return found;
}
let java = java_home.map(|home| home.join("bin").join(if windows { "java.exe" } else { "java" }));
java.filter(|java| java.is_file()).or(found)
}
/// `KEY="value"` from the JDK `release` file next to `bin/java` (or JDK 8's `jre/bin/java`).
fn release_field(java: &Path, key: &str) -> Option<String> {
let java = std::fs::canonicalize(java).unwrap_or_else(|_| java.to_path_buf());
@@ -247,42 +226,6 @@ fn split_text(text: &str) -> Vec<String> {
mod tests {
use super::*;
/// A JDK home with `bin/java` and a `release` file naming `implementor`.
#[cfg(unix)]
fn jdk(root: &Path, name: &str, implementor: &str) -> PathBuf {
let home = root.join(name);
std::fs::create_dir_all(home.join("bin")).unwrap();
std::fs::write(home.join("bin/java"), "#!/bin/sh\n").unwrap();
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(home.join("bin/java"), std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::write(home.join("release"), format!("JAVA_VERSION=\"21\"\nIMPLEMENTOR=\"{implementor}\"\n")).unwrap();
home
}
#[cfg(unix)]
#[test]
fn a_bare_java_is_the_one_the_launch_finds() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let jbr = jdk(dir.path(), "jbr", "JetBrains s.r.o.");
let openjdk = jdk(dir.path(), "openjdk", "Eclipse Adoptium");
// A JDK's own launcher on the search path is what runs, whatever JAVA_HOME says.
let search = std::env::join_paths([jbr.join("bin")]).unwrap();
let java = launched_java("java", &search, Some(&openjdk)).unwrap();
assert!(jdk_allows(Some(&java), Some("jetbrains")));
// A stub outside any JDK (macOS /usr/bin/java) runs JAVA_HOME's.
let stub = dir.path().join("usr/bin");
std::fs::create_dir_all(&stub).unwrap();
std::fs::write(stub.join("java"), "#!/bin/sh\n").unwrap();
std::fs::set_permissions(stub.join("java"), std::fs::Permissions::from_mode(0o755)).unwrap();
let search = std::env::join_paths([stub]).unwrap();
let java = launched_java("java", &search, Some(&jbr)).unwrap();
assert!(jdk_allows(Some(&java), Some("jetbrains")));
assert!(!jdk_allows(launched_java("java", &search, Some(&openjdk)).as_deref(), Some("jetbrains")));
// A path is itself.
assert_eq!(launched_java("/opt/jdk/bin/java", &search, Some(&jbr)), Some(PathBuf::from("/opt/jdk/bin/java")));
}
fn strings(a: &[&str]) -> Vec<String> {
a.iter().map(|s| (*s).to_owned()).collect()
}
+10 -10
Переглянути файл
@@ -313,8 +313,8 @@ for (const surface of ["new", "task"] as const) {
const settings = page.getByRole("button", { name: /^Model settings:/ });
await settings.click();
await expect(page.getByRole("button", { name: "Back to models" })).toHaveCount(0);
await page.getByRole("option", { name: "Thorough" }).click();
await page.getByRole("option", { name: "1M" }).click();
await page.getByRole("radio", { name: "Thorough" }).click();
await page.getByRole("radio", { name: "1M" }).click();
await expect(settings).toHaveText("Thorough · 1M");
await page.keyboard.press("Escape");
await expect(box(page)).toHaveText("Review the project structure");
@@ -418,7 +418,7 @@ test("Settings and effort popup exclude the agent shortcut", async ({ workbench:
await expect(search).toHaveValue("keymap");
await settings.getByRole("button", { name: "Cancel", exact: true }).click();
await effortLabel(page).click();
const popup = page.getByRole("listbox", { name: "Effort Level", exact: true });
const popup = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await expect(popup).toBeVisible();
await page.keyboard.press("Alt+t");
expect(await ipcCalls(page, "agent_set_config")).toEqual([]);
@@ -642,10 +642,10 @@ test("New Task discovers uncached model effort before the first prompt", async (
await page.evaluate(() => document.dispatchEvent(new Event("test:model-settings-ready")));
await expectEffort(page, "Quick");
await effortLabel(page).click();
const efforts = page.getByRole("listbox", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("option", { name: "Quick", exact: true })).toBeVisible();
await expect(efforts.getByRole("option", { name: "Thorough", exact: true })).toBeVisible();
await expect(efforts.getByRole("option", { name: "Gentle", exact: true })).toHaveCount(0);
const efforts = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("radio", { name: "Quick", exact: true })).toBeVisible();
await expect(efforts.getByRole("radio", { name: "Thorough", exact: true })).toBeVisible();
await expect(efforts.getByRole("radio", { name: "Gentle", exact: true })).toHaveCount(0);
await page.keyboard.press("Escape");
await expect(box(page)).toHaveText("Keep this first task unsent");
await expectNoSubmission(page);
@@ -675,9 +675,9 @@ test("an existing chat can choose effort for a refreshed model before sending",
await expect(modelButton(page)).toHaveAttribute("title", /^Model: Swift\b/);
await expectEffort(page, "Quick");
await effortLabel(page).click();
const efforts = page.getByRole("listbox", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("option", { name: "Gentle", exact: true })).toHaveCount(0);
await efforts.getByRole("option", { name: "Thorough", exact: true }).click();
const efforts = page.getByRole("radiogroup", { name: "Effort Level", exact: true });
await expect(efforts.getByRole("radio", { name: "Gentle", exact: true })).toHaveCount(0);
await efforts.getByRole("radio", { name: "Thorough", exact: true }).click();
await page.keyboard.press("Escape");
await expectEffort(page, "Thorough");
await expect(send).toBeEnabled();
+7 -6
Переглянути файл
@@ -413,7 +413,8 @@ test("keeps chat history readable and selections free of timestamps and status l
expect(selected).not.toMatch(/AM|PM|5s|Reasoning|Requesting task context/);
await page.keyboard.press("ControlOrMeta+c");
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(selected);
// The latest turn stays open: its reasoning shows as its own collapsed row.
// The finished turn's reasoning is folded with its work.
await stream.locator("[class*='_turnFold_'] > summary").click();
await stream.locator("[class*='_thought_'] > summary").click();
await expect(stream.locator("[class*='_thoughtPreview_']")).toHaveText("Requesting task context");
await expect(stream.locator("[class*='_thoughtBody_'] strong")).toHaveText("Requesting task context");
@@ -794,7 +795,8 @@ test("Find in Conversation skips user-select:none summaries and closed <details>
}, TASK);
const stream = page.locator("[class*='_stream_']:visible");
// A command is its own row, outside the reasoning's run.
const runSummary = stream.locator("details[class*='_processRun_'] > summary");
await runSummary.click();
await expect(stream.getByText("stop_bash")).toBeVisible();
await stream.focus();
@@ -892,14 +894,13 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less
entries: new Map([
[
task.id,
// Reasoning and read-only calls group into one run; commands and edits would be rows of their own.
[
{ type: "thought", text: "**Checking CI Status**\n\nInspecting workflow runs." },
{
type: "tool",
id: "t1",
title: "gh pr checks 3631 --repo l0ng-ai/openidea",
kind: "fetch",
kind: "execute",
status: "completed",
locations: [],
output: "All checks pending",
@@ -910,7 +911,7 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less
type: "tool",
id: "t2",
title: "read_bash",
kind: "read",
kind: "other",
status: "completed",
locations: [],
output: "E2E pass",
@@ -920,7 +921,7 @@ test("indents process-run thoughts and tool calls clearly and aligns output-less
type: "tool",
id: "t3",
title: "read_bash",
kind: "read",
kind: "other",
status: "running",
locations: [],
output: "",
+9 -14
Переглянути файл
@@ -40,17 +40,13 @@ const entries: AgentEntry[] = Array.from({ length: 80 }, (_, turn): AgentEntry[]
},
]).flat();
/** Opens the 80-turn chat; `foldTurns` folds each earlier turn's work into one row. */
async function openHistory(page: Page, foldTurns = false) {
async function openHistory(page: Page) {
await page.goto("/");
await page.getByRole("tree", { name: "Project" }).waitFor();
await page.evaluate(
async ({ task, entries, foldTurns }) => {
async ({ task, entries }) => {
const path = "/src/features/agents/store.ts";
const projectPath = "/src/platform/project.ts";
const store = await import(path);
const { useProject } = await import(projectPath);
useProject.setState({ settings: { agents: { foldTurns } } });
store.useAgents.setState({
loaded: true,
error: null,
@@ -62,12 +58,10 @@ async function openHistory(page: Page, foldTurns = false) {
});
store.openTaskInEditorLocation(task.id);
},
{ task, entries, foldTurns },
{ task, entries },
);
const stream = page.locator("[class*='_stream_']:visible");
// A turn shows its request, the read and the reasoning runs, the command, the edit and the reply;
// folded, its work is one row. The latest turn stays open.
await expect(stream.locator(":scope > *")).toHaveCount(foldTurns ? 79 * 3 + 6 : 80 * 6);
await expect(stream.locator(":scope > *")).toHaveCount(80 * 3);
await page.evaluate(() => document.fonts.ready);
return stream;
}
@@ -91,7 +85,7 @@ for (const placement of ["editor", "toolWindow"] as const) {
);
// The working indicator ends the conversation, after its rows; the turn ends with a reply.
await expect(stream.getByRole("status").getByText("Writing…", { exact: true })).toBeVisible();
await expect(stream.locator(":scope > *")).toHaveCount(80 * 6 + 1);
await expect(stream.locator(":scope > *")).toHaveCount(80 * 3 + 1);
await expect.poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(2);
const timer = await page.evaluate(async (id) => {
const path = "/src/features/agents/store.ts";
@@ -192,7 +186,7 @@ for (const selected of [false, true]) {
}
test("opens a folded turn with the keyboard and jumps back to the latest reply", async ({ page }) => {
const stream = await openHistory(page, true);
const stream = await openHistory(page);
await stream.evaluate((el) => {
el.scrollTop = 0;
});
@@ -203,8 +197,9 @@ test("opens a folded turn with the keyboard and jumps back to the latest reply",
await summary.focus();
await page.keyboard.press("Enter");
await expect(fold).toHaveAttribute("open", "");
// A folded turn lists its work without nesting runs.
await expect(fold.locator("[class*='_processRun_']")).toHaveCount(0);
const run = fold.locator("[class*='_processRun_']").first();
await expect(run).toBeVisible();
await run.locator(":scope > summary").click();
await expect(fold.getByText("read src/module-0.ts", { exact: true })).toBeVisible();
await summary.focus();
await page.keyboard.press("Space");
-9
Переглянути файл
@@ -132,14 +132,6 @@ function useOffscreenRows(
mark();
const rows = new MutationObserver(mark);
rows.observe(el, { childList: true });
// Earlier rows load in front of the first one shown, which then loses its author header while
// it may be off-screen: lay it out again, or it keeps the height it had with the header.
const authors = new MutationObserver((records) => {
for (const { target } of records)
if (target.parentNode === el) (target as Element).removeAttribute("data-measured");
mark();
});
authors.observe(el, { subtree: true, attributes: true, attributeFilter: ["data-author"] });
const resize = new ResizeObserver(() => {
window.clearTimeout(timer);
timer = window.setTimeout(() => {
@@ -152,7 +144,6 @@ function useOffscreenRows(
cancelAnimationFrame(frame);
window.clearTimeout(timer);
rows.disconnect();
authors.disconnect();
resize.disconnect();
};
}, [ref, visible, enabled, fitWindowWidth, fontZoom]);
-44
Переглянути файл
@@ -1,44 +0,0 @@
import { describe, expect, it } from "vitest";
import type { RootFolder } from "@/platform/languageSettings";
import { javaPackageAt, pastedJavaClass, withJavaPackage } from "./javaPaste";
describe("Java code pasted into the Project view", () => {
it("is named after its first public top-level type, else its first", () => {
const text = "package a;\n/** Doc */\n@Deprecated class Helper {}\npublic final class Main<T> { class Inner {} }\n";
expect(pastedJavaClass(text)).toBe("Main");
expect(pastedJavaClass("record Point(int x, int y) {}\nenum Color { RED }")).toBe("Point");
expect(pastedJavaClass("public @interface Marker {}")).toBe("Marker");
expect(pastedJavaClass("interface Shape { double area(); }")).toBe("Shape");
});
it("is not code without a type: a statement, prose, a class only named in a comment", () => {
expect(pastedJavaClass("int x = 1;")).toBeNull();
expect(pastedJavaClass("hello world")).toBeNull();
expect(pastedJavaClass("// see class Foo\nfoo();")).toBeNull();
expect(pastedJavaClass("")).toBeNull();
});
it("takes the package of its folder below a Java source or test root", () => {
const roots: RootFolder[] = [
{ path: "app/src/main/java", kind: "source", detectedFrom: "app/pom.xml" },
{ path: "app/src/test/java", kind: "test", detectedFrom: "app/pom.xml" },
{ path: "web/src", kind: "source", detectedFrom: "web/package.json" },
];
expect(javaPackageAt("app/src/main/java/com/acme", roots)).toBe("com.acme");
expect(javaPackageAt("app/src/test/java/com", roots)).toBe("com");
expect(javaPackageAt("app/src/main/java", roots)).toBe("");
expect(javaPackageAt("docs", roots)).toBeNull();
expect(javaPackageAt("web/src/lib", roots)).toBeNull();
});
it("declares the folder's package, replacing or adding the statement", () => {
expect(withJavaPackage("package old.pkg;\n\nclass A {}", "com.acme")).toBe("package com.acme;\n\nclass A {}");
expect(withJavaPackage("import java.util.List;\nclass A {}", "com.acme")).toBe(
"package com.acme;\n\nimport java.util.List;\nclass A {}",
);
const same = "package com . acme;\nclass A {}";
expect(withJavaPackage(same, "com.acme")).toBe(same);
// Pasted into the source root itself: the default package keeps the code as it is.
expect(withJavaPackage("package old;\nclass A {}", "")).toBe("package old;\nclass A {}");
});
});
-66
Переглянути файл
@@ -1,66 +0,0 @@
// IDEA's Java file paste: Java code pasted into a folder of the Project view becomes
// `<Class>.java`, declaring the folder's package.
import { javaLanguage } from "@codemirror/lang-java";
import type { SyntaxNode } from "@lezer/common";
import { rootFor, type RootFolder } from "@/platform/languageSettings";
import { isJvmSourcePackage } from "@/ui/folderPresentation";
const TYPE_DECLARATIONS = new Set([
"ClassDeclaration",
"InterfaceDeclaration",
"EnumDeclaration",
"RecordDeclaration",
"AnnotationTypeDeclaration",
]);
const typeName = (text: string, declaration: SyntaxNode) => {
const name = declaration.getChild("Definition") ?? declaration.getChild("Identifier");
return name ? text.slice(name.from, name.to) : null;
};
const isPublic = (text: string, declaration: SyntaxNode) => {
const modifiers = declaration.getChild("Modifiers");
return !!modifiers && /(^|\s)public(\s|$)/.test(text.slice(modifiers.from, modifiers.to));
};
/**
* The class pasted Java code is named after: its first public top-level type, else its first
* top-level type; null when the text declares none (a statement, plain prose).
*/
export function pastedJavaClass(text: string): string | null {
if (!/\b(class|interface|enum|record)\b/.test(text)) return null;
const top = javaLanguage.parser.parse(text).topNode;
let first: string | null = null;
for (let node = top.firstChild; node; node = node.nextSibling) {
if (!TYPE_DECLARATIONS.has(node.name)) continue;
const name = typeName(text, node);
if (!name) continue;
if (isPublic(text, node)) return name;
first ??= name;
}
return first;
}
/**
* The package of the project-relative folder `rel`: its path below the Java source or test root
* it is in; null outside one, where a pasted file keeps the package it declares.
*/
export function javaPackageAt(rel: string, roots: readonly RootFolder[]): string | null {
if (!isJvmSourcePackage(rel, roots)) return null;
const root = rootFor(roots, rel)!;
const below = root.path ? rel.slice(root.path.length).replace(/^\/+/, "") : rel;
return below.split("/").filter(Boolean).join(".");
}
/**
* `text` declaring `pkg`: its package statement replaced, or one added in front. Unchanged for the
* default package (`""`), as in IDEA, which leaves the statement of code pasted into a source root.
*/
export function withJavaPackage(text: string, pkg: string): string {
if (!pkg) return text;
const declaration = javaLanguage.parser.parse(text).topNode.getChild("PackageDeclaration");
if (!declaration) return `package ${pkg};\n\n${text}`;
const name = declaration.getChild("ScopedIdentifier") ?? declaration.getChild("Identifier");
if (name && text.slice(name.from, name.to).replace(/\s+/g, "") === pkg) return text;
return `${text.slice(0, declaration.from)}package ${pkg};${text.slice(declaration.to)}`;
}
-53
Переглянути файл
@@ -22,21 +22,9 @@ import { initProjectTree, loadDir, setClipboard, setSelection, useProjectTree }
import { setOsClipboardForTests } from "./clipboard";
const askMock = vi.hoisted(() => vi.fn());
const confirmMock = vi.hoisted(() => vi.fn());
vi.mock("@/workbench/messages", async (original) => ({
...(await original<typeof import("@/workbench/messages")>()),
ask: askMock,
confirm: confirmMock,
}));
const clipboardText = vi.hoisted(() => vi.fn(async () => ""));
vi.mock("@/platform/clipboard", async (original) => ({
...(await original<typeof import("@/platform/clipboard")>()),
readClipboardPlainText: clipboardText,
}));
const roots = vi.hoisted(() => vi.fn((): unknown[] => []));
vi.mock("@/platform/projectRoots", async (original) => ({
...(await original<typeof import("@/platform/projectRoots")>()),
currentRoots: roots,
}));
let fs: MemoryFs;
@@ -260,47 +248,6 @@ describe("OS file imports", () => {
expect(notify).not.toHaveBeenCalled();
});
it("turns pasted Java code into <Class>.java declaring the folder's package, asking before replacing", async () => {
roots.mockReturnValue([{ path: "target", kind: "source", detectedFrom: "pom.xml" }]);
fs = new MemoryFs({ "/p/target/com/acme": null }, "/p");
setProjectFsForTests(fs, "/p");
initProjectTree("/p", "p");
await loadDir("/p");
setOsClipboardForTests({});
const written: string[] = [];
const create = fs.createFileBytes.bind(fs);
vi.spyOn(fs, "createFileBytes").mockImplementation(async (path, data) => {
written.push(`${path}: ${new TextDecoder().decode(data)}`);
await create(path, data);
});
clipboardText.mockResolvedValue("package old;\r\n\r\npublic class Greeter {}\r\n");
await paste("/p/target/com/acme");
expect(written).toEqual(["/p/target/com/acme/Greeter.java: package com.acme;\n\npublic class Greeter {}\n"]);
expect(useProjectTree.getState().revealRequest?.path).toBe("/p/target/com/acme/Greeter.java");
// The file exists: kept when the user declines, replaced when they agree.
confirmMock.mockResolvedValueOnce(false);
await paste("/p/target/com/acme");
expect(written).toHaveLength(1);
confirmMock.mockResolvedValueOnce(true);
await paste("/p/target/com/acme");
expect(confirmMock).toHaveBeenCalledWith(
expect.objectContaining({ message: "File 'Greeter.java' already exists. Do you want to overwrite it?" }),
);
expect(written).toHaveLength(2);
// Outside a source root the code keeps its own package; text without a type is not pasted.
clipboardText.mockResolvedValue("package demo;\nclass Note {}");
await paste("/p");
expect(written.at(-1)).toBe("/p/Note.java: package demo;\nclass Note {}");
clipboardText.mockResolvedValue("System.out.println(1);");
await paste("/p");
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: "No files on the clipboard" }));
expect(written).toHaveLength(3);
clipboardText.mockResolvedValue("");
roots.mockReturnValue([]);
});
it("says the clipboard is empty when it holds neither files nor an image", async () => {
setOsClipboardForTests({});
await paste("/p/target");
+5 -53
Переглянути файл
@@ -2,7 +2,7 @@
* File operations behind the project view's actions: new / rename / delete,
* internal copy-cut-paste, drag & drop moves and OS file imports.
*/
import { readClipboardPlainText, writeClipboardText } from "@/platform/clipboard";
import { writeClipboardText } from "@/platform/clipboard";
import { createElement, Fragment } from "react";
import { askUsagesDetected, fileUsages, showFileUsages, viewUsages } from "@/editor/refactor";
import { executeAction, getAction } from "@/platform/actions";
@@ -14,15 +14,13 @@ import {
revealInFileManager,
} from "@/platform/fileManager";
import { maybeEditorService, notifications } from "@/workbench/contributions";
import { ask, confirm, confirmChecked } from "@/workbench/messages";
import { ask, confirmChecked } from "@/workbench/messages";
import { osClipboard } from "./clipboard";
import { lastFileRefactoring, nextFileOperation, runFileRefactoring, undoFileRefactoring } from "./fileRefactor";
import { openFileRefactorDialog, rememberedOptions } from "./FileRefactorDialogs";
import { beginLocalImport, projectFs } from "./fs";
import { renameCopiedJavaType } from "./javaCopy";
import { javaPackageAt, pastedJavaClass, withJavaPackage } from "./javaPaste";
import { currentRoots } from "@/platform/projectRoots";
import { IpcError, isCancelled, isTauri } from "@/platform/ipc";
import { IpcError, isCancelled } from "@/platform/ipc";
import { MEMBER_PREFIX, type ProjectNode } from "./model";
import {
isInside,
@@ -53,7 +51,7 @@ import { tx, txPart } from "@/platform/i18n";
import { hostOs, isRemoteWindow } from "@/platform/remote";
import { usePlatform } from "@/platform/platformInfo";
import { pathToCopy, type PathKind } from "@/platform/copyPath";
import { projectFolder, relativePath, useProject } from "@/platform/project";
import { projectFolder, useProject } from "@/platform/project";
export type { PathKind } from "@/platform/copyPath";
/** Nodes that may be renamed, moved or deleted (not roots, groups or library sources). */
@@ -588,8 +586,6 @@ export function copySelection(cut: boolean) {
/** Files or an image on the OS clipboard, cached: `canPaste` runs while a menu renders. */
let osHasFiles = false;
let osHasImage = false;
/** The clipboard holds Java code, which Paste turns into a file. */
let osHasJava = false;
/** Keeps Paste enabled for what Explorer copied; called when the window gains focus. */
export async function refreshOsClipboard() {
@@ -608,10 +604,6 @@ async function readOsClipboard(): Promise<string[] | null> {
if (get().clipboard !== clipboard) return null;
osHasFiles = external.length > 0;
osHasImage = image;
// Only the desktop app reads the text without asking; in a browser Paste still tries. Checked on
// every window focus, so a huge clipboard is not parsed for the menu item.
const text = !osHasFiles && !image && isTauri() ? await readClipboardPlainText().catch(() => "") : "";
osHasJava = text.length <= 1_000_000 && !!pastedJavaClass(text);
// Our remote text write removes file URLs, so any files were copied later.
// A failed write leaves ownership uncertain; retain the remote copy then.
if (handedOff && (clipboard?.remote ? external.length > 0 : !sameFiles(external, clipboard?.paths)))
@@ -620,7 +612,7 @@ async function readOsClipboard(): Promise<string[] | null> {
}
export function canPaste(): boolean {
return !!get().clipboard?.paths.length || osHasFiles || osHasImage || osHasJava;
return !!get().clipboard?.paths.length || osHasFiles || osHasImage;
}
/**
@@ -648,7 +640,6 @@ export async function paste(target = targetFolder()) {
return pasteFromOsClipboard(external, target);
if (!clipboard?.paths.length) {
if (await pasteImage(target)) return;
if (await pasteJavaCode(target)) return;
notifications().notify({ level: "info", title: "No files on the clipboard" });
return;
}
@@ -663,45 +654,6 @@ export async function paste(target = targetFolder()) {
});
}
/**
* Java code on the clipboard becomes `<Class>.java` in `target`, declaring the folder's package
* inside a source root, and opens (IDEA's Java file paste). Asks before replacing a file of that
* name. False when the clipboard holds no Java type.
*/
async function pasteJavaCode(target: string): Promise<boolean> {
const text = (await readClipboardPlainText().catch(() => "")).replace(/\r\n?/g, "\n");
const className = pastedJavaClass(text);
if (!className) return false;
const name = `${className}.java`;
const root = get().root ?? target;
const pkg = javaPackageAt(target === root ? "" : relativePath(root, target), currentRoots());
const path = joinPath(target, name);
await loadDir(target);
const exists = (get().listings.get(target) ?? []).some((e) => e.name === name);
if (
exists &&
!(await confirm({
title: tx("Paste"),
message: tx`File '${name}' already exists. Do you want to overwrite it?`,
ok: "Overwrite",
}))
)
return true;
const fs = projectFs(root);
try {
// The replaced file goes to Local History, like any delete.
if (exists) await fs.delete(path);
await fs.createFileBytes(path, new TextEncoder().encode(pkg === null ? text : withJavaPackage(text, pkg)));
} catch (e) {
fail(tx`Cannot paste ${name}`, e);
return true;
}
await loadDir(target, true);
revealPath(path, true);
await maybeEditorService()?.openFile(path, { focus: true });
return true;
}
/**
* Saves the clipboard's image in `target` as `img.png`, or `img_1.png`, `img_2.png`
* … when taken, and selects it. False when the clipboard holds no image.
-11
Переглянути файл
@@ -316,17 +316,6 @@ describe("Find in Files popup", () => {
expect(screen.getByRole("button", { name: "Open in Find Window" })).toBeEnabled();
});
it("clicking a scope tab keeps focus in the search field", async () => {
render(<FindInFilesOverlay />);
act(() => showFindPopup(false, { query: "order" }));
await settle();
const down = new MouseEvent("mousedown", { bubbles: true, cancelable: true });
screen.getByRole("tab", { name: "Module" }).dispatchEvent(down);
expect(down.defaultPrevented).toBe(true);
fireEvent.click(screen.getByRole("tab", { name: "Module" }));
expect(useFindPopup.getState().scopeTab).toBe("module");
});
it("closing remembers the search text", async () => {
render(<FindInFilesOverlay />);
act(() => showFindPopup(false, { query: "order" }));
-1
Переглянути файл
@@ -778,7 +778,6 @@ function FindInFilesDialog() {
}))}
activeId={s.scopeTab}
onSelect={(id) => selectScope(id as ScopeTab)}
keepFocusOnClick
/>
<div className={styles.scopeDetail}>
{s.scopeTab === "directory" && (
+1 -18
Переглянути файл
@@ -161,22 +161,17 @@
overflow: hidden;
text-overflow: ellipsis;
}
/* Checkable changes tree in the Shelve / Create Patch / Rollback dialogs. */
/* Checkable changes tree in the Shelve / Create Patch dialogs. */
.fileTree {
display: flex;
flex-direction: column;
height: 260px;
margin: 0 14px;
border: 1px solid var(--border);
border-radius: var(--radius-small);
overflow: hidden;
}
.fileTreeView {
flex: 1;
min-width: 0;
min-height: 0;
/* Override Tree's `height: 100%`: WebKit doesn't resolve percentage heights against a flex-basis height. */
height: auto;
}
.fileTreeRow {
composes: fileRow;
@@ -249,12 +244,6 @@
max-width: 100%;
font-size: var(--fs-ui);
}
/* A bare inline span puts its inline-flex checkbox child on the text baseline,
lifting it above the sibling controls; keep the tooltip wrapper centred. */
.pushOptionWrap {
display: inline-flex;
align-items: center;
}
.pushTargetBar {
display: flex;
flex-wrap: wrap;
@@ -922,18 +911,12 @@
.comparisonTree {
flex: 1;
min-width: 0;
min-height: 0;
/* Stretch instead of Tree's `height: 100%`: WebKit doesn't resolve percentage heights against a flex-basis height. */
height: auto;
align-self: stretch;
border: 1px solid var(--border);
}
.comparisonWithDiff .comparisonTree {
flex: 0 0 30%;
}
.comparisonDiff {
display: flex;
flex-direction: column;
flex: 1;
min-width: 0;
min-height: 0;
+1 -4
Переглянути файл
@@ -1265,10 +1265,7 @@ function PushDialog({
resizable="both"
footerStart={
<div className={styles.pushOptions}>
<span
className={styles.pushOptionWrap}
title={protectedTarget ? `Force push to protected branch '${target}' is prohibited` : undefined}
>
<span title={protectedTarget ? `Force push to protected branch '${target}' is prohibited` : undefined}>
<Checkbox
checked={force && forceAvailable}
disabled={!forceAvailable || inspection.fetching}
+1 -2
Переглянути файл
@@ -6110,6 +6110,5 @@
"Couldn't roll back": "No se pudo revertir",
"This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "Este mensaje y los posteriores se eliminan, y los archivos que el agente modificó desde entonces vuelven a como estaban antes de enviarlo. El mensaje vuelve al cuadro de texto.",
"This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.": "Esto borra toda la conversación, devuelve los archivos que el agente modificó a como estaban al empezar la tarea e inicia una nueva sesión del agente con este mensaje.",
"Resets in {resetIn}": "Se restablece en {resetIn}",
"Cannot paste {name}": "No se puede pegar {name}"
"Resets in {resetIn}": "Se restablece en {resetIn}"
}
+1 -2
Переглянути файл
@@ -5753,6 +5753,5 @@
"Couldn't roll back": "Impossible de revenir en arrière",
"This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "Ce message et les suivants sont supprimés, et les fichiers modifiés par l'agent depuis reviennent à leur état d'avant l'envoi. Le message revient dans la zone de saisie.",
"This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.": "Cela efface toute la conversation, remet les fichiers modifiés par l'agent dans leur état du début de la tâche et démarre une nouvelle session de l'agent avec ce message.",
"Resets in {resetIn}": "Réinitialisation dans {resetIn}",
"Cannot paste {name}": "Impossible de coller {name}"
"Resets in {resetIn}": "Réinitialisation dans {resetIn}"
}
+1 -2
Переглянути файл
@@ -6220,6 +6220,5 @@
"Couldn't roll back": "롤백할 수 없습니다",
"This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "이 메시지와 이후 메시지가 제거되고, 그 이후 에이전트가 변경한 파일은 메시지를 보내기 전 상태로 돌아갑니다. 메시지는 입력란으로 돌아갑니다.",
"This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.": "전체 대화를 지우고, 에이전트가 변경한 파일을 작업 시작 시점의 상태로 되돌린 뒤, 이 메시지로 새 에이전트 세션을 시작합니다.",
"Resets in {resetIn}": "{resetIn} 후 재설정",
"Cannot paste {name}": "{name}을(를) 붙여넣을 수 없습니다"
"Resets in {resetIn}": "{resetIn} 후 재설정"
}
+1 -2
Переглянути файл
@@ -5918,6 +5918,5 @@
"Couldn't roll back": "Nie udało się wycofać",
"This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "Ta wiadomość i kolejne zostaną usunięte, a pliki zmienione od tego czasu przez agenta wrócą do stanu sprzed jej wysłania. Wiadomość wróci do pola tekstowego.",
"This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.": "To wyczyści całą rozmowę, przywróci pliki zmienione przez agenta do stanu z początku zadania i rozpocznie nową sesję agenta z tą wiadomością.",
"Resets in {resetIn}": "Resetuje się za {resetIn}",
"Cannot paste {name}": "Nie można wkleić {name}"
"Resets in {resetIn}": "Resetuje się za {resetIn}"
}
+1 -2
Переглянути файл
@@ -5933,6 +5933,5 @@
"Couldn't roll back": "Não foi possível reverter",
"This message and the ones after it are removed, and the files the agent changed since go back to how they were before it was sent. The message returns to the composer.": "Esta mensagem e as seguintes são removidas, e os arquivos que o agente alterou desde então voltam a como estavam antes do envio. A mensagem volta para a caixa de texto.",
"This clears the entire conversation, puts the files the agent changed back as they were when the task started, and starts a fresh agent session with this message.": "Isso limpa toda a conversa, devolve os arquivos que o agente alterou a como estavam no início da tarefa e inicia uma nova sessão do agente com esta mensagem.",
"Resets in {resetIn}": "Redefine em {resetIn}",
"Cannot paste {name}": "Não é possível colar {name}"
"Resets in {resetIn}": "Redefine em {resetIn}"
}
-1
Переглянути файл
@@ -371,7 +371,6 @@
"Make configurations pinned by default": "Закреплять конфигурации по умолчанию",
"A finished pinned tab stays open: a later run opens a new tab instead of taking its place.": "Завершённая закреплённая вкладка остаётся открытой: последующий запуск откроет новую вкладку вместо замены текущей.",
"Cannot paste the image into {name}": "Не удалось вставить изображение в {name}",
"Cannot paste {name}": "Не удалось вставить {name}",
"New Worktree from '{name}'…": "Новый Worktree из «{name}»…",
"Prune Worktrees": "Очистить Worktree",
"Prune Worktrees…": "Очистить Worktree…",
-1
Переглянути файл
@@ -143,7 +143,6 @@
"Make configurations pinned by default": "Yapılandırmaları varsayılan olarak sabitle",
"A finished pinned tab stays open: a later run opens a new tab instead of taking its place.": "Tamamlanmış sabitlenmiş sekme açık kalır; sonraki çalıştırma bu sekmenin yerine yeni bir sekme açar.",
"Cannot paste the image into {name}": "Görsel {name} içine yapıştırılamıyor",
"Cannot paste {name}": "{name} yapıştırılamıyor",
"Worktree Conflict": "Çalışma Ağacı Çakışması",
"Branch '{branch}' is already checked out in a worktree at:\n{path}": "'{branch}' dalı zaten şu konumdaki çalışma ağacında kullanılıyor:\n{path}",
"Checkout Anyway": "Yine de Geçiş Yap",
-1
Переглянути файл
@@ -132,7 +132,6 @@
"Make configurations pinned by default": "預設固定執行/偵錯分頁",
"A finished pinned tab stays open: a later run opens a new tab instead of taking its place.": "固定的分頁結束後會保留:之後的執行會開啟新分頁,而不是取代它。",
"Cannot paste the image into {name}": "無法將圖片貼上為 {name}",
"Cannot paste {name}": "無法貼上 {name}",
"Worktree Conflict": "工作樹衝突",
"Branch '{branch}' is already checked out in a worktree at:\n{path}": "分支 '{branch}' 已在以下位置的工作樹中籤出:\n{path}",
"Checkout Anyway": "仍然簽出",
-1
Переглянути файл
@@ -381,7 +381,6 @@
"Make configurations pinned by default": "默认固定运行/调试标签页",
"A finished pinned tab stays open: a later run opens a new tab instead of taking its place.": "固定的标签页结束后会保留:之后的运行会打开新标签页,而不是替换它。",
"Cannot paste the image into {name}": "无法将图片粘贴为 {name}",
"Cannot paste {name}": "无法粘贴 {name}",
"New Worktree from '{name}'…": "从“{name}”新建工作树…",
"Prune Worktrees": "清理工作树",
"Prune Worktrees…": "清理工作树…",
+1 -2
Переглянути файл
@@ -7,8 +7,7 @@
flex-direction: column;
min-width: 0;
min-height: 0;
/* Stretch inside [data-panel]'s row flex box: `height: 100%` fails to resolve against a flex-basis height in WebKit. */
align-self: stretch;
height: 100%;
}
.handle {
position: relative;
-12
Переглянути файл
@@ -169,18 +169,6 @@ describe("Tabs interactions", () => {
expect(onClose).toHaveBeenCalledWith("b");
});
it("leaves focus where it was on click only when the strip asks to", () => {
const { rerender } = render(<Tabs items={items} activeId="b" onSelect={() => {}} keepFocusOnClick />);
const down = () => {
const event = new MouseEvent("mousedown", { bubbles: true, cancelable: true });
screen.getByRole("tab", { name: "C" }).dispatchEvent(event);
return event.defaultPrevented;
};
expect(down()).toBe(true);
rerender(<Tabs items={items} activeId="b" onSelect={() => {}} />);
expect(down()).toBe(false);
});
it("keeps Shift+click selection where the strip does not opt in", () => {
const onClose = vi.fn();
const onSelect = vi.fn();
-7
Переглянути файл
@@ -158,11 +158,6 @@ export interface TabsProps {
closePosition?: "right" | "left";
/** `vertical`: a column of tabs (editor tabs placed left / right); always scrolls, `layout` is ignored. */
orientation?: "horizontal" | "vertical";
/**
* Clicking a tab leaves keyboard focus where it was (a scope strip under a search field, like the
* Find in Files scopes); keyboard navigation of a focused strip is unchanged.
*/
keepFocusOnClick?: boolean;
}
export function Tabs({
@@ -185,7 +180,6 @@ export function Tabs({
hiddenTabsOnly = false,
closePosition = "right",
orientation = "horizontal",
keepFocusOnClick = false,
...aria
}: TabsProps) {
const vertical = orientation === "vertical";
@@ -502,7 +496,6 @@ export function Tabs({
tabIndex={selected || (!activeId && index === 0) ? 0 : -1}
className={clsx(styles.tabButton, item.dimmed && styles.dimmed)}
style={item.color ? { color: item.color } : undefined}
onMouseDown={keepFocusOnClick ? (e) => e.preventDefault() : undefined}
onClick={(e) => {
// Shift+click is mouse-only: a keyboard Enter with Shift held still selects.
if (closeOnShiftClick && e.shiftKey && e.detail > 0 && closable) {