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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 0a03615988 feat(vcs): Deployment submenu in the changes tree's context menu
The Commit tool window's changes tree had no Deployment entries, so uploading changed
files meant finding them again in the Project view. Its context menu now takes other
features' groups through a new "changes" menu slot; Deployment contributes its submenu
there (Upload to, Download from, Sync with, Delete from Server, ...) for the selected
files that are still on disk.
2026-11-17 01:10:30 +08:00
xiaohuiduanтаxiaohuiduan 8b6c71095a feat(agents): add DeepSeek Harness as a built-in ACP agent (#3786)
Adds the deepseek-harness provider (dsh --profile acp) with its logo, resolved like the other CLI agents.

DeepSeek Harness advertises sessionCapabilities.resume instead of loadSession and does not implement session/load, so its saved tasks counted as non-reloadable and restarted fresh. The ACP client now treats a v1 resume-only agent as reloadable and sends session/load as session/resume; agents that advertise loadSession (or neither) are unchanged.

Co-authored-by: xiaohuiduan <[email protected]>
2026-11-17 01:03:51 +08:00
Yann abe7c58cb9 feat(vcs): View Options › Show Unversioned Files Separately (#3702)
Adds a View Options toggle, on by default. Turning it off lists untracked files under Changes (the active changelist), or Unstaged Changes when grouping by staging state. The files stay untracked and excluded from commits by default; the choice is remembered independently of Staging State.

Co-authored-by: YannABC <[email protected]>
2026-11-17 01:00:56 +08:00
zhangdagouтаPLZY d3d799b8fe feat(vcs): checkable directory tree in the Shelve, Unshelve and Create Patch dialogs (#3778)
The files of the Shelve, Unshelve and Create Patch dialogs were a flat list. They are now a tree under the repository node, grouped by directory with file counts; a directory's checkbox checks or clears every file below it and shows a dash when only some are included. Unshelve lists the shelved files too and applies only the checked ones.

Co-authored-by: PLZY <[email protected]>
2026-11-17 00:58:14 +08:00
l0ng-ai 122d7f3d0f fix(ui): show cut-off text whole in a tooltip (#3800)
Text shortened with an ellipsis gave no way to read it whole. The tooltip host now shows such text in full after the usual delay, only while it is actually cut off and when it has no native title. Inside an element with a tooltip of its own (an editor tab, a commit-panel file with its change kind) the whole text comes first and that tooltip beside it. The commit panel's change kind moves from title to the tooltip host.
2026-11-17 00:54:31 +08:00
l0ng-ai 6cdb2f1f1e fix(plugins): say why a marketplace download failed (#3798)
A failed plugin download, marketplace read or plugin network request reported only reqwest's top-level message, with the URL twice and no cause. These errors now carry their causes (DNS, connection refused, TLS, ...) as the HTTP client already does; the agent panel's MCP server requests too.
2026-11-17 00:43:05 +08:00
25 змінених файлів з 786 додано та 62 видалено

No files matched your search

+1 -1
Переглянути файл
@@ -4,7 +4,7 @@
`src/ui/brands/*.svg` use the unmodified logo paths from
[Simple Icons](https://github.com/simple-icons/simple-icons), retrieved through
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
Iconify (`simple-icons:angular`, `simple-icons:astro`, `simple-icons:cplusplus`, `simple-icons:dart`, `simple-icons:deepseek`, `simple-icons:django`, `simple-icons:dotnet`, `simple-icons:elixir`, `simple-icons:express`, `simple-icons:fastapi`, `simple-icons:flask`, `simple-icons:flutter`, `simple-icons:go`, `simple-icons:haskell`, `simple-icons:html5`, `simple-icons:kotlin`, `simple-icons:ktor`, `simple-icons:laravel`, `simple-icons:nestjs`, `simple-icons:nextdotjs`, `simple-icons:nodedotjs`, `simple-icons:nuxt`, `simple-icons:openjdk`, `simple-icons:phoenixframework`, `simple-icons:php`, `simple-icons:python`, `simple-icons:quarkus`, `simple-icons:ruby`, `simple-icons:rubyonrails`, `simple-icons:rust`, `simple-icons:scala`, `simple-icons:springboot`, `simple-icons:svelte`, `simple-icons:swift`, `simple-icons:symfony`, `simple-icons:vite`, `simple-icons:zig`) and filled with the brand colors (the standard icon grey for black logos). Licensed under [CC0 1.0 Universal](https://github.com/simple-icons/simple-icons/blob/develop/LICENSE.md).
## Project Lombok
+21 -3
Переглянути файл
@@ -27,7 +27,7 @@ use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use tokio::sync::oneshot;
/// ACP's error code for a request that needs the user to sign in.
@@ -162,9 +162,16 @@ impl Negotiated {
Self { generation: 2, capabilities, agent_info: response.get("info").cloned(), auth_methods, meta }
}
/// Whether a saved session can be reopened (`session/load` on v1, `session/resume` on v2).
/// Whether a saved session can be reopened: `loadSession`, or a v1 agent's
/// `sessionCapabilities.resume` (DeepSeek Harness), which stands in for it.
pub fn load_session(&self) -> bool {
self.capabilities.get("loadSession").and_then(Value::as_bool) == Some(true)
self.capabilities.get("loadSession").and_then(Value::as_bool) == Some(true) || self.session("resume")
}
/// Whether `session/load` must be sent as `session/resume`: a v1 agent that advertises
/// `sessionCapabilities.resume` instead of `loadSession` (DeepSeek Harness).
pub fn resume_instead_of_load(&self) -> bool {
self.capabilities.get("loadSession").and_then(Value::as_bool) != Some(true) && self.session("resume")
}
/// `promptCapabilities.<name>` (`image`, `audio`, `embeddedContext`).
@@ -205,6 +212,8 @@ pub(crate) struct Dialect {
inner: Arc<dyn Handler>,
/// 0 until `initialize` answers; then 1 or 2.
generation: AtomicU8,
/// Set by `initialize`: a v1 agent's `session/load` is sent as `session/resume`.
resume_load: AtomicBool,
normalizer: Mutex<Normalizer>,
/// Running v2 prompts, by session id.
turns: Mutex<HashMap<String, Turn>>,
@@ -222,6 +231,7 @@ impl Dialect {
Arc::new(Self {
inner,
generation: AtomicU8::new(0),
resume_load: AtomicBool::new(false),
normalizer: Mutex::new(Normalizer::default()),
turns: Mutex::new(HashMap::new()),
})
@@ -231,6 +241,10 @@ impl Dialect {
self.generation.load(Ordering::Acquire)
}
fn resume_load(&self) -> bool {
self.resume_load.load(Ordering::Acquire)
}
fn v2(&self) -> bool {
self.generation() == 2
}
@@ -380,6 +394,7 @@ impl Conn {
let response: Value = self.peer.request("initialize", initialize_params(client_info), None).await?;
let negotiated = Negotiated::from_initialize(&response);
self.dialect.generation.store(negotiated.generation, Ordering::Release);
self.dialect.resume_load.store(negotiated.resume_instead_of_load(), Ordering::Release);
Ok(negotiated)
}
@@ -393,6 +408,9 @@ impl Conn {
let params = serde_json::to_value(params).map_err(|e| RpcError::Protocol(e.to_string()))?;
let value = if self.dialect.v2() {
self.request_v2(method, params, cancel).await?
} else if method == "session/load" && self.dialect.resume_load() {
// Same request shape, without a replay and without v2's setup translation.
self.peer.request("session/resume", params, cancel).await?
} else {
self.peer.request(method, params, cancel).await?
};
+85
Переглянути файл
@@ -180,6 +180,7 @@ async fn discovery_reads_effort_and_fast_from_session_new_then_stops_the_agent()
fn a_v2_initialize_response_reads_as_v1_capabilities() {
let n = Negotiated::from_initialize(&result(TURN, 1));
assert_eq!(n.generation, 2);
assert!(!n.resume_instead_of_load(), "v2 maps `session/load` itself");
assert!(n.load_session());
assert!(n.prompt("image") && n.prompt("embeddedContext") && !n.prompt("audio"));
assert!(n.session("fork") && n.session("resume") && n.session("close") && n.session("delete"));
@@ -681,3 +682,87 @@ fn stdio_mcp_is_v1_baseline_and_negotiated_in_v2() {
.mcp_stdio()
);
}
/// A v1 agent that answers `initialize` with `init` and records every request it gets.
/// Keeps its own `Peer` so the duplex stays open while the client sends.
struct V1Agent {
init: Value,
peer: std::sync::OnceLock<Peer>,
requests: parking_lot::Mutex<Vec<(String, Value)>>,
}
impl Handler for V1Agent {
fn on_notification(&self, _: &str, _: Value) {}
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
self.requests.lock().push((method.to_owned(), params));
Ok(if method == "initialize" { self.init.clone() } else { json!({}) })
}
}
async fn connect_v1(agent: Arc<V1Agent>) -> (Conn, Negotiated) {
let (a, b) = tokio::io::duplex(1 << 20);
let (ar, aw) = tokio::io::split(a);
let (br, bw) = tokio::io::split(b);
let _ = agent.peer.set(Peer::connect_framed(br, bw, agent.clone(), Framing::Lines));
let dialect = Dialect::wrap(Arc::new(Recorder::default()));
let conn = Conn::new(Peer::connect_framed(ar, aw, dialect.clone(), Framing::Lines), dialect);
let n = conn.initialize(&json!({ "name": "OpenIDEA", "version": "0" })).await.unwrap();
assert_eq!((n.generation, conn.generation()), (1, 1));
(conn, n)
}
fn v1_agent(init: Value) -> Arc<V1Agent> {
Arc::new(V1Agent { init, peer: Default::default(), requests: Default::default() })
}
/// A v1 agent that advertises `sessionCapabilities.resume` instead of `loadSession`
/// (DeepSeek Harness) can reopen a saved session, but only through `session/resume`.
#[tokio::test(flavor = "multi_thread")]
async fn a_v1_agent_with_resume_instead_of_load_reopens_through_session_resume() {
let agent = v1_agent(json!({
"protocolVersion": 1,
"agentInfo": { "name": "deepseek-harness-acp", "version": "0.0.1" },
"agentCapabilities": { "sessionCapabilities": { "close": {}, "list": {}, "resume": {} } },
}));
let (conn, n) = connect_v1(agent.clone()).await;
assert!(n.load_session(), "a resume-only agent is reloadable");
assert!(n.resume_instead_of_load());
assert!(n.session("resume"));
let params = json!({ "sessionId": "s1", "cwd": "/p", "mcpServers": [] });
let _: Value = conn.request("session/load", params.clone(), None).await.unwrap();
let requests = agent.requests.lock().clone();
assert_eq!(requests.iter().map(|(m, _)| m.as_str()).collect::<Vec<_>>(), ["initialize", "session/resume"]);
assert_eq!(requests[1].1, params, "same request shape as `session/load`");
}
/// Every other v1 agent is untouched: `loadSession` still sends `session/load`, and an
/// agent advertising neither capability is not treated as loadable.
#[tokio::test(flavor = "multi_thread")]
async fn v1_agents_that_do_not_advertise_resume_keep_session_load() {
for (init, loadable) in [
(json!({ "protocolVersion": 1, "agentCapabilities": { "loadSession": true } }), true),
(json!({ "protocolVersion": 1, "agentCapabilities": { "loadSession": false } }), false),
(json!({ "protocolVersion": 1, "agentCapabilities": { "sessionCapabilities": { "resume": null } } }), false),
(json!({ "protocolVersion": 1 }), false),
] {
let agent = v1_agent(init);
let (conn, n) = connect_v1(agent.clone()).await;
assert_eq!(n.load_session(), loadable);
assert!(!n.resume_instead_of_load());
let _: Value = conn.request("session/load", json!({ "sessionId": "s1" }), None).await.unwrap();
let methods: Vec<String> = agent.requests.lock().iter().map(|(m, _)| m.clone()).collect();
assert_eq!(methods, ["initialize", "session/load"]);
}
// `loadSession: true` wins over a resume-only advertisement.
let agent = v1_agent(json!({
"protocolVersion": 1,
"agentCapabilities": { "loadSession": true, "sessionCapabilities": { "resume": {} } },
}));
let (conn, n) = connect_v1(agent.clone()).await;
assert!(n.load_session() && !n.resume_instead_of_load());
let _: Value = conn.request("session/load", json!({ "sessionId": "s1" }), None).await.unwrap();
let methods: Vec<String> = agent.requests.lock().iter().map(|(m, _)| m.clone()).collect();
assert_eq!(methods, ["initialize", "session/load"]);
}
+7
Переглянути файл
@@ -56,6 +56,13 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
&["npx", "-y", "@agentclientprotocol/[email protected]"],
"Run `codex login` in a terminal.",
),
(
"deepseek-harness",
"DeepSeek Harness",
Driver::Acp,
&["dsh", "--profile", "acp"],
"Run `dsh` in a terminal and sign in.",
),
("gemini", "Gemini CLI", Driver::Acp, &["gemini", "--experimental-acp"], "Run `gemini` in a terminal and sign in."),
(
"copilot",
+2
Переглянути файл
@@ -49,6 +49,8 @@ OpenIDEA finds the repository that contains the project and nested repositories
The **Commit** tool window lists your changes in groups: **Merge Conflicts**, **Changes** (one group per changelist) and **Unversioned Files**. With **View Options › Group By › Staging State**, the changes split into **Staged Changes** and **Unstaged Changes**.
Turn off **View Options › Show Unversioned Files Separately** to list untracked files under **Changes** (the active changelist), or **Unstaged Changes** when grouping by staging state. This only changes the display; the files remain untracked and excluded from commits by default. The option is on by default and is remembered independently of **Staging State**.
<Steps>
<Step title="Choose what to commit">
Check the files to include. Unversioned files and conflicts are not included by default, and only the active
+1
Переглянути файл
@@ -65,6 +65,7 @@ const PROVIDER_ICONS = new Set([
"kiro",
"vibe",
"omp",
"deepseek-harness",
]);
/** The agent's logo; custom agents get the generic agents icon. */
+1 -1
Переглянути файл
@@ -87,7 +87,7 @@ export function activate(): () => void {
registerOverlay({ id: "deployment.dialogs", component: DeploymentDialogs }),
registerMenuGroup({
id: "deployment",
menus: ["projectView", "editor", "editorTab"],
menus: ["projectView", "editor", "editorTab", "changes"],
order: 60,
items: (_menu, { paths }) => deploymentMenu(paths),
prepare: async (_menu, { paths }) => {
+37 -5
Переглянути файл
@@ -38,12 +38,19 @@ import {
registerDropTarget,
showContextMenu,
startPointerDrag,
tooltipAttrs,
type MenuItem,
type TabItem,
type TreeHandle,
T,
} from "@/ui";
import { editorService, maybeEditorService, type EditorInput, useMenuSlotItems } from "@/workbench/contributions";
import {
editorService,
maybeEditorService,
menuGroupItems,
type EditorInput,
useMenuSlotItems,
} from "@/workbench/contributions";
import { evaluateWhen, useContextKeys } from "@/platform/context";
import { useToolWindowLayout } from "@/workbench/toolwindows/store";
import {
@@ -74,6 +81,7 @@ import {
setGroupByDir,
setGroupByRepo,
setGroupByStaging,
setShowUnversionedSeparately,
useCommit,
type CommitTab,
} from "./commitStore";
@@ -291,9 +299,11 @@ export function listMenu(id: string, active: boolean, files: readonly FileStatus
/** Paths Delete… applies to: only when every selected file is unversioned (versioned ones are rolled back). */
/** The selected files that still exist in the working tree (Delete… removes them from disk). */
/** Whether the change leaves the file in the working tree. */
const onDisk = (f: FileStatus) => f.unstaged !== "deleted" && !(f.staged === "deleted" && !f.unstaged);
export function deletableFiles(nodes: ChangeNode[]): string[] {
const files = filesOf(nodes);
const onDisk = (f: FileStatus) => f.unstaged !== "deleted" && !(f.staged === "deleted" && !f.unstaged);
return files.length && files.every(onDisk) ? files.map((f) => f.path) : [];
}
@@ -426,6 +436,10 @@ export function nodeMenu(
{ kind: "action", action: "vcs.localHistory", arg: first?.path },
{ kind: "action", action: "vcs.annotate", arg: first?.path },
{ kind: "separator" },
// Other features' groups (Deployment) for the files that exist.
...menuGroupItems("changes", {
paths: files.filter(onDisk).map((f) => stripSlash(f.path)),
}),
{ label: "Copy Path", icon: "copy", run: () => copyChangePaths(nodes, "absolute") },
{ label: "Copy File Name", icon: "copy", run: () => copyChangePaths(nodes, "name") },
);
@@ -612,6 +626,7 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
const staging = useStagingArea() && mode === "commit";
const groupByStaging = useCommit((s) => s.groupByStaging) || staging;
const groupByRepo = useCommit((s) => s.groupByRepo);
const showUnversionedSeparately = useCommit((s) => s.showUnversionedSeparately);
const diffPreview = useCommit((s) => s.diffPreview);
const commitDiffPreview = useCommit((s) => s.commitDiffPreview);
const doubleClickOpensDiff = useWorkflowSettings((s) => s.vcs.commit.doubleClickOpensDiff);
@@ -630,8 +645,19 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
const heads = useVcs((s) => s.heads);
const projectRoots = useEffectiveRoots();
const roots = useMemo(
() => buildChangeTree(status, root, groupByDir, lists, repos, groupByStaging, heads, groupByRepo),
[status, root, groupByDir, lists, repos, groupByStaging, heads, groupByRepo],
() =>
buildChangeTree(
status,
root,
groupByDir,
lists,
repos,
groupByStaging,
heads,
groupByRepo,
showUnversionedSeparately,
),
[status, root, groupByDir, lists, repos, groupByStaging, heads, groupByRepo, showUnversionedSeparately],
);
const [byKey, parents] = useMemo(() => {
const m = new Map<string, ChangeNode>();
@@ -756,6 +782,12 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
...(staging
? []
: [{ label: "Staging State", checked: groupByStaging, run: () => setGroupByStaging(!groupByStaging) }]),
{ kind: "separator" },
{
label: "Show Unversioned Files Separately",
checked: showUnversionedSeparately,
run: () => setShowUnversionedSeparately(!showUnversionedSeparately),
},
...(mode === "local"
? [
{ kind: "separator" } as const,
@@ -884,7 +916,7 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
n.type === "group" && n.changelist && !n.active && styles.inactiveList,
)}
style={n.type === "file" && n.kind ? { color: KIND_COLOR[n.kind] } : undefined}
title={n.type === "file" && n.kind ? tx(KIND_LABEL[n.kind]) : undefined}
{...(n.type === "file" && n.kind && tooltipAttrs(KIND_LABEL[n.kind]))}
>
{nodeText(n)}
</span>
+75
Переглянути файл
@@ -10,6 +10,7 @@ import {
initialCheck,
hunkIncluded,
groupFileNodes,
groupOf,
planCommit,
remainingOverrides,
stagingSide,
@@ -110,6 +111,80 @@ describe("buildChangeTree", () => {
});
});
describe("unversioned file grouping", () => {
it.each([true, false])(
"keeps staged additions deleted from disk visible with separate unversioned grouping %s",
(separate) => {
const added = fs("added.txt", "added", "deleted");
const untracked = fs("new.txt", null, "untracked");
const tree = buildChangeTree([added, untracked], "/r", false, undefined, [], true, {}, true, separate);
expect(tree.find((n) => n.group === "staged")?.files).toEqual([added]);
expect(tree.find((n) => n.group === "unstaged")?.files).toEqual(separate ? [added] : [added, untracked]);
expect(tree.find((n) => n.group === "unversioned")?.files).toEqual(separate ? [untracked] : undefined);
const changes = buildChangeTree([added, untracked], "/r", false, undefined, [], false, {}, true, separate);
expect(changeFileNodes(changes).some((n) => n.path === added.path)).toBe(false);
expect(groupOf(untracked)).toBe("unversioned");
},
);
it.each([false, true])("can merge untracked files independently of staging grouping (%s)", (byStaging) => {
const tree = buildChangeTree(status, "/r", false, undefined, [], byStaging, {}, true, false);
expect(tree.some((n) => n.group === "unversioned")).toBe(false);
expect(tree.find((n) => n.group === "conflicts")?.files).toEqual([status[5]]);
const merged = tree.find((n) => n.group === (byStaging ? "unstaged" : "changes"))!;
const untracked = merged.children!.find((n) => n.path === status[4]!.path)!;
expect(untracked.kind).toBe("untracked");
expect(groupOf(untracked.files[0]!)).toBe("unversioned");
expect(checkOf(untracked.files[0]!, new Map())).toBe("none");
expect(ignoreTargets([merged], [])).toEqual([status[4]!.path]);
expect(planCommit(status, new Map()).included).not.toContain(status[4]);
if (byStaging) expect(tree.find((n) => n.group === "staged")!.files).not.toContain(status[4]);
});
it.each([false, true])("shows a repository containing only untracked files (%s)", (byStaging) => {
const tree = buildChangeTree([status[4]!], "/r", true, undefined, [], byStaging, {}, true, false);
expect(tree).toHaveLength(1);
expect(tree[0]!.group).toBe(byStaging ? "unstaged" : "changes");
expect(tree[0]!.files).toEqual([status[4]]);
});
it("merges into the same directory and repository as tracked changes", () => {
const tracked = fs("libs/core/src/App.kt", null, "modified");
const untracked = fs("libs/core/src/New.kt", null, "untracked");
const tree = buildChangeTree(
[status[0]!, tracked, untracked],
"/r",
true,
undefined,
["/r", "/r/libs/core"],
true,
{},
true,
false,
);
const repo = tree[0]!.children!.find((n) => n.path === "/r/libs/core")!;
expect(repo.files).toEqual([tracked, untracked]);
expect(shape(repo.children!)).toEqual(["src", " App.kt", " New.kt"]);
expect(ignoreTargets([repo], ["/r", "/r/libs/core"])).toEqual([untracked.path]);
});
it("displays untracked files in the active changelist without assigning them to it", () => {
const lists = {
active: "feature",
lists: [
{ id: "default", name: "Changes", comment: "" },
{ id: "feature", name: "Feature", comment: "" },
],
files: { "notes.txt": "default" },
};
const tree = buildChangeTree([status[4]!], "/r", false, lists, [], false, {}, true, false);
expect(tree.find((n) => n.changelist === "default")!.files).toEqual([]);
expect(tree.find((n) => n.changelist === "feature")!.files).toEqual([status[4]]);
expect(lists.files).toEqual({ "notes.txt": "default" });
expect(initialCheck(status[4]!)).toBe("none");
});
});
describe("several repositories", () => {
const nested = [...status, fs("libs/core/Lib.kt", null, "modified"), fs("libs/core/new.txt", null, "untracked")];
const repos = ["/r", "/r/libs/core"];
+29
Переглянути файл
@@ -0,0 +1,29 @@
import { afterEach, expect, it, vi } from "vitest";
import type { FileStatus } from "@/bindings";
import type { MenuItem } from "@/ui";
import { registerMenuGroup } from "@/workbench/contributions";
import type { ChangeNode } from "../changes";
const { nodeMenu } = await import("../CommitView");
const file = (rel: string, unstaged: FileStatus["unstaged"], staged: FileStatus["staged"] = null): ChangeNode => {
const f: FileStatus = { path: `/p/${rel}`, relPath: rel, staged, unstaged, renamedFrom: null };
return { key: f.path, type: "file", label: rel, group: "changes", files: [f], path: f.path };
};
let dispose: () => void = () => {};
afterEach(() => dispose());
it("adds other features' groups for the changed files still on disk", () => {
const items = vi.fn((_menu: string, { paths }: { paths: string[] }): MenuItem[] =>
paths.length ? [{ id: "deployment", label: "Deployment", submenu: [] }] : [],
);
dispose = registerMenuGroup({ id: "deployment", menus: ["changes"], items });
const labels = (menu: MenuItem[]) => menu.flatMap((i) => (i.kind !== "separator" && "label" in i ? [i.label] : []));
const menu = nodeMenu([file("a.txt", "modified"), file("gone.txt", "deleted"), file("new.txt", "untracked")], ["/p"]);
expect(items).toHaveBeenLastCalledWith("changes", { paths: ["/p/a.txt", "/p/new.txt"] });
expect(labels(menu)).toContain("Deployment");
expect(labels(nodeMenu([file("gone.txt", "deleted")], ["/p"]))).not.toContain("Deployment");
});
+59
Переглянути файл
@@ -0,0 +1,59 @@
import { afterEach, beforeEach, expect, it } from "vitest";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { useState } from "react";
import type { FileStatus } from "@/bindings";
import { FileChecklist } from "../shelf";
import { useVcs } from "../store";
const file = (rel: string): FileStatus => ({
path: `/repo/${rel}`,
relPath: rel,
staged: null,
unstaged: "modified",
renamedFrom: null,
});
const files = [
file("src/chat/web/ChatApiController.java"),
file("src/chat/web/ChatController.java"),
file("src/chat/config/AiConfig.java"),
file("pom.xml"),
];
function Harness() {
const [selected, setSelected] = useState<ReadonlySet<string>>(() => new Set(files.map((f) => f.path)));
return <FileChecklist files={files} selected={selected} onChange={setSelected} label="Files to shelve" />;
}
const box = (name: string) => screen.getByRole("checkbox", { name: `Include ${name}` });
beforeEach(() => useVcs.setState({ root: "/repo" }));
afterEach(cleanup);
it("groups the files by directory, merging single-child chains and counting files", () => {
render(<Harness />);
expect(screen.getByRole("tree", { name: "Files to shelve" })).toBeTruthy();
expect(screen.getByText("repo")).toBeTruthy();
expect(screen.getByText("4 files")).toBeTruthy();
expect(screen.getByText("src/chat")).toBeTruthy();
expect(screen.getByText("3 files")).toBeTruthy();
expect(screen.getByText("web")).toBeTruthy();
expect(screen.getByText("2 files")).toBeTruthy();
expect(box("pom.xml")).toBeChecked();
});
it("checks or clears a directory's files at once and shows a partly included one as mixed", () => {
render(<Harness />);
fireEvent.click(box("ChatController.java"));
expect(box("ChatController.java")).not.toBeChecked();
expect(box("web")).toHaveAttribute("aria-checked", "mixed");
expect(box("src/chat")).toHaveAttribute("aria-checked", "mixed");
expect(box("repo")).toHaveAttribute("aria-checked", "mixed");
fireEvent.click(box("web"));
expect(box("ChatController.java")).toBeChecked();
expect(box("web")).toHaveAttribute("aria-checked", "true");
fireEvent.click(box("src/chat"));
for (const name of ["ChatApiController.java", "ChatController.java", "AiConfig.java"])
expect(box(name)).not.toBeChecked();
expect(box("pom.xml")).toBeChecked();
});
+25 -2
Переглянути файл
@@ -3,7 +3,14 @@ import { act, fireEvent, render, screen, waitFor, cleanup } from "@testing-libra
import { afterEach } from "vitest";
import type { ShelvedChangeList } from "@/bindings";
const mocks = vi.hoisted(() => ({ openDiff: vi.fn(), execute: vi.fn(), ipc: vi.fn(), patch: vi.fn(), probe: vi.fn() }));
const mocks = vi.hoisted(() => ({
openDiff: vi.fn(),
execute: vi.fn(),
ipc: vi.fn(),
patch: vi.fn(),
probe: vi.fn(),
unshelve: vi.fn(),
}));
vi.mock("../diffInput", async (original) => ({
...(await original<typeof import("../diffInput")>()),
openDiff: mocks.openDiff,
@@ -22,7 +29,7 @@ vi.mock("@/platform/ipc", async (original) => ({
vcsShelfDiff: () => Promise.resolve(null),
fsProbe: mocks.probe,
vcsShelfPatch: mocks.patch,
vcsUnshelve: () => Promise.resolve(null),
vcsUnshelve: mocks.unshelve,
},
}));
import { ShelfPanel, copyShelfPatch, shelfDiffs, shelfTarget, showShelfDiff, unshelve, useShelf } from "../shelf";
@@ -166,6 +173,22 @@ describe("shelf scope and diffs", () => {
fireEvent.click(screen.getByRole("button", { name: "Unshelve" }));
await waitFor(() => expect(useChangelists.getState().state.files).toEqual({ [expected]: "target" }));
});
it("unshelves only the files left checked, one by one", async () => {
useChangelists.setState({
loaded: false,
state: { lists: [{ id: "target", name: "Target", comment: "" }], active: "target", files: {} },
});
mocks.ipc.mockReset().mockResolvedValue({ applied: [], conflicts: [] });
render(<VcsDialogHost />);
act(() => unshelve(entry));
expect(screen.getByRole("tree", { name: "Files to unshelve" })).toBeTruthy();
expect(screen.getAllByText("Added")).toHaveLength(2);
fireEvent.click(screen.getByRole("checkbox", { name: "Include b.txt" }));
expect(screen.getByRole("checkbox", { name: "Include repo" })).toHaveAttribute("aria-checked", "mixed");
fireEvent.click(screen.getByRole("button", { name: "Unshelve" }));
await waitFor(() => expect(mocks.unshelve).toHaveBeenCalledTimes(2));
expect(mocks.unshelve.mock.calls.map((c) => c[2])).toEqual(["a.txt", "binary.dat"]);
});
it("copies only the selected file patch through the scoped patch command", async () => {
const previous = Object.getOwnPropertyDescriptor(navigator, "clipboard");
const writeText = vi.fn().mockResolvedValue(undefined);
+121
Переглянути файл
@@ -0,0 +1,121 @@
import { act, fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return { ...real, call: vi.fn(async () => null) };
});
vi.mock("../DiffEditor", () => ({ DiffEditor: () => <div /> }));
import { call } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useContextMenuStore } from "@/ui/Menu";
import { ChangesTree } from "../CommitView";
import { initialChangelists, useChangelists } from "../changelists";
import { setShowUnversionedSeparately, useCommit } from "../commitStore";
import { useVcs } from "../store";
const label = "Show Unversioned Files Separately";
function toggleSeparate() {
fireEvent.click(screen.getByRole("button", { name: "View Options" }));
const item = useContextMenuStore.getState().menu!.items.find((i) => "label" in i && i.label === label);
expect(item).toMatchObject({ checked: useCommit.getState().showUnversionedSeparately });
act(() => {
(item as { run: () => void }).run();
useContextMenuStore.setState({ menu: null });
});
}
describe("unversioned grouping in View Options", () => {
beforeEach(() => {
vi.clearAllMocks();
localStorage.clear();
useCommit.setState({
groupByDir: false,
groupByStaging: false,
groupByRepo: true,
showUnversionedSeparately: true,
diffPreview: false,
commitDiffPreview: false,
checks: new Map(),
selection: [],
});
useChangelists.setState({ state: initialChangelists() });
useProject.setState({
project: { name: "p", root: "/p", trusted: true, isGit: true, settings: {} } as never,
settings: {} as never,
});
useVcs.setState({
root: "/p",
repo: "/p",
roots: ["/p"],
heads: {},
status: [
{ path: "/p/old.txt", relPath: "old.txt", staged: null, unstaged: "modified", renamedFrom: null },
{ path: "/p/new.txt", relPath: "new.txt", staged: null, unstaged: "untracked", renamedFrom: null },
],
});
});
it.each([false, true])("merges and separates without changing staging grouping (%s)", (groupByStaging) => {
useCommit.setState({ groupByStaging });
render(<ChangesTree mode="local" />);
expect(screen.getByText("Unversioned Files")).toBeTruthy();
toggleSeparate();
expect(screen.queryByText("Unversioned Files")).toBeNull();
expect(screen.getByText("new.txt")).toBeTruthy();
expect(screen.getByText(groupByStaging ? "Unstaged Changes" : "Changes")).toBeTruthy();
expect(useCommit.getState().groupByStaging).toBe(groupByStaging);
expect(localStorage.getItem("openidea.vcs.showUnversionedSeparately")).toBe("false");
expect(call).not.toHaveBeenCalled();
toggleSeparate();
expect(screen.getByText("Unversioned Files")).toBeTruthy();
expect(localStorage.getItem("openidea.vcs.showUnversionedSeparately")).toBe("true");
});
it("keeps merged untracked files unchecked in the Commit tool window", () => {
render(<ChangesTree mode="commit" />);
toggleSeparate();
const checkbox = screen.getByRole("checkbox", { name: "Include new.txt in commit" });
expect(checkbox.getAttribute("aria-checked")).toBe("false");
});
it("also merges untracked files when the Git staging area forces staging groups", () => {
useProject.setState({ settings: { vcs: { git: { stagingArea: true } } } as never });
render(<ChangesTree mode="commit" />);
toggleSeparate();
expect(screen.queryByText("Unversioned Files")).toBeNull();
expect(screen.getByText("Unstaged Changes")).toBeTruthy();
expect(screen.getByText("new.txt")).toBeTruthy();
expect(useCommit.getState().groupByStaging).toBe(false);
});
it("remembers the choice when remounting the tree", () => {
const view = render(<ChangesTree mode="local" />);
toggleSeparate();
view.unmount();
render(<ChangesTree mode="local" />);
expect(screen.queryByText("Unversioned Files")).toBeNull();
expect(screen.getByText("new.txt")).toBeTruthy();
});
});
describe("unversioned grouping persistence", () => {
beforeEach(() => {
localStorage.clear();
vi.resetModules();
});
it("starts on with no stored choice", async () => {
const { useCommit: fresh } = await import("../commitStore");
expect(fresh.getState().showUnversionedSeparately).toBe(true);
});
it("loads a disabled choice from storage", async () => {
setShowUnversionedSeparately(false);
const { useCommit: fresh } = await import("../commitStore");
expect(fresh.getState().showUnversionedSeparately).toBe(false);
});
});
+1
Переглянути файл
@@ -432,6 +432,7 @@ export function registerVcsActions(): () => void {
useCommit.getState().groupByStaging,
undefined,
useCommit.getState().groupByRepo,
useCommit.getState().showUnversionedSeparately,
);
// The modal interface has one front diff window (#1863): a file with its group
// as the F7 chain, or several selected files as the chain.
+6 -2
Переглянути файл
@@ -255,6 +255,8 @@ function tagList(nodes: ChangeNode[], id: string): ChangeNode[] {
* repositories (`repos`), each group's files are grouped by repository first, with
* each repository's branch (`heads`) beside its name, unless `byRepo` is off. With
* `byStaging`, "Changes" becomes "Staged Changes" and "Unstaged Changes" instead.
* Without `showUnversionedSeparately`, untracked files join Changes (the active list)
* or Unstaged Changes; their Git status and default commit inclusion stay unchanged.
*/
export function buildChangeTree(
status: readonly FileStatus[],
@@ -265,11 +267,13 @@ export function buildChangeTree(
byStaging = false,
heads: Readonly<Record<string, RepoHead>> = {},
byRepo = true,
showUnversionedSeparately = true,
): ChangeNode[] {
const repoRoots = byRepo ? repos : [];
const byGroup = new Map<GroupId, FileStatus[]>();
for (const fs of status) {
const g = groupOf(fs) ?? (byStaging && addedThenDeleted(fs) ? "changes" : null);
const kind = groupOf(fs) ?? (byStaging && addedThenDeleted(fs) ? "changes" : null);
const g = kind === "unversioned" && !showUnversionedSeparately ? "changes" : kind;
if (!g) continue;
let list = byGroup.get(g);
if (!list) byGroup.set(g, (list = []));
@@ -301,7 +305,7 @@ export function buildChangeTree(
if (g === "changes" && lists) {
const byList = new Map<string, FileStatus[]>(lists.lists.map((l) => [l.id, []]));
for (const f of files) {
const id = lists.files?.[relTo(root, stripSlash(f.path))];
const id = groupOf(f) === "unversioned" ? lists.active : lists.files?.[relTo(root, stripSlash(f.path))];
byList.get(id && byList.has(id) ? id : lists.active)?.push(f);
}
for (const l of lists.lists) {
+12
Переглянути файл
@@ -19,6 +19,8 @@ interface CommitState {
groupByStaging: boolean;
/** With several repositories, a node per repository above their files. */
groupByRepo: boolean;
/** Keep untracked files in their own group instead of Changes / Unstaged Changes. */
showUnversionedSeparately: boolean;
/** Whether the Git window's Local Changes tab previews the selection's diff. */
diffPreview: boolean;
/** Whether the Commit tool window previews the selection's diff beside the changes (#1599). */
@@ -57,6 +59,7 @@ export const useCommit = create<CommitState>(() => ({
groupByDir: readBool("openidea.vcs.groupByDir", false),
groupByStaging: readBool("openidea.vcs.groupByStaging", false),
groupByRepo: readBool("openidea.vcs.groupByRepo", true),
showUnversionedSeparately: readBool("openidea.vcs.showUnversionedSeparately", true),
diffPreview: readBool("openidea.vcs.diffPreview", true),
commitDiffPreview: readBool("openidea.vcs.commitDiffPreview", false),
checks: new Map(),
@@ -116,6 +119,15 @@ export function setGroupByRepo(v: boolean) {
}
}
export function setShowUnversionedSeparately(v: boolean) {
useCommit.setState({ showUnversionedSeparately: v });
try {
localStorage.setItem("openidea.vcs.showUnversionedSeparately", String(v));
} catch {
// ignore
}
}
export function setDiffPreview(v: boolean) {
useCommit.setState({ diffPreview: v });
try {
+17
Переглянути файл
@@ -78,6 +78,23 @@
overflow: hidden;
text-overflow: ellipsis;
}
/* Checkable changes tree in the Shelve / Create Patch dialogs. */
.fileTree {
display: flex;
height: 260px;
margin: 0 14px;
border: 1px solid var(--border);
border-radius: var(--radius-small);
}
.fileTreeView {
flex: 1;
min-width: 0;
}
.fileTreeRow {
composes: fileRow;
flex: 1;
padding: 0;
}
.grow {
flex: 1;
}
+149 -40
Переглянути файл
@@ -6,7 +6,7 @@
import { writeClipboardText } from "@/platform/clipboard";
import { useEffect, useMemo, useState, type MouseEvent } from "react";
import { create } from "zustand";
import type { ApplyOutcome, FileStatus, ShelvedChangeList, ShelfDiffFile } from "@/bindings";
import type { ApplyOutcome, ChangedFile, FileStatus, ShelvedChangeList, ShelfDiffFile } from "@/bindings";
import { setContext } from "@/platform/context";
import { shortcutLabel } from "@/platform/keymap";
import { openDiff, openVcsDiff, withChain, type DiffData } from "./diffInput";
@@ -17,11 +17,22 @@ import { workflowSettings } from "@/platform/workflowSettings";
import { Checkbox, Dialog, Icon, IconButton, Input, Select, Tree, fileIconName, showContextMenu, T } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { groupOf } from "./changes";
import { buildFileTree, dirKeys, type FileTreeNode } from "./fileTree";
import { activeList, listOf, moveFiles, relOf, updateChangelists, useChangelists } from "./changelists";
import { useCommit } from "./commitStore";
import { showLocalChanges } from "./commitUi";
import { confirmDialog, openDialog, promptText } from "./dialogs";
import { KIND_COLOR, baseName, dirName, effectiveKind, fileCount, formatTime, relTo, stripSlash } from "./model";
import {
KIND_COLOR,
KIND_LABEL,
baseName,
dirName,
effectiveKind,
fileCount,
formatTime,
relTo,
stripSlash,
} from "./model";
import { errorMessage, logConsole, runOp, saveAll } from "./ops";
import { conflictedFiles, currentRepo, refreshNow, useVcs } from "./store";
import { repositoryPath } from "./repositoryPaths";
@@ -88,7 +99,93 @@ export function shelveChanges(paths?: readonly string[]) {
openDialog((close) => <ShelveDialog files={files} initialName={name} onClose={close} />);
}
/** A checkable list of changed files (Shelve, Create Patch). */
/** Files of `node` and everything below it. */
function filesBelow<F>(node: FileTreeNode<F>, out: F[] = []): F[] {
if (node.file) out.push(node.file);
for (const child of node.children) filesBelow(child, out);
return out;
}
/**
* A checkable tree of changed files under the repository's node, grouped by directory (Shelve,
* Unshelve, Create Patch), as IDEA's changes tree: a directory's box checks or clears every file
* below it and shows a dash when only some are included.
*/
function ChangeChecklist<F>({
files,
keyOf,
relPath,
colorOf,
detailOf,
rootName,
selected,
onChange,
label,
}: {
files: readonly F[];
keyOf: (f: F) => string;
relPath: (f: F) => string;
colorOf: (f: F) => string | undefined;
/** Muted text after a file name, e.g. its change kind. */
detailOf?: (f: F) => string;
rootName: string;
selected: ReadonlySet<string>;
onChange: (next: Set<string>) => void;
label: string;
}) {
const tree: FileTreeNode<F>[] = [
{ key: "r:", name: rootName, file: null, children: buildFileTree(files, relPath), count: files.length },
];
const [expanded, setExpanded] = useState<ReadonlySet<string> | null>(null);
const toggle = (node: FileTreeNode<F>) => {
const below = filesBelow(node);
const include = !below.every((f) => selected.has(keyOf(f)));
const next = new Set(selected);
for (const f of below) {
if (include) next.add(keyOf(f));
else next.delete(keyOf(f));
}
onChange(next);
};
return (
<div className={styles.fileTree}>
<Tree<FileTreeNode<F>>
roots={tree}
getKey={(n) => n.key}
getLabel={(n) => n.name}
getChildren={(n) => (n.file ? undefined : n.children)}
isExpandable={(n) => !n.file}
expanded={expanded ?? new Set(dirKeys(tree))}
onExpandedChange={setExpanded}
onActivate={toggle}
aria-label={label}
className={styles.fileTreeView}
renderNode={(n) => {
const below = filesBelow(n);
const on = below.filter((f) => selected.has(keyOf(f))).length;
return (
<span className={styles.fileTreeRow}>
<Checkbox
tabIndex={-1}
aria-label={tx`Include ${n.name}`}
checked={on > 0 && on === below.length}
indeterminate={on > 0 && on < below.length}
onChange={() => toggle(n)}
/>
<Icon name={n.file ? fileIconName(n.name, relPath(n.file)) : "folder"} size={14} />
<span className={styles.fileName} style={{ color: n.file ? colorOf(n.file) : undefined }}>
{n.name}
</span>
<span className={styles.fileDir}>{n.file ? (detailOf?.(n.file) ?? "") : fileCount(n.count)}</span>
</span>
);
}}
/>
</div>
);
}
/** The checkable tree of working tree changes (Shelve, Create Patch). */
export function FileChecklist({
files,
selected,
@@ -102,33 +199,18 @@ export function FileChecklist({
}) {
const root = useVcs((s) => s.root) ?? "";
return (
<div className={styles.fileList} role="group" aria-label={label}>
{files.map((f) => {
const kind = effectiveKind(f) ?? "modified";
return (
<div key={f.path} className={styles.fileRow}>
<Checkbox
aria-label={tx`Include ${baseName(f.path)}`}
checked={selected.has(f.path)}
onChange={(v) => {
const n = new Set(selected);
if (v) n.add(f.path);
else n.delete(f.path);
onChange(n);
}}
/>
<Icon name={fileIconName(baseName(f.path), f.path)} size={14} />
<span className={styles.fileName} style={{ color: KIND_COLOR[kind] }}>
{baseName(stripSlash(f.path))}
</span>
<span className={styles.fileDir}>{dirName(relTo(root, stripSlash(f.path)))}</span>
</div>
);
})}
</div>
<ChangeChecklist
files={files}
keyOf={(f) => f.path}
relPath={(f) => relTo(root, stripSlash(f.path))}
colorOf={(f) => KIND_COLOR[effectiveKind(f) ?? "modified"]}
rootName={baseName(root)}
selected={selected}
onChange={onChange}
label={label}
/>
);
}
function ShelveDialog({
files,
initialName,
@@ -210,21 +292,39 @@ export function unshelve(entry: ShelvedChangeList, path?: string) {
openDialog((close) => <UnshelveDialog entry={entry} path={path} onClose={close} />);
}
/** Applies the shelved `paths` of `entry`: in one go when that is all of it, else file by file. */
async function unshelveFiles(entry: ShelvedChangeList, paths: readonly string[], remove: boolean) {
if (paths.length === entry.files.length) return call(commands.vcsUnshelve(entry.id, remove, null));
const outcome: ApplyOutcome = { applied: [], conflicts: [] };
for (const path of paths) {
const one = await call(commands.vcsUnshelve(entry.id, remove, path));
outcome.applied.push(...one.applied);
outcome.conflicts.push(...one.conflicts);
}
return outcome;
}
function UnshelveDialog({ entry, path, onClose }: { entry: ShelvedChangeList; path?: string; onClose: () => void }) {
const lists = useChangelists((s) => s.state);
const [target, setTarget] = useState(lists.active);
const [remove, setRemove] = useState(() => workflowSettings().vcs.shelf.removeApplied);
const repo = shelfRepository(entry);
const files = useMemo<ChangedFile[]>(() => {
if (path === undefined) return entry.files;
const own = entry.files.filter((f) => f.path === path);
return own.length ? own : [{ path, kind: "modified", oldPath: null }];
}, [entry, path]);
const [selected, setSelected] = useState<ReadonlySet<string>>(() => new Set(files.map((f) => f.path)));
const projectRoot = useVcs((s) => s.root);
const root = repo ?? projectRoot ?? "";
const run = async () => {
const chosen = files.filter((f) => selected.has(f.path)).map((f) => f.path);
if (!chosen.length) return;
onClose();
await saveAll();
const outcome = await runOp(
tx`Unshelve “${entry.name}”`,
() => call(commands.vcsUnshelve(entry.id, remove, path ?? null)),
{
refresh: false,
},
);
const outcome = await runOp(tx`Unshelve “${entry.name}”`, () => unshelveFiles(entry, chosen, remove), {
refresh: false,
});
if (!outcome) return;
await refreshNow();
const rels = [...outcome.applied, ...outcome.conflicts].map((p) => relOf(repositoryPath(repo, p)));
@@ -237,15 +337,24 @@ function UnshelveDialog({ entry, path, onClose }: { entry: ShelvedChangeList; pa
open
title="Unshelve Changes"
onClose={onClose}
width={480}
width={560}
buttons={[
{ label: "Unshelve", role: "default", autoFocus: true, onClick: () => void run() },
{ label: "Unshelve", role: "default", autoFocus: true, disabled: !selected.size, onClick: () => void run() },
{ label: "Cancel", role: "cancel" },
]}
>
<div className={styles.section}>
{path ?? entry.name} · {fileCount(path ? 1 : entry.files.length)}
</div>
<div className={styles.section}>{entry.name}</div>
<ChangeChecklist
files={files}
keyOf={(f) => f.path}
relPath={(f) => f.path}
colorOf={(f) => KIND_COLOR[f.kind === "untracked" ? "added" : f.kind]}
detailOf={(f) => tx(KIND_LABEL[f.kind === "untracked" ? "added" : f.kind])}
rootName={baseName(root)}
selected={selected}
onChange={setSelected}
label="Files to unshelve"
/>
<div className={styles.form}>
<label className={styles.fieldLabel}>
<T>Changelist:</T>
+1
Переглянути файл
@@ -1998,6 +1998,7 @@
"Foreign Keys": "Foreign Keys",
"Indexes": "Indexes",
"Columns": "Columns",
"Show Unversioned Files Separately": "Show Unversioned Files Separately",
"Add JDK from Disk…": "Add JDK from Disk…",
"Select Home Directory for JDK": "Select Home Directory for JDK",
"The selected directory is not a valid home for JDK: {path}": "The selected directory is not a valid home for JDK: {path}",
+2
Переглянути файл
@@ -1365,6 +1365,7 @@
"Files to include": "要包括的文件",
"Files to roll back": "要回滚的文件",
"Files to shelve": "要搁置的文件",
"Files to unshelve": "要取消搁置的文件",
"Files will be reverted to the state of the selected commit, but local changes will be kept intact.": "文件将还原到所选提交的状态,但本地更改将保持不变。",
"Files will be reverted to the state of the selected commit. Warning: any local changes will be lost.": "文件将还原到所选提交的状态。警告:所有本地更改都将丢失。",
"Files won't change, differences will be staged for commit.": "文件不会更改,差异将被暂存以供提交。",
@@ -8382,6 +8383,7 @@
"Different": "不同",
"Foreign Keys": "外键",
"Indexes": "索引",
"Show Unversioned Files Separately": "单独显示未跟踪文件",
"Add JDK from Disk…": "从磁盘添加 JDK…",
"Select Home Directory for JDK": "选择 JDK 主目录",
"The selected directory is not a valid home for JDK: {path}": "所选目录不是有效的 JDK 主目录:{path}",
+88
Переглянути файл
@@ -92,3 +92,91 @@ describe("TooltipHost", () => {
}
});
});
describe("TooltipHost on cut-off text", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
cleanup();
vi.useRealTimers();
});
/** jsdom lays nothing out: give `el` the widths a browser would. */
const widths = (el: HTMLElement, scroll: number, client: number) => {
Object.defineProperty(el, "scrollWidth", { configurable: true, value: scroll });
Object.defineProperty(el, "clientWidth", { configurable: true, value: client });
};
const hover = (el: Element) => {
fireEvent.pointerOver(el);
act(() => {
vi.advanceTimersByTime(TOOLTIP_DELAY);
});
return screen.queryByRole("tooltip")?.textContent ?? null;
};
it("shows the whole text only while it is cut off", () => {
render(
<>
<TooltipHost />
<div style={{ textOverflow: "ellipsis", overflow: "hidden" }} data-testid="row">
<span>origin/feature/REQ-126-明细汇总多选</span>
</div>
</>,
);
const row = screen.getByTestId("row");
widths(row, 300, 120);
expect(hover(row.firstElementChild!)).toBe("origin/feature/REQ-126-明细汇总多选");
fireEvent.pointerOut(row);
widths(row, 120, 120);
expect(hover(row.firstElementChild!)).toBeNull();
});
it("leaves text with a title alone, and text without an ellipsis; adds its own tooltip beside it", () => {
render(
<>
<TooltipHost />
<div style={{ textOverflow: "ellipsis" }} title="native" data-testid="titled">
long name
</div>
<div style={{ textOverflow: "clip" }} data-testid="clipped">
long name
</div>
<div style={{ textOverflow: "ellipsis" }} data-testid="own" {...tooltipAttrs("Own tooltip", undefined, true)}>
long name
</div>
</>,
);
for (const id of ["titled", "clipped", "own"]) widths(screen.getByTestId(id), 300, 120);
expect(hover(screen.getByTestId("titled"))).toBeNull();
expect(hover(screen.getByTestId("clipped"))).toBeNull();
expect(hover(screen.getByTestId("own"))).toBe("long nameOwn tooltip");
});
});
it("shows a tab's cut-off title whole, with the tab's own tooltip beside it", () => {
vi.useFakeTimers();
render(
<>
<TooltipHost />
<div role="tab" {...tooltipAttrs("/repo/src/history/PscPrinted.js", undefined, true)}>
<span style={{ textOverflow: "ellipsis" }} data-testid="label">
历史记录: PscPrinted.js
</span>
</div>
</>,
);
const label = screen.getByTestId("label");
Object.defineProperty(label, "scrollWidth", { configurable: true, value: 300 });
Object.defineProperty(label, "clientWidth", { configurable: true, value: 100 });
fireEvent.pointerOver(label);
act(() => {
vi.advanceTimersByTime(TOOLTIP_DELAY);
});
expect(screen.getByRole("tooltip").textContent).toBe("历史记录: PscPrinted.js/repo/src/history/PscPrinted.js");
cleanup();
vi.useRealTimers();
});
+43 -8
Переглянути файл
@@ -2,6 +2,9 @@
* Tooltips are attribute-driven: any element with `data-tooltip` (and optional
* `data-tooltip-shortcut`) gets one, shown by the single `<TooltipHost/>` after
* 600ms of hover. Hidden on scroll, key press, pointer down or leave.
*
* Text cut off with an ellipsis gets one too, showing it whole, while it is cut off and
* has no tooltip or `title` of its own.
*/
import { useEffect, useRef, useState } from "react";
import clsx from "clsx";
@@ -22,6 +25,34 @@ export function tooltipAttrs(text: string | undefined, shortcut?: string, verbat
return attrs;
}
/** How far up from the hovered node an ellipsised text is looked for. */
const TRUNCATED_DEPTH = 4;
/** The element whose text is cut off with an ellipsis around `node`, up to `stop`, if any. */
function truncatedText(node: Element | null, stop: Element | null): HTMLElement | null {
for (let el = node, depth = 0; el instanceof HTMLElement && depth < TRUNCATED_DEPTH; el = el.parentElement, depth++) {
// A native tooltip shows instead.
if (el.hasAttribute("title")) return null;
if (isTruncated(el)) return el;
if (el === stop) break;
}
return null;
}
const isTruncated = (el: HTMLElement) =>
el.scrollWidth > el.clientWidth && getComputedStyle(el).textOverflow === "ellipsis" && !!el.textContent?.trim();
/**
* What the tooltip of `el` shows: its own text, and the whole of `cut`'s text while that is
* cut off (with its own text beside it, when that says something else).
*/
function tooltipText(el: HTMLElement, cut: HTMLElement | null): { text: string; note?: string } | undefined {
const own = el.dataset.tooltipVerbatim === undefined ? tx(el.dataset.tooltip) : el.dataset.tooltip;
const whole = cut?.isConnected && isTruncated(cut) ? cut.textContent!.trim().replace(/\s+/g, " ") : undefined;
if (!whole) return own ? { text: own, note: el.dataset.tooltipShortcut } : undefined;
return { text: whole, note: own && !own.includes(whole) ? own : undefined };
}
interface Shown {
text: string;
shortcut?: string;
@@ -49,15 +80,15 @@ export function TooltipHost() {
setShown(null);
};
const show = (el: HTMLElement) => {
const text = el.dataset.tooltipVerbatim === undefined ? tx(el.dataset.tooltip) : el.dataset.tooltip;
if (!text || !el.isConnected) return;
const show = (el: HTMLElement, cut: HTMLElement | null) => {
const shows = el.isConnected ? tooltipText(el, cut) : undefined;
if (!shows) return;
visible = true;
anchorRef.current = el;
const stripe = el.dataset.tooltipStripe;
setShown({
text,
shortcut: el.dataset.tooltipShortcut,
text: shows.text,
shortcut: shows.note,
x: -9999,
y: -9999,
placed: false,
@@ -66,16 +97,20 @@ export function TooltipHost() {
};
const onOver = (e: PointerEvent) => {
const el = (e.target as Element | null)?.closest?.<HTMLElement>("[data-tooltip]");
const target = e.target as Element | null;
const owner = target?.closest?.<HTMLElement>("[data-tooltip]") ?? null;
// Cut-off text inside an element with a tooltip shows in that tooltip.
const cut = truncatedText(target, owner);
const el = owner ?? cut;
if (!el) return;
if (el === anchorRef.current) return;
clearTimeout(timer);
if (visible) {
show(el);
show(el, cut);
return;
}
const warm = performance.now() - lastHidden < WARM_MS;
timer = setTimeout(() => show(el), warm ? 0 : TOOLTIP_DELAY);
timer = setTimeout(() => show(el, cut), warm ? 0 : TOOLTIP_DELAY);
anchorRef.current = el;
};
+1
Переглянути файл
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24"><path fill="#4D6BFE" d="M23.748 4.651c-.254-.124-.364.113-.512.233c-.051.04-.094.09-.137.137c-.372.397-.806.657-1.373.626c-.829-.046-1.537.214-2.163.848c-.133-.782-.575-1.248-1.247-1.548c-.352-.155-.708-.311-.955-.65c-.172-.24-.219-.509-.305-.774c-.055-.16-.11-.323-.293-.35c-.2-.031-.278.136-.356.276c-.313.572-.434 1.202-.422 1.84c.027 1.436.633 2.58 1.838 3.393c.137.094.172.187.129.323c-.082.28-.18.553-.266.833c-.055.179-.137.218-.328.14a5.5 5.5 0 0 1-1.737-1.179c-.857-.828-1.631-1.743-2.597-2.46a12 12 0 0 0-.689-.47c-.985-.957.13-1.743.387-1.836c.27-.098.094-.433-.778-.428c-.872.003-1.67.295-2.687.685a3 3 0 0 1-.465.136a9.6 9.6 0 0 0-2.883-.101c-1.885.21-3.39 1.1-4.497 2.622C.082 8.776-.231 10.854.152 13.02c.403 2.284 1.568 4.175 3.36 5.653c1.857 1.533 3.997 2.284 6.438 2.14c1.482-.085 3.132-.284 4.994-1.86c.47.234.962.328 1.78.398c.629.058 1.235-.031 1.705-.129c.735-.155.684-.836.418-.961c-2.155-1.004-1.682-.595-2.112-.926c1.095-1.295 2.768-3.598 3.284-6.733c.05-.346.115-.834.108-1.114c-.004-.171.035-.238.23-.257a4.2 4.2 0 0 0 1.545-.475c1.397-.763 1.96-2.016 2.093-3.517c.02-.23-.004-.467-.247-.588M11.58 18.168c-2.088-1.642-3.101-2.183-3.52-2.16c-.39.024-.32.472-.234.763c.09.288.207.487.371.74c.114.167.192.416-.113.603c-.673.416-1.842-.14-1.897-.168c-1.361-.801-2.5-1.86-3.301-3.306c-.775-1.393-1.225-2.888-1.299-4.482c-.02-.385.094-.522.477-.592a4.7 4.7 0 0 1 1.53-.038c2.131.311 3.946 1.264 5.467 2.774c.868.86 1.525 1.887 2.202 2.89c.72 1.066 1.494 2.082 2.48 2.915c.348.291.626.513.892.677c-.802.09-2.14.109-3.055-.615zm1.001-6.44a.306.306 0 0 1 .415-.287a.3.3 0 0 1 .113.074a.3.3 0 0 1 .086.214c0 .17-.136.307-.308.307a.303.303 0 0 1-.306-.307m3.11 1.596c-.2.081-.4.151-.591.16a1.25 1.25 0 0 1-.798-.254c-.274-.23-.47-.358-.551-.758a1.7 1.7 0 0 1 .015-.588c.07-.327-.007-.537-.238-.727c-.188-.156-.426-.199-.689-.199a.6.6 0 0 1-.254-.078a.253.253 0 0 1-.114-.358a1 1 0 0 1 .192-.21c.356-.202.767-.136 1.146.016c.352.144.618.408 1.001.782c.392.451.462.576.685.915c.176.264.336.536.446.848c.066.194-.02.353-.25.45"/></svg>

Після

Ширина:  |  Висота:  |  Розмір: 2.1 KiB

+1
Переглянути файл
@@ -265,6 +265,7 @@ const ICONS = {
"agent-kiro": "openidea/agents/kiro",
"agent-vibe": "openidea/agents/vibe",
"agent-omp": "openidea/agents/omp",
"agent-deepseek-harness": "brands/deepseek",
"toolwindow-maven": "toolwindows/maven",
"toolwindow-gradle": "toolwindows/gradle",
"toolwindow-build": "toolwindows/build",
+1
Переглянути файл
@@ -1273,6 +1273,7 @@ export type ContextMenuId =
| "editor"
| "projectView"
| "editorTab"
| "changes"
| "problems"
| "searchResults"
| "editorGutter"