Merge remote-tracking branch 'origin/main' into fix/editor-breadcrumb-layout

Цей коміт міститься в:
l0ng-ai committed 2026-11-20 02:59:24 +08:00
коміт 3eff08d2f8
82 files changed
+2861 -379

No files matched your search

+2
Переглянути файл
@@ -89,6 +89,8 @@ pub enum IdeEvent {
DocDirty {
doc: DocId,
dirty: bool,
/// Text version when this transition occurred, including when it was saved.
version: u32,
},
/// A complete workspace edit can be undone as one operation.
WorkspaceEditApplied {
+16 -1
Переглянути файл
@@ -65,8 +65,23 @@ pub fn build_with_redirect(proxy: &ProxySettings, redirect: reqwest::redirect::P
/// The client for the current proxy settings, rebuilt when they change.
pub fn shared() -> IdeResult<reqwest::Client> {
static CLIENT: Mutex<Option<(Arc<ProxySettings>, reqwest::Client)>> = Mutex::new(None);
cached_client(&CLIENT, build)
}
/// The client the HTTP Client executes requests with: redirects off, `exec`
/// follows them by hand — that is what lets a `POST` stay a `POST` on a
/// 301/302 and puts the redirect chain into the response.
pub fn shared_without_redirects() -> IdeResult<reqwest::Client> {
static CLIENT: Mutex<Option<(Arc<ProxySettings>, reqwest::Client)>> = Mutex::new(None);
cached_client(&CLIENT, |proxy| build_with_redirect(proxy, reqwest::redirect::Policy::none()))
}
fn cached_client(
slot: &Mutex<Option<(Arc<ProxySettings>, reqwest::Client)>>,
build: fn(&ProxySettings) -> IdeResult<reqwest::Client>,
) -> IdeResult<reqwest::Client> {
let proxy = ide_core::proxy_settings::proxy();
let mut cached = CLIENT.lock();
let mut cached = slot.lock();
if let Some((settings, client)) = cached.as_ref()
&& **settings == *proxy
{
+288 -15
Переглянути файл
@@ -13,6 +13,19 @@ use std::time::Instant;
/// Bodies above this are cut (the full size is still reported).
pub const MAX_BODY: usize = 16 * 1024 * 1024;
/// Redirects followed per request; beyond this the redirect response itself is
/// returned (IntelliJ's HTTP Client follows the same number).
pub const MAX_REDIRECTS: usize = 50;
/// Responses whose `Location` is followed: 301, 302, 303, 307 and 308, the set
/// IntelliJ's HTTP Client redirects on.
const REDIRECT_STATUSES: [u16; 5] = [301, 302, 303, 307, 308];
/// Request headers not re-sent to a redirect on another host. IntelliJ's HTTP
/// Client strips the same set and restores it when the redirect stays on the
/// original host.
const SENSITIVE_HEADERS: [&str; 5] = ["authorization", "cookie", "cookie2", "www-authenticate", "proxy-authorization"];
/// A request ready to send: variables substituted, includes read.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
@@ -24,6 +37,15 @@ pub struct PreparedRequest {
pub body: Option<String>,
}
/// One followed redirect: the response and the `Location` it pointed to.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct RedirectHop {
pub status: u16,
pub status_text: String,
pub location: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct HttpResponse {
@@ -32,6 +54,9 @@ pub struct HttpResponse {
pub version: String,
pub headers: Vec<(String, String)>,
pub content_type: Option<String>,
/// Followed redirects, first hop first; empty when not redirected.
#[serde(default)]
pub redirects: Vec<RedirectHop>,
/// Body as text (lossy UTF-8); `None` for binary bodies.
pub body: Option<String>,
/// Size in bytes as received (after decompression).
@@ -128,25 +153,84 @@ fn looks_textual(content_type: Option<&str>, bytes: &[u8]) -> bool {
}
}
/// Sends `req`; cancelled when `cancel` fires.
/// The request for one hop: `req`'s headers and body against `url`, the
/// sensitive headers dropped when the redirect crosses to another host.
fn request_to(
client: &reqwest::Client,
method: &reqwest::Method,
req: &PreparedRequest,
body: Option<&str>,
original: &reqwest::Url,
url: &reqwest::Url,
) -> IdeResult<reqwest::Request> {
let same_host = url.host_str() == original.host_str();
let mut builder = client.request(method.clone(), url.clone());
for (k, v) in &req.headers {
if same_host || !SENSITIVE_HEADERS.iter().any(|s| k.eq_ignore_ascii_case(s)) {
builder = builder.header(k, v);
}
}
if let Some(body) = body {
builder = builder.body(body.to_owned());
}
builder.build().map_err(|e| IdeError::invalid(format!("invalid request: {e}")))
}
/// Sends `request`; cancelled when `cancel` fires.
async fn send(
client: &reqwest::Client,
request: reqwest::Request,
cancel: &CancellationToken,
) -> IdeResult<reqwest::Response> {
let send = client.execute(request);
tokio::select! {
r = send => r.map_err(|e| IdeError::new(ide_core::error::ErrorKind::Io, describe(&e))),
() = cancel.cancelled() => Err(IdeError::cancelled()),
}
}
/// Sends `req`, following redirects the way IntelliJ's HTTP Client does:
/// 301, 302, 303, 307 and 308 up to [`MAX_REDIRECTS`] times, `303` continuing
/// as `GET` without the body, the other statuses keeping the method and body —
/// so a `POST` redirected to `https` on the same host is re-sent as a `POST`.
/// Sensitive headers (Authorization, cookies, proxy credentials) are not
/// re-sent across hosts. The followed hops are reported in the response.
/// Cancelled when `cancel` fires.
pub async fn execute(req: &PreparedRequest, cancel: &CancellationToken) -> IdeResult<HttpResponse> {
let client = crate::client::shared()?;
let client = crate::client::shared_without_redirects()?;
let method = reqwest::Method::from_bytes(req.method.as_bytes())
.map_err(|_| IdeError::invalid(format!("invalid method {}", req.method)))?;
let mut builder = client.request(method, &req.url);
for (k, v) in &req.headers {
builder = builder.header(k, v);
}
if let Some(body) = &req.body {
builder = builder.body(body.clone());
}
let request = builder.build().map_err(|e| IdeError::invalid(format!("invalid request: {e}")))?;
let original = req.url.parse::<reqwest::Url>().map_err(|e| IdeError::invalid(format!("invalid request: {e}")))?;
let mut url = original.clone();
let mut method = method;
let mut body = req.body.clone();
let mut redirects = Vec::new();
let started = Instant::now();
let send = client.execute(request);
let mut response = tokio::select! {
r = send => r.map_err(|e| IdeError::new(ide_core::error::ErrorKind::Io, describe(&e)))?,
() = cancel.cancelled() => return Err(IdeError::cancelled()),
};
let mut response;
loop {
let request = request_to(&client, &method, req, body.as_deref(), &original, &url)?;
response = send(&client, request, cancel).await?;
let status = response.status();
if redirects.len() >= MAX_REDIRECTS || !REDIRECT_STATUSES.contains(&status.as_u16()) {
break;
}
let next = response
.headers()
.get(reqwest::header::LOCATION)
.and_then(|v| v.to_str().ok())
.and_then(|location| url.join(location).ok());
let Some(next) = next else { break };
redirects.push(RedirectHop {
status: status.as_u16(),
status_text: status.canonical_reason().unwrap_or("").to_owned(),
location: next.to_string(),
});
if status == reqwest::StatusCode::SEE_OTHER {
method = reqwest::Method::GET;
body = None;
}
url = next;
}
let ttfb = started.elapsed();
let status = response.status();
let version = format!("{:?}", response.version());
@@ -179,6 +263,7 @@ pub async fn execute(req: &PreparedRequest, cancel: &CancellationToken) -> IdeRe
version,
headers,
content_type,
redirects,
body,
size: size as f64,
truncated: size > bytes.len(),
@@ -249,6 +334,47 @@ mod tests {
assert_eq!(url("GET https://api.test/cb?u=http://x\n"), "https://api.test/cb?u=http://x");
}
/// A loopback server answering each accepted connection with the next of
/// `responses`, returning every request as its head and body.
async fn scripted(responses: Vec<String>) -> (u16, tokio::task::JoinHandle<Vec<(String, String)>>) {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let handle = tokio::spawn(async move {
let mut seen = Vec::new();
for response in responses {
let (mut socket, _) = listener.accept().await.unwrap();
let mut request = Vec::new();
let (head, body) = loop {
let mut buffer = [0u8; 4096];
let read = socket.read(&mut buffer).await.unwrap();
assert!(read > 0, "request ended before its body");
request.extend_from_slice(&buffer[..read]);
let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") else { continue };
let head = String::from_utf8_lossy(&request[..end]).into_owned();
let length: usize = head
.lines()
.find_map(|line| {
let (name, value) = line.split_once(':')?;
name.eq_ignore_ascii_case("content-length").then(|| value.trim().parse().unwrap())
})
.unwrap_or(0);
if request.len() >= end + 4 + length {
break (head, String::from_utf8_lossy(&request[end + 4..end + 4 + length]).into_owned());
}
};
seen.push((head, body));
socket.write_all(response.as_bytes()).await.unwrap();
}
seen
});
(port, handle)
}
fn response(status_line: &str, headers: &str, body: &str) -> String {
format!("HTTP/1.1 {status_line}\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len())
}
#[tokio::test]
async fn sends_exact_environment_numbers_to_a_local_server() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
@@ -341,6 +467,7 @@ mod tests {
assert_eq!(r.status_text, "Created");
assert_eq!(r.body.as_deref(), Some("{\"ok\":true}"));
assert!(r.headers.iter().any(|(k, v)| k == "x-a" && v == "b"));
assert!(r.redirects.is_empty());
assert!(r.total_ms >= r.ttfb_ms);
}
@@ -369,4 +496,150 @@ mod tests {
let err = execute(&req, &cancel).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
}
#[tokio::test]
async fn post_keeps_method_and_body_on_301_302_307_308() {
for status_line in ["301 Moved Permanently", "302 Found", "307 Temporary Redirect", "308 Permanent Redirect"] {
let status: u16 = status_line[..3].parse().unwrap();
let (port, server) =
scripted(vec![response(status_line, "Location: /landing\r\n", ""), response("200 OK", "", "ok")]).await;
let req = PreparedRequest {
name: None,
method: "POST".into(),
url: format!("http://127.0.0.1:{port}/submit"),
headers: vec![("Content-Type".into(), "application/json".into())],
body: Some("{\"a\":1}".into()),
};
let r = execute(&req, &CancellationToken::new()).await.unwrap();
let seen = server.await.unwrap();
let (head, body) = &seen[1];
assert_eq!(head.lines().next().unwrap(), "POST /landing HTTP/1.1", "{status_line}");
assert!(head.to_ascii_lowercase().contains("content-type: application/json"), "{head}");
assert_eq!(body, "{\"a\":1}", "{status_line}");
assert_eq!(r.status, 200, "{status_line}");
assert_eq!(r.body.as_deref(), Some("ok"), "{status_line}");
assert_eq!(
r.redirects,
vec![RedirectHop {
status,
status_text: status_line[4..].to_owned(),
location: format!("http://127.0.0.1:{port}/landing"),
}],
"{status_line}"
);
}
}
#[tokio::test]
async fn see_other_303_resends_as_get_without_the_body() {
let (port, server) =
scripted(vec![response("303 See Other", "Location: /after\r\n", ""), response("200 OK", "", "done")]).await;
let req = PreparedRequest {
name: None,
method: "POST".into(),
url: format!("http://127.0.0.1:{port}/submit"),
headers: vec![],
body: Some("{\"a\":1}".into()),
};
let r = execute(&req, &CancellationToken::new()).await.unwrap();
let seen = server.await.unwrap();
assert_eq!(seen[1].0.lines().next().unwrap(), "GET /after HTTP/1.1");
assert_eq!(seen[1].1, "");
assert_eq!(r.status, 200);
assert_eq!(r.body.as_deref(), Some("done"));
assert_eq!(r.redirects[0].status, 303);
}
#[tokio::test]
async fn same_host_redirect_keeps_authorization() {
let (port, server) = scripted(vec![
response("301 Moved Permanently", "Location: /landing\r\n", ""),
response("200 OK", "", "ok"),
])
.await;
let req = PreparedRequest {
name: None,
method: "GET".into(),
url: format!("http://127.0.0.1:{port}/start"),
headers: vec![("Authorization".into(), "Bearer secret".into())],
body: None,
};
execute(&req, &CancellationToken::new()).await.unwrap();
let seen = server.await.unwrap();
assert!(seen[1].0.to_ascii_lowercase().contains("authorization: bearer secret"), "{}", seen[1].0);
}
#[tokio::test]
async fn cross_host_redirect_keeps_the_method_but_drops_authorization() {
let (port_b, server_b) = scripted(vec![response("200 OK", "", "moved")]).await;
let (port_a, server_a) = scripted(vec![response(
"301 Moved Permanently",
&format!("Location: http://127.0.0.1:{port_b}/x\r\n"),
"",
)])
.await;
let req = PreparedRequest {
name: None,
method: "POST".into(),
url: format!("http://localhost:{port_a}/start"),
headers: vec![("Authorization".into(), "Bearer secret".into())],
body: Some("{\"a\":1}".into()),
};
let r = execute(&req, &CancellationToken::new()).await.unwrap();
let seen_a = server_a.await.unwrap();
let seen_b = server_b.await.unwrap();
assert!(seen_a[0].0.to_ascii_lowercase().contains("authorization: bearer secret"), "{}", seen_a[0].0);
assert_eq!(seen_b[0].0.lines().next().unwrap(), "POST /x HTTP/1.1");
assert!(!seen_b[0].0.to_ascii_lowercase().contains("authorization"), "{}", seen_b[0].0);
assert_eq!(seen_b[0].1, "{\"a\":1}");
assert_eq!(r.status, 200);
assert_eq!(r.body.as_deref(), Some("moved"));
assert_eq!(r.redirects.len(), 1);
}
#[tokio::test]
async fn redirects_beyond_the_limit_return_the_last_redirect_response() {
let responses = vec![response("301 Moved Permanently", "Location: /loop\r\n", ""); MAX_REDIRECTS + 1];
let (port, server) = scripted(responses).await;
let req = PreparedRequest {
name: None,
method: "GET".into(),
url: format!("http://127.0.0.1:{port}/start"),
headers: vec![],
body: None,
};
let r = execute(&req, &CancellationToken::new()).await.unwrap();
let seen = server.await.unwrap();
assert_eq!(r.status, 301);
assert_eq!(r.status_text, "Moved Permanently");
assert_eq!(r.redirects.len(), MAX_REDIRECTS);
assert_eq!(seen.len(), MAX_REDIRECTS + 1);
}
#[tokio::test]
async fn redirect_chain_is_recorded_across_hops() {
let (port, server) = scripted(vec![
response("302 Found", "Location: /b\r\n", ""),
response("302 Found", "Location: /c\r\n", ""),
response("200 OK", "", "end"),
])
.await;
let req = PreparedRequest {
name: None,
method: "GET".into(),
url: format!("http://127.0.0.1:{port}/a"),
headers: vec![],
body: None,
};
let r = execute(&req, &CancellationToken::new()).await.unwrap();
let seen = server.await.unwrap();
assert_eq!(r.status, 200);
assert_eq!(r.body.as_deref(), Some("end"));
assert_eq!(r.redirects.len(), 2);
assert_eq!(r.redirects[0].status, 302);
assert_eq!(r.redirects[0].location, format!("http://127.0.0.1:{port}/b"));
assert_eq!(r.redirects[1].status, 302);
assert_eq!(r.redirects[1].location, format!("http://127.0.0.1:{port}/c"));
assert_eq!(seen[2].0.lines().next().unwrap(), "GET /c HTTP/1.1");
}
}
+1 -1
Переглянути файл
@@ -672,7 +672,7 @@ impl Documents {
fn set_dirty(&self, doc: DocId, st: &mut DocState, dirty: bool) {
if st.dirty != dirty {
st.dirty = dirty;
self.sink.emit(IdeEvent::DocDirty { doc, dirty });
self.sink.emit(IdeEvent::DocDirty { doc, dirty, version: st.doc.version() });
}
}
+113
Переглянути файл
@@ -228,6 +228,109 @@ fn dirty_events(events: &[IdeEvent]) -> Vec<bool> {
events.iter().filter_map(|e| if let IdeEvent::DocDirty { dirty, .. } = e { Some(*dirty) } else { None }).collect()
}
fn assert_failed_save_preserves_edit(f: &Fixture, doc: DocId, text: &str, before: usize) {
let snapshot = f.docs.snapshot(doc).unwrap();
assert!(snapshot.dirty, "failed save marked the document clean");
assert_eq!(snapshot.text, text, "failed save changed the unsaved buffer");
assert!(!dirty_events(&f.events.lock()[before..]).contains(&false), "failed save emitted a clean-state event");
}
#[test]
fn unencodable_save_preserves_the_dirty_buffer_and_disk_bytes() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, b"caf\xe9").unwrap();
let doc = f.docs.open(&path).unwrap().id;
assert_eq!(f.docs.set_encoding(doc, "windows-1252", true).unwrap().encoding, "windows-1252");
let reloaded = f.docs.snapshot(doc).unwrap();
assert_eq!(reloaded.text, "café");
f.docs.edit(doc, reloaded.version, change(4, 4, "漢")).unwrap();
let original = fs::read(&path).unwrap();
let before = f.events.lock().len();
let err = f.docs.save(doc).expect_err("Windows-1252 cannot encode the edit");
assert_eq!(err.kind, ErrorKind::InvalidInput, "{err}");
assert_failed_save_preserves_edit(&f, doc, "café漢", before);
assert_eq!(fs::read(&path).unwrap(), original, "failed encoding changed disk bytes");
}
#[cfg(unix)]
#[test]
fn permission_denied_save_preserves_the_edit_and_can_be_retried() {
use std::os::unix::fs::PermissionsExt;
struct RestorePermissions<'a>(&'a Path, fs::Permissions);
impl Drop for RestorePermissions<'_> {
fn drop(&mut self) {
let result = fs::set_permissions(self.0, self.1.clone());
if !std::thread::panicking() {
result.expect("restore fixture permissions");
}
}
}
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, b"original").unwrap();
let doc = f.docs.open(&path).unwrap().id;
f.docs.edit(doc, 0, change(0, 8, "edited")).unwrap();
{
let _dir_permissions = RestorePermissions(&f.root, fs::metadata(&f.root).unwrap().permissions());
let _file_permissions = RestorePermissions(&path, fs::metadata(&path).unwrap().permissions());
// Deny both sibling temp-file creation and the fallback write to the existing file.
fs::set_permissions(&path, fs::Permissions::from_mode(0o444)).unwrap();
fs::set_permissions(&f.root, fs::Permissions::from_mode(0o555)).unwrap();
let sibling = fs::OpenOptions::new().write(true).create_new(true).open(f.root.join("probe"));
let in_place = fs::OpenOptions::new().write(true).open(&path);
for (probe, access) in [(sibling, "create a sibling file"), (in_place, "open the target for writing")] {
match probe {
Ok(_) => {
eprintln!("skipping permission-denied save: test process can {access} despite permission bits");
return;
}
Err(err) => assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied, "{access}: {err}"),
}
}
let before = f.events.lock().len();
let err = f.docs.save(doc).expect_err("neither atomic nor in-place save should be writable");
assert_eq!(err.kind, ErrorKind::PermissionDenied, "{err}");
assert_failed_save_preserves_edit(&f, doc, "edited", before);
assert_eq!(fs::read(&path).unwrap(), b"original", "failed write changed disk bytes");
}
let before = f.events.lock().len();
f.docs.save(doc).expect("retry after restoring file and directory permissions");
assert_eq!(fs::read(&path).unwrap(), b"edited");
assert!(!f.docs.snapshot(doc).unwrap().dirty, "successful retry left the document dirty");
assert_eq!(dirty_events(&f.events.lock()[before..]), vec![false]);
}
#[test]
fn save_to_a_path_replaced_by_a_directory_preserves_the_dirty_buffer() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, b"original").unwrap();
let doc = f.docs.open(&path).unwrap().id;
f.docs.edit(doc, 0, change(0, 8, "edited")).unwrap();
assert!(f.docs.snapshot(doc).unwrap().dirty);
fs::remove_file(&path).unwrap();
fs::create_dir(&path).unwrap();
let before = f.events.lock().len();
f.docs.save(doc).expect_err("save must not replace a directory with a file");
assert_failed_save_preserves_edit(&f, doc, "edited", before);
assert!(fs::symlink_metadata(&path).unwrap().is_dir(), "save removed the replacement directory");
assert_eq!(fs::read_dir(&path).unwrap().count(), 0, "save left artifacts inside the replacement directory");
assert_eq!(fs::read_dir(&f.root).unwrap().count(), 1, "save left artifacts beside the replacement directory");
}
#[test]
fn autosave_leaves_a_file_changed_on_disk_after_an_edit() {
let f = fixture();
@@ -249,6 +352,16 @@ fn autosave_leaves_a_file_changed_on_disk_after_an_edit() {
f.docs.edit(info.id, 1, change(0, 0, "x")).unwrap();
assert!(f.docs.autosave(info.id).unwrap());
assert_eq!(fs::read_to_string(&path).unwrap(), "xedited\nbeta\n");
let transitions: Vec<_> = f
.events
.lock()
.iter()
.filter_map(|event| match event {
IdeEvent::DocDirty { doc, dirty, version } if *doc == info.id => Some((*version, *dirty)),
_ => None,
})
.collect();
assert_eq!(transitions, [(1, true), (1, false), (2, true), (2, false)]);
}
#[test]
+2
Переглянути файл
@@ -136,6 +136,8 @@ With tabs placed left or right, the tab column is as wide as its longest name, u
As in IntelliJ IDEA, there is no per-file save: files are saved when you switch to another application or to the built-in terminal, and **File › Save All** (`⌘S` / `Ctrl+S`) saves everything at once. **Settings › Appearance & Behavior › System Settings**, section **Autosave**, can also save after the IDE has been idle for a while.
If you keep typing during a save, edits not included in that write stay marked as unsaved.
Changes made outside the IDE are picked up when you switch back to its window. **Reload from Disk** (`⌥⌘Y` / `Ctrl+Alt+Y`) reloads the current file now.
## Related
+4 -2
Переглянути файл
@@ -111,7 +111,7 @@ The toolbar has **Stop Request**, **Reload History** and **Clear History**. The
- HTTP/1.1 and HTTP/2. gzip, deflate and brotli responses are decoded.
- TLS certificates are verified against the system trust store.
- Redirects are followed.
- Redirects are followed (up to 50): a 303 continues as GET without the body, other redirects keep the method and body, and the hops are shown in the response.
- Cookies are not kept between requests.
- Connections time out after 30 seconds; there is no overall request timeout.
- The proxy comes from **Settings › Appearance & Behavior › System Settings › HTTP Proxy**.
@@ -135,7 +135,9 @@ In Java and Kotlin `@FeignClient` interfaces, click the **Go to Feign Endpoint**
The built-in index matches HTTP methods and literal paths, including whole `{variable}` segments. A literal Feign `name` or `value` narrows candidates against an unambiguous `spring.application.name` in the destination module's `src/main/resources/application.properties`, `.yml` or `.yaml` (also under `resources/config`). Configuration is never inherited from a parent module or test sources. Conflicting profile names, dynamic or missing identities, and clients with explicit/dynamic `url` retain method/path candidates. No HTTP request is sent.
This is source navigation, not service-discovery or effective runtime configuration resolution. Custom source sets, composed/aliased annotations, inherited mappings, dynamic mapping paths, `@RequestLine`, Ant/regex path patterns and reverse controller-to-client navigation are outside this first version. Navigation reads bounded local configuration and rechecks current controller text, including unsaved editor changes.
To see which Feign interfaces declare a request to a Spring endpoint, open the endpoint’s gutter menu and choose **Find Feign Clients**. You can also invoke the action from the editor menu or Find Action with the caret in the controller method. A single service match opens directly. When several clients match, the chooser shows each interface method and its source path. Clients whose service cannot be established appear below known matches as **Possible match**, even when only one is found. A client known to target another service is excluded.
Navigation reads local source and module configuration, including unsaved editor changes. Custom source sets, composed or aliased annotations, inherited mappings, dynamic mapping paths, `@RequestLine`, Ant/regex path patterns, and runtime service discovery are outside its scope.
## Not supported
+2
Переглянути файл
@@ -155,6 +155,8 @@ When a project loads and unloads:
**Open now** lists the loaded projects, each with what it is doing (answering a request, kept open by a run, or how long it has been idle and when it unloads) and an **Unload** button. Unloading does not wait for **Apply**. The project loads again on the next tool call that names it, if the setting still serves it.
While any project is loaded, the **Background Projects** item in the status bar (a layers icon and the count) opens the same list. Each row has the **Open in New Window** and **Unload** icon buttons, and below the list are **Unload All** and **MCP Server Settings…**.
What trust decides: a trusted project works as one open in a window, with its language servers and the tools that write. A listed folder you have not trusted opens in Restricted Mode and gets only the read-only tools.
A background project has no window, so some tools differ:
+2
Переглянути файл
@@ -136,6 +136,8 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
和 IntelliJ IDEA 一样,这里没有逐个文件保存的概念:切换到其他应用或内置终端时文件会自动保存,**文件 › 全部保存**(`⌘S` / `Ctrl+S`)立即保存所有文件。**设置 › 外观与行为 › 系统设置** 的 **自动保存** 一节还可以设置在 IDE 空闲一段时间后保存。
如果在保存期间继续编辑,未写入磁盘的改动仍会标记为未保存。
在 IDE 之外修改的文件,会在切回 IDE 窗口时同步。**从磁盘重新加载**(`⌥⌘Y` / `Ctrl+Alt+Y`)立即重新加载当前文件。
## 相关页面
+4 -2
Переглянути файл
@@ -111,7 +111,7 @@ OpenIDEA 会从请求文件所在目录开始,逐级向上查找到项目根
- 支持 HTTP/1.1 和 HTTP/2,自动解码 gzip、deflate 和 brotli。
- TLS 证书按系统信任库校验。
- 自动跟随重定向。
- 自动跟随重定向(最多 50 次):303 之后以不带请求体的 GET 继续,其余重定向保留方法与请求体,并在响应中显示跳转链。
- 请求之间不保留 Cookie。
- 连接超时为 30 秒,没有整体请求超时。
- 代理使用 **设置 › 外观与行为 › 系统设置 › HTTP 代理** 中的配置。
@@ -135,7 +135,9 @@ OpenIDEA 会为 Java 和 Kotlin 中的 Spring Web 端点(带 `@RequestMapping`
内置索引按 HTTP 方法和字面量路径匹配控制器,支持完整的 `{variable}` 路径段。Feign 的字面量 `name` 或 `value` 会与目标模块 `src/main/resources` 或其 `config` 子目录中 `application.properties`、`.yml`、`.yaml` 的明确 `spring.application.name` 比较。不会继承父模块或测试资源的配置。配置身份缺失、动态或有冲突,以及客户端指定显式或动态 `url` 时,仍保留方法和路径匹配的候选。导航不会发送 HTTP 请求。
这是源码导航,不解析服务发现或运行时生效配置。首个版本不支持自定义源码目录、组合或别名注解、继承映射、动态路径、`@RequestLine`、Ant/正则路径模式及控制器到客户端的反向导航。配置读取有数量和大小限制;跳转前会重新检查当前控制器文本,包括未保存的编辑。
要查看哪些 Feign 接口声明了对 Spring 端点的请求,请打开端点的装订线菜单并选择**查找 Feign 客户端**。光标位于控制器方法中时,也可以从编辑器菜单或查找操作中执行。只有一个服务匹配时会直接打开该声明。多个结果会列出各接口方法及其源码路径。无法确认目标服务的客户端排在已知匹配之后,并标为**可能匹配**,即便只有一个候选也会显示选择器。明确指向其他服务的客户端会被排除。
导航读取本地源码和模块配置,包括未保存的修改。暂不支持自定义源码目录、组合或别名注解、继承映射、动态映射路径、`@RequestLine`、Ant/正则路径模式和运行时服务发现。
## 暂不支持
+2
Переглянути файл
@@ -154,6 +154,8 @@ stdio 配置大致如下(路径以你机器上的为准):
**当前已打开** 列出已加载的项目,每个项目显示它正在做什么(正在处理请求、因某个运行保持打开,或已空闲多久以及何时卸载),并带有 **卸载** 按钮。卸载不必等到 **应用**。如果设置仍然提供该项目,下一次指向它的工具调用会再次加载它。
只要有项目处于加载状态,状态栏中的 **后台项目**(层叠图标和数量)就会打开同样的列表。每一行有 **在新窗口中打开** 和 **卸载** 两个图标按钮,列表下方是 **全部卸载** 和 **MCP 服务器设置…**。
信任决定什么:受信任的项目与在窗口中打开的项目一样,可以使用语言服务器和会写入的工具。你没有信任的列出文件夹会以受限模式打开,只开放只读工具。
后台项目没有窗口,所以有些工具不同:
+40 -2
Переглянути файл
@@ -6,6 +6,9 @@ import type { Page } from "@playwright/test";
import { expect, stubDesktop, test } from "./fixtures";
const ROOT = "/dev/acme-api";
const NESTED_REF = "teams/payments/reporting/month-end/exports/regions/europe/accounting/invoice-export";
const TRACKING_REF = "origin/releases/payments/month-end/reconciliation/invoice-export";
const BRANCH_FIXTURE = { root: ROOT, ref: NESTED_REF, upstream: TRACKING_REF };
async function openBranches(page: Page) {
await page.evaluate(async () => {
@@ -22,7 +25,7 @@ async function openBranches(page: Page) {
test.beforeEach(async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async (root) => {
await page.evaluate(async ({ root, ref, upstream }) => {
const h = window.__ipc.handlers;
const branch = (name: string, current = false) => ({
name,
@@ -47,6 +50,7 @@ test.beforeEach(async ({ workbench: page }) => {
h.vcs_tags = () => [];
h.vcs_branches = () => [
branch("main", true),
{ ...branch(ref), upstream, ahead: 2, behind: 3 },
...Array.from({ length: 40 }, (_, i) => branch(`task-${i}-a-long-branch-name-that-gets-cut-off`)),
];
const vcsModule = "/src/features/vcs/store.ts";
@@ -54,7 +58,41 @@ test.beforeEach(async ({ workbench: page }) => {
useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false });
await refreshNow();
await loadBranches();
}, ROOT);
}, BRANCH_FIXTURE);
});
test("narrow Git Branches keeps a deeply nested branch and its controls readable", async ({ workbench: page }) => {
await page.evaluate(() => {
localStorage.setItem("openidea.vcs.branchesPopup.size", JSON.stringify({ w: 280, h: 420 }));
});
const popup = await openBranches(page);
const search = popup.getByRole("textbox", { name: "Search branches and actions" });
await search.fill("invoice-export");
const row = popup.getByRole("option", { name: /invoice-export/ });
await expect(row).toBeVisible();
const name = row.locator("[class*=branchName]");
const tracking = row.getByText(TRACKING_REF, { exact: true });
const chevron = row.locator("svg").last();
const folder = popup.getByRole("option", { name: "accounting", exact: true });
const rowBox = (await row.boundingBox())!;
const nameBox = (await name.boundingBox())!;
const trackingBox = (await tracking.boundingBox())!;
const chevronBox = (await chevron.boundingBox())!;
const indent = (option: typeof row) =>
option.locator("[data-row-key]").evaluate((el) => parseFloat(getComputedStyle(el).paddingInlineStart));
expect(await indent(row)).toBeGreaterThan(await indent(folder));
expect(chevronBox.x + chevronBox.width).toBeLessThanOrEqual(rowBox.x + rowBox.width);
expect(nameBox.width).toBeGreaterThan(42);
expect(trackingBox.width).toBeGreaterThan(12);
expect(trackingBox.width).toBeLessThan(rowBox.width * 0.4);
await expect(name).toHaveCSS("font-size", "13px");
await expect(tracking).toHaveCSS("font-size", "13px");
await expect(row.getByRole("img", { name: "3 incoming commits" })).toBeVisible();
await expect(row.getByRole("img", { name: "2 outgoing commits" })).toBeVisible();
await expect(row.locator("[data-row-key]")).toHaveAttribute("title", NESTED_REF);
await expect(tracking).toHaveAttribute("title", TRACKING_REF);
await chevron.click();
await expect(page.getByRole("menu", { name: `Branch ${NESTED_REF}` })).toBeVisible();
});
test("Git Branches resizes by its corner and right edge and reopens at that size", async ({ workbench: page }) => {
+99
Переглянути файл
@@ -0,0 +1,99 @@
import type { Page } from "@playwright/test";
import type { BuildModel, BuildTool } from "../src/platform/ipc";
import { expect, stubDesktop, test } from "./fixtures";
const model: BuildModel = {
maven: {
projects: [
{
pom: "pom.xml",
dir: "",
groupId: "com.example",
artifactId: "orders",
version: "1.0.0",
packaging: "jar",
displayName: "Orders service",
parent: null,
modules: [],
aggregated: false,
plugins: [],
dependencies: [],
profiles: [],
javaVersion: 21,
command: "mvn",
options: [],
env: {},
},
],
profiles: [],
syncedAt: 1,
stale: false,
syncError: null,
},
gradle: [
{
dir: "",
command: "gradle",
env: {},
javaVersion: 21,
syncedAt: 1,
stale: false,
syncError: null,
projects: [{ path: ":", name: "orders", dir: "", buildFile: "build.gradle", tasks: [] }],
},
],
};
async function showTool(page: Page, tool: BuildTool) {
await stubDesktop(page);
await page.evaluate(
async ({ tool, model }) => {
window.__ipc.handlers.build_model = () => model;
window.__ipc.handlers.run_configs = () => [];
const buildStore = "/src/features/build-tools/store.ts";
await (await import(/* @vite-ignore */ buildStore)).loadModel();
const layout = "/src/workbench/toolwindows/store.ts";
const { setToolWindowSize, showToolWindow } = await import(/* @vite-ignore */ layout);
showToolWindow(tool, true);
setToolWindowSize("right", 190);
},
{ tool, model },
);
}
async function setWidth(page: Page, width: number) {
await page.evaluate(async (px) => {
const layout = "/src/workbench/toolwindows/store.ts";
(await import(/* @vite-ignore */ layout)).setToolWindowSize("right", px);
}, width);
}
for (const tool of ["maven", "gradle"] as const) {
const name = tool === "maven" ? "Maven" : "Gradle";
test(`${name} keeps its toolbar actions reachable as the pane resizes`, async ({ workbench: page }) => {
await showTool(page, tool);
const toolbar = page.getByRole("toolbar", { name: `${name} actions` });
const more = toolbar.getByRole("button", { name: "More Actions", exact: true });
const menu = page.getByRole("menu", { name: "More Actions", exact: true });
const skipTests = "Toggle 'Skip Tests' Mode";
await expect(toolbar.getByRole("button", { name: `Reload All ${name} Projects` })).toBeVisible();
await expect(toolbar.getByRole("button", { name: new RegExp(`Execute ${name}`) })).toBeVisible();
await expect(page.getByRole("tree", { name: `${name} projects` })).toBeVisible();
expect(await toolbar.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await more.click();
await expect(menu.getByRole("menuitem", { name: "Analyze Dependencies…" })).toBeVisible();
await expect(menu.getByRole("menuitem", { name: "Expand All" })).toBeVisible();
await menu.getByRole("menuitemcheckbox", { name: skipTests, checked: false }).click();
await expect(menu).toBeHidden();
await more.click();
await expect(menu.getByRole("menuitemcheckbox", { name: skipTests, checked: true })).toBeVisible();
await setWidth(page, 360);
await expect(menu).toBeHidden();
await expect(more).toBeHidden();
await expect(toolbar.getByRole("button", { name: skipTests, pressed: true })).toBeVisible();
await expect(toolbar.getByRole("button", { name: "Collapse All" })).toBeVisible();
await setWidth(page, 190);
await expect(more).toBeVisible();
await expect(menu).toBeHidden();
});
}
+161
Переглянути файл
@@ -65,6 +65,7 @@ test("completion lists the server's items and inserts the chosen one", async ({
const popup = page.locator(".cm-tooltip-autocomplete");
await expect(popup.getByText("total", { exact: true })).toBeVisible();
await expect(popup.getByText("toDto", { exact: true })).toBeVisible();
expect((await popup.boundingBox())!.width).toBeLessThan(360);
const field = popup.locator("li").filter({ has: page.locator(".cm-completionLabel", { hasText: /^total$/ }) });
await expect(field.locator(".cm-completionDetail")).toHaveCount(0);
await expect(field.locator(".cm-lsp-type")).toHaveText("BigDecimal");
@@ -83,6 +84,17 @@ test("completion lists the server's items and inserts the chosen one", async ({
const label = await method.locator(".cm-completionLabel").boundingBox();
// Subpixel rounding differs per platform/font; a mis-set inset is a whole icon column off.
expect(Math.abs(label!.x - wordStart)).toBeLessThanOrEqual(2);
const zoomedSize = await editor.locator(".cm-content").evaluate(async (content) => {
const viewModule = "/node_modules/.vite/deps/@codemirror_view.js";
const prefsModule = "/src/editor/core/cm/prefs.ts";
const { EditorView } = await import(/* @vite-ignore */ viewModule);
const { stepFontZoom } = await import(/* @vite-ignore */ prefsModule);
const fontSize = Number.parseFloat(getComputedStyle(content).fontSize);
stepFontZoom(EditorView.findFromDOM(content as HTMLElement)!, 6);
return `${fontSize + 6}px`;
});
await expect(editor.locator(".cm-content")).toHaveCSS("font-size", zoomedSize);
await expect(method.locator(".cm-completionLabel")).toHaveCSS("font-size", zoomedSize);
await page.keyboard.type("toD");
await expect(popup.getByText("total", { exact: true })).toBeHidden();
// Refreshing the results rebuilds the list; the hint bar must stay below it, not jump to the top.
@@ -98,6 +110,76 @@ test("completion lists the server's items and inserts the chosen one", async ({
expect((await ipcCalls(page, "lsp_completion")).length).toBeGreaterThan(0);
});
test("long completion signatures fit the editor when the workbench is narrowed", async ({ workbench: page }) => {
const editor = await openSample(page);
const label = "transformOrder" + "AcrossParticipatingRegions".repeat(5);
await page.evaluate((label) => {
const item: CompletionItem = {
label,
labelDetail: "(order: Order, options: TransformationOptions)",
labelDescription: "Promise<TransformationResult>",
detail: `${label}(order: Order, options: TransformationOptions): Promise<TransformationResult>`,
kind: "method",
documentation: { kind: "markdown", value: "Transforms the order." },
sortText: null,
filterText: null,
preselect: true,
deprecated: false,
insertText: `${label}()`,
isSnippet: false,
replaceRange: null,
replaceRangeTab: null,
additionalEdits: [],
commitCharacters: [],
command: null,
data: null,
server: 1,
};
window.__ipc.handlers.lsp_completion = () => ({ isIncomplete: false, items: [item] });
}, label);
await editor.locator(".cm-line", { hasText: "return order.toDto()" }).click();
await page.keyboard.press("End");
await page.keyboard.press("Enter");
await page.keyboard.type("order.");
await page.keyboard.press("Control+Space");
const popup = page.locator(".cm-tooltip-autocomplete");
const option = popup.getByRole("option").filter({
has: page.locator(".cm-completionLabel", { hasText: label }),
});
await expect(option.locator(".cm-completionLabel")).toHaveText(label);
await page.setViewportSize({ width: 580, height: 900 });
const bounds = (await editor.boundingBox())!;
await expect
.poll(async () => {
const box = (await popup.boundingBox())!;
return Math.max(bounds.x - box.x, box.x + box.width - (bounds.x + bounds.width));
})
.toBeLessThanOrEqual(2);
const geometry = await option.evaluate((row) => {
const label = row.querySelector<HTMLElement>(".cm-completionLabel")!;
const type = row.querySelector<HTMLElement>(".cm-lsp-type")!;
return {
nameTruncated: label.scrollWidth > label.clientWidth,
nameWidth: label.clientWidth,
typeWidth: type.clientWidth,
typeOverflow: type.getBoundingClientRect().right - row.getBoundingClientRect().right,
};
});
expect(geometry.nameTruncated).toBe(true);
expect(geometry.nameWidth).toBeGreaterThan(40);
expect(geometry.typeWidth).toBeGreaterThan(16);
expect(geometry.typeOverflow).toBeLessThanOrEqual(1);
await page.keyboard.press("F1");
await expect(popup.locator(".cm-completionInfo")).toContainText(
`${label}(order: Order, options: TransformationOptions)`,
);
await page.keyboard.press("Enter");
await expect(popup).toBeHidden();
await expect(editor.locator(".cm-activeLine")).toContainText(`order.${label}()`);
});
test("documentation shows beside the lookup instead of being clipped by it", async ({ workbench: page }, info) => {
const editor = await openSample(page);
await page.evaluate(async () => {
@@ -416,6 +498,85 @@ test("indexed single-file rename previews all anchors and applies only after con
expect(apply.edit).toMatchObject({ preconditions: [{ path: FILE, hash: "indexed-snapshot" }] });
});
test("intention previews fit narrow windows and wrap long code lines", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1600, height: 900 });
const editor = await openSample(page);
await page.evaluate(async () => {
const path = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ path);
const { settings } = useProject.getState();
useProject.setState({ settings: { ...settings, editor: { ...settings?.editor, fontSize: 16 } } });
});
await expect(editor.locator(".cm-content")).toHaveCSS("font-size", "16px");
const replacement = "com.acme.orders." + "SharedDevelopmentOrderModel".repeat(6);
await page.evaluate(
({ file, replacement, edit }) => {
window.__ipc.handlers.lsp_code_actions = () => [
{
title: "Replace Order with the fully qualified shared development order model",
kind: "quickfix",
isPreferred: true,
disabledReason: null,
edit: { files: [{ kind: "edit", path: file, edits: [{ range: edit, new_text: replacement }] }] },
command: null,
data: null,
server: 1,
},
...Array.from({ length: 11 }, (_, i) => ({
title: `Create alternative Order model ${i + 1}`,
kind: "quickfix",
isPreferred: false,
disabledReason: null,
edit: null,
command: null,
data: null,
server: 1,
})),
];
window.__ipc.handlers.lsp_execute_code_action = () => [];
},
{ file: FILE, replacement, edit: range(20, 19, 24) },
);
await caretAt(editor, page, "val order: Order", "Order ");
await page.keyboard.press("Alt+Enter");
const popup = page.getByRole("dialog", { name: "Intentions", exact: true });
const options = popup.getByRole("listbox", { name: "Intentions" });
const preview = popup.locator('[aria-label="Preview"]');
await expect(preview.locator("pre")).toContainText(replacement);
const wide = (await options.boundingBox())!;
const widePreview = (await preview.boundingBox())!;
expect(widePreview.x).toBeGreaterThanOrEqual(wide.x + wide.width - 1);
await page.setViewportSize({ width: 1050, height: 900 });
await expect
.poll(async () => {
const list = (await options.boundingBox())!;
const code = (await preview.boundingBox())!;
return code.x + code.width - list.x;
})
.toBeLessThanOrEqual(1);
await page.setViewportSize({ width: 520, height: 540 });
await expect
.poll(async () => {
const menu = (await popup.boundingBox())!;
const list = (await options.boundingBox())!;
const code = (await preview.boundingBox())!;
return {
popupFits: menu.x >= 0 && menu.y >= 0 && menu.x + menu.width <= 521 && menu.y + menu.height <= 541,
previewBelow: code.y >= list.y + list.height - 1,
previewFits: code.x >= menu.x && code.x + code.width <= menu.x + menu.width + 1,
};
})
.toEqual({ popupFits: true, previewBelow: true, previewFits: true });
expect(await preview.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
await expect(preview.locator("pre")).toHaveCSS("font-size", "16px");
await expect(options).toBeFocused();
await page.keyboard.press("Enter");
await expect(popup).toBeHidden();
await expect.poll(() => ipcCalls(page, "lsp_execute_code_action")).toHaveLength(1);
});
test("diagnostics underline the range and ⌥⏎ applies the preferred quick fix", async ({ workbench: page }) => {
const editor = await openSample(page);
await page.evaluate(
+110 -6
Переглянути файл
@@ -2,13 +2,10 @@ import { expect, stubDesktop, test } from "./fixtures";
test.use({ video: "on" });
test("Feign navigation selects the named service and offers ambiguous source targets", async ({
workbench: page,
}, testInfo) => {
test.beforeEach(async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
const backend = "/src/editor/core/backend.ts";
const contributions = "/src/workbench/contributions.ts";
const { docBackend } = await import(backend);
const files: Map<string, string> = docBackend().files;
const root = "/dev/acme-api";
@@ -37,7 +34,9 @@ class UserController {
files.set(`${root}/${service}/src/main/resources/application.properties`, `spring.application.name=${service}\n`);
}
window.__ipc.handlers.spring_route_sources = () =>
[...files].filter(([p]) => p.endsWith("UserController.java")).map(([path, text]) => ({ path, text }));
[...files]
.filter(([path, text]) => /\.(java|kt)$/.test(path) && text.includes("Mapping"))
.map(([path, text]) => ({ path, text }));
window.__ipc.handlers.fs_read_text = ({ path }) => {
if (!files.has(String(path))) throw { kind: "notFound", message: "No fixture file" };
return files.get(String(path));
@@ -60,7 +59,21 @@ class UserController {
hidden: false,
}));
window.__ipc.handlers.lsp_goto = () => [];
await (await import(contributions)).editorService().openFile(`${root}/client/src/main/java/UserClient.java`);
window.__ipc.handlers.fs_probe = ({ path }) => ({
size: files.get(String(path))?.length ?? 0,
binary: false,
tooLarge: false,
});
window.__ipc.handlers.find_files = () => [];
});
});
test("Feign navigation selects the named service and offers ambiguous source targets", async ({
workbench: page,
}, testInfo) => {
await page.evaluate(async () => {
const contributions = "/src/workbench/contributions.ts";
await (await import(contributions)).editorService().openFile("/dev/acme-api/client/src/main/java/UserClient.java");
});
await expect(page.locator(".cm-content").last()).toContainText("@FeignClient");
await page.screenshot({ path: testInfo.outputPath("feign-source.png"), animations: "disabled" });
@@ -111,3 +124,94 @@ class UserController {
await declarations.getByRole("option").filter({ hasText: "admin/" }).click();
await expect(page.locator(".cm-content").last()).toContainText('return "admin"');
});
test("a Spring endpoint lists Feign clients by module and flags unresolved services", async ({
workbench: page,
}, testInfo) => {
await page.evaluate(async () => {
const backend = "/src/editor/core/backend.ts";
const contributions = "/src/workbench/contributions.ts";
const files: Map<string, string> = (await import(backend)).docBackend().files;
const root = "/dev/acme-api";
const original = `${root}/client/src/main/java/UserClient.java`;
const template = files.get(original)!;
files.delete(original);
for (const [module, type, service] of [
["orders", "OrderUsers", "users"],
["admin-ui", "AdminUsers", "admin"],
["gateway", "GatewayUsers", "${SERVICE}"],
] as const) {
files.set(
`${root}/${module}/src/main/java/${type}.java`,
template.replace("UserClient", type).replace('"users"', `"${service}"`),
);
}
files.set(
`${root}/billing/src/main/kotlin/BillingUsers.kt`,
`package shop
import org.springframework.cloud.openfeign.FeignClient
import org.springframework.web.bind.annotation.GetMapping
@FeignClient("users")
interface BillingUsers {
@GetMapping("/users/{userId}")
fun find(): String
}`,
);
await (await import(contributions)).editorService().openFile(`${root}/users/src/main/java/UserController.java`);
});
await page.locator('[data-icon-source="spring"][title="GET /users/{id}"]').click();
await expect(page.getByRole("menuitem", { name: "Generate Request in HTTP Client" })).toBeVisible();
await page.screenshot({ path: testInfo.outputPath("controller-menu.png"), animations: "disabled" });
await page.getByRole("menuitem", { name: "Find Feign Clients" }).click({ timeout: 5_000 });
const picker = page.getByRole("dialog", { name: "Feign Clients" });
const rows = picker.getByRole("option");
await expect(rows).toHaveCount(3);
await expect(rows.nth(0)).toContainText("BillingUsers.find");
await expect(rows.nth(0)).toContainText("billing");
await expect(rows.nth(1)).toContainText("OrderUsers.find");
await expect(rows.nth(1)).toContainText("orders");
await expect(rows.nth(2)).toContainText("GatewayUsers.find");
await expect(rows.nth(2)).toContainText("Possible match");
await page.screenshot({ path: testInfo.outputPath("feign-clients.png"), animations: "disabled" });
await rows.nth(0).click();
await expect(page.locator(".cm-content").last()).toContainText("interface BillingUsers");
});
test("one possible client requires a choice and a changed workspace invalidates that choice", async ({
workbench: page,
}) => {
await page.evaluate(async () => {
const backend = "/src/editor/core/backend.ts";
const api = "/src/editor/api.ts";
const actions = "/src/platform/actions.ts";
const contributions = "/src/workbench/contributions.ts";
const root = "/dev/acme-api";
const files: Map<string, string> = (await import(backend)).docBackend().files;
files.set(`${root}/users/src/main/resources/application.properties`, "spring.application.name=${SERVICE}");
await (await import(contributions)).editorService().openFile(`${root}/users/src/main/java/UserController.java`);
const view = (await import(api)).activeEditor().view;
view.dispatch({ selection: { anchor: view.state.doc.toString().indexOf("return") } });
await (await import(actions)).executeAction("http.findFeignClients");
});
const picker = page.getByRole("dialog", { name: "Feign Clients" });
const candidate = picker.getByRole("option");
await expect(candidate).toHaveCount(1);
await expect(candidate).toContainText("Possible match");
await page.evaluate(async () => {
const backend = "/src/editor/core/backend.ts";
const ipc = "/src/platform/ipc.ts";
const path = "/dev/acme-api/users/src/main/resources/application.properties";
(await import(backend)).docBackend().files.set(path, "spring.application.name=users");
(await import(ipc)).emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [path], removed: [] });
});
await candidate.click();
await expect(picker).not.toBeVisible();
await expect(page.locator(".cm-content").last()).toContainText("class UserController");
await page.evaluate(async () => {
const actions = "/src/platform/actions.ts";
await (await import(actions)).executeAction("http.findFeignClients");
});
await expect(page.locator(".cm-content").last()).toContainText("interface UserClient");
});
+73
Переглянути файл
@@ -0,0 +1,73 @@
import type { Page } from "@playwright/test";
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
async function quickDocumentation(page: Page, markdown: string) {
const editor = await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate((value) => {
window.__ipc.handlers.lsp_hover = () => ({ contents: { kind: "markdown", value }, range: null });
}, markdown);
const line = editor.locator(".cm-line", { hasText: "return order.toDto()" });
await line.click();
await page.keyboard.press("End");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("ArrowLeft");
await page.keyboard.press("F1");
const popup = page.getByRole("dialog", { name: "Documentation", exact: true });
await expect(popup.locator(".cm-lsp-markdown")).toBeVisible();
return popup;
}
test("short quick documentation uses a readable width and a compact corner of actions", async ({ workbench: page }) => {
const popup = await quickDocumentation(page, "Returns the total.");
const back = popup.getByRole("button", { name: "Back", exact: true });
const dock = popup.getByRole("button", { name: "Show in Documentation Tool Window" });
await expect(dock).toBeVisible();
const bounds = (await popup.boundingBox())!;
expect(bounds.width).toBeGreaterThanOrEqual(298);
expect(bounds.width).toBeLessThan(320);
const backBounds = (await back.boundingBox())!;
const dockBounds = (await dock.boundingBox())!;
expect(backBounds.x).toBeGreaterThan(bounds.x + bounds.width / 2);
expect(bounds.x + bounds.width - dockBounds.x - dockBounds.width).toBeLessThan(16);
await expect(popup.locator(".cm-lsp-markdown")).toHaveCSS("font-size", "13px");
await page.keyboard.press("Escape");
await expect(popup).toBeHidden();
});
test("long quick documentation scrolls with its actions in view", async ({ workbench: page }) => {
const signature = "fun calculateTotal(order: Order, options: ExtendedPricingOptions): CalculationResult";
const markdown = [
`\`\`\`kotlin\n${signature}\n\`\`\``,
...Array.from({ length: 22 }, (_, i) => {
return `Section ${i + 1}. Explains the applicable pricing rules, shipping restrictions and currency options.`;
}),
"End of pricing documentation.",
].join("\n\n");
const popup = await quickDocumentation(page, markdown);
const dock = popup.getByRole("button", { name: "Show in Documentation Tool Window" });
await expect(dock).toBeVisible();
expect((await popup.boundingBox())!.width).toBeLessThan(508);
await page.setViewportSize({ width: 430, height: 500 });
await expect
.poll(async () => {
const box = (await popup.boundingBox())!;
return Math.max(-box.x, -box.y, box.x + box.width - 430, box.y + box.height - 500);
})
.toBeLessThanOrEqual(1);
const body = popup.locator(".cm-lsp-markdown").locator("..");
const last = popup.getByText("End of pricing documentation.");
const dockBefore = (await dock.boundingBox())!;
await expect(body.locator("pre")).toContainText(signature);
const scroll = await body.evaluate((node) => {
node.scrollTop = node.scrollHeight;
return { top: node.scrollTop, horizontalOverflow: node.scrollWidth - node.clientWidth };
});
expect(scroll.top).toBeGreaterThan(0);
expect(scroll.horizontalOverflow).toBeLessThanOrEqual(1);
const lastBounds = (await last.boundingBox())!;
expect(lastBounds.y + lastBounds.height).toBeLessThanOrEqual(dockBefore.y + 1);
expect(await dock.boundingBox()).toEqual(dockBefore);
await expect(dock).toBeInViewport();
});
+25 -3
Переглянути файл
@@ -1,8 +1,8 @@
import type { Page } from "@playwright/test";
import { expect, test } from "./fixtures";
async function openConfigurations(page: Page) {
await page.evaluate(async () => {
async function openConfigurations(page: Page, target?: string) {
await page.evaluate(async (target) => {
const path = "/src/features/run/store.ts";
const { useRun } = await import(/* @vite-ignore */ path);
const base = {
@@ -21,6 +21,7 @@ async function openConfigurations(page: Page) {
...base,
id: "layout:app",
name: "Payments development server",
target,
beforeLaunch: [{ kind: "run", target: "layout:prepare" }],
},
{ ...base, id: "layout:prepare", name: "Prepare generated sources for the payments development server" },
@@ -29,10 +30,31 @@ async function openConfigurations(page: Page) {
loaded: true,
editorOpen: true,
});
});
}, target);
await expect(page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true })).toBeVisible();
}
test("long run target names leave room for configuration names in the sidebar", async ({ workbench: page }) => {
const target = "payments-development-shared-staging-runner-west";
await openConfigurations(page, target);
const dialog = page.getByRole("dialog", { name: "Run/Debug Configurations", exact: true });
const tree = dialog.getByRole("tree", { name: "Run configurations", exact: true });
const row = tree.getByRole("treeitem", { name: /^Payments development server/ });
const name = row.getByText("Payments development server", { exact: true });
const badge = row.getByText(`@ ${target}`, { exact: true });
await expect(badge).toBeVisible();
for (const width of [1100, 520]) {
await page.setViewportSize({ width, height: 820 });
await expect.poll(async () => (await name.boundingBox())!.width).toBeGreaterThan(width === 1100 ? 80 : 50);
await expect.poll(() => tree.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
}
await expect(badge).toBeHidden();
await expect(row).toHaveAttribute("title", new RegExp(`Payments development server @ ${target}`));
await expect(dialog.getByRole("textbox", { name: "Name", exact: true })).toHaveValue("Payments development server");
});
test("run configuration sidebar resizes with mouse and keyboard and remembers the layout", async ({
workbench: page,
}) => {
+64
Переглянути файл
@@ -60,6 +60,70 @@ for (const { width, split } of [{ width: 220 }, { width: 280 }, { width: 520 },
});
}
test("wide terminal search leaves the grid in place and avoids covering the active match", async ({
workbench: page,
}) => {
await page.evaluate(async () => {
const path = "/src/workbench/toolwindows/store.ts";
const layout = await import(path);
layout.setToolWindowSize("bottom", 280);
layout.showToolWindow("terminal", true);
});
const terminal = page.getByRole("region", { name: "Terminal", exact: true });
await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused();
const panel = terminal.getByRole("tabpanel");
const before = (await panel.boundingBox())!;
await page.evaluate(async () => {
const path = "/src/features/terminal/runtime.ts";
const { activeSession } = await import(path);
const { term } = activeSession();
await new Promise<void>((resolve) =>
term.write(`\x1b[2J\x1b[1;${term.cols - 16}Hright-edge\x1b[1;2Hleft-side\x1b[6;1H`, resolve),
);
});
await page.keyboard.press("Meta+f");
const search = terminal.getByRole("search", { name: "Find in terminal" });
const input = search.getByRole("textbox", { name: "Find in terminal" });
await expect(input).toBeFocused();
expect(await panel.boundingBox()).toEqual(before);
const top = (await search.boundingBox())!;
expect(top.y).toBeCloseTo(before.y, 0);
expect(top.x + top.width).toBeCloseTo(before.x + before.width, 0);
expect(top.width).toBeLessThan(before.width);
await input.fill("right-edge");
await expect(search.locator("[aria-live=polite]")).toHaveText("1/1");
await expect
.poll(async () => {
const box = (await search.boundingBox())!;
return box.y + box.height;
})
.toBeCloseTo(before.y + before.height, 0);
await expect(input).toBeFocused();
expect(await panel.boundingBox()).toEqual(before);
await input.fill("left-side");
await expect(search.locator("[aria-live=polite]")).toHaveText("1/1");
await expect.poll(async () => (await search.boundingBox())!.y).toBeCloseTo(before.y, 0);
await page.evaluate(async () => {
const path = "/src/workbench/toolwindows/store.ts";
const { setToolWindowSize } = await import(path);
setToolWindowSize("bottom", 130);
});
await expect
.poll(async () => {
const box = (await search.boundingBox())!;
return box.y + box.height - (await panel.boundingBox())!.y;
})
.toBeCloseTo(0, 0);
await expect(input).toHaveValue("left-side");
await page.keyboard.press("Escape");
await expect(search).toBeHidden();
await expect(terminal.locator(".xterm-helper-textarea")).toBeFocused();
});
test("terminal highlights visible occurrences of selected text in a single overlay layer", async ({
workbench: page,
}) => {
+12 -1
Переглянути файл
@@ -6974,6 +6974,8 @@ export type HttpResponse = {
version: string,
headers: ([string, string])[],
contentType: string | null,
/** Followed redirects, first hop first; empty when not redirected. */
redirects?: RedirectHop[],
/** Body as text (lossy UTF-8); `None` for binary bodies. */
body: string | null,
/** Size in bytes as received (after decompression). */
@@ -7043,7 +7045,9 @@ ignoreRules?: IpcPath[] } |
/** Part of a grouped transaction; the editor must not record a file-local undo. */
workspaceEdit?: boolean } |
/** A document's dirty flag changed (saved / modified externally). */
{ type: "docDirty"; doc: DocId; dirty: boolean } |
{ type: "docDirty"; doc: DocId; dirty: boolean;
/** Text version when this transition occurred, including when it was saved. */
version: number } |
/** A complete workspace edit can be undone as one operation. */
{ type: "workspaceEditApplied"; id: number; paths: IpcPath[];
/**
@@ -10315,6 +10319,13 @@ export type RecentProjectGroup = {
expanded?: boolean,
};
/** One followed redirect: the response and the `Location` it pointed to. */
export type RedirectHop = {
status: number,
statusText: string,
location: string,
};
export type RefactoringProblem = {
severity: ProblemSeverity,
message: string,
+7 -3
Переглянути файл
@@ -16,6 +16,7 @@ import {
type DocumentInfo,
type DocumentLanguage,
type FoldRange,
type IdeEvent,
type LanguageInfo_Serialize,
type LineEnding,
type OutlineItem,
@@ -38,6 +39,8 @@ export interface DocPatchedEvent {
changes: TextChange[];
}
export type DocDirtyEvent = Extract<IdeEvent, { type: "docDirty" }>;
export interface DocBackend {
open(path: string): Promise<DocumentInfo>;
/** Opens a read-only language-server document (library or disk class contents). */
@@ -71,7 +74,7 @@ export interface DocBackend {
*/
languageOf?(path: string, firstLine?: string): Promise<DocumentLanguage>;
onPatched(handler: (e: DocPatchedEvent) => void): () => void;
onDirty(handler: (e: { doc: DocId; dirty: boolean }) => void): () => void;
onDirty(handler: (e: DocDirtyEvent) => void): () => void;
/** Files changed on disk (used to refresh nothing but closed-file state). */
onFsChanged?(handler: (e: { removed: string[] }) => void): () => void;
/**
@@ -393,7 +396,7 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
const docs = new Map<DocId, MemDoc>();
const byPath = new Map<string, DocId>();
const patched = new Set<(e: DocPatchedEvent) => void>();
const dirtyHandlers = new Set<(e: { doc: DocId; dirty: boolean }) => void>();
const dirtyHandlers = new Set<(e: DocDirtyEvent) => void>();
let nextId = 1;
const store = new Map(Object.entries(files));
const savedBoms = new Map<string, boolean>();
@@ -442,7 +445,8 @@ export function createMemoryBackend(files: Record<string, string> = {}): MemoryB
};
const setDirty = (d: MemDoc, before: boolean) => {
const now = d.text !== d.saved || d.hasBom !== d.savedBom;
if (now !== before) dirtyHandlers.forEach((h) => h({ doc: d.id, dirty: now }));
if (now !== before)
dirtyHandlers.forEach((h) => h({ type: "docDirty", doc: d.id, dirty: now, version: d.version }));
};
const delay = <T>(v: () => T): Promise<T> =>
backend.latency > 0
+168
Переглянути файл
@@ -30,6 +30,14 @@ async function settle() {
for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0));
}
function deferred() {
let resolve!: () => void;
const promise = new Promise<void>((done) => {
resolve = done;
});
return { promise, resolve };
}
function setup(files: Record<string, string>, settings = {}) {
_resetLanguages();
const backend: MemoryBackend = createMemoryBackend(files);
@@ -217,6 +225,166 @@ describe("DocumentManager + slots", () => {
expect(useDocMeta.getState()["/p/a.txt"]?.dirty).toBe(false);
});
it.each(["dirty before response", "dirty after response", "clean and dirty after response"] as const)(
"keeps a newer edit dirty with %s",
async (order) => {
const path = "/p/a.txt";
const { backend, manager } = setup({ [path]: "base\n" }, { files: { autoSave: false } });
const model = await manager.acquire(path);
const slot = new EditorSlot(model, "t1", host);
const events: Array<() => void> = [];
const originalOnDirty = backend.onDirty.bind(backend);
let deferDirty = false;
const onDirty = vi.spyOn(backend, "onDirty").mockImplementation((handler) =>
originalOnDirty((event) => {
if (deferDirty) events.push(() => handler(event));
else handler(event);
}),
);
manager.stop();
manager.start();
const response = deferred();
const originalSave = backend.save.bind(backend);
const save = vi.spyOn(backend, "save").mockImplementationOnce(async (doc) => {
await originalSave(doc);
await response.promise;
});
const transitions: boolean[] = [];
const unsubscribe = useDocMeta.subscribe((state, previous) => {
const dirty = state[path]?.dirty;
if (dirty !== undefined && dirty !== previous[path]?.dirty) transitions.push(dirty);
});
let pending: Promise<void> | undefined;
try {
slot.dispatchLocal({ changes: { from: 4, insert: " saved" } });
await model.sync.whenIdle();
expect(transitions).toEqual([true]);
deferDirty = order === "clean and dirty after response";
pending = model.save("explicit");
await vi.waitFor(() => expect(backend.files.get(path)).toBe("base saved\n"));
expect(await backend.snapshot(model.doc)).toMatchObject({ text: "base saved\n", dirty: false });
transitions.length = 0;
deferDirty = order !== "dirty before response";
slot.dispatchLocal({ changes: { from: 10, insert: " newer" } });
await model.sync.whenIdle();
expect(await backend.snapshot(model.doc)).toMatchObject({ text: "base saved newer\n", dirty: true });
response.resolve();
await pending;
expect(slot.currentState().doc.toString()).toBe("base saved newer\n");
expect(backend.files.get(path)).toBe("base saved\n");
expect(model.getMeta().dirty).toBe(true);
const deferredCount = order === "dirty before response" ? 0 : order === "dirty after response" ? 1 : 2;
expect(events).toHaveLength(deferredCount);
events.splice(0).forEach((deliver) => deliver());
expect(useDocMeta.getState()[path]?.dirty).toBe(true);
expect(transitions).not.toContain(false);
deferDirty = false;
await model.save("explicit");
expect(backend.files.get(path)).toBe("base saved newer\n");
expect(await backend.snapshot(model.doc)).toMatchObject({ text: "base saved newer\n", dirty: false });
expect(useDocMeta.getState()[path]?.dirty).toBe(false);
expect(transitions.at(-1)).toBe(false);
} finally {
response.resolve();
try {
await pending;
} finally {
unsubscribe();
save.mockRestore();
onDirty.mockRestore();
slot.dispose();
manager.releaseProjectDocuments();
manager.stop();
}
}
},
);
it("marks an unchanged buffer clean when its save succeeds", async () => {
const path = "/p/a.txt";
const { backend, manager } = setup({ [path]: "base\n" });
const model = await manager.acquire(path);
const slot = new EditorSlot(model, "t1", host);
const transitions: Array<{ dirty: boolean; persisted: string | undefined }> = [];
const unsubscribe = useDocMeta.subscribe((state, previous) => {
const dirty = state[path]?.dirty;
if (dirty !== undefined && dirty !== previous[path]?.dirty)
transitions.push({ dirty, persisted: backend.files.get(path) });
});
try {
slot.dispatchLocal({ changes: { from: 4, insert: " saved" } });
await model.save("explicit");
expect(slot.currentState().doc.toString()).toBe("base saved\n");
expect(await backend.snapshot(model.doc)).toMatchObject({ text: "base saved\n", dirty: false });
expect(transitions).toEqual([
{ dirty: true, persisted: "base\n" },
{ dirty: false, persisted: "base saved\n" },
]);
} finally {
unsubscribe();
slot.dispose();
manager.releaseProjectDocuments();
manager.stop();
}
});
it("reconciles a save that includes an edit whose acknowledgement is still pending", async () => {
const path = "/p/a.txt";
const { backend, manager } = setup({ [path]: "base\n" }, { files: { autoSave: false } });
const model = await manager.acquire(path);
const slot = new EditorSlot(model, "t1", host);
const write = deferred();
const editReply = deferred();
const originalSave = backend.save.bind(backend);
const originalEdit = backend.edit.bind(backend);
const edit = vi.spyOn(backend, "edit");
const save = vi.spyOn(backend, "save").mockImplementationOnce(async (doc) => {
await write.promise;
await originalSave(doc);
});
let pending: Promise<void> | undefined;
try {
slot.dispatchLocal({ changes: { from: 4, insert: " first" } });
await model.sync.whenIdle();
pending = model.save("explicit");
await vi.waitFor(() => expect(save).toHaveBeenCalledWith(model.doc));
edit.mockImplementationOnce(async (...args) => {
const version = await originalEdit(...args);
await editReply.promise;
return version;
});
slot.dispatchLocal({ changes: { from: 10, insert: " second" } });
const synced = model.sync.whenIdle();
await vi.waitFor(async () => {
expect(await backend.snapshot(model.doc)).toMatchObject({ text: "base first second\n", dirty: true });
});
write.resolve();
await pending;
editReply.resolve();
await synced;
expect(slot.currentState().doc.toString()).toBe("base first second\n");
expect(backend.files.get(path)).toBe("base first second\n");
expect(useDocMeta.getState()[path]?.dirty).toBe(false);
} finally {
editReply.resolve();
write.resolve();
try {
await pending;
} finally {
edit.mockRestore();
save.mockRestore();
slot.dispose();
manager.releaseProjectDocuments();
manager.stop();
}
}
});
it.each(["explicit", "auto"] as const)(
"%s save leaves untouched documents byte-for-byte unchanged",
async (reason) => {
+32 -12
Переглянути файл
@@ -28,7 +28,7 @@ import {
} from "@/editor/api";
import { isUntitledUri, isVirtualUri } from "@/platform/virtualDocs";
import { DocSync, type Scheduler, frameScheduler } from "../sync/DocSync";
import type { DocBackend, LanguageInfo } from "../backend";
import type { DocBackend, DocDirtyEvent, LanguageInfo } from "../backend";
import {
findLanguageDescription,
languageInfo,
@@ -261,6 +261,7 @@ export class DocModel {
handoffRelease = false;
private refreshTimer: ReturnType<typeof setTimeout> | undefined;
private saving: Promise<void> = Promise.resolve();
private backendDirty: DocDirtyEvent | null = null;
private meta: DocMeta;
constructor(
@@ -321,6 +322,7 @@ export class DocModel {
changes: eventChanges,
});
},
onSynced: () => this.applyBackendClean(),
onDiscarded: (reason) => {
logError(`document ${this.path}: unsaved edits replaced by the file's content`, reason);
manager.notify({
@@ -345,6 +347,26 @@ export class DocModel {
if (!this.closed) useDocMeta.setState({ [this.path]: this.meta });
}
onBackendDirty(event: DocDirtyEvent) {
if (this.backendDirty && event.version < this.backendDirty.version) return;
this.backendDirty = event;
if (event.dirty) {
if (!this.meta.dirty) this.setMeta({ dirty: true });
} else this.applyBackendClean();
}
private applyBackendClean() {
const event = this.backendDirty;
if (event && !event.dirty) this.markClean(event.version);
}
private markClean(version: number) {
// A clean event can arrive before an edit acknowledgement or after a newer edit.
if (!this.meta.dirty || !this.sync.idle || this.sync.serverVersion !== version) return;
this.modified.clear();
this.setMeta({ dirty: false });
}
ctx(): EditorDocContext {
return {
doc: this.doc,
@@ -713,16 +735,20 @@ export class DocModel {
// an explicit save asks for one (Save As re-points the buffer, or stays
// dirty on Cancel).
if (reason === "auto") return;
if (await this.manager.saveAs(this)) this.modified.clear();
await this.manager.saveAs(this);
return;
}
const backend = this.manager.backend;
const version = this.sync.serverVersion;
const observedDirty = this.backendDirty;
// Autosave never overwrites external changes made after the buffer was edited.
if (reason === "auto" && backend.autosave) {
if (!(await backend.autosave(this.doc))) return;
} else await backend.save(this.doc);
this.modified.clear();
this.setMeta({ dirty: false });
// The reply does not identify what was saved. It only confirms the version
// we sent if the buffer and the observed backend dirty state haven't moved on.
if (this.backendDirty === observedDirty && (!observedDirty || observedDirty.version <= version))
this.markClean(version);
_emitEditorEvent({ type: "docSaved", doc: this.doc, path: this.path });
};
this.saving = this.saving.then(run, run);
@@ -732,6 +758,7 @@ export class DocModel {
/** Save As turned this untitled buffer into the file `info` points at. */
retarget(info: DocumentInfo) {
const old = this.path;
if (!this.backendDirty?.dirty || this.backendDirty.version < info.version) this.markClean(info.version);
this.path = info.path;
this.info = languageInfo(info.language);
this.editorconfig = info.editorconfig ?? null;
@@ -743,7 +770,6 @@ export class DocModel {
hasBom: info.hasBom,
lineEnding: info.lineEnding,
canReloadEncoding: info.canReloadEncoding,
dirty: false,
};
useDocMeta.setState((s) => {
const next = { ...s };
@@ -803,13 +829,7 @@ export class DocumentManager {
this.workspaceHistory.start(),
this.backend.onPatched((e) => this.byId.get(e.doc)?.sync.remote(e)),
this.backend.onLanguage?.((e) => this.byId.get(e.doc)?.setLanguage(e.language, e.uiMode)) ?? (() => {}),
this.backend.onDirty((e) => {
const m = this.byId.get(e.doc);
if (m && m.getMeta().dirty !== e.dirty) {
m.setMeta({ dirty: e.dirty });
if (!e.dirty) m.modified.clear();
}
}),
this.backend.onDirty((e) => this.byId.get(e.doc)?.onBackendDirty(e)),
);
let prev = useEditorRegistry.getState().contributions;
this.disposers.push(
+4
Переглянути файл
@@ -38,6 +38,8 @@ export interface SyncHost {
applyRemote(changes: ChangeSet, workspaceEdit?: boolean): void;
/** A locally produced batch accepted by the versioned backend. */
onLocalCommitted?(baseVersion: number, version: number, changes: ChangeSet): void;
/** The local buffer has no pending edits or resync. */
onSynced?(): void;
/** Called after a hard resync discarded local changes the backend never saw. */
onDiscarded?(reason: unknown): void;
/** Non-recoverable transport errors (logged by default). */
@@ -157,6 +159,7 @@ export class DocSync {
if (this.disposed || patch.version <= this.serverVersion) return;
this.pendingRemote.push(patch);
this.drainRemote();
this.resolveIdle();
}
dispose() {
@@ -356,6 +359,7 @@ export class DocSync {
private resolveIdle(force = false) {
if (!force && !this.idle) return;
if (this.idle && !this.disposed) this.host.onSynced?.();
const waiters = this.idleWaiters;
this.idleWaiters = [];
waiters.forEach((w) => w());
+34
Переглянути файл
@@ -101,6 +101,40 @@ describe("untitled editor input", () => {
expect(JSON.stringify(session)).not.toContain("untitled:");
});
it("keeps edits made after a Save As write dirty when retargeting the tab", async () => {
await ctrl!.openUntitled({ focus: false });
const slot = ctrl!.slotFor(activeTab().id)!;
const model = await editActive("draft");
const path = "/p/saved.txt";
vi.mocked(save).mockResolvedValue(path);
let release!: () => void;
const response = new Promise<void>((resolve) => {
release = resolve;
});
const originalSaveAs = backend.saveAs.bind(backend);
const saveAs = vi.spyOn(backend, "saveAs").mockImplementationOnce(async (...args) => {
const info = await originalSaveAs(...args);
await response;
return info;
});
const pending = model.save("explicit");
try {
await vi.waitFor(() => expect(backend.files.get(path)).toBe("draft\n"));
slot.dispatchLocal({ changes: { from: 5, insert: " newer" } });
await model.sync.whenIdle();
release();
await pending;
expect(activeTab().input.path).toBe(path);
expect(slot.currentState().doc.toString()).toBe("draft newer\n");
expect(backend.files.get(path)).toBe("draft\n");
expect(await backend.snapshot(model.doc)).toMatchObject({ text: "draft newer\n", dirty: true });
expect(useDocMeta.getState()[path]?.dirty).toBe(true);
} finally {
release();
await pending.finally(() => saveAs.mockRestore());
}
});
it("offers the registered languages as save-as types", async () => {
await ctrl!.openUntitled({ focus: false });
const slot = ctrl!.slotFor(activeTab().id)!;
+54 -9
Переглянути файл
@@ -30,8 +30,7 @@
}
.withPreview {
flex-direction: row;
width: auto;
max-width: min(1160px, 94vw);
min-width: 0;
}
.listMain {
display: flex;
@@ -39,6 +38,11 @@
min-width: 0;
flex: none;
}
.withPreview .listMain {
flex: 1 1 320px;
min-width: 300px;
min-height: 0;
}
.mnemonic {
width: 10px;
flex: none;
@@ -48,14 +52,39 @@
text-align: right;
}
.previewPanel {
width: 420px;
flex: none;
flex: 0 1 var(--list-preview-width);
min-width: 300px;
min-height: 60px;
max-height: 340px;
max-height: 300px;
overflow: auto;
border-left: 1px solid var(--border-popup);
background: var(--bg-popup-inline, var(--bg-elev));
}
.previewLeft {
flex-direction: row-reverse;
}
.previewLeft .previewPanel {
border-left: 0;
border-right: 1px solid var(--border-popup);
}
.previewBelow {
flex-direction: column;
}
.previewBelow .listMain {
flex: 0 1 auto;
min-width: 0;
}
.previewBelow .previewPanel {
flex: 0 1 auto;
min-width: 0;
min-height: 0;
max-height: min(300px, 40vh);
border-left: 0;
border-top: 1px solid var(--border-popup);
}
.previewBelow .previewPanel[aria-busy] {
height: 60px;
}
.previewText {
padding: 8px 10px;
font-size: var(--fs-small);
@@ -66,12 +95,13 @@
padding: 6px 0;
font-family: var(--openidea-editor-font, var(--font-mono));
font-weight: var(--fw-code);
font-size: var(--fs-small);
font-size: var(--openidea-editor-font-size, var(--fs-code));
color: var(--fg-editor);
}
.diffLine {
padding: 0 10px;
white-space: pre;
white-space: pre-wrap;
overflow-wrap: anywhere;
min-height: 1.4em;
}
.diff-added {
@@ -238,6 +268,10 @@
flex-direction: column;
overflow: hidden;
}
.docPopup:not([data-resized]) {
width: max-content;
min-width: min(300px, 90vw);
}
.docScope {
display: contents;
}
@@ -246,21 +280,32 @@
}
.docPopup .docFrame {
flex: 1 1 auto;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
}
.docPopup:not([data-resized]) .docFrame {
max-width: min(600px, 90vw);
max-height: 420px;
max-width: min(500px, 90vw);
max-height: 500px;
}
.docPopup .docBody {
flex: 1 1 auto;
min-height: 0;
overflow: auto;
overscroll-behavior: contain;
padding: var(--space-2) var(--space-4) var(--space-1);
}
.docPopup .docToolbar {
position: static;
flex: none;
align-self: flex-end;
margin: 0 var(--space-2) var(--space-1);
padding: 0;
border: 0;
}
.docPopup .docToolbar .spacer {
display: none;
}
.docWindowFrame {
height: 100%;
+67 -14
Переглянути файл
@@ -1,5 +1,5 @@
/** React popups for LSP editor features, rendered as a workbench overlay. */
import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
import { useEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent } from "react";
import clsx from "clsx";
import {
Checkbox,
@@ -49,11 +49,17 @@ function ItemIcon({ item }: { item: ListPopupItem }) {
return <span className={styles.iconSpacer} />;
}
function ListPreviewPanel({ preview }: { preview: ListPreview | null | "loading" }) {
function ListPreviewPanel({
preview,
themeClasses,
}: {
preview: ListPreview | null | "loading";
themeClasses?: string;
}) {
if (preview === "loading") return <div className={styles.previewPanel} aria-busy="true" />;
if (!preview) return null;
return (
<div className={styles.previewPanel} aria-label={tx("Preview")}>
<div className={clsx(styles.previewPanel, themeClasses)} role="region" aria-label={tx("Preview")}>
{preview.kind === "text" ? (
<div className={styles.previewText}>{preview.text}</div>
) : (
@@ -70,6 +76,9 @@ function ListPreviewPanel({ preview }: { preview: ListPreview | null | "loading"
);
}
const LIST_PREVIEW_WIDTH = 420;
const MIN_SIDE_BY_SIDE_WIDTH = 660;
function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
const [query, setQuery] = useState("");
const filtered = useMemo(() => {
@@ -91,6 +100,13 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
const [preview, setPreview] = useState<{ id: string; data: ListPreview | null } | null>(null);
const fetchPreview = popup.preview;
const [viewportWidth, setViewportWidth] = useState(() => window.innerWidth);
useEffect(() => {
if (!fetchPreview) return;
const resize = () => setViewportWidth(window.innerWidth);
window.addEventListener("resize", resize);
return () => window.removeEventListener("resize", resize);
}, [fetchPreview]);
useEffect(() => {
if (!fetchPreview || !activeItem || activeItem.disabled) return;
const ctrl = new AbortController();
@@ -164,22 +180,46 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
? ("loading" as const)
: null
: null;
const hasPreview = shownPreview !== null;
const previewBelow = hasPreview && viewportWidth <= MIN_SIDE_BY_SIDE_WIDTH;
const previewLeft =
hasPreview &&
!previewBelow &&
popup.anchor.x + width + LIST_PREVIEW_WIDTH > viewportWidth - 6 &&
popup.anchor.x >= LIST_PREVIEW_WIDTH + 6;
const anchor = useMemo(() => {
if (!fetchPreview) return popup.anchor;
const x = popup.anchor.x - (previewLeft ? LIST_PREVIEW_WIDTH : 0);
return {
getBoundingClientRect: () =>
new DOMRect(
Math.max(0, Math.min(x, window.innerWidth)),
Math.max(0, Math.min(popup.anchor.y, window.innerHeight)),
0,
0,
),
};
}, [fetchPreview, popup.anchor, previewLeft]);
const popupSize = {
width: hasPreview ? width + LIST_PREVIEW_WIDTH : width,
"--list-preview-width": `${LIST_PREVIEW_WIDTH}px`,
} as CSSProperties;
const indexOf = (item: ListPopupItem) => popup.items.indexOf(item);
return (
<Popup
open
anchor={popup.anchor}
anchor={anchor}
onClose={closePopup}
aria-label={popup.title}
className={clsx(styles.listPopup, popup.preview && styles.withPreview)}
style={popup.preview ? undefined : { width }}
className={clsx(
styles.listPopup,
hasPreview && styles.withPreview,
previewBelow && styles.previewBelow,
previewLeft && styles.previewLeft,
)}
style={popupSize}
>
<div
className={styles.listMain}
style={popup.preview ? { width } : undefined}
data-testid="list-popup"
aria-busy={popup.busy || undefined}
>
<div className={styles.listMain} data-testid="list-popup" aria-busy={popup.busy || undefined}>
<div className={styles.listHeader}>
<span className={styles.listTitle}>{popup.title}</span>
{popup.busy && <Spinner size={12} />}
@@ -260,7 +300,7 @@ function ListPopup({ popup }: { popup: Extract<LspPopup, { kind: "list" }> }) {
/>
</div>
</div>
{popup.preview && <ListPreviewPanel preview={shownPreview} />}
{popup.preview && <ListPreviewPanel preview={shownPreview} themeClasses={popup.themeClasses} />}
{sub?.item.submenu && (
<Popup
open
@@ -356,6 +396,19 @@ function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
const focusSeq = useLspPopup((s) => s.focusSeq);
const scope = useRef<HTMLDivElement>(null);
const opened = useRef(focusSeq);
// The captured caret can end up outside the viewport while the popup is open.
const anchor = useMemo(
() => ({
getBoundingClientRect: () =>
new DOMRect(
Math.max(0, Math.min(popup.anchor.x, window.innerWidth)),
Math.max(0, Math.min(popup.anchor.y, window.innerHeight)),
0,
0,
),
}),
[popup.anchor],
);
useEffect(() => {
if (focusSeq !== opened.current)
scope.current?.querySelector<HTMLElement>("[data-lsp-doc]")?.focus({ preventScroll: true });
@@ -364,7 +417,7 @@ function DocPopup({ popup }: { popup: Extract<LspPopup, { kind: "doc" }> }) {
return (
<Popup
open
anchor={popup.anchor}
anchor={anchor}
onClose={closePopup}
aria-label="Documentation"
className={styles.docPopup}
+32 -21
Переглянути файл
@@ -25,7 +25,7 @@ import {
type CompletionSource,
} from "@codemirror/autocomplete";
import { EditorSelection, EditorState, Prec, StateEffect, StateField, type Text } from "@codemirror/state";
import { EditorView, ViewPlugin, keymap, type Rect, type ViewUpdate } from "@codemirror/view";
import { EditorView, ViewPlugin, getTooltip, keymap, showTooltip, type Rect, type ViewUpdate } from "@codemirror/view";
import {
call,
commands,
@@ -59,6 +59,8 @@ import { showHint } from "./hint";
import { inplaceRenameActive } from "./inplaceRename";
import { languageSemantics } from "./semantic";
import { remoteChange } from "@/editor/api";
import { tooltipBounds } from "@/editor/core/cm/setup";
import { completionLabelOffset } from "./theme";
interface RequestContext {
doc: number;
@@ -983,36 +985,45 @@ function sortToggle(view: EditorView): HTMLElement {
return button;
}
/** IDEA's advertiser bar under the list (one tip: "Press ↵ to insert, ⇥ to replace") and its Sort by Name toggle. */
const completionFooter = ViewPlugin.fromClass(
const completionPopup = ViewPlugin.fromClass(
class {
constructor(private view: EditorView) {}
update(u: ViewUpdate) {
if (completionStatus(u.state) !== "active") return;
this.view.requestMeasure({
read: () => null,
write: () => {
const scope = this.view.dom.ownerDocument;
const tooltips = [
...this.view.dom.querySelectorAll<HTMLElement>(".cm-tooltip-autocomplete"),
...scope.querySelectorAll<HTMLElement>(".cm-tooltip-autocomplete"),
];
for (const t of tooltips) {
let footer = t.querySelector<HTMLElement>(":scope > .cm-lsp-completion-footer");
if (footer) {
// CodeMirror rebuilds the option list by appending a fresh <ul>,
// which would leave an existing footer above the list.
const list = t.querySelector(":scope > ul");
if (list && list.nextElementSibling !== footer) list.after(footer);
continue;
}
key: this,
read: () => {
const { left, right } = tooltipBounds(this.view);
return {
width: `${Math.max(0, Math.floor(right - left))}px`,
fontSize: getComputedStyle(this.view.contentDOM).fontSize,
};
},
write: ({ width, fontSize }) => {
const popup = this.view.state
.facet(showTooltip)
.map((tooltip) => tooltip && getTooltip(this.view, tooltip))
.find((tooltip) => tooltip?.dom.classList.contains("cm-lsp-completion"));
if (!popup) return;
// Apply the label alignment inside CodeMirror's viewport clamp.
popup.offset = { x: -completionLabelOffset, y: 0 };
const t = popup.dom;
if (t.style.getPropertyValue("--cm-completion-max-width") !== width)
t.style.setProperty("--cm-completion-max-width", width);
// The body-level tooltip does not inherit the editor's temporary font zoom.
if (t.style.getPropertyValue("--openidea-editor-font-size") !== fontSize)
t.style.setProperty("--openidea-editor-font-size", fontSize);
let footer = t.querySelector<HTMLElement>(":scope > .cm-lsp-completion-footer");
if (!footer) {
footer = document.createElement("div");
footer.className = "cm-lsp-completion-footer";
const tip = document.createElement("span");
tip.textContent = tx("Press ↵ to insert, ⇥ to replace");
footer.append(tip, sortToggle(this.view));
t.appendChild(footer);
}
// CodeMirror appends a fresh list when the candidates change.
const list = t.querySelector(":scope > ul");
if (list && list.nextElementSibling !== footer) list.after(footer);
},
});
}
@@ -1067,7 +1078,7 @@ export function completionExtension() {
tooltipClass: () => "cm-lsp-completion",
positionInfo: positionCompletionInfo,
}),
completionFooter,
completionPopup,
lookupTracker,
serverInsertAt,
caretAfterServerInsert,
+1
Переглянути файл
@@ -552,6 +552,7 @@ export async function showIntentions(view: EditorView) {
items,
busy,
preview,
themeClasses: view.themeClasses,
onClose: () => {
dismissed = true;
},
+1
Переглянути файл
@@ -104,6 +104,7 @@ export type LspPopup =
pin?: { label: string; run: () => void };
/** Side panel for the selected row, fetched lazily; `signal` aborts when the selection moves. */
preview?: (item: ListPopupItem, signal: AbortSignal) => Promise<ListPreview | null>;
themeClasses?: string;
/** Runs when the popup goes away (closed, replaced or a row ran). */
onClose?: () => void;
}
+29 -24
Переглянути файл
@@ -10,19 +10,17 @@ const tooltipSurface = {
color: "var(--fg)",
};
/**
* Row metrics that put a label one icon column right of the popup's left edge. They live on the
* popup as custom properties so every rule consuming them — including the popup's negative
* offset below — changes together. The remaining 1px is tooltipSurface's border, shared with
* the hover and signature tooltips.
*/
const completionInsets = { edge: 4, padding: 6, icon: 16, gap: 6 };
export const completionLabelOffset =
1 + completionInsets.edge + completionInsets.padding + completionInsets.icon + completionInsets.gap;
const completionRowMetrics = {
// Rows grow with the editor font size (lookup text uses the editor font, as typed text does).
"--cm-completion-row": "max(var(--h-list-row), calc(var(--openidea-editor-font-size, var(--fs-code)) * 1.7))",
"--cm-completion-edge": "4px",
"--cm-completion-inset": "6px",
"--cm-completion-icon": "16px",
"--cm-completion-gap": "6px",
"--cm-completion-edge": `${completionInsets.edge}px`,
"--cm-completion-inset": `${completionInsets.padding}px`,
"--cm-completion-icon": `${completionInsets.icon}px`,
"--cm-completion-gap": `${completionInsets.gap}px`,
};
const markdown = {
@@ -103,22 +101,19 @@ export const lspTheme = EditorView.theme({
fontFamily: "var(--openidea-editor-font, var(--font-mono))",
fontWeight: "var(--fw-code, 400)",
fontSize: "var(--openidea-editor-font-size, var(--fs-code))",
// CodeMirror anchors the popup at the completed word's start. Pull it left by one row's
// leading inset so the labels, not the icon column, sit on the text. CodeMirror's horizontal
// clamp measures the border box (margins excluded), so this offset sits outside its math:
// near the right edge it leaves that much extra space, and a word starting within one inset
// of the viewport's left edge would let the popup clip there. The normal editor layout
// (gutter + project sidebar) keeps the word well clear of that edge.
marginLeft:
"calc(-1 * (1px + var(--cm-completion-edge) + var(--cm-completion-inset) + var(--cm-completion-icon) + var(--cm-completion-gap)))",
display: "flex",
flexDirection: "column",
width: "max-content",
maxWidth: "min(720px, var(--cm-completion-max-width, 100vw))",
// No overflow clipping: CodeMirror nests the documentation pane in this box and
// positions it outside it (see `positionCompletionInfo`). The footer rounds itself.
},
".cm-tooltip.cm-tooltip-autocomplete.cm-lsp-completion > ul": {
fontFamily: "var(--openidea-editor-font, var(--font-mono))",
fontWeight: "var(--fw-code, 400)",
minWidth: "420px",
maxWidth: "min(720px, 80vw)",
minWidth: "0",
maxWidth: "100%",
height: "auto",
maxHeight: "calc(var(--cm-completion-row) * 11 + 8px)",
padding: "4px 0",
},
@@ -153,9 +148,15 @@ export const lspTheme = EditorView.theme({
alignItems: "center",
justifyContent: "center",
},
".cm-lsp-completion .cm-completionLabel": { flex: "none", overflow: "hidden", textOverflow: "ellipsis" },
".cm-lsp-completion .cm-completionLabel": {
flex: "0 1 auto",
minWidth: "0",
overflow: "hidden",
textOverflow: "ellipsis",
},
".cm-lsp-completion .cm-completionDetail": {
flex: "0 1 auto",
minWidth: "0",
marginLeft: "0",
fontStyle: "normal",
color: "var(--fg-subtle)",
@@ -172,7 +173,8 @@ export const lspTheme = EditorView.theme({
marginLeft: "calc(-1 * var(--cm-completion-gap))",
},
".cm-lsp-completion .cm-lsp-type": {
flex: "1 0 auto",
flex: "0 1 auto",
minWidth: "0",
maxWidth: "60%",
marginLeft: "auto",
paddingLeft: "16px",
@@ -188,18 +190,21 @@ export const lspTheme = EditorView.theme({
},
".cm-lsp-completion-footer": {
display: "flex",
flex: "none",
flexWrap: "wrap",
alignItems: "center",
padding: "5px 12px",
backgroundColor: "var(--bg-popup-inline, var(--bg-elev))",
color: "var(--fg-subtle)",
fontFamily: "var(--font-ui)",
fontSize: "var(--fs-small)",
whiteSpace: "nowrap",
gap: "12px",
gap: "var(--space-1) var(--space-3)",
justifyContent: "space-between",
borderRadius: "0 0 calc(var(--radius-popup) - 1px) calc(var(--radius-popup) - 1px)",
},
".cm-lsp-completion-sort": {
flex: "none",
maxWidth: "100%",
padding: "0",
border: "none",
background: "none",
+1
Переглянути файл
@@ -54,6 +54,7 @@ vi.mock("@/platform/ipc", async (original) => ({
agentCommands: async () => ok([]),
vcsBranchInfo: async () => ok({ head: "main" }),
vcsConfigGet: async () => ok(null),
vcsRemotes: async () => ok([]),
vcsBranches: async () => ok([]),
agentCreate: (request: NewAgentTask) => backend.create(request),
agentEntries: async () => ok([{ type: "user", text: "Earlier message", attachments: [] }] satisfies AgentEntry[]),
+4 -4
Переглянути файл
@@ -260,14 +260,14 @@ it("includes pending local edits and restored dirty buffers before backend dirty
const uninstall = installCloseGuard(d);
const spy = vi.spyOn(service, "maybeEditorService").mockReturnValue({ dirtyDocumentIds: () => [10, 11] } as never);
try {
emitLocalIdeEvent({ type: "docDirty", doc: 11, dirty: true });
emitLocalIdeEvent({ type: "docDirty", doc: 12, dirty: true });
emitLocalIdeEvent({ type: "docDirty", doc: 11, dirty: true, version: 1 });
emitLocalIdeEvent({ type: "docDirty", doc: 12, dirty: true, version: 1 });
expect(dirtyCount()).toBe(3);
await expect(confirmLeave(d)).resolves.toBe(false);
expect(asked[0]?.body).toContain("3");
} finally {
emitLocalIdeEvent({ type: "docDirty", doc: 11, dirty: false });
emitLocalIdeEvent({ type: "docDirty", doc: 12, dirty: false });
emitLocalIdeEvent({ type: "docDirty", doc: 11, dirty: false, version: 1 });
emitLocalIdeEvent({ type: "docDirty", doc: 12, dirty: false, version: 1 });
uninstall();
spy.mockRestore();
}
+91 -31
Переглянути файл
@@ -1,6 +1,6 @@
/** The Maven and Gradle tool windows: toolbar, status banner and the project tree. */
import { writeClipboardText } from "@/platform/clipboard";
import { useCallback, useEffect, useMemo, useState, type MouseEvent } from "react";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from "react";
import clsx from "clsx";
import type { BuildTool, GradleModel, MavenModel, RunConfig } from "@/platform/ipc";
import { downloadJdkActions } from "@/platform/jdk";
@@ -12,6 +12,7 @@ import {
EmptyState,
Icon,
IconButton,
Menu,
Spinner,
Tree,
showContextMenu,
@@ -125,25 +126,99 @@ function nodeProject(n: BuildNode): string | undefined {
return undefined;
}
type ToolbarItem = Extract<MenuItem, { kind: "action" }> & { icon: string };
function toolbarButton({ action, icon, checked, label }: ToolbarItem) {
return <IconButton key={action} action={action} icon={icon} title={label} size="small" pressed={checked} />;
}
function MoreActions({ items }: { items: MenuItem[] }) {
const anchor = useRef<HTMLButtonElement>(null);
const [open, setOpen] = useState(false);
return (
<>
<IconButton
ref={anchor}
className={styles.toolbarMore}
icon="more"
title="More Actions"
size="small"
aria-haspopup="menu"
aria-expanded={open}
onClick={() => setOpen((value) => !value)}
/>
<Menu
anchor={anchor}
open={open}
onClose={() => setOpen(false)}
placement="bottom-end"
aria-label={tx("More Actions")}
items={items}
/>
</>
);
}
// Small buttons, separators, gaps and padding in the full toolbar.
const FULL_TOOLBAR_WIDTH: Record<BuildTool, number> = { maven: 274, gradle: 230 };
function Toolbar({ tool, selection }: { tool: BuildTool; selection: BuildNode[] }) {
const toolbar = useRef<HTMLDivElement>(null);
const [compact, setCompact] = useState(false);
const syncing = useBuild((s) => !!s.syncing[tool]);
const settings = useBuild((s) => s.settings);
const settings = useBuild((s) => s.settings[tool]);
const model = useBuild((s) => s.model);
useLayoutEffect(() => {
const node = toolbar.current;
if (!node) return;
const measure = () => {
if (node.clientWidth > 0) setCompact(node.clientWidth < FULL_TOOLBAR_WIDTH[tool]);
};
measure();
if (typeof ResizeObserver === "undefined") return;
const observer = new ResizeObserver(measure);
observer.observe(node);
return () => observer.disconnect();
}, [tool]);
const config = model && nodeConfig(selection.filter(isRunnable), model);
const runSelected = () => {
if (config) runConfig(config, "run");
};
const maven = tool === "maven";
const projectActions: ToolbarItem[] = [
...(maven ? [{ kind: "action" as const, action: "maven.generateSources", icon: "folder-generated-source" }] : []),
{ kind: "action", action: maven ? "maven.addProjects" : "gradle.linkProjects", icon: "plus" },
];
const buildActions: ToolbarItem[] = [
{ kind: "action", action: `${tool}.toggleOffline`, icon: "build-offline", checked: settings.offline },
{ kind: "action", action: `${tool}.analyzeDependencies`, icon: "build-dependencies" },
{ kind: "action", action: `${tool}.toggleSkipTests`, icon: "skip-tests", checked: settings.skipTests },
];
const treeActions: ToolbarItem[] = [
{ kind: "action", action: `${tool}.expandAll`, icon: "expand-all" },
{ kind: "action", action: `${tool}.collapseAll`, icon: "collapse-all" },
...(maven
? [{ kind: "action" as const, action: "maven.settings", icon: "settings", label: "Maven Settings…" }]
: []),
];
return (
<div className={styles.toolbar} role="toolbar" aria-label={maven ? "Maven actions" : "Gradle actions"}>
<div
ref={toolbar}
className={styles.toolbar}
role="toolbar"
aria-label={maven ? "Maven actions" : "Gradle actions"}
>
{syncing ? (
<IconButton icon="stop" size="small" iconSize={16} action={`${tool}.cancelReload`} />
) : (
<IconButton icon="refresh" size="small" iconSize={16} action={`${tool}.reload`} />
)}
{maven && <IconButton icon="folder-generated-source" size="small" iconSize={16} action="maven.generateSources" />}
<IconButton icon="plus" size="small" iconSize={16} action={maven ? "maven.addProjects" : "gradle.linkProjects"} />
<span className={styles.sep} />
{!compact && (
<>
{projectActions.map(toolbarButton)}
<span className={styles.sep} />
</>
)}
<IconButton
icon="run"
size="small"
@@ -158,31 +233,16 @@ function Toolbar({ tool, selection }: { tool: BuildTool; selection: BuildNode[]
iconSize={16}
action={maven ? "maven.executeGoal" : "gradle.executeTask"}
/>
<IconButton
icon="build-offline"
size="small"
iconSize={16}
action={`${tool}.toggleOffline`}
pressed={maven ? settings.maven.offline : settings.gradle.offline}
/>
<IconButton
icon="build-dependencies"
size="small"
iconSize={16}
action={maven ? "maven.analyzeDependencies" : "gradle.analyzeDependencies"}
/>
<IconButton
icon="skip-tests"
size="small"
iconSize={16}
action={`${tool}.toggleSkipTests`}
pressed={maven ? settings.maven.skipTests : settings.gradle.skipTests}
/>
<span className={styles.sep} />
<IconButton icon="expand-all" size="small" iconSize={16} action={`${tool}.expandAll`} />
<IconButton icon="collapse-all" size="small" iconSize={16} action={`${tool}.collapseAll`} />
{maven && (
<IconButton icon="settings" size="small" iconSize={16} action="maven.settings" title="Maven Settings…" />
{compact ? (
<MoreActions
items={[...projectActions, { kind: "separator" }, ...buildActions, { kind: "separator" }, ...treeActions]}
/>
) : (
<>
{buildActions.map(toolbarButton)}
<span className={styles.sep} />
{treeActions.map(toolbarButton)}
</>
)}
</div>
);
+3
Переглянути файл
@@ -12,6 +12,9 @@
gap: var(--space-0-5);
padding: 0 6px;
}
.toolbarMore {
margin-left: auto;
}
.sep {
width: 1px;
height: 16px;
+1
Переглянути файл
@@ -46,6 +46,7 @@ vi.mock("@/platform/workflowSettings", () => ({
vi.mock("@/workbench/contributions", () => ({
notifications: () => ({ notify: mocks.notify }),
projectViewSelection: () => [],
changesViewSelection: () => [],
toolWindowService: vi.fn(),
}));
vi.mock("@/workbench/inputDialogs", () => ({ chooseItem: mocks.choose }));
+9 -3
Переглянути файл
@@ -22,7 +22,12 @@ import {
type DeploymentServerValid,
} from "@/platform/remoteSettings";
import { workflowSettings } from "@/platform/workflowSettings";
import { notifications, projectViewSelection, toolWindowService } from "@/workbench/contributions";
import {
changesViewSelection,
notifications,
projectViewSelection,
toolWindowService,
} from "@/workbench/contributions";
import { chooseItem } from "@/workbench/inputDialogs";
import { confirm } from "@/workbench/messages";
import { defaultGroup, initialSyncChoices, resolveServer, serverLabel, summarizeReport, targetPaths } from "./model";
@@ -37,12 +42,13 @@ const errorText = (e: unknown) => txTemplate(e instanceof Error ? e.message : St
const projectRoot = () => useProject.getState().project?.root ?? null;
const deployment = () => workflowSettings().deployment;
/** The files an action works on (menu argument, project view selection or the editor's file). */
/** The files an action works on (menu, Commit selection, Project view or the editor). */
export function actionTargets(arg: unknown): string[] {
const editorPath = getContext().editorPath;
return targetPaths(arg, {
part: useDeployment.getState().part,
selection: projectViewSelection(),
changesSelection: changesViewSelection(),
editorPath: typeof editorPath === "string" ? editorPath : null,
projectRoot: projectRoot(),
});
@@ -61,7 +67,7 @@ function notifyNoServers() {
function notifyNoTargets() {
notifications().notify({
level: "info",
title: "Select files in the Project view or open a file in the editor",
title: "Select files in the Project view, Commit tool window, or open a file in the editor",
group: GROUP,
key: "deployment.noTarget",
});
+26
Переглянути файл
@@ -45,6 +45,32 @@ describe("targetPaths", () => {
expect(targetPaths(undefined, { ...ctx, part: "editor", selection: [`${ROOT}/src`] })).toEqual([]);
});
it("prefers the Commit / Local Changes selection over Project view and the editor", () => {
const changes = [`${ROOT}/a.php`, `${ROOT}/b.php`];
expect(
targetPaths(undefined, {
...ctx,
part: "project",
selection: [`${ROOT}/only-project`],
editorPath: `${ROOT}/editor.php`,
changesSelection: changes,
}),
).toEqual(changes);
// Menu arg still wins.
expect(
targetPaths({ paths: [`${ROOT}/menu.php`] }, { ...ctx, changesSelection: changes, part: "project" }),
).toEqual([`${ROOT}/menu.php`]);
// Empty changes selection falls through to Project / editor.
expect(
targetPaths(undefined, {
...ctx,
part: "project",
selection: [`${ROOT}/proj`],
changesSelection: [],
}),
).toEqual([`${ROOT}/proj`]);
});
it("drops paths outside the project and paths inside selected folders", () => {
expect(targetPaths([`${ROOT}/src`, `${ROOT}/src/a.php`, "/elsewhere/b", `${ROOT}/srcx`], ctx)).toEqual([
`${ROOT}/src`,
+20 -9
Переглянути файл
@@ -16,24 +16,35 @@ export function pathsFromArg(arg: unknown): string[] | null {
}
/**
* Files an action works on: the paths passed by a menu, else the project view
* Files an action works on: the paths passed by a menu, else the Commit / Local
* Changes selection while that window is focused, else the project view
* selection when it had focus last, else the active editor's file. Paths
* outside the project are dropped.
*/
export function targetPaths(
arg: unknown,
ctx: { part: FocusedPart; selection: readonly string[]; editorPath: string | null; projectRoot: string | null },
ctx: {
part: FocusedPart;
selection: readonly string[];
/** Absolute paths from the Commit/Local Changes tree while it has focus. */
changesSelection?: readonly string[];
editorPath: string | null;
projectRoot: string | null;
},
): string[] {
const passed = pathsFromArg(arg);
const changes = ctx.changesSelection?.length ? [...ctx.changesSelection] : null;
const picked = passed
? passed
: ctx.part === "project" && ctx.selection.length
? [...ctx.selection]
: ctx.editorPath
? [ctx.editorPath]
: ctx.selection.length && ctx.part !== "editor"
? [...ctx.selection]
: [];
: changes
? changes
: ctx.part === "project" && ctx.selection.length
? [...ctx.selection]
: ctx.editorPath
? [ctx.editorPath]
: ctx.selection.length && ctx.part !== "editor"
? [...ctx.selection]
: [];
const root = ctx.projectRoot;
if (!root) return [];
const inside = picked.filter((p) => p === root || p.startsWith(`${root}/`));
+15
Переглянути файл
@@ -132,6 +132,21 @@
font-size: var(--fs-small);
text-align: right;
}
.redirects {
display: flex;
flex-direction: column;
gap: var(--space-0-5);
padding: 2px 8px;
border-bottom: 1px solid var(--border);
font-family: var(--font-mono);
font-size: var(--fs-small);
color: var(--fg-secondary);
}
.redirectHop {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.tabBody {
flex: 1;
min-height: 0;
+10
Переглянути файл
@@ -127,6 +127,16 @@ function ExchangeView({ ex }: { ex: HttpExchange }) {
{ex.request.method} {ex.request.url}
</span>
</div>
{r != null && (r.redirects?.length ?? 0) > 0 && (
<div className={styles.redirects}>
{r.redirects?.map((hop, i) => (
// A redirect loop repeats locations: the hop's position is its identity.
<div key={i} className={styles.redirectHop} title={hop.location}>
{hop.status} {hop.statusText} → {hop.location}
</div>
))}
</div>
)}
<Tabs
variant="compact"
activeId={tab}
+12 -2
Переглянути файл
@@ -37,8 +37,9 @@ import { registerSpringEndpointProvider } from "./spring/routeIndex";
import {
feignEditorExtension,
feignMenuItems,
FIND_FEIGN_CLIENTS,
GO_TO_FEIGN_ENDPOINT,
goToFeignEndpoint,
navigateFeign,
registerFeignNavigation,
} from "./spring/feignNavigation";
@@ -184,7 +185,16 @@ export function activate(): () => void {
icon: "arrow-right",
keywords: ["spring", "feign", "microservice", "endpoint"],
when: SPRING_WHEN,
run: ({ arg }) => goToFeignEndpoint(arg),
run: ({ arg }) => navigateFeign("endpoint", arg),
},
{
id: FIND_FEIGN_CLIENTS,
title: "Find Feign Clients",
category: "Navigate",
icon: "search",
keywords: ["spring", "feign", "client", "endpoint", "caller"],
when: SPRING_WHEN,
run: ({ arg }) => navigateFeign("clients", arg),
},
{
id: OPEN_ENDPOINT,
+1
Переглянути файл
@@ -29,6 +29,7 @@ const exchange: HttpExchange = {
version: "HTTP/1.1",
headers: [["content-type", "text/plain"]],
contentType: "text/plain",
redirects: [],
body: "alpha beta\nbeta gamma\nBeta",
size: 26,
truncated: false,
+17 -13
Переглянути файл
@@ -21,6 +21,7 @@ import { gutterIconMarkup, showContextMenu, type MenuItem } from "@/ui";
import { notifications, type MenuGroupContext } from "@/workbench/contributions";
import { constantPool } from "./constants";
import { springAt, springControllers, type Controller, type Endpoint } from "./endpoints";
import { findClientItems } from "./feignNavigation";
import { bodyLookup, findHost, renderRequest, skeleton, type SourceReader } from "./request";
import { parseSource } from "./source";
import styles from "../HttpClient.module.css";
@@ -83,17 +84,15 @@ export async function generateRequests(sourcePath: string, text: string, targets
}
}
function endpointItems(sourcePath: string, text: string, e: Endpoint): MenuItem[] {
function generateRequestItem(sourcePath: string, text: string, e: Endpoint): MenuItem {
const generate = (path?: string) => void generateRequests(sourcePath, text, [{ endpoint: e, path }]);
return [
e.paths.length > 1
? {
label: "Generate Request in HTTP Client",
icon: "file-http",
submenu: e.paths.map((p) => ({ label: `${e.httpMethod} ${p}`, verbatim: true, run: () => generate(p) })),
}
: { label: "Generate Request in HTTP Client", icon: "file-http", run: () => generate() },
];
return e.paths.length > 1
? {
label: "Generate Request in HTTP Client",
icon: "file-http",
submenu: e.paths.map((p) => ({ label: `${e.httpMethod} ${p}`, verbatim: true, run: () => generate(p) })),
}
: { label: "Generate Request in HTTP Client", icon: "file-http", run: () => generate() };
}
function controllerItems(sourcePath: string, text: string, c: Controller): MenuItem[] {
@@ -120,8 +119,9 @@ export function springMenuItems(sourcePath: string, text: string, offset: number
if (endpoint)
items.push(
endpoint.paths.length > 1
? endpointItems(sourcePath, text, endpoint)[0]!
? generateRequestItem(sourcePath, text, endpoint)
: { kind: "action", action: GENERATE_REQUEST, icon: "file-http" },
...findClientItems(sourcePath, text, endpoint.offset),
);
if (controller?.endpoints.length)
items.push({ kind: "action", action: GENERATE_CONTROLLER_REQUESTS, icon: "file-http" });
@@ -163,6 +163,7 @@ export async function generateAtCaret(scope: "endpoint" | "controller"): Promise
interface Mark {
pos: number;
offset: number;
/** Endpoint key or the controller's name. */
key: string;
title: string;
@@ -188,6 +189,7 @@ function computeMarks(state: EditorState): Mark[] {
if (c.endpoints.length)
marks.push({
pos: lineStart(c.offset),
offset: c.offset,
key: `class:${c.name}`,
title: "Generate Requests for Controller",
items: (path, text) => controllerItems(path, text, c),
@@ -195,9 +197,10 @@ function computeMarks(state: EditorState): Mark[] {
for (const e of c.endpoints)
marks.push({
pos: lineStart(e.offset),
offset: e.offset,
key: `${e.httpMethod} ${e.paths.join(",")}`,
title: `${e.httpMethod} ${e.paths[0] ?? "/"}`,
items: (path, text) => endpointItems(path, text, e),
items: (path, text) => [generateRequestItem(path, text, e), ...findClientItems(path, text, e.offset)],
});
}
// One icon per line (the first wins).
@@ -243,7 +246,8 @@ export function springEditorExtension(ctx: EditorDocContext): Extension {
const found = computeMarks(this.view.state);
const cur = this.view.state.field(marksField);
const same =
cur.length === found.length && cur.every((m, i) => m.pos === found[i]!.pos && m.key === found[i]!.key);
cur.length === found.length &&
cur.every((m, i) => m.pos === found[i]!.pos && m.offset === found[i]!.offset && m.key === found[i]!.key);
if (!same) this.view.dispatch({ effects: setMarks.of(found) });
// Paths built from other classes' constants: load those classes, then mark again.
if (found.length) {
+18 -15
Переглянути файл
@@ -1,7 +1,7 @@
/** Source-only Feign relationships. Request generation's default GET is not a
* server constraint: unconstrained controller mappings accept every method. */
import { joinPaths } from "./endpoints";
import { allClasses, parseSource, type Annotation, type Expr, type SourceFile, type Tok } from "./source";
import { allClasses, parseSource, type Annotation, type Expr, type Method, type SourceFile, type Tok } from "./source";
const WEB = "org.springframework.web.bind.annotation";
const FEIGN = "org.springframework.cloud.openfeign.FeignClient";
@@ -19,19 +19,27 @@ export interface HttpShape {
paths: string[];
methods: string[];
}
export interface FeignMethod extends HttpShape {
export interface MappedMethod extends HttpShape {
name: string;
/** Whole declaration, including its annotations. */
from: number;
to: number;
nameFrom: number;
nameTo: number;
}
export interface FeignMethod extends MappedMethod {
/** Literal URL spans, excluding quotes, for modifier-click navigation. */
links: { from: number; to: number }[];
service: string | null;
}
export interface ControllerMethod extends HttpShape {
name: string;
from: number;
to: number;
function declaration(owner: string, method: Method) {
return {
name: `${owner}.${method.name}`,
from: method.start,
to: method.end,
nameFrom: method.nameStart,
nameTo: method.nameStart + method.name.length,
};
}
function owned(a: Annotation, file: SourceFile, qualified: string): boolean {
@@ -156,10 +164,7 @@ export function feignMethods(text: string): FeignMethod[] {
verbs = methods(annotation, file);
if (!urls || !verbs) continue;
result.push({
name: `${cls.name}.${method.name}`,
from: method.start,
to: method.end,
nameFrom: method.nameStart,
...declaration(cls.name, method),
paths: combine([prefix], urls.values),
methods: verbs.map((v) => (v === "*" ? "GET" : v)),
links: urls.links,
@@ -170,10 +175,10 @@ export function feignMethods(text: string): FeignMethod[] {
return result;
}
export function controllerMethods(text: string, file?: SourceFile): ControllerMethod[] {
export function controllerMethods(text: string, file?: SourceFile): MappedMethod[] {
if (text.length > MAX_NAVIGATION_SOURCE || !text.includes("Controller")) return [];
file ??= parseSource(text);
const result: ControllerMethod[] = [];
const result: MappedMethod[] = [];
for (const cls of allClasses(file)) {
if (
!cls.annotations.some(
@@ -199,9 +204,7 @@ export function controllerMethods(text: string, file?: SourceFile): ControllerMe
verbs = methods(annotation, file);
if (!own || !verbs) continue;
result.push({
name: `${cls.name}.${method.name}`,
from: method.nameStart,
to: method.nameStart + method.name.length,
...declaration(cls.name, method),
paths: combine(base.values, own.values),
methods: verbs.includes("*")
? classMethods
+132 -2
Переглянути файл
@@ -2,8 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { _emitEditorEvent } from "@/editor/api";
import { commands, emitLocalIdeEvent, type ProjectInfo } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { feignMethods } from "./feign";
import { feignTargets, registerFeignNavigation } from "./feignNavigation";
import { controllerMethods, feignMethods } from "./feign";
import { feignClients, feignTargets, registerFeignNavigation } from "./feignNavigation";
const root = "/p";
const clientPath = "/p/client/src/main/java/Client.java";
@@ -169,3 +169,133 @@ describe("core service-aware Feign navigation", () => {
expect(vi.mocked(commands.fsReadText).mock.calls.every(([path]) => path.endsWith(".java"))).toBe(true);
});
});
describe("finding Feign declarations from a controller", () => {
const clients = (controller = server, source = users) => feignClients(source, controllerMethods(controller)[0]!);
const config = "/p/users/src/main/resources/application.properties";
it("orders service matches first, excludes other services and returns each declaration at its UTF-16 identifier", async () => {
const unknown = "/p/a/src/main/java/Dynamic.java";
const direct = "/p/b/src/main/java/Direct.java";
const source = client.replace(
'@GetMapping("/users/{id}")',
'@GetMapping({"/users/{key}", "/users/{id}"}) /* 🛒 */',
);
files.set(clientPath, source);
files.set(unknown, client.replace('name="users"', 'name="${service}"'));
files.set(direct, client.replace('name="users"', 'name="elsewhere",url="https://example.org"'));
files.set("/p/z/src/main/java/Other.java", client.replace('name="users"', 'name="admin"'));
files.set("/p/admin/src/main/java/OtherVerb.java", client.replaceAll("GetMapping", "PostMapping"));
files.set("/p/admin/src/main/java/OtherPath.java", client.replace("/users/{id}", "/users/all/active"));
await resolve(); // Both lookups share the same inventory.
const results = await clients();
expect(results.map((t) => [t.path, !!t.possible])).toEqual([
[clientPath, false],
[unknown, true],
[direct, true],
]);
const col = source.split("\n")[2]!.indexOf("find()");
expect(results[0]).toMatchObject({
name: "Client.find",
range: { start: { line: 2, col }, end: { line: 2, col: col + 4 } },
});
expect(commands.springRouteSources).toHaveBeenCalledTimes(1);
});
it("keeps the roles of client and server for HEAD and unconstrained mappings", async () => {
files.set(
clientPath,
client
.replace(
"import org.springframework.web.bind.annotation.GetMapping",
"import org.springframework.web.bind.annotation.*",
)
.replace('@GetMapping("/users/{id}")', '@RequestMapping(path="/users/{id}", method=RequestMethod.HEAD)'),
);
const post = "/p/client/src/main/java/Post.java";
files.set(post, client.replaceAll("GetMapping", "PostMapping"));
expect((await clients()).map((t) => t.path)).toEqual([clientPath]);
expect((await clients(server.replace("GetMapping", "RequestMapping"))).map((t) => t.path)).toEqual([
clientPath,
post,
]);
expect(await clients(server.replace("GetMapping", "PutMapping"))).toEqual([]);
});
it("rechecks edited and deleted declarations and the controller's current service without rescanning on typing", async () => {
const edit = (path: string) =>
_emitEditorEvent({ type: "docChanged", doc: 9, path, baseVersion: 1, version: 2, changes: [] });
files.set(clientPath, client);
expect((await clients()).map((t) => t.name)).toEqual(["Client.find"]);
files.set(clientPath, client.replace('name="users"', 'name="admin"'));
expect(await clients()).toEqual([]); // Revalidate even when the source event has not arrived yet.
const added = "/p/orders/src/main/kotlin/New.kt";
files.set(
added,
`import org.springframework.cloud.openfeign.FeignClient
import org.springframework.web.bind.annotation.GetMapping
@FeignClient("users")
interface New { @GetMapping("/users/{key}") fun lookup(): String }`,
);
edit(added); // Newly edited, without a visible editor or an entry in the disk index.
expect((await clients()).map((t) => t.name)).toEqual(["New.lookup"]);
files.set(config, "spring.application.name=admin\n");
edit(config);
edit(clientPath);
expect((await clients()).map((t) => t.name)).toEqual(["Client.find"]);
files.delete(clientPath);
expect(await clients()).toEqual([]);
expect(commands.springRouteSources).toHaveBeenCalledTimes(1);
});
it("marks every match as possible if the controller's owning module has no unique identity", async () => {
files.set(clientPath, client);
files.set("/p/src/main/resources/application.properties", "spring.application.name=users\n");
files.set("/p/users/src/main/resources/application-live.yml", "spring.application.name: alternate\n");
files.set("/outside/src/main/java/Other.java", client);
expect((await clients()).map((t) => [t.path, t.possible])).toEqual([[clientPath, true]]);
expect(vi.mocked(commands.fsReadText).mock.calls.every(([path]) => path.startsWith("/p/"))).toBe(true);
});
it("finds a Java client for a Kotlin endpoint across linked projects and ignores unattached siblings", async () => {
const kotlin = `import org.springframework.web.bind.annotation.*
@RestController class Users { @GetMapping("/users/{user}") fun find(): String = "" }`;
const source = "/p/users/src/main/kotlin/Users.kt";
useProject.setState({
project: {
...project("/workspace"),
workspace: {
version: 1,
name: "Services",
projects: ["/p/users", "/p/client"],
},
},
});
files.set(source, kotlin);
files.set(clientPath, client);
files.set("/p/unattached/src/main/java/Other.java", client);
expect((await clients(kotlin, source)).map((t) => [t.path, !!t.possible])).toEqual([[clientPath, false]]);
expect(commands.fsReadText).not.toHaveBeenCalledWith("/p/unattached/src/main/java/Other.java");
});
it("skips untrusted and outside sources, and cancels a pending lookup on workspace switch", async () => {
useProject.setState({ project: { ...project(), trusted: false } });
expect(await clients()).toEqual([]);
useProject.setState({ project: project() });
expect(await clients(server, "/elsewhere/Users.java")).toEqual([]);
expect(commands.springRouteSources).not.toHaveBeenCalled();
expect(commands.fsReadDir).not.toHaveBeenCalled();
let finish!: (value: Awaited<ReturnType<typeof commands.springRouteSources>>) => void;
vi.mocked(commands.springRouteSources).mockImplementationOnce(
() =>
new Promise((resolve) => {
finish = resolve;
}),
);
const pending = clients();
useProject.setState({ project: project("/elsewhere") });
finish({ status: "ok", data: [{ path: clientPath, text: client }] });
expect(await pending).toEqual([]);
expect(commands.fsReadText).not.toHaveBeenCalledWith(clientPath);
});
});
+169 -79
Переглянути файл
@@ -10,21 +10,31 @@ import {
} from "@/editor/api";
import { docOf } from "@/editor/lsp/lsp";
import { locationItems, navigateTo } from "@/editor/lsp/navigation";
import { caretAnchor, openPopup } from "@/editor/lsp/popupStore";
import { caretAnchor, openPopup, type ListPopupItem } from "@/editor/lsp/popupStore";
import { invalidateNavigationProviders, registerNavigationProvider } from "@/editor/navigationProviders";
import { executeAction } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import { call, commands, onIdeEvent, type Location, type ProjectInfo } from "@/platform/ipc";
import { isSameOrInside } from "@/platform/paths";
import { projectFolder, useProject } from "@/platform/project";
import { projectFolder, relativePath, useProject } from "@/platform/project";
import { gutterIconMarkup, type MenuItem } from "@/ui";
import { notifications, type MenuGroupContext } from "@/workbench/contributions";
import { callsEndpoint, controllerMethods, feignMethods, MAX_NAVIGATION_SOURCE, type FeignMethod } from "./feign";
import { clearRouteIndex, controllerIndex, isRouteSource, type ControllerTarget } from "./routeIndex";
import {
callsEndpoint,
controllerMethods,
feignMethods,
MAX_NAVIGATION_SOURCE,
type FeignMethod,
type HttpShape,
type MappedMethod,
} from "./feign";
import { clearRouteIndex, controllerIndex, feignClientIndex, isRouteSource } from "./routeIndex";
import { isServiceConfiguration, loadServiceName, sourceModule } from "./serviceIdentity";
import styles from "../HttpClient.module.css";
export const GO_TO_FEIGN_ENDPOINT = "http.goToFeignEndpoint";
export const FIND_FEIGN_CLIENTS = "http.findFeignClients";
const TARGET_LIMIT = 256;
const serviceNames = new Map<string, Promise<string | null>>();
const changedSources = new Set<string>();
let epoch = 0;
@@ -60,78 +70,115 @@ function named(module: string): Promise<string | null> {
return pending;
}
function location(
path: string,
text: string,
method: ReturnType<typeof controllerMethods>[number],
): Location & { name: string } {
const doc = Text.of(text.split("\n"));
const from = doc.lineAt(method.from),
to = doc.lineAt(method.to);
interface FeignLocation extends Location {
name: string;
possible?: boolean;
}
function location(path: string, doc: Text, method: MappedMethod): FeignLocation {
const from = doc.lineAt(method.nameFrom);
return {
path,
name: method.name,
range: {
start: { line: from.number - 1, col: method.from - from.from },
end: { line: to.number - 1, col: method.to - to.from },
start: { line: from.number - 1, col: method.nameFrom - from.from },
end: { line: from.number - 1, col: method.nameTo - from.from },
},
};
}
/** The index supplies candidates; current source/configuration supplies the navigation target. */
export async function feignTargets(source: string, client: FeignMethod): Promise<(Location & { name: string })[]> {
function lookupScope(source: string) {
const project = useProject.getState().project;
if (!project?.trusted || !inside(project, source)) return [];
if (!project?.trusted || !inside(project, source)) return null;
const key = projectKey(project),
started = epoch;
const stale = () => started !== epoch || key !== projectKey(useProject.getState().project);
const indexed = await controllerIndex(project.root);
if (stale()) return [];
const overlays = new Set(
[...new Set([...changedSources, ...[...useEditorRegistry.getState().editors].map((e) => e.ctx.path)])]
.filter((path) => isRouteSource(path) && inside(project, path))
.slice(0, 256),
);
const currentText = new Map<string, string>();
const candidates: ControllerTarget[] = indexed.filter((target) => !overlays.has(target.path));
// Visible and recently edited source files include unsaved/new controllers
// that the filesystem inventory has not seen yet. Never keep their full text.
for (const path of overlays) {
return { project, stale: () => started !== epoch || key !== projectKey(useProject.getState().project) };
}
function controllerService(project: ProjectInfo, path: string): Promise<string | null> {
const module = sourceModule(path);
const folder = projectFolder(project, path);
return module && folder && isSameOrInside(module, folder.root) ? named(module) : Promise.resolve(null);
}
/** The disk index narrows the search. Open and recently edited files may contain new
* mappings, and the current source supplies the identifier range we actually open. */
async function* currentMappings<T extends MappedMethod>(
scope: NonNullable<ReturnType<typeof lookupScope>>,
indexedPaths: string[],
parse: (text: string) => T[],
matches: (method: T) => boolean,
) {
const paths = new Set([...new Set(indexedPaths)].slice(0, TARGET_LIMIT));
const overlays = new Set([...changedSources, ...[...useEditorRegistry.getState().editors].map((e) => e.ctx.path)]);
for (const path of [...overlays].filter((p) => isRouteSource(p) && inside(scope.project, p)).slice(0, TARGET_LIMIT))
paths.add(path);
for (const path of [...paths].sort()) {
if (scope.stale()) return;
const text = await read(path).catch(() => null);
if (text === null || text.length > MAX_NAVIGATION_SOURCE || stale()) continue;
currentText.set(path, text);
candidates.push(...controllerMethods(text).map((method) => ({ ...method, path })));
}
const paths = [
...new Set(candidates.filter((target) => callsEndpoint(client, target)).map((target) => target.path)),
].sort();
const result: (Location & { name: string })[] = [];
for (const path of paths.slice(0, 256)) {
if (stale()) return [];
const module = sourceModule(path);
const folder = projectFolder(project, path);
if (client.service && module && folder && isSameOrInside(module, folder.root)) {
const name = await named(module);
if (name && name !== client.service) continue;
}
const text = currentText.get(path) ?? (await read(path).catch(() => null));
if (scope.stale()) return;
if (text === null || text.length > MAX_NAVIGATION_SOURCE) continue;
for (const method of controllerMethods(text).filter((method) => callsEndpoint(client, method))) {
const target = location(path, text, method);
if (
!result.some(
(r) =>
r.path === path &&
r.range.start.line === target.range.start.line &&
r.range.start.col === target.range.start.col,
)
)
result.push(target);
if (result.length === 256) break;
}
if (result.length === 256) break;
const methods = parse(text).filter(matches);
if (methods.length) yield { path, doc: Text.of(text.split("\n")), methods };
}
return stale() ? [] : result;
}
export async function feignTargets(source: string, client: FeignMethod): Promise<FeignLocation[]> {
const scope = lookupScope(source);
if (!scope) return [];
const indexed = await controllerIndex(scope.project.root);
if (scope.stale()) return [];
const matches = (method: HttpShape) => callsEndpoint(client, method);
const paths = indexed
.filter(matches)
.map((entry) => entry.path)
.sort();
const result: FeignLocation[] = [];
for await (const { path, doc, methods } of currentMappings(scope, paths, controllerMethods, matches)) {
const service = client.service && (await controllerService(scope.project, path));
if (service && service !== client.service) continue;
for (const method of methods) {
result.push(location(path, doc, method));
if (result.length === TARGET_LIMIT) break;
}
if (result.length === TARGET_LIMIT) break;
}
return scope.stale() ? [] : result;
}
export async function feignClients(source: string, controller: MappedMethod): Promise<FeignLocation[]> {
const scope = lookupScope(source);
if (!scope) return [];
const [indexed, service] = await Promise.all([
feignClientIndex(scope.project.root),
controllerService(scope.project, source),
]);
if (scope.stale()) return [];
const matches = (client: HttpShape & { service: string | null }) =>
(!service || !client.service || client.service === service) && callsEndpoint(client, controller);
const candidates = indexed.filter(matches);
// Keep named clients ahead of ambiguous ones when the candidate limit is reached.
const paths = [
...candidates
.filter((entry) => service && entry.service)
.map((entry) => entry.path)
.sort(),
...candidates
.filter((entry) => !service || !entry.service)
.map((entry) => entry.path)
.sort(),
];
const confirmed: FeignLocation[] = [],
possible: FeignLocation[] = [];
for await (const { path, doc, methods } of currentMappings(scope, paths, feignMethods, matches)) {
for (const method of methods) {
if (service && method.service) confirmed.push(location(path, doc, method));
else if (possible.length < TARGET_LIMIT) possible.push({ ...location(path, doc, method), possible: true });
if (confirmed.length === TARGET_LIMIT) break;
}
if (confirmed.length === TARGET_LIMIT) break;
}
return scope.stale() ? [] : [...confirmed, ...possible].slice(0, TARGET_LIMIT);
}
export function registerFeignNavigation(): () => void {
@@ -183,44 +230,87 @@ export function registerFeignNavigation(): () => void {
};
}
export async function goToFeignEndpoint(arg?: unknown): Promise<void> {
function clientItem(target: FeignLocation): ListPopupItem {
const project = useProject.getState().project;
const folder = projectFolder(project, target.path);
const path = folder ? relativePath(folder.root, target.path) : target.path;
const display = project?.workspace && folder ? `${folder.name}/${path}` : path;
const { line, col } = target.range.start;
return {
id: `${target.path}:${line}:${col}`,
label: target.name,
detail: `${display}:${line + 1}`,
preview: target.possible ? tx("Possible match") : undefined,
symbol: "method",
location: { path: target.path, line },
run: () => navigateTo(target),
};
}
export async function navigateFeign(direction: "endpoint" | "clients", arg?: unknown): Promise<void> {
const requested = arg as { path?: unknown; offset?: unknown } | undefined;
const editor = typeof requested?.path === "string" ? editorsFor(requested.path)[0] : activeEditor();
if (!editor || editor.ctx.virtual || !["java", "kotlin"].includes(editor.ctx.language)) return;
const scope = lookupScope(editor.ctx.path);
if (!scope) return;
const view = editor.view,
before = view.state.doc,
started = epoch;
before = view.state.doc;
const offset = typeof requested?.offset === "number" ? requested.offset : view.state.selection.main.head;
const client = feignMethods(before.toString()).find((c) => c.from <= offset && offset <= c.to);
if (!client) return;
const atCaret = (m: MappedMethod) => m.from <= offset && offset <= m.to;
const stale = () =>
view.state.doc !== before || started !== epoch || !editorsFor(editor.ctx.path).some((e) => e.view === view);
view.state.doc !== before || scope.stale() || !editorsFor(editor.ctx.path).some((e) => e.view === view);
try {
const targets = await feignTargets(editor.ctx.path, client);
let targets: FeignLocation[];
if (direction === "clients") {
const controller = controllerMethods(before.toString()).find(atCaret);
if (!controller) {
notifications().notify({
level: "info",
title: tx("No Spring request mapping at the caret"),
key: "feign-navigation",
});
return;
}
targets = await feignClients(editor.ctx.path, controller);
} else {
const client = feignMethods(before.toString()).find(atCaret);
if (!client) return;
targets = await feignTargets(editor.ctx.path, client);
}
if (stale()) return;
if (!targets.length) {
notifications().notify({ level: "info", title: tx("No matching Feign endpoint found"), key: "feign-navigation" });
} else if (targets.length === 1) await navigateTo(targets[0]!);
notifications().notify({
level: "info",
title: direction === "clients" ? tx("No matching Feign clients found") : tx("No matching Feign endpoint found"),
key: "feign-navigation",
});
} else if (targets.length === 1 && !targets[0]!.possible) await navigateTo(targets[0]!);
else {
const items = await locationItems(targets);
const items = direction === "clients" ? targets.map(clientItem) : await locationItems(targets);
if (stale()) return;
openPopup({
kind: "list",
title: tx("Choose Feign Endpoint"),
title: direction === "clients" ? tx("Feign Clients") : tx("Choose Feign Endpoint"),
anchor: caretAnchor(view, Math.min(offset, before.length)),
items: items.map((item) => ({ ...item, run: () => (stale() ? undefined : item.run()) })),
});
}
} catch (error) {
notifications().notify({
level: "error",
title: tx("Cannot navigate to Feign endpoint"),
body: String(error),
key: "feign-navigation",
});
if (!stale())
notifications().notify({
level: "error",
title: direction === "clients" ? tx("Cannot find Feign clients") : tx("Cannot navigate to Feign endpoint"),
body: String(error),
key: "feign-navigation",
});
}
}
export function findClientItems(path: string, text: string, offset: number): MenuItem[] {
if (!lookupScope(path) || !controllerMethods(text).some((method) => method.nameFrom === offset)) return [];
return [{ kind: "action", action: FIND_FEIGN_CLIENTS, icon: "search", arg: { path, offset } }];
}
export function feignMenuItems(context: MenuGroupContext): MenuItem[] {
const editor = activeEditor();
if (!editor || editor.ctx.path !== context.paths[0]) return [];
+15 -4
Переглянути файл
@@ -5,15 +5,19 @@ import { projectFolder, relativePath, useProject } from "@/platform/project";
import { registerEndpointProvider, type EndpointEntry } from "@/workbench/contributions";
import { constantPool, resetConstantPool } from "./constants";
import { controllersOf } from "./endpoints";
import { controllerMethods, type ControllerMethod } from "./feign";
import { controllerMethods, feignMethods, type HttpShape } from "./feign";
import { parseSource } from "./source";
export interface ControllerTarget extends ControllerMethod {
interface ControllerTarget extends HttpShape {
path: string;
}
interface ClientSource extends ControllerTarget {
service: string | null;
}
interface RouteIndex {
routes: EndpointEntry[];
controllers: ControllerTarget[];
clients: ClientSource[];
}
export function registerSpringEndpointProvider(): () => void {
@@ -51,8 +55,12 @@ export function controllerIndex(root: string | null): Promise<ControllerTarget[]
return index(root).then((result) => result.controllers);
}
export function feignClientIndex(root: string): Promise<ClientSource[]> {
return index(root).then((result) => result.clients);
}
function index(root: string | null): Promise<RouteIndex> {
if (!root) return Promise.resolve({ routes: [], controllers: [] });
if (!root) return Promise.resolve({ routes: [], controllers: [], clients: [] });
const current = useProject.getState().project;
const project = current?.root === root ? current : null;
const key = JSON.stringify([root, project?.workspace?.projects ?? null]);
@@ -67,6 +75,7 @@ function index(root: string | null): Promise<RouteIndex> {
async function scan(root: string, project: ProjectInfo | null): Promise<RouteIndex> {
const sources = await call(commands.springRouteSources());
const clients: ClientSource[] = [];
const routes: EndpointEntry[] = [];
const controllers: ControllerTarget[] = [];
const parsed = [];
@@ -76,6 +85,8 @@ async function scan(root: string, project: ProjectInfo | null): Promise<RouteInd
if (!folder) continue;
const base = ipcPath(folder).replace(/\/$/, "");
if (!isSameOrInside(path, base)) continue;
for (const { paths, methods, service } of feignMethods(source.text))
clients.push({ path, paths, methods, service });
if (!source.text.includes("Controller")) continue;
parsed.push({ source, path, base, file: parseSource(source.text) });
}
@@ -104,7 +115,7 @@ async function scan(root: string, project: ProjectInfo | null): Promise<RouteInd
}
}
}
return { routes, controllers };
return { routes, controllers, clients };
}
function lineCol(text: string, offset: number): { line: number; col: number } {
+119
Переглянути файл
@@ -0,0 +1,119 @@
/* Mirrors the title bar's project popup: two-line project rows, then action rows. */
.panel {
display: flex;
flex-direction: column;
width: 400px;
padding: var(--space-1-5) 0;
font-family: var(--font-ui);
font-size: var(--fs-ui);
color: var(--fg);
outline: none;
}
.header {
padding: var(--space-1) var(--space-4);
color: var(--fg-muted);
font-size: var(--fs-small);
font-weight: 600;
}
.projects {
display: flex;
flex-direction: column;
max-height: 320px;
margin: 0;
padding: 0;
overflow-y: auto;
list-style: none;
}
.project {
position: relative;
display: flex;
align-items: center;
gap: var(--space-3);
min-width: 0;
margin: 0 var(--space-1-5);
padding: var(--space-1-5) var(--space-2);
border-radius: var(--radius-selection);
}
.project:hover,
.project:focus-within {
background: var(--bg-tree-selected);
}
.text {
display: flex;
flex: 1;
flex-direction: column;
gap: var(--space-0-5);
min-width: 0;
}
.top {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: var(--space-3);
min-width: 0;
}
.name,
.path,
.state {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.name {
color: var(--fg-strong);
}
.path,
.state {
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.state {
flex: none;
max-width: 60%;
}
/* The row's actions take the place of its state while the row is hovered or focused. */
.actions {
position: absolute;
top: 50%;
right: var(--space-2);
display: flex;
gap: var(--space-0-5);
transform: translateY(-50%);
opacity: 0;
}
.project:hover .actions,
.project:focus-within .actions {
opacity: 1;
}
.project:hover .state,
.project:focus-within .state {
visibility: hidden;
}
.project:hover .path,
.project:focus-within .path {
padding-right: 52px;
}
.separator {
height: 1px;
margin: var(--space-1-5) var(--space-3);
background: var(--border);
}
.action {
display: flex;
align-items: center;
min-height: var(--h-list-row);
margin: 0 var(--space-1-5);
padding: 0 var(--space-2);
border: 0;
border-radius: var(--radius-selection);
background: none;
color: var(--fg-strong);
font: inherit;
text-align: left;
cursor: default;
}
.action:hover,
.action:focus-visible {
background: var(--bg-tree-selected);
outline: none;
}
+139
Переглянути файл
@@ -0,0 +1,139 @@
import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { McpBackgroundProject } from "@/bindings";
const mocks = vi.hoisted(() => ({
list: vi.fn(),
unload: vi.fn(),
execute: vi.fn(async (_id: string, _arg?: unknown) => {}),
}));
vi.mock("@/platform/actions", async (original) => ({
...(await original<object>()),
executeAction: mocks.execute,
}));
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return {
...real,
isTauri: () => true,
commands: { ...real.commands, mcpBackgroundProjects: mocks.list, mcpUnloadBackgroundProject: mocks.unload },
};
});
const { emitLocalIdeEvent } = await import("@/platform/ipc");
const { useRemote } = await import("@/platform/remote");
const { BackgroundStatus } = await import("./BackgroundStatus");
const ok = <T,>(data: T) => ({ status: "ok" as const, data });
const project = (root: string, patch: Partial<McpBackgroundProject> = {}): McpBackgroundProject => ({
root,
idleSeconds: 0,
...patch,
});
const inventory = project("/projects/inventory");
const billing = project("/projects/billing", { keptOpenBy: { kind: "request" } });
async function show(projects: McpBackgroundProject[]) {
mocks.list.mockResolvedValue(ok(projects));
render(<BackgroundStatus />);
await act(async () => {});
}
const openPopup = async () => {
fireEvent.click(screen.getByRole("button", { name: /Background Projects/ }));
await act(async () => {});
return screen.getByRole("dialog", { name: "Background Projects" });
};
beforeEach(() => {
mocks.list.mockReset();
mocks.unload.mockReset().mockResolvedValue(ok(null));
mocks.execute.mockClear();
});
afterEach(() => {
cleanup();
useRemote.setState({ session: null });
});
describe("background projects in the status bar", () => {
it("renders nothing while no project is loaded", async () => {
await show([]);
expect(screen.queryByRole("button")).toBeNull();
});
it("shows how many projects are loaded", async () => {
await show([inventory, billing]);
expect(screen.getByRole("button", { name: /Background Projects/ })).toHaveTextContent("2");
});
it("lists each project with its name, path and state", async () => {
await show([inventory, billing]);
const popup = await openPopup();
expect(within(popup).getByText("inventory")).toBeInTheDocument();
expect(within(popup).getByText("/projects/billing")).toBeInTheDocument();
expect(within(popup).getByText("Answering a request")).toBeInTheDocument();
expect(within(popup).getByText("Last request just now")).toBeInTheDocument();
});
it("opens with the focus on the list, so no row's state gives way to its actions", async () => {
await show([inventory]);
const popup = await openPopup();
expect(popup.contains(document.activeElement)).toBe(true);
expect(document.activeElement).not.toBeInstanceOf(HTMLButtonElement);
});
it("stays hidden in a remote window, whose server serves no background projects", async () => {
useRemote.setState({
session: { root: "/srv/app" } as NonNullable<ReturnType<typeof useRemote.getState>["session"]>,
});
await show([inventory]);
expect(screen.queryByRole("button")).toBeNull();
});
it("names a project at the file system root by its path", async () => {
await show([project("/")]);
const popup = await openPopup();
expect(within(popup).getAllByText("/").length).toBe(2);
});
it("opens a project in its own window from its row", async () => {
await show([inventory, billing]);
const popup = await openPopup();
fireEvent.click(within(popup).getByRole("button", { name: "Open /projects/billing in a new window" }));
expect(mocks.execute).toHaveBeenCalledWith("file.openInNewWindow", "/projects/billing");
});
it("unloads the project of the row", async () => {
await show([inventory, billing]);
const popup = await openPopup();
fireEvent.click(within(popup).getByRole("button", { name: "Unload /projects/inventory" }));
expect(mocks.unload).toHaveBeenCalledTimes(1);
expect(mocks.unload).toHaveBeenCalledWith("/projects/inventory");
});
it("unloads every listed project once with Unload All", async () => {
await show([inventory, billing]);
const popup = await openPopup();
fireEvent.click(within(popup).getByRole("button", { name: "Unload All" }));
expect(mocks.unload.mock.calls.map((c) => c[0])).toEqual(["/projects/inventory", "/projects/billing"]);
});
it("closes the popup before it opens the MCP server settings", async () => {
await show([inventory]);
const popup = await openPopup();
mocks.execute.mockImplementationOnce(async () => {
expect(popup.isConnected).toBe(false);
});
fireEvent.click(within(popup).getByRole("button", { name: "MCP Server Settings…" }));
expect(mocks.execute).toHaveBeenCalledWith("file.settings", "agents.mcpServer");
expect(screen.queryByRole("dialog", { name: "Background Projects" })).toBeNull();
});
it("closes the popup and hides the item when the last project unloads", async () => {
await show([inventory]);
await openPopup();
mocks.list.mockResolvedValue(ok([]));
await act(async () => emitLocalIdeEvent({ type: "mcpBackgroundProjectsChanged" }));
expect(screen.queryByRole("dialog", { name: "Background Projects" })).toBeNull();
expect(screen.queryByRole("button")).toBeNull();
});
});
+112
Переглянути файл
@@ -0,0 +1,112 @@
import { useRef, useState } from "react";
import { flushSync } from "react-dom";
import { BarButton, Icon, IconButton, Popup, T } from "@/ui";
import { executeAction } from "@/platform/actions";
import { useTx } from "@/platform/i18n";
import { backgroundProjectState, unloadBackgroundProject, useBackgroundProjects } from "@/platform/mcpBackground";
import { basename } from "@/platform/project";
import { useRemote } from "@/platform/remote";
import { ProjectBadge } from "@/workbench/ProjectBadge";
import styles from "./BackgroundStatus.module.css";
/** Status bar item for the projects the MCP server holds open without a window. */
export function BackgroundStatus() {
const t = useTx();
const loaded = useBackgroundProjects();
// A remote window's commands reach its server, which serves none: the desktop's list stays out of it.
const remote = useRemote((s) => s.session !== null);
const projects = remote ? [] : loaded;
const [open, setOpen] = useState(false);
const ref = useRef<HTMLButtonElement>(null);
const count = projects.length;
// Reset during render, so the popup does not reappear with the next project that loads.
if (count === 0 && open) setOpen(false);
if (count === 0) return null;
return (
<>
<BarButton
ref={ref}
aria-expanded={open}
aria-label={t`Background Projects: ${count}`}
tooltip={t("Projects the MCP server holds open without a window")}
onClick={() => setOpen((o) => !o)}
>
<Icon name="layers" size={14} />
{count}
</BarButton>
<Popup
open={open}
anchor={ref}
placement="top-end"
offset={6}
onClose={() => setOpen(false)}
aria-label={t("Background Projects")}
>
{/* The focus starts on the list: on a row it would swap that row's state for its actions. */}
<div className={styles.panel} tabIndex={-1} data-autofocus>
<div className={styles.header}>
<T>Served without a window</T>
</div>
<ul className={styles.projects}>
{projects.map((project) => {
const path = project.root;
const name = basename(path) || path;
return (
<li key={path} className={styles.project}>
<ProjectBadge name={name} path={path} />
<div className={styles.text}>
<span className={styles.top}>
<span className={styles.name} title={name}>
{name}
</span>
<span className={styles.state}>{backgroundProjectState(project)}</span>
</span>
<span className={styles.path} title={path}>
{path}
</span>
</div>
<span className={styles.actions}>
<IconButton
icon="external-link"
size="small"
title="Open in New Window"
aria-label={t`Open ${path} in a new window`}
onClick={() => void executeAction("file.openInNewWindow", path)}
/>
<IconButton
icon="close"
size="small"
title="Unload"
aria-label={t`Unload ${path}`}
onClick={() => unloadBackgroundProject(path)}
/>
</span>
</li>
);
})}
</ul>
<div className={styles.separator} role="separator" />
<button
type="button"
className={styles.action}
onClick={() => projects.forEach((p) => unloadBackgroundProject(p.root))}
>
<T>Unload All</T>
</button>
<button
type="button"
className={styles.action}
onClick={() => {
flushSync(() => setOpen(false));
void executeAction("file.settings", "agents.mcpServer");
}}
>
<T>MCP Server Settings…</T>
</button>
</div>
</Popup>
</>
);
}
+11 -1
Переглянути файл
@@ -4,12 +4,21 @@ import { commands, call, onIdeEvent, ideEventsReady } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { useRemote } from "@/platform/remote";
import { registerOverlay } from "@/workbench/contributions";
import { registerOverlay, registerStatusItem } from "@/workbench/contributions";
import { BackgroundStatus } from "./BackgroundStatus";
import { McpConfirmHost } from "./ConfirmDialog";
import { denyAll, dropConfirm, handleMcpRequest } from "./requests";
export function activate(): () => void {
const offOverlay = registerOverlay({ id: "mcp.confirm", component: McpConfirmHost });
const offStatus = registerStatusItem({
id: "mcp.background",
align: "right",
priority: 4,
title: "Background Projects",
component: BackgroundStatus,
lightEdit: true,
});
const offRequests = onIdeEvent("mcpRequest", (e) => void handleMcpRequest(e.id, e.request));
const offClosed = onIdeEvent("mcpRequestClosed", (e) => dropConfirm(e.id));
const ready = () => {
@@ -104,6 +113,7 @@ export function activate(): () => void {
disposed = true;
unload();
offOverlay();
offStatus();
offRequests();
offClosed();
window.removeEventListener("beforeunload", unload);
+6 -1
Переглянути файл
@@ -73,8 +73,13 @@ vi.mock("@/platform/ipc", () => ({
mcpSetFocusedEditor: state.reportFocused,
},
}));
vi.mock("@/workbench/contributions", () => ({ registerOverlay: () => () => {}, editorService: vi.fn() }));
vi.mock("@/workbench/contributions", () => ({
registerOverlay: () => () => {},
registerStatusItem: () => () => {},
editorService: vi.fn(),
}));
vi.mock("./ConfirmDialog", () => ({ McpConfirmHost: () => null }));
vi.mock("./BackgroundStatus", () => ({ BackgroundStatus: () => null }));
const { activate } = await import("./index");
describe("MCP editor reports", () => {
+10 -5
Переглянути файл
@@ -511,6 +511,7 @@ function EditConfigsDialog() {
aria-expanded={!collapsed.has(r.key)}
className={styles.editItem}
style={{ paddingLeft: 6 }}
title={tx(r.label)}
onClick={() => toggle(r.key)}
onDragOver={(e) => e.preventDefault()}
onDrop={(e) => onDrop(e, r.kind, null)}
@@ -534,6 +535,7 @@ function EditConfigsDialog() {
aria-expanded={!collapsed.has(r.key)}
className={clsx(styles.editItem, sel && styles.editItemSelected)}
style={{ paddingLeft: 22 }}
title={r.name}
onClick={() => setSelection({ type: "folder", kind: r.kind, name: r.name })}
onDoubleClick={() => toggle(r.key)}
onDragOver={(e) => e.preventDefault()}
@@ -547,6 +549,9 @@ function EditConfigsDialog() {
}
const c = r.config;
const isTomcat = c.kind === "tomcat";
const name = c.name || tx("Unnamed");
const target = c.target ? targetName(c, runTargets) : null;
const scope = !c.detected && !isTomcat ? (c.local ? "local" : "user") : null;
const tomcatNoArtifact =
isTomcat &&
((c.params?.deployment ?? "artifact") === "artifact"
@@ -561,7 +566,9 @@ function EditConfigsDialog() {
className={clsx(styles.editItem, current?.id === c.id && styles.editItemSelected)}
style={{ paddingLeft: r.depth === 2 ? 50 : 34 }}
onClick={() => setSelection({ type: "config", id: c.id })}
title={commandLine(c)}
title={[name + (target ? ` @ ${target}` : "") + (scope ? ` (${scope})` : ""), commandLine(c)]
.filter(Boolean)
.join("\n")}
draggable
onDragStart={(e) => {
dragged.current = c.id;
@@ -579,11 +586,9 @@ function EditConfigsDialog() {
)}
</span>
<span className={styles.chooserName}>{c.name || <T>Unnamed</T>}</span>
{c.target && <span className={styles.chooserMuted}>@ {targetName(c, runTargets)}</span>}
{target && <span className={clsx(styles.chooserMuted, styles.editTarget)}>@ {target}</span>}
{errorsById[c.id] && <Icon name="error" size={12} className={styles.failed} label="Invalid" />}
{!c.detected && !isTomcat && (
<span className={styles.chooserMuted}>{c.local ? "local" : "user"}</span>
)}
{scope && <span className={styles.chooserMuted}>{scope}</span>}
</button>
);
})}
+18
Переглянути файл
@@ -553,6 +553,7 @@
flex: 1;
}
.editSidebar {
container: run-config-navigation / inline-size;
min-height: 0;
display: flex;
flex-direction: column;
@@ -596,6 +597,22 @@
background: var(--bg-selected-strong);
color: var(--fg-strong);
}
.editTarget {
flex: 0 1 auto;
min-width: 0;
max-width: 25%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.editItem .failed {
flex: none;
}
@container run-config-navigation (max-width: 220px) {
.editItem .chooserMuted {
display: none;
}
}
.editForm {
flex: 1;
min-width: 0;
@@ -701,6 +718,7 @@
}
.editGroupName {
color: var(--fg-strong);
font-weight: 600;
}
.editEmpty {
flex: 1;
+112
Переглянути файл
@@ -332,3 +332,115 @@ describe("Export Test Results", () => {
expect(testTree.exportResults).not.toBeNull();
});
});
describe("Sorting Options", () => {
beforeEach(() => localStorage.setItem("openidea.run.testFilters", JSON.stringify({ showPassed: true })));
afterEach(() => localStorage.clear());
/** Run order: beta (item10, Item2, item1), Alpha (zeta); item1 reported no duration. */
function timed() {
const r = new TestResults();
r.apply([
{ type: "result", path: ["beta", "item10()"], status: "passed", durationMs: 5 },
{ type: "result", path: ["beta", "Item2()"], status: "passed", durationMs: 30 },
{ type: "result", path: ["beta", "item1()"], status: "failed" },
{ type: "result", path: ["Alpha", "zeta()"], status: "passed", durationMs: 100 },
]);
r.finish(1);
return r;
}
const view = (results: TestResults, running = false) => (
<TestTreeView results={results} version={1} cwd="/p" selected={null} onSelect={() => {}} running={running} />
);
const rows = () => screen.getAllByRole("treeitem").map((el) => el.textContent!.replace(/[\d.]+ m?s$/, ""));
const option = (name: string) => {
fireEvent.click(screen.getByRole("button", { name: "Sorting Options" }));
return screen.getByRole("menuitemcheckbox", { name });
};
it("keeps the run order until a sort is chosen", () => {
render(view(timed()));
expect(rows()).toEqual(["beta", "item10()", "Item2()", "item1()", "Alpha", "zeta()"]);
expect(screen.getByRole("button", { name: "Sorting Options" })).toHaveAttribute("aria-pressed", "false");
});
it("Sort Alphabetically orders suites and tests by name, ignoring case and comparing numbers, and is remembered", () => {
const { unmount } = render(view(timed()));
fireEvent.click(option("Sort Alphabetically"));
expect(rows()).toEqual(["Alpha", "zeta()", "beta", "item1()", "Item2()", "item10()"]);
expect(screen.getByRole("button", { name: "Sorting Options" })).toHaveAttribute("aria-pressed", "true");
unmount();
render(view(timed()));
expect(rows()).toEqual(["Alpha", "zeta()", "beta", "item1()", "Item2()", "item10()"]);
fireEvent.click(option("Sort Alphabetically"));
expect(rows()).toEqual(["beta", "item10()", "Item2()", "item1()", "Alpha", "zeta()"]);
});
it("Sort by Duration puts the slowest first at each level, tests without a duration last", () => {
render(view(timed()));
fireEvent.click(option("Sort by Duration"));
expect(rows()).toEqual(["Alpha", "zeta()", "beta", "Item2()", "item10()", "item1()"]);
});
it("the two sorts replace each other, as in IDEA", () => {
render(view(timed()));
fireEvent.click(option("Sort by Duration"));
expect(option("Sort by Duration")).toHaveAttribute("aria-checked", "true");
fireEvent.click(screen.getByRole("menuitemcheckbox", { name: "Sort Alphabetically" }));
expect(option("Sort Alphabetically")).toHaveAttribute("aria-checked", "true");
expect(screen.getByRole("menuitemcheckbox", { name: "Sort by Duration" })).toHaveAttribute("aria-checked", "false");
fireEvent.click(screen.getByRole("menuitemcheckbox", { name: "Sort by Duration" }));
expect(rows()).toEqual(["Alpha", "zeta()", "beta", "Item2()", "item10()", "item1()"]);
expect(option("Sort Alphabetically")).toHaveAttribute("aria-checked", "false");
});
it("a saved pair of sorts loads as Sort by Duration alone", () => {
localStorage.setItem(
"openidea.run.testFilters",
JSON.stringify({ showPassed: true, sortAlphabetically: true, sortByDuration: true }),
);
render(view(timed()));
expect(rows()).toEqual(["Alpha", "zeta()", "beta", "Item2()", "item10()", "item1()"]);
expect(option("Sort Alphabetically")).toHaveAttribute("aria-checked", "false");
});
it("the button opens and closes the menu", () => {
render(view(timed()));
const button = screen.getByRole("button", { name: "Sorting Options" });
expect(button).toHaveAttribute("aria-haspopup", "menu");
fireEvent.click(button);
expect(button).toHaveAttribute("aria-expanded", "true");
fireEvent.click(button);
expect(button).toHaveAttribute("aria-expanded", "false");
expect(screen.queryByRole("menuitemcheckbox", { name: "Sort by Duration" })).toBeNull();
});
it("Sort by Duration waits for the run to finish", () => {
localStorage.setItem("openidea.run.testFilters", JSON.stringify({ showPassed: true, sortByDuration: true }));
const { rerender } = render(view(timed(), true));
expect(rows()).toEqual(["beta", "item10()", "Item2()", "item1()", "Alpha", "zeta()"]);
expect(option("Sort by Duration")).toHaveAttribute("aria-disabled", "true");
fireEvent.keyDown(document.activeElement!, { key: "Escape" });
rerender(view(timed(), false));
expect(rows()).toEqual(["Alpha", "zeta()", "beta", "Item2()", "item10()", "item1()"]);
});
it("Previous / Next Failed Test follow the sorted order", () => {
const r = new TestResults();
r.apply([
{ type: "result", path: ["s", "b()"], status: "failed" },
{ type: "result", path: ["s", "a()"], status: "failed" },
]);
r.finish(1);
function Selecting() {
const [selected, setSelected] = useState<string | null>(null);
return (
<TestTreeView results={r} version={1} cwd="/p" selected={selected} onSelect={setSelected} running={false} />
);
}
render(<Selecting />);
fireEvent.click(option("Sort Alphabetically"));
act(() => void occurrenceNavigator("run")!.go(1, false));
expect(screen.getByRole("treeitem", { selected: true }).textContent).toBe("a()");
});
});
+58 -6
Переглянути файл
@@ -5,6 +5,7 @@ import {
findOccurrence,
Icon,
IconButton,
Menu,
showContextMenu,
useContextMenuStore,
Spinner,
@@ -21,21 +22,28 @@ import { ExportTestResultsDialog } from "./ExportTestResultsDialog";
import styles from "./Run.module.css";
import { tx } from "@/platform/i18n";
/** Test tree filters, kept across runs and restarts (IDEA hides passed tests by default). */
/** Test tree filters and sorting, kept across runs and restarts (IDEA hides passed tests by default). */
const FILTERS_KEY = "openidea.run.testFilters";
interface TestFilters {
showPassed: boolean;
showIgnored: boolean;
sortAlphabetically: boolean;
sortByDuration: boolean;
}
export function loadTestFilters(): TestFilters {
try {
const raw = globalThis.localStorage?.getItem(FILTERS_KEY);
const v = raw ? (JSON.parse(raw) as Partial<TestFilters>) : {};
return { showPassed: v.showPassed === true, showIgnored: v.showIgnored !== false };
return {
showPassed: v.showPassed === true,
showIgnored: v.showIgnored !== false,
sortAlphabetically: v.sortAlphabetically === true && v.sortByDuration !== true,
sortByDuration: v.sortByDuration === true,
};
} catch {
return { showPassed: false, showIgnored: true };
return { showPassed: false, showIgnored: true, sortAlphabetically: false, sortByDuration: false };
}
}
@@ -106,6 +114,17 @@ function filterTree(nodes: readonly TestNode[], keep: (n: TestNode) => boolean):
return out;
}
/** IDEA's test tree sorts: by name (ignoring case, numbers by value), or slowest first with untimed nodes last. */
const names = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
const byName = (a: TestNode, b: TestNode) => names.compare(a.name, b.name);
function sortTree(nodes: readonly TestNode[], byDuration: boolean): TestNode[] {
const sorted = nodes.map((n) => (n.children.length ? { ...n, children: sortTree(n.children, byDuration) } : n));
if (!byDuration) return sorted.sort(byName);
const duration = new Map(sorted.map((n) => [n, nodeDuration(n) ?? -1]));
return sorted.sort((a, b) => duration.get(b)! - duration.get(a)!);
}
export interface TestTreeViewProps {
results: TestResults;
version: number;
@@ -132,13 +151,18 @@ export function TestTreeView({
canRunTests,
}: TestTreeViewProps) {
const [filters, setFilters] = useState(loadTestFilters);
const { showPassed, showIgnored } = filters;
const { showPassed, showIgnored, sortAlphabetically, sortByDuration } = filters;
const toggle = (key: keyof TestFilters) =>
setFilters((f) => {
const next = { ...f, [key]: !f[key] };
// The sorts replace each other, as in IDEA.
if (key === "sortAlphabetically" && next.sortAlphabetically) next.sortByDuration = false;
if (key === "sortByDuration" && next.sortByDuration) next.sortAlphabetically = false;
saveTestFilters(next);
return next;
});
const sortButton = useRef<HTMLButtonElement>(null);
const [sortMenu, setSortMenu] = useState(false);
const [expanded, setExpanded] = useState<Set<string> | null>(null);
const [exporting, setExporting] = useState(false);
const [selection, setSelection] = useState<Set<string>>(new Set());
@@ -203,10 +227,13 @@ export function TestTreeView({
};
const counts = useMemo(() => results.counts(), [results, version]); // eslint-disable-line react-hooks/exhaustive-deps
// Like IDEA, Sort by Duration applies once the run has finished, so rows don't jump while tests report.
const byDuration = sortByDuration && !running;
const roots = useMemo(() => {
const keep = (n: TestNode) => (showPassed || n.own !== "passed") && (showIgnored || n.own !== "skipped");
return showPassed && showIgnored ? [...results.roots] : filterTree(results.roots, keep);
}, [results, version, showPassed, showIgnored]); // eslint-disable-line react-hooks/exhaustive-deps
const shown = showPassed && showIgnored ? [...results.roots] : filterTree(results.roots, keep);
return byDuration || sortAlphabetically ? sortTree(shown, byDuration) : shown;
}, [results, version, showPassed, showIgnored, sortAlphabetically, byDuration]); // eslint-disable-line react-hooks/exhaustive-deps
// Expand failed suites by default (IDEA reveals failures); the user's toggles win afterwards.
const effectiveExpanded = useMemo(() => {
@@ -280,6 +307,31 @@ export function TestTreeView({
pressed={showIgnored}
onClick={() => toggle("showIgnored")}
/>
<IconButton
ref={sortButton}
icon="test-sort"
size="small"
iconSize={16}
title="Sorting Options"
aria-haspopup="menu"
aria-expanded={sortMenu}
pressed={sortAlphabetically || sortByDuration}
onClick={() => setSortMenu((v) => !v)}
/>
<Menu
open={sortMenu}
anchor={sortButton}
items={[
{ label: "Sort Alphabetically", checked: sortAlphabetically, run: () => toggle("sortAlphabetically") },
{
label: "Sort by Duration",
checked: sortByDuration,
disabled: running,
run: () => toggle("sortByDuration"),
},
]}
onClose={() => setSortMenu(false)}
/>
<IconButton icon="expand-all" action="run.expandAllTests" size="small" iconSize={16} disabled={!hasSuites} />
<IconButton
icon="collapse-all"
+22 -13
Переглянути файл
@@ -12,43 +12,52 @@
align-items: center;
gap: var(--space-2);
}
.path {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-family: var(--font-mono);
font-size: var(--fs-small);
}
/* Framed like the Folders list above it; rows as in the status bar's Background Projects popup. */
.projects {
display: flex;
flex-direction: column;
gap: var(--space-2);
width: 100%;
max-width: 480px;
min-width: 0;
margin: 0;
padding: 0;
border-radius: var(--radius-small);
box-shadow: inset 0 0 0 1px var(--border-strong);
list-style: none;
}
.project {
display: flex;
align-items: center;
gap: var(--space-2);
gap: var(--space-3);
min-width: 0;
padding: var(--space-2) var(--space-3);
}
.project + .project {
border-top: 1px solid var(--border);
}
.projectText {
display: flex;
flex: 1;
flex-direction: column;
gap: var(--space-0-5);
min-width: 0;
}
.projectName {
.projectName,
.projectPath,
.projectState {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-weight: 600;
}
.projectName {
color: var(--fg-strong);
}
.projectPath,
.projectState {
color: var(--fg-subtle);
font-size: var(--fs-small);
}
.unload {
flex: none;
}
+7 -6
Переглянути файл
@@ -1,10 +1,11 @@
/** Built-in MCP server status and client configurations. */
import { useEffect, useState } from "react";
import { commands, call, isTauri, onIdeEvent, type McpServerStatus } from "@/platform/ipc";
import { backgroundProjectState, useBackgroundProjects } from "@/platform/mcpBackground";
import { backgroundProjectState, unloadBackgroundProject, useBackgroundProjects } from "@/platform/mcpBackground";
import { basename, useProject } from "@/platform/project";
import { WORKFLOW_LIMITS } from "@/platform/workflowSettings";
import { useTx } from "@/platform/i18n";
import { ProjectBadge } from "@/workbench/ProjectBadge";
import { useRemote } from "@/platform/remote";
import { Button, Input, T, copyText } from "@/ui";
import { GlobListEditor, Row, SettingNumber, SettingSelect } from "../components/Form";
@@ -233,7 +234,6 @@ function BackgroundOpenNow() {
const projects = remote ? [] : loaded;
const [mode] = useSetting<string>("mcpServer.backgroundProjects");
const [enabled] = useSetting<boolean>("mcpServer.enabled");
const unload = (root: string) => void call(commands.mcpUnloadBackgroundProject(root)).catch(() => undefined);
return (
<Row
label="Open now"
@@ -255,23 +255,24 @@ function BackgroundOpenNow() {
) : (
<ul className={styles.projects}>
{projects.map((project) => {
const name = basename(project.root);
const name = basename(project.root) || project.root;
return (
<li key={project.root} className={styles.project}>
<ProjectBadge name={name} path={project.root} />
<div className={styles.projectText}>
<span className={styles.projectName} title={name}>
{name}
</span>
<span className={styles.path} title={project.root}>
<span className={styles.projectPath} title={project.root}>
{project.root}
</span>
<span className={styles.status}>{backgroundProjectState(project)}</span>
<span className={styles.projectState}>{backgroundProjectState(project)}</span>
</div>
<Button
size="small"
className={styles.unload}
aria-label={tx`Unload ${project.root}`}
onClick={() => unload(project.root)}
onClick={() => unloadBackgroundProject(project.root)}
>
<T>Unload</T>
</Button>
+44 -3
Переглянути файл
@@ -1,9 +1,9 @@
/** ⌘F in the terminal: search the scrollback (xterm addon-search) with Match Case / Words / Regex. */
import { useEffect, useRef, useState, type KeyboardEvent } from "react";
import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import { create } from "zustand";
import { IconButton, SearchField } from "@/ui";
import type { TerminalSearchOptions, TerminalSearchResult } from "./session";
import { ACTIVE_SEARCH_DECORATION_CLASS, type TerminalSearchOptions, type TerminalSearchResult } from "./session";
import { activeSession } from "./store";
import styles from "./Terminal.module.css";
import { formatBinding, hasPrimaryModifier } from "@/platform/keymap";
@@ -52,6 +52,7 @@ let focusedSeq = 0;
export function TerminalFindBar({ sessionKey }: { sessionKey: string | null }) {
const { open, seq, query, options } = useTerminalFind();
const bar = useRef<HTMLDivElement>(null);
const input = useRef<HTMLInputElement>(null);
const [result, setResult] = useState<TerminalSearchResult | null>(null);
@@ -79,6 +80,46 @@ export function TerminalFindBar({ sessionKey }: { sessionKey: string | null }) {
};
}, [open, query, options, sessionKey]);
// Measure against the bar's default upper-right position, even when it has moved.
useLayoutEffect(() => {
if (!open) return;
const element = bar.current;
const output = element?.parentElement;
const session = activeSession();
if (!element || !output || !session) return;
let frame = 0;
const update = () => {
if (frame) return;
frame = requestAnimationFrame(() => {
frame = 0;
const match = session.isSearchSelection
? session.host.querySelector(`.${ACTIVE_SEARCH_DECORATION_CLASS}`)?.getBoundingClientRect()
: undefined;
if (!match?.width) {
element.removeAttribute("data-match-covered");
return;
}
const top = output.getBoundingClientRect().top;
const { left, right, height } = element.getBoundingClientRect();
element.toggleAttribute(
"data-match-covered",
match.bottom > top && match.top < top + height && match.right > left && match.left < right,
);
});
};
const render = session.term.onRender(update);
const observer = new ResizeObserver(update);
observer.observe(output);
observer.observe(element);
update();
return () => {
render.dispose();
observer.disconnect();
cancelAnimationFrame(frame);
element.removeAttribute("data-match-covered");
};
}, [open, sessionKey]);
if (!open) return null;
const find = (direction: "next" | "previous") => activeSession()?.find(query, options, direction);
@@ -110,6 +151,7 @@ export function TerminalFindBar({ sessionKey }: { sessionKey: string | null }) {
return (
<div
ref={bar}
className={styles.find}
role="search"
aria-label={tx("Find in terminal")}
@@ -170,7 +212,6 @@ export function TerminalFindBar({ sessionKey }: { sessionKey: string | null }) {
disabled={!query || !result?.count}
onClick={() => find("next")}
/>
<span className={styles.findSpacer} />
<IconButton icon="close" title="Close" shortcut="⎋" size="small" onClick={closeTerminalFind} />
</div>
);
+27 -9
Переглянути файл
@@ -27,7 +27,6 @@
/* A tab group: its header (while split) over its tabs' terminals. */
.group {
container: terminal-group / inline-size;
flex: 1;
display: flex;
flex-direction: column;
@@ -35,6 +34,15 @@
min-height: 0;
}
.output {
container: terminal-output / size;
flex: 1;
min-height: 0;
position: relative;
display: flex;
flex-direction: column;
}
.panels {
flex: 1;
position: relative;
@@ -160,12 +168,12 @@
border-bottom: 1px solid var(--border);
}
.findField {
flex: 0 1 360px;
flex: 1;
min-width: 160px;
}
.findCount {
font-family: var(--font-mono);
font-size: var(--fs-small);
font-variant-numeric: tabular-nums;
color: var(--fg-subtle);
padding: 0 6px;
white-space: nowrap;
@@ -174,11 +182,24 @@
.findCountNone {
color: var(--danger);
}
.findSpacer {
flex: 1;
@container terminal-output (min-width: 500px) and (min-height: 160px) {
.find {
position: absolute;
top: 0;
right: 0;
z-index: 6;
width: 500px;
border-left: 1px solid var(--border);
}
.find[data-match-covered] {
top: auto;
bottom: 0;
border-top: 1px solid var(--border);
border-bottom: 0;
}
}
@container terminal-group (max-width: 360px) {
@container terminal-output (max-width: 360px) {
.find {
display: grid;
grid-template-columns: minmax(0, 1fr) repeat(3, var(--h-control-small));
@@ -187,7 +208,4 @@
grid-column: 1 / -1;
min-width: 0;
}
.findSpacer {
display: none;
}
}
+17 -15
Переглянути файл
@@ -218,21 +218,23 @@ function TabGroup({ group, corners }: { group: string; corners: Corners | null }
<GroupTabs group={group} />
</ToolWindowHeader>
)}
{active && <TerminalFindBar sessionKey={active.session} />}
<div ref={panelsRef} className={styles.panels}>
{dropZone && <div className={clsx(styles.dropZone, styles[`drop-${dropZone}`])} />}
{tabs.map((t) => (
<div
key={t.id}
role="tabpanel"
id={`${TAB_PREFIX}-panel-${t.id}`}
aria-labelledby={`${TAB_PREFIX}-tab-${t.id}`}
className={styles.panel}
hidden={t.id !== selected}
>
<TerminalPane sessionKey={t.session} active={t.id === selected} autofocus={t.id === activeTab} />
</div>
))}
<div className={styles.output}>
{active && <TerminalFindBar sessionKey={active.session} />}
<div ref={panelsRef} className={styles.panels}>
{dropZone && <div className={clsx(styles.dropZone, styles[`drop-${dropZone}`])} />}
{tabs.map((t) => (
<div
key={t.id}
role="tabpanel"
id={`${TAB_PREFIX}-panel-${t.id}`}
aria-labelledby={`${TAB_PREFIX}-tab-${t.id}`}
className={styles.panel}
hidden={t.id !== selected}
>
<TerminalPane sessionKey={t.session} active={t.id === selected} autofocus={t.id === activeTab} />
</div>
))}
</div>
</div>
</div>
);
+3 -1
Переглянути файл
@@ -45,6 +45,8 @@ import {
} from "./theme";
import { wheelZoomStep } from "@/platform/wheelZoom";
export const ACTIVE_SEARCH_DECORATION_CLASS = "xterm-find-active-result-decoration";
export interface TerminalSearchOptions {
caseSensitive: boolean;
regex: boolean;
@@ -350,7 +352,7 @@ export class TerminalSession {
const active = this.searchDecorations?.activeMatchBackground;
const isActive = !!active && options.backgroundColor?.toLowerCase() === active.toLowerCase();
const d = registerDecoration(isActive ? { ...options, layer: "top" } : options);
if (d && isActive) d.onRender((el) => el.classList.add("xterm-find-active-result-decoration"));
if (d && isActive) d.onRender((el) => el.classList.add(ACTIVE_SEARCH_DECORATION_CLASS));
return d;
};
const runSearch =
+12 -17
Переглянути файл
@@ -96,8 +96,13 @@
text-overflow: ellipsis;
}
.branchName {
font-family: var(--font-mono);
font-size: var(--fs-small);
min-width: 0;
}
.branchName,
.upstream,
.repoHead {
font-family: var(--font-ui);
font-size: var(--fs-ui);
}
.current {
color: var(--fg-strong);
@@ -111,15 +116,15 @@
font-size: var(--fs-tiny);
line-height: 15px;
}
.upstream {
.upstream,
.repoHead {
flex: 0 4 auto;
margin-left: auto;
min-width: 0;
min-width: min(3ch, 35%);
max-width: 35%;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-faint);
font-family: var(--font-mono);
font-size: var(--fs-tiny);
color: var(--fg-muted);
}
.keys {
margin-left: auto;
@@ -175,16 +180,6 @@
margin: 0 2px;
border-radius: 2px;
}
.repoHead {
flex: 0 4 auto;
margin-left: auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-muted);
font-family: var(--font-mono);
font-size: var(--fs-small);
}
.subChevron {
flex: none;
color: var(--fg-faint);
+15 -6
Переглянути файл
@@ -862,6 +862,11 @@ function MultiRepoPanel({ onClose, actions: popupActions }: { onClose: () => voi
);
}
function branchIndent(depth: number) {
// Leave room for the row controls while keeping each deeper level indented.
return depth ? { paddingInlineStart: `min(${depth * INDENT}px, ${(30 * depth) / (depth + 3)}%)` } : undefined;
}
function RepoRowView({ row, operation }: { row: RepoRow; operation?: string }) {
switch (row.type) {
case "action":
@@ -886,7 +891,7 @@ function RepoRowView({ row, operation }: { row: RepoRow; operation?: string }) {
return <GroupRowView row={row} />;
case "common":
return (
<span className={styles.row} data-row-key={row.key} style={{ paddingLeft: row.depth * INDENT }}>
<span className={styles.row} data-row-key={row.key} style={branchIndent(row.depth)} title={row.branch.name}>
<Icon
name={row.branch.current ? "current-branch" : row.branch.favorite ? "star" : "branch"}
size={14}
@@ -917,7 +922,7 @@ function GroupRowView({ row }: { row: { key: string; label: string; expanded: bo
<span
className={clsx(styles.row, row.depth === 0 && styles.groupRow)}
data-row-key={row.key}
style={row.depth ? { paddingLeft: row.depth * INDENT } : undefined}
style={branchIndent(row.depth)}
aria-expanded={row.expanded}
>
<Icon name={row.expanded ? "chevron-down" : "chevron-right"} size={12} className={styles.rowIcon} />
@@ -928,7 +933,7 @@ function GroupRowView({ row }: { row: { key: string; label: string; expanded: bo
}
function BranchRowView({ row }: { row: BranchRow | Extract<RepoRow, { type: "action" | "branch" | "tag" }> }) {
const indent = "depth" in row && row.depth ? { paddingLeft: row.depth * INDENT } : undefined;
const indent = "depth" in row ? branchIndent(row.depth) : undefined;
if (row.type === "action") {
const keys = shortcutLabel(row.action.id);
return (
@@ -949,7 +954,7 @@ function BranchRowView({ row }: { row: BranchRow | Extract<RepoRow, { type: "act
}
if (row.type === "tag") {
return (
<span className={styles.row} data-row-key={row.key} style={indent}>
<span className={styles.row} data-row-key={row.key} style={indent} title={row.tag}>
<Icon name="tag" size={14} className={styles.rowIcon} />
<HighlightedText
className={clsx(styles.label, styles.branchName)}
@@ -964,7 +969,7 @@ function BranchRowView({ row }: { row: BranchRow | Extract<RepoRow, { type: "act
if (row.type !== "branch") return null;
const b = row.branch;
return (
<span className={styles.row} data-row-key={row.key} style={indent}>
<span className={styles.row} data-row-key={row.key} style={indent} title={b.name}>
{b.current ? (
<Icon name="current-branch" size={14} className={clsx(styles.rowIcon, styles.currentIcon)} />
) : (
@@ -997,7 +1002,11 @@ function BranchRowView({ row }: { row: BranchRow | Extract<RepoRow, { type: "act
</span>
)}
<BranchSync behind={b.behind} ahead={b.ahead} />
{!b.remote && b.upstream && <span className={styles.upstream}>{b.upstream}</span>}
{!b.remote && b.upstream && (
<span className={styles.upstream} title={b.upstream}>
{b.upstream}
</span>
)}
<Icon name="chevron-right" size={10} className={styles.chevron} />
</span>
);
+2 -2
Переглянути файл
@@ -109,7 +109,7 @@ import { showChangesDiff, toLogChanges, type LogChange } from "./logChanges";
import { OperationBanner } from "./operations";
import { runOp } from "./ops";
import { ShelfPanel, loadShelves, useShelf } from "./shelf";
import { refreshNow, repoName, selectRepo, useVcs } from "./store";
import { existsOnDisk, refreshNow, repoName, selectRepo, useVcs } from "./store";
import { saveVcsSetting } from "./settingsUi";
import styles from "./CommitView.module.css";
@@ -302,7 +302,7 @@ 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);
const onDisk = existsOnDisk;
export function deletableFiles(nodes: ChangeNode[]): string[] {
const files = filesOf(nodes);
+19 -3
Переглянути файл
@@ -7,6 +7,7 @@ import { onWorkflowSettingsChange, workflowSettings } from "@/platform/workflowS
import { editorsFor, registerEditorContribution } from "@/editor/api";
import {
notifications,
provideChangesViewSelection,
registerEditorKind,
registerMenuGroup,
registerOverlay,
@@ -16,7 +17,7 @@ import {
import { executeAction, registerActions } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { lazyComponent } from "@/ui";
import { registerVcsActions } from "./actions";
import { commitWindowFocused, registerVcsActions } from "./actions";
import { installChangelists } from "./changelists";
import { registerHistoryActions, trackOperationContext } from "./historyActions";
import { registerLogPaneActions } from "./logPaneActions";
@@ -39,7 +40,7 @@ import { SELECTION_HISTORY_KIND, type SelectionHistoryData } from "./selectionHi
import { registerLocalHistoryActions } from "./localHistoryActions";
import { MERGE_KIND, type MergeData } from "./mergeKind";
import { registerMergeActions } from "./mergeActions";
import { baseName } from "./model";
import { baseName, stripSlash } from "./model";
import { installCommitChecks, installDiagnosticsTracking } from "./commitChecks";
import { installPreparedMessage, useCommit } from "./commitStore";
import { installDraftRevision, provideCommit } from "./commitSelection";
@@ -49,7 +50,7 @@ import { MergeRebaseWidget } from "./MergeRebaseWidget";
import { installFileConfirmations } from "./confirmations";
import { installIncomingCheck } from "./incoming";
import { closeLogTab, installGitLog, selectGitTab, useGitLog } from "./logStore";
import { installVcsStore, onConflictsAppeared, onConflictsCleared, useVcs } from "./store";
import { existsOnDisk, installVcsStore, onConflictsAppeared, onConflictsCleared, useVcs } from "./store";
import { installRootSync } from "./rootSync";
import { tx } from "@/platform/i18n";
import { openOnRemoteActions, registerOpenOnRemote } from "./openOnRemote";
@@ -203,6 +204,21 @@ export function activate(): () => void {
installPreparedMessage(),
installDraftRevision(),
provideCommit(),
// Deployment shortcuts (and similar) use this while Commit / Local Changes is focused.
provideChangesViewSelection(() => {
if (!commitWindowFocused()) return [];
// As the context menu: deleted files have nothing to upload.
const deleted = new Set(
useVcs
.getState()
.status.filter((f) => !existsOnDisk(f))
.map((f) => f.path),
);
return useCommit
.getState()
.selection.filter((p) => !deleted.has(p))
.map(stripSlash);
}),
installIncomingCheck(),
installFileConfirmations(),
installDiffEditorHost(),
+3
Переглянути файл
@@ -145,6 +145,9 @@ export async function focusRepo(root: string): Promise<void> {
if (!useVcs.getState().branchesLoaded) await loadBranches();
}
/** Whether the changed file still exists in the working tree (not deleted there). */
export const existsOnDisk = (f: FileStatus) => f.unstaged !== "deleted" && !(f.staged === "deleted" && !f.unstaged);
export function conflictedFiles(status: readonly FileStatus[] = useVcs.getState().status): FileStatus[] {
return status.filter((f) => effectiveKind(f) === "conflicted");
}
+17 -1
Переглянути файл
@@ -55,6 +55,11 @@
"macOS shortcuts on Windows and Linux, Windows/Linux shortcuts on macOS.": "macOS shortcuts on Windows and Linux, Windows/Linux shortcuts on macOS.",
"Trust Project in Codex": "Trust Project in Codex",
"Go to Feign Endpoint": "Go to Feign Endpoint",
"Find Feign Clients": "Find Feign Clients",
"Feign Clients": "Feign Clients",
"Possible match": "Possible match",
"No matching Feign clients found": "No matching Feign clients found",
"Cannot find Feign clients": "Cannot find Feign clients",
"Choose Feign Endpoint": "Choose Feign Endpoint",
"No matching Feign endpoint found": "No matching Feign endpoint found",
"Cannot navigate to Feign endpoint": "Cannot navigate to Feign endpoint",
@@ -855,6 +860,8 @@
"Builds or starts the project's dev container (devcontainer.json) with the Dev Containers CLI and opens the project in it.": "Builds or starts the project's dev container (devcontainer.json) with the Dev Containers CLI and opens the project in it.",
"devcontainer up exited with {status}": "devcontainer up exited with {status}",
"Select an item to view details": "Select an item to view details",
"Select files in the Project view, Commit tool window, or open a file in the editor": "Select files in the Project view, Commit tool window, or open a file in the editor",
"Nothing to show": "Nothing to show",
"IDE-managed Tomcat runtime directory must not overlap Tomcat home or base directory": "IDE-managed Tomcat runtime directory must not overlap Tomcat home or base directory",
"Invalid log stream configuration": "Invalid log stream configuration",
@@ -1732,6 +1739,13 @@
"Unload {path}": "Unload {path}",
"Background projects are off": "Background projects are off",
"A remote host serves only the project open in its window": "A remote host serves only the project open in its window",
"Served without a window": "Served without a window",
"Background Projects": "Background Projects",
"Background Projects: {count}": "Background Projects: {count}",
"Projects the MCP server holds open without a window": "Projects the MCP server holds open without a window",
"Open {path} in a new window": "Open {path} in a new window",
"Unload All": "Unload All",
"MCP Server Settings…": "MCP Server Settings…",
"The MCP server is off": "The MCP server is off",
"Archived ({count})": "Archived ({count})",
"Insert": "Insert",
@@ -2718,5 +2732,7 @@
"Hover actions": "Hover actions",
"Hover action": "Hover action",
"{count} hover actions": "{count} hover actions",
"{description}; JVM options: {flags}": "{description}; JVM options: {flags}"
"{description}; JVM options: {flags}": "{description}; JVM options: {flags}",
"Sorting Options": "Sorting Options",
"Sort by Duration": "Sort by Duration"
}
+2 -2
Переглянути файл
@@ -4363,7 +4363,6 @@
"Edit the deployment servers and options": "Editar los servidores y opciones de despliegue",
"Configuration…": "Configuración…",
"No deployment server configured": "No hay ningún servidor de despliegue configurado",
"Select files in the Project view or open a file in the editor": "Seleccione archivos en la vista Proyecto o abra un archivo en el editor",
"Upload to": "Subir a",
"Download from": "Descargar de",
"Sync with Deployed to": "Sincronizar con lo desplegado en",
@@ -6137,5 +6136,6 @@
"Plugin update available": "Actualización de plugin disponible",
"{length} plugin updates available": "{length} actualizaciones de plugins disponibles",
"Updated {updated} plugins": "Se actualizaron {updated} plugins",
"This version is signed with a different key than the installed one, and the publisher's earlier key doesn't vouch for it. Only continue if you know the publisher changed keys.": "Esta versión está firmada con una clave diferente a la instalada y la clave anterior del editor no la avala. Continúe solo si sabe que el editor cambió de clave."
"This version is signed with a different key than the installed one, and the publisher's earlier key doesn't vouch for it. Only continue if you know the publisher changed keys.": "Esta versión está firmada con una clave diferente a la instalada y la clave anterior del editor no la avala. Continúe solo si sabe que el editor cambió de clave.",
"Select files in the Project view, Commit tool window, or open a file in the editor": "Seleccione archivos en la vista Proyecto, la ventana de Confirmación, o abra un archivo en el editor"
}
+2 -2
Переглянути файл
@@ -4219,7 +4219,6 @@
"Edit the deployment servers and options": "Modifier les serveurs et les options de déploiement",
"Configuration…": "Configuration…",
"No deployment server configured": "Aucun serveur de déploiement configuré",
"Select files in the Project view or open a file in the editor": "Sélectionnez des fichiers dans la vue Projet ou ouvrez un fichier dans l'éditeur",
"Upload to": "Envoyer vers",
"Download from": "Télécharger depuis",
"Sync with Deployed to": "Synchroniser avec la version déployée sur",
@@ -5765,5 +5764,6 @@
"Keep abstract": "Garder abstrait",
"Methods pulled up to an interface are declared abstract there.": "Les méthodes remontées dans une interface y sont déclarées abstraites.",
"The file changed; open the dialog again": "Le fichier a changé ; rouvrez la boîte de dialogue",
"Replace preview": "Aperçu du remplacement"
"Replace preview": "Aperçu du remplacement",
"Select files in the Project view, Commit tool window, or open a file in the editor": "Sélectionnez des fichiers dans la vue Projet, la fenêtre Commit, ou ouvrez un fichier dans l'éditeur"
}
+2 -2
Переглянути файл
@@ -4425,7 +4425,6 @@
"Edit the deployment servers and options": "배포 서버 및 옵션 편집",
"Configuration…": "구성…",
"No deployment server configured": "구성된 배포 서버가 없습니다",
"Select files in the Project view or open a file in the editor": "프로젝트 뷰에서 파일을 선택하거나 편집기에서 파일을 여세요",
"Upload to": "업로드 대상",
"Download from": "다운로드 위치",
"Sync with Deployed to": "배포된 항목과 동기화",
@@ -6248,5 +6247,6 @@
"Empty: where the service mounts the project.": "비워 두면 서비스가 프로젝트를 마운트하는 위치를 사용합니다.",
"The project is mounted here; paths and the working directory are mapped into it.": "프로젝트가 여기에 마운트되며, 경로와 작업 디렉터리가 이 위치로 매핑됩니다.",
"Published ports": "게시된 포트",
"Run as the image's user, not the project folder's owner (Linux)": "프로젝트 폴더 소유자가 아닌 이미지의 사용자로 실행(Linux)"
"Run as the image's user, not the project folder's owner (Linux)": "프로젝트 폴더 소유자가 아닌 이미지의 사용자로 실행(Linux)",
"Select files in the Project view, Commit tool window, or open a file in the editor": "프로젝트 뷰나 커밋 도구 창에서 파일을 선택하거나 편집기에서 파일을 여세요"
}
+2 -2
Переглянути файл
@@ -4316,7 +4316,6 @@
"Edit the deployment servers and options": "Edytuj serwery wdrażania i opcje",
"Configuration…": "Konfiguracja…",
"No deployment server configured": "Brak skonfigurowanego serwera wdrażania",
"Select files in the Project view or open a file in the editor": "Wybierz pliki w widoku Projektu lub otwórz plik w edytorze",
"Upload to": "Prześlij do",
"Download from": "Pobierz z",
"Sync with Deployed to": "Synchronizuj z wdrożeniem na",
@@ -5943,5 +5942,6 @@
"Back to Changed Files": "Powrót do zmienionych plików",
"Default (the module's JDK)": "Domyślnie (zestaw JDK modułu)",
"Use classpath of module": "Użyj ścieżki klas modułu",
"Find by main class": "Znajdź według klasy głównej"
"Find by main class": "Znajdź według klasy głównej",
"Select files in the Project view, Commit tool window, or open a file in the editor": "Wybierz pliki w widoku Projektu, oknie Commit lub otwórz plik w edytorze"
}
+2 -2
Переглянути файл
@@ -4329,7 +4329,6 @@
"Edit the deployment servers and options": "Editar os servidores e opções de implantação",
"Configuration…": "Configuração…",
"No deployment server configured": "Nenhum servidor de implantação configurado",
"Select files in the Project view or open a file in the editor": "Selecione arquivos na visualização do projeto ou abra um arquivo no editor",
"Upload to": "Fazer upload para",
"Download from": "Fazer download de",
"Sync with Deployed to": "Sincronizar com implantado em",
@@ -5957,5 +5956,6 @@
"Back to Changed Files": "Voltar para Arquivos alterados",
"Default (the module's JDK)": "Padrão (JDK do módulo)",
"Use classpath of module": "Usar classpath do módulo",
"Find by main class": "Localizar por classe principal"
"Find by main class": "Localizar por classe principal",
"Select files in the Project view, Commit tool window, or open a file in the editor": "Selecione arquivos na visualização do projeto, na janela Commit, ou abra um arquivo no editor"
}
+17 -2
Переглянути файл
@@ -53,6 +53,11 @@
"macOS shortcuts on Windows and Linux, Windows/Linux shortcuts on macOS.": "在 Windows 和 Linux 上显示 macOS 快捷键,在 macOS 上显示 Windows/Linux 快捷键。",
"Trust Project in Codex": "在 Codex 中信任项目",
"Go to Feign Endpoint": "跳转到 Feign 端点",
"Find Feign Clients": "查找 Feign 客户端",
"Feign Clients": "Feign 客户端",
"Possible match": "可能匹配",
"No matching Feign clients found": "未找到匹配的 Feign 客户端",
"Cannot find Feign clients": "无法查找 Feign 客户端",
"Choose Feign Endpoint": "选择 Feign 端点",
"No matching Feign endpoint found": "未找到匹配的 Feign 端点",
"Cannot navigate to Feign endpoint": "无法跳转到 Feign 端点",
@@ -5219,7 +5224,8 @@
"Edit the deployment servers and options": "编辑部署服务器和选项",
"Configuration…": "配置…",
"No deployment server configured": "未配置部署服务器",
"Select files in the Project view or open a file in the editor": "请在项目视图中选择文件,或在编辑器中打开文件",
"Select files in the Project view, Commit tool window, or open a file in the editor": "请在项目视图或提交工具窗口中选择文件,或在编辑器中打开文件",
"Upload to": "上传到",
"Download from": "下载自",
"Sync with Deployed to": "与已部署的同步",
@@ -8136,6 +8142,13 @@
"Unload {path}": "卸载 {path}",
"Background projects are off": "后台项目已关闭",
"A remote host serves only the project open in its window": "远程主机只为其窗口中打开的项目提供服务",
"Served without a window": "无窗口提供服务",
"Background Projects": "后台项目",
"Background Projects: {count}": "后台项目:{count}",
"Projects the MCP server holds open without a window": "MCP 服务器在没有窗口的情况下保持打开的项目",
"Open {path} in a new window": "在新窗口中打开 {path}",
"Unload All": "全部卸载",
"MCP Server Settings…": "MCP 服务器设置…",
"The MCP server is off": "MCP 服务器已关闭",
"Archived ({count})": "归档({count})",
"Insert": "插入",
@@ -9091,5 +9104,7 @@
"Hover actions": "悬停操作",
"Hover action": "悬停操作",
"{count} hover actions": "{count} 个悬停操作",
"{description}; JVM options: {flags}": "{description};JVM 选项:{flags}"
"{description}; JVM options: {flags}": "{description};JVM 选项:{flags}",
"Sorting Options": "排序选项",
"Sort by Duration": "按持续时间排序"
}
+5
Переглянути файл
@@ -23,6 +23,11 @@ export function backgroundProjectState(project: McpBackgroundProject): string {
return tx`Idle ${n} min, unloads in ${m} min`;
}
/** Unloads one background project at once; one that is not loaded is already unloaded. */
export function unloadBackgroundProject(root: string): void {
void call(commands.mcpUnloadBackgroundProject(root)).catch(() => undefined);
}
/**
* The background projects, current: fetched on mount and when the backend reports a change, and every 30 s
* while any is loaded, every 3 s while one answers a request (the end of a request and an idle project's
+7
Переглянути файл
@@ -0,0 +1,7 @@
<!-- Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. -->
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7.5 3.5H14.5" stroke="#6C707E" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M9.5 8H14.5" stroke="#6C707E" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M11.5 12.5H14.5" stroke="#6C707E" stroke-linecap="round" stroke-linejoin="round"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M7.85355 9.85355C8.04881 9.65829 8.04881 9.34171 7.85355 9.14645C7.65829 8.95118 7.34171 8.95118 7.14645 9.14645L5 11.2929L5 3.5C5 3.22386 4.77615 3 4.5 3C4.22386 3 4 3.22386 4 3.5L4 11.2929L1.85355 9.14645C1.65829 8.95118 1.34171 8.95118 1.14645 9.14645C0.951184 9.34171 0.951184 9.65829 1.14645 9.85355L4.14644 12.8536C4.23693 12.944 4.36193 13 4.5 13C4.63885 13 4.76447 12.9434 4.85507 12.852L7.85355 9.85355Z" fill="#6C707E"/>
</svg>

Після

Ширина:  |  Висота:  |  Розмір: 980 B

+7
Переглянути файл
@@ -0,0 +1,7 @@
<!-- Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. -->
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7.5 3.5H14.5" stroke="#CED0D6" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M9.5 8H14.5" stroke="#CED0D6" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M11.5 12.5H14.5" stroke="#CED0D6" stroke-linecap="round" stroke-linejoin="round"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M7.85355 9.85355C8.04881 9.65829 8.04881 9.34171 7.85355 9.14645C7.65829 8.95118 7.34171 8.95118 7.14645 9.14645L5 11.2929L5 3.5C5 3.22386 4.77615 3 4.5 3C4.22386 3 4 3.22386 4 3.5L4 11.2929L1.85355 9.14645C1.65829 8.95118 1.34171 8.95118 1.14645 9.14645C0.951184 9.34171 0.951184 9.65829 1.14645 9.85355L4.14644 12.8536C4.23693 12.944 4.36193 13 4.5 13C4.63885 13 4.76447 12.9434 4.85507 12.852L7.85355 9.85355Z" fill="#CED0D6"/>
</svg>

Після

Ширина:  |  Висота:  |  Розмір: 980 B

+2
Переглянути файл
@@ -312,6 +312,7 @@ const ICONS = {
"page-first": "openidea/general/pageFirst",
"page-last": "openidea/general/pageLast",
sliders: "openidea/general/sliders",
layers: "openidea/general/layers",
"graphql-variables": "openidea/general/graphqlVariables",
layout: "general/layout",
split: "general/splitVertically",
@@ -448,6 +449,7 @@ const ICONS = {
"test-pending": "run/testNotRunYet",
"test-show-passed": "run/showPassed",
"test-show-ignored": "run/showIgnored",
"test-sort": "runConfigurations/sortByDuration",
debug: "run/debug",
"run-coverage": "run/runWithCoverage",
profile: "run/profile",
+4
Переглянути файл
@@ -0,0 +1,4 @@
<!-- OpenIDEA: Layers (stacked planes) -->
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8 2L13.5 4.75L8 7.5L2.5 4.75L8 2Z" stroke="#6C707E" stroke-linejoin="round"/><path d="M2.5 7.5L8 10.25L13.5 7.5M2.5 10.25L8 13L13.5 10.25" stroke="#6C707E" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

Після

Ширина:  |  Висота:  |  Розмір: 361 B

+14
Переглянути файл
@@ -0,0 +1,14 @@
.badge {
display: flex;
flex: none;
align-items: center;
justify-content: center;
width: 26px;
height: 26px;
border-radius: var(--radius-selection);
background: linear-gradient(135deg, var(--project-color), var(--project-color-end));
color: var(--fg-button-primary);
font-size: var(--fs-tiny);
font-weight: 600;
letter-spacing: 0.02em;
}
+15
Переглянути файл
@@ -0,0 +1,15 @@
import { useSyncExternalStore } from "react";
import clsx from "clsx";
import { projectInitials } from "./projectColor";
import { subscribeTabColors, tabColorOverride, tabColorVars, tabColorsVersion } from "./tabColors";
import styles from "./ProjectBadge.module.css";
/** Square project avatar for a two-line row: the title bar widget's colour and initials. */
export function ProjectBadge({ name, path, className }: { name: string; path: string; className?: string }) {
useSyncExternalStore(subscribeTabColors, tabColorsVersion);
return (
<span className={clsx(styles.badge, className)} style={tabColorVars(name, tabColorOverride(path))} aria-hidden>
{projectInitials(name)}
</span>
);
}
+14
Переглянути файл
@@ -1464,6 +1464,20 @@ export function provideProjectViewSelection(get: () => string[]): () => void {
/** Selected project view paths (absolute); empty without a project view. */
export const projectViewSelection = (): string[] => projectSelection?.() ?? [];
// Commit / Local Changes selection while that tool window has focus. Provided by
// features/vcs so Deployment (and similar) shortcuts see multi-file picks there.
let changesSelection: (() => string[]) | undefined;
export function provideChangesViewSelection(get: () => string[]): () => void {
changesSelection = get;
return () => {
if (changesSelection === get) changesSelection = undefined;
};
}
/** Selected change-tree paths (absolute) while Commit/Local Changes is focused. */
export const changesViewSelection = (): string[] => changesSelection?.() ?? [];
/** The project view node the user last selected; `dir` decides the icon and popup of the last crumb. */
export interface ProjectViewLead {
path: string;