дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-29 13:52:36 +02:00
Порівняти коміти
28
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
d28bf8eeae | ||
|
|
b89febd61f | ||
|
|
99ca421a0e | ||
|
|
e6fd000bb7 | ||
|
|
9e2e229a56 | ||
|
|
60564f4b33 | ||
|
|
db1fff2f6a | ||
|
|
1c09fbe28a | ||
|
|
834fac89b4 | ||
|
|
844e290729 | ||
|
|
a1ab5b6c29 | ||
|
|
9797598864 | ||
|
|
21a8856dfd | ||
|
|
9c523bba36 | ||
|
|
8f3e20cdf8 | ||
|
|
affee5452d | ||
|
|
4149c1b5d7 | ||
|
|
52010b95b1 | ||
|
|
9e530a9024 | ||
|
|
aebc7f7f99 | ||
|
|
1586738468 | ||
|
|
7ec5080047 | ||
|
|
06d7487913 | ||
|
|
e676138956 | ||
|
|
1a1ea14b9c | ||
|
|
5c0917b849 | ||
|
|
19f2c0ef5d | ||
|
|
8c696b8fe7 |
No files matched your search
Створено
@@ -4511,6 +4511,7 @@ dependencies = [
|
||||
name = "ide-http"
|
||||
version = "0.1.49"
|
||||
dependencies = [
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
"parking_lot",
|
||||
|
||||
@@ -141,7 +141,7 @@ struct Shared {
|
||||
paths: AgentPaths,
|
||||
runtime: tokio::runtime::Handle,
|
||||
connector: Connector,
|
||||
sink: RwLock<Option<AgentSink>>,
|
||||
sinks: RwLock<HashMap<String, AgentSink>>,
|
||||
security: RwLock<Option<SecurityHook>>,
|
||||
new_task_approvals: RwLock<Option<NewTaskApprovalsHook>>,
|
||||
known: Arc<Mutex<HashMap<String, Known>>>,
|
||||
@@ -213,10 +213,12 @@ impl Shared {
|
||||
}
|
||||
|
||||
fn emit(&self, event: AgentEvent) {
|
||||
let sink = self.sink.read().clone();
|
||||
if let Some(sink) = sink {
|
||||
sink(event);
|
||||
let mut sinks: Vec<_> = self.sinks.read().values().cloned().collect();
|
||||
let Some(last) = sinks.pop() else { return };
|
||||
for sink in sinks {
|
||||
sink(event.clone());
|
||||
}
|
||||
last(event);
|
||||
}
|
||||
|
||||
/// The MCP servers passed to a session, and the names of the ones off for it.
|
||||
@@ -561,7 +563,7 @@ impl AgentManager {
|
||||
paths,
|
||||
runtime,
|
||||
connector,
|
||||
sink: RwLock::new(None),
|
||||
sinks: RwLock::new(HashMap::new()),
|
||||
security: RwLock::new(None),
|
||||
new_task_approvals: RwLock::new(None),
|
||||
known,
|
||||
@@ -604,12 +606,22 @@ impl AgentManager {
|
||||
|
||||
/// Routes events to `sink` (replacing the previous subscriber); returns every task.
|
||||
pub fn subscribe(&self, sink: AgentSink) -> Vec<AgentTask> {
|
||||
*self.shared.sink.write() = Some(sink);
|
||||
self.subscribe_as("", sink)
|
||||
}
|
||||
|
||||
/// Routes events to `sink` too, replacing only the sink `subscriber` (a view of the project) had.
|
||||
pub fn subscribe_as(&self, subscriber: &str, sink: AgentSink) -> Vec<AgentTask> {
|
||||
self.shared.sinks.write().insert(subscriber.to_owned(), sink);
|
||||
let mut tasks: Vec<AgentTask> = self.tasks.read().values().map(|t| t.state.lock().snapshot()).collect();
|
||||
tasks.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
|
||||
tasks
|
||||
}
|
||||
|
||||
/// A closed view releases its sink, never the task or its agent process.
|
||||
pub fn unsubscribe(&self, subscriber: &str) {
|
||||
self.shared.sinks.write().remove(subscriber);
|
||||
}
|
||||
|
||||
/// Sets the callback used to read the active command execution security policy.
|
||||
pub fn set_security_hook(&self, hook: SecurityHook) {
|
||||
*self.shared.security.write() = Some(hook);
|
||||
@@ -2000,7 +2012,7 @@ impl AgentManager {
|
||||
// What arrived after the last save (a subagent's late updates).
|
||||
task.persist();
|
||||
}
|
||||
*self.shared.sink.write() = None;
|
||||
self.shared.sinks.write().clear();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -452,6 +452,35 @@ fn manager(dir: &Path, agent: Arc<FakeAgent>) -> AgentManager {
|
||||
manager_at(dir, &dir.join("models.json"), agent)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn subscribers_do_not_replace_or_close_each_other() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mgr = manager(tmp.path(), Arc::new(FakeAgent::default()));
|
||||
let main = Arc::new(Mutex::new(Vec::new()));
|
||||
let child = Arc::new(Mutex::new(Vec::new()));
|
||||
let subscribe = |window: &str, events: &Arc<Mutex<Vec<AgentEvent>>>| {
|
||||
let events = events.clone();
|
||||
mgr.subscribe_as(window, Arc::new(move |event| events.lock().push(event)));
|
||||
};
|
||||
subscribe("main", &main);
|
||||
subscribe("editor-main-1", &child);
|
||||
mgr.shared.emit(AgentEvent::Providers);
|
||||
assert_eq!(main.lock().len(), 1);
|
||||
assert_eq!(child.lock().len(), 1);
|
||||
// A reloaded webview replaces only its own old channel.
|
||||
let reloaded = Arc::new(Mutex::new(Vec::new()));
|
||||
subscribe("editor-main-1", &reloaded);
|
||||
mgr.shared.emit(AgentEvent::Providers);
|
||||
assert_eq!(main.lock().len(), 2);
|
||||
assert_eq!(child.lock().len(), 1);
|
||||
assert_eq!(reloaded.lock().len(), 1);
|
||||
mgr.unsubscribe("editor-main-1");
|
||||
mgr.shared.emit(AgentEvent::Providers);
|
||||
assert_eq!(main.lock().len(), 3);
|
||||
assert_eq!(reloaded.lock().len(), 1);
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
fn manager_at(dir: &Path, models_file: &Path, agent: Arc<FakeAgent>) -> AgentManager {
|
||||
// These tests speak to FakeAgent, never an installed CLI, including after a provider reload.
|
||||
let agents = dir.join("agents");
|
||||
|
||||
@@ -602,7 +602,13 @@ impl DbManager {
|
||||
pub(crate) async fn jdbc_completion(&self, id: &str, pool: &JdbcPool) -> IdeResult<crate::CompletionModel> {
|
||||
let mut tables = vec![];
|
||||
let mut column_count = 0;
|
||||
let schemas = self.schemas(id).await?;
|
||||
// Read the schemas the source's Schemas tab picks, like the database tree does. It also
|
||||
// keeps large instances usable: an Oracle server exposes dozens of system schemas, and
|
||||
// dumping the columns of all of them takes minutes, during which the bridge (a single
|
||||
// Java process that runs one command at a time) executes none of the user's statements.
|
||||
let introspection = self.source(id)?.introspection;
|
||||
let schemas: Vec<String> =
|
||||
self.schemas(id).await?.into_iter().filter(|s| introspection.shows_schema(s)).collect();
|
||||
for schema in &schemas {
|
||||
// Columns of the whole namespace in one call; a driver that refuses it still completes tables.
|
||||
let mut columns = if column_count < crate::MAX_META_ROWS {
|
||||
|
||||
@@ -124,6 +124,45 @@ impl Default for DbIntrospection {
|
||||
}
|
||||
}
|
||||
|
||||
impl DbIntrospection {
|
||||
/// Whether the tree shows this schema: every one with `all_schemas`, otherwise it has to
|
||||
/// match one of the `schemas` patterns. The completion model uses the same test, so it
|
||||
/// offers exactly the tables the tree lists (and does not read the ones it never shows).
|
||||
pub fn shows_schema(&self, name: &str) -> bool {
|
||||
self.all_schemas
|
||||
|| self.schemas.iter().map(|p| p.trim()).filter(|p| !p.is_empty()).any(|p| schema_matches(p, name))
|
||||
}
|
||||
}
|
||||
|
||||
/// `*` matches any run of characters, `?` a single one; a pattern without wildcards matches the
|
||||
/// name as typed (the dialog fills names from the list the server returned, so case is settled).
|
||||
fn schema_matches(pattern: &str, name: &str) -> bool {
|
||||
if !pattern.contains('*') && !pattern.contains('?') {
|
||||
return pattern == name;
|
||||
}
|
||||
let p: Vec<char> = pattern.chars().collect();
|
||||
let n: Vec<char> = name.chars().collect();
|
||||
let (mut pi, mut ni) = (0, 0);
|
||||
// Position of the last `*` and how much of the name it has already swallowed.
|
||||
let mut star: Option<(usize, usize)> = None;
|
||||
while ni < n.len() {
|
||||
if pi < p.len() && (p[pi] == '?' || p[pi] == n[ni]) {
|
||||
pi += 1;
|
||||
ni += 1;
|
||||
} else if pi < p.len() && p[pi] == '*' {
|
||||
star = Some((pi, ni));
|
||||
pi += 1;
|
||||
} else if let Some((at, taken)) = star {
|
||||
pi = at + 1;
|
||||
ni = taken + 1;
|
||||
star = Some((at, taken + 1));
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
p[pi..].iter().all(|&c| c == '*')
|
||||
}
|
||||
|
||||
/// Advanced tab: a driver property. PostgreSQL: run-time parameters (and
|
||||
/// `application_name`); MySQL: session variables (and `charset`, `collation`);
|
||||
/// SQLite: pragmas. See [`crate::conn`].
|
||||
@@ -765,4 +804,24 @@ mod tests {
|
||||
assert_eq!(r.snowflake().auth, DbSnowflakeAuth::Browser);
|
||||
assert_eq!(scheme_driver("snowflake"), Some(DbDriver::Snowflake));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn introspection_shows_only_the_picked_schemas() {
|
||||
let mut i = DbIntrospection::default();
|
||||
assert!(i.shows_schema("SYS"), "the default reads every schema");
|
||||
|
||||
i.all_schemas = false;
|
||||
assert!(!i.shows_schema("SYS"), "nothing picked: the tree lists nothing either");
|
||||
|
||||
i.schemas = vec!["XMCB".into(), " APP_* ".into()];
|
||||
assert!(i.shows_schema("XMCB"));
|
||||
assert!(i.shows_schema("APP_INFO"));
|
||||
assert!(!i.shows_schema("APP"), "`*` needs the text that follows it");
|
||||
assert!(!i.shows_schema("SYS"));
|
||||
assert!(!i.shows_schema("xmcb"), "patterns match the names the server returned");
|
||||
|
||||
i.schemas = vec!["?".into()];
|
||||
assert!(i.shows_schema("A"));
|
||||
assert!(!i.shows_schema("AB"));
|
||||
}
|
||||
}
|
||||
@@ -17,12 +17,28 @@ use ide_tools::InstallEvent;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
|
||||
/// Streams the project's agent events to this window; returns every task.
|
||||
/// Streams the project's agent events to `subscriber`, one of the project's windows (a remote
|
||||
/// host sees them all as one `window`); returns every task.
|
||||
#[command(trust = always)]
|
||||
pub fn agent_subscribe(host: &Host, window: &str, on_event: Channel<AgentEvent>) -> IdeResult<Vec<AgentTask>> {
|
||||
Ok(host.project(window)?.agents.subscribe(std::sync::Arc::new(move |e| {
|
||||
let _ = on_event.send(e);
|
||||
})))
|
||||
pub fn agent_subscribe(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
on_event: Channel<AgentEvent>,
|
||||
subscriber: String,
|
||||
) -> IdeResult<Vec<AgentTask>> {
|
||||
Ok(host.project(window)?.agents.subscribe_as(
|
||||
&subscriber,
|
||||
std::sync::Arc::new(move |e| {
|
||||
let _ = on_event.send(e);
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
/// Stops the events of a window that closed.
|
||||
#[command(trust = always)]
|
||||
pub fn agent_unsubscribe(host: &Host, window: &str, subscriber: String) -> IdeResult<()> {
|
||||
host.project(window)?.agents.unsubscribe(&subscriber);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[command(trust = trusted)]
|
||||
@@ -1125,4 +1141,5 @@ ide_command::domain!(
|
||||
agent_subscribe,
|
||||
agent_unarchive,
|
||||
agent_unqueue,
|
||||
agent_unsubscribe,
|
||||
);
|
||||
@@ -633,8 +633,14 @@ pub async fn vcs_add_to_ignore(
|
||||
host.require_trust(window)?;
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
// The Changes view lists every repository of the window (the project's and the
|
||||
// attached ones'): a path inside the project folder, or in any of those repositories.
|
||||
// The folder check stays so a request right after opening, before the repositories
|
||||
// are discovered, still works.
|
||||
let repos = project.repos();
|
||||
for path in &paths {
|
||||
if path == &project.root || !path.starts_with(&project.root) {
|
||||
let in_project = path != &project.root && path.starts_with(&project.root);
|
||||
if !in_project && repos.for_path(path).is_none() {
|
||||
return Err(ide_core::IdeError::invalid("Ignore selection is outside the project"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ async fn patches_read_and_write_the_requested_repository() {
|
||||
git(root, &["init", "-b", "main"]);
|
||||
git(root, &["config", "user.name", "Test"]);
|
||||
git(root, &["config", "user.email", "[email protected]"]);
|
||||
git(root, &["config", "core.autocrlf", "false"]);
|
||||
std::fs::write(root.join("same.txt"), format!("root {i}\n")).unwrap();
|
||||
git(root, &["add", "."]);
|
||||
git(root, &["commit", "-m", "initial"]);
|
||||
@@ -65,3 +66,75 @@ async fn patches_read_and_write_the_requested_repository() {
|
||||
assert!(vcs::vcs_apply_patch(&host, "main", Some(base.join("outside")), String::new()).await.is_err());
|
||||
host.close_project("main");
|
||||
}
|
||||
|
||||
/// The Changes view also lists attached projects' repositories, and their untracked files
|
||||
/// offer Add to .gitignore / .git/info/exclude: the guard must follow the window's
|
||||
/// repository set, not the project folder alone.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn add_to_ignore_accepts_the_repositories_of_attached_projects() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let project_root = base.join("project");
|
||||
let attached_root = base.join("attached");
|
||||
for root in [&project_root, &attached_root] {
|
||||
std::fs::create_dir_all(root).unwrap();
|
||||
git(root, &["init", "-b", "main"]);
|
||||
git(root, &["config", "user.name", "Test"]);
|
||||
git(root, &["config", "user.email", "[email protected]"]);
|
||||
git(root, &["config", "core.autocrlf", "false"]);
|
||||
std::fs::write(root.join("tracked.txt"), "x\n").unwrap();
|
||||
git(root, &["add", "."]);
|
||||
git(root, &["commit", "-m", "initial"]);
|
||||
}
|
||||
// Untracked files, one per repository; the attached one is what failed.
|
||||
let own = project_root.join("own.ignore-me");
|
||||
let attached = attached_root.join("attached.ignore-me");
|
||||
std::fs::write(&own, "x").unwrap();
|
||||
std::fs::write(&attached, "x").unwrap();
|
||||
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
local_data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(NullSink)),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
host.trust.decide(&project_root, true, false).unwrap();
|
||||
host.trust.decide(&attached_root, true, false).unwrap();
|
||||
let project = host.open_project("main", &project_root).unwrap();
|
||||
ide_host::ops::project::attach_workspace(&host, "main", &attached_root).unwrap();
|
||||
for _ in 0..500 {
|
||||
if project.repos().all().len() == 2 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
assert_eq!(project.repos().all().len(), 2);
|
||||
|
||||
vcs::vcs_add_to_ignore(&host, "main", vec![attached.clone()], ide_vcs::IgnoreDestination::Gitignore).await.unwrap();
|
||||
assert!(
|
||||
std::fs::read_to_string(attached_root.join(".gitignore")).unwrap().contains("/attached.ignore-me"),
|
||||
"the attached repository's .gitignore did not receive the rule"
|
||||
);
|
||||
vcs::vcs_add_to_ignore(&host, "main", vec![own.clone()], ide_vcs::IgnoreDestination::LocalExclude).await.unwrap();
|
||||
assert!(
|
||||
std::fs::read_to_string(project_root.join(".git/info/exclude")).unwrap().contains("/own.ignore-me"),
|
||||
"the project repository's exclude did not receive the rule"
|
||||
);
|
||||
|
||||
// A repository of an unattached sibling folder stays outside.
|
||||
let sibling_root = base.join("sibling");
|
||||
std::fs::create_dir_all(&sibling_root).unwrap();
|
||||
git(&sibling_root, &["init", "-b", "main"]);
|
||||
let sibling = sibling_root.join("sibling.ignore-me");
|
||||
std::fs::write(&sibling, "x").unwrap();
|
||||
let error =
|
||||
vcs::vcs_add_to_ignore(&host, "main", vec![sibling], ide_vcs::IgnoreDestination::Gitignore).await.unwrap_err();
|
||||
assert!(error.message.contains("outside the project"), "{error:?}");
|
||||
assert!(!sibling_root.join(".gitignore").exists());
|
||||
host.close_project("main");
|
||||
}
|
||||
@@ -15,6 +15,8 @@ tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
parking_lot.workspace = true
|
||||
reqwest.workspace = true
|
||||
# The system proxy reqwest reads, to notice when it changes (see `client::shared`).
|
||||
hyper-util = { version = "0.1", default-features = false, features = ["client-proxy", "client-proxy-system"] }
|
||||
rustls.workspace = true
|
||||
rustls-platform-verifier.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
@@ -5,7 +5,7 @@ use ide_core::proxy_settings::{ProxyMode, ProxyRoute, ProxySettings};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// `builder` routed as `proxy` says: direct, the environment's proxy (reqwest's
|
||||
/// default), or the manual proxy except for the "No proxy for" hosts.
|
||||
@@ -62,33 +62,61 @@ pub fn build_with_redirect(proxy: &ProxySettings, redirect: reqwest::redirect::P
|
||||
with_proxy(builder, proxy).build().map_err(|e| fail(e.to_string()))
|
||||
}
|
||||
|
||||
/// A client built for these proxy settings and, in Auto mode, this system proxy.
|
||||
struct Cached {
|
||||
settings: Arc<ProxySettings>,
|
||||
system: Option<String>,
|
||||
client: reqwest::Client,
|
||||
}
|
||||
|
||||
/// 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)
|
||||
static CLIENT: Mutex<Option<Cached>> = Mutex::new(None);
|
||||
cached_client(&CLIENT, build, system_proxy)
|
||||
}
|
||||
|
||||
/// 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()))
|
||||
static CLIENT: Mutex<Option<Cached>> = Mutex::new(None);
|
||||
cached_client(&CLIENT, |proxy| build_with_redirect(proxy, reqwest::redirect::Policy::none()), system_proxy)
|
||||
}
|
||||
|
||||
/// The system proxy (the environment's, then macOS / Windows settings) as reqwest reads
|
||||
/// it when a client is built, re-read at most every few seconds. A client in Auto mode
|
||||
/// keeps the proxy it was built with, so a proxy app that switches the system proxy on
|
||||
/// after launch would otherwise leave downloads going direct until a restart.
|
||||
fn system_proxy() -> String {
|
||||
static LAST: Mutex<Option<(Instant, String)>> = Mutex::new(None);
|
||||
let mut last = LAST.lock();
|
||||
if let Some((at, seen)) = last.as_ref()
|
||||
&& at.elapsed() < Duration::from_secs(3)
|
||||
{
|
||||
return seen.clone();
|
||||
}
|
||||
// Credentials are left out of the matcher's `Debug`.
|
||||
let seen = format!("{:?}", hyper_util::client::proxy::matcher::Matcher::from_system());
|
||||
*last = Some((Instant::now(), seen.clone()));
|
||||
seen
|
||||
}
|
||||
|
||||
fn cached_client(
|
||||
slot: &Mutex<Option<(Arc<ProxySettings>, reqwest::Client)>>,
|
||||
build: fn(&ProxySettings) -> IdeResult<reqwest::Client>,
|
||||
slot: &Mutex<Option<Cached>>,
|
||||
build: impl Fn(&ProxySettings) -> IdeResult<reqwest::Client>,
|
||||
system: fn() -> String,
|
||||
) -> IdeResult<reqwest::Client> {
|
||||
let proxy = ide_core::proxy_settings::proxy();
|
||||
let system = (proxy.mode == ProxyMode::Auto).then(system);
|
||||
let mut cached = slot.lock();
|
||||
if let Some((settings, client)) = cached.as_ref()
|
||||
&& **settings == *proxy
|
||||
if let Some(c) = cached.as_ref()
|
||||
&& *c.settings == *proxy
|
||||
&& c.system == system
|
||||
{
|
||||
return Ok(client.clone());
|
||||
return Ok(c.client.clone());
|
||||
}
|
||||
let client = build(&proxy)?;
|
||||
*cached = Some((proxy, client.clone()));
|
||||
*cached = Some(Cached { settings: proxy, system, client: client.clone() });
|
||||
Ok(client)
|
||||
}
|
||||
|
||||
@@ -142,6 +170,36 @@ pub fn describe(e: &reqwest::Error) -> String {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn auto_mode_rebuilds_the_shared_client_when_the_system_proxy_changes() {
|
||||
static SYSTEM: Mutex<String> = Mutex::new(String::new());
|
||||
static BUILDS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
fn system() -> String {
|
||||
SYSTEM.lock().clone()
|
||||
}
|
||||
let slot = Mutex::new(None);
|
||||
let get = || {
|
||||
cached_client(
|
||||
&slot,
|
||||
|proxy| {
|
||||
BUILDS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
build(proxy)
|
||||
},
|
||||
system,
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(ide_core::proxy_settings::proxy().mode, ProxyMode::Auto);
|
||||
get();
|
||||
get();
|
||||
assert_eq!(BUILDS.load(std::sync::atomic::Ordering::SeqCst), 1);
|
||||
// A proxy app switches the system proxy on after launch.
|
||||
*SYSTEM.lock() = "Matcher { https: 127.0.0.1:7890 }".into();
|
||||
get();
|
||||
get();
|
||||
assert_eq!(BUILDS.load(std::sync::atomic::Ordering::SeqCst), 2);
|
||||
}
|
||||
use ide_core::proxy_settings::ProxyKind;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpListener;
|
||||
|
||||
@@ -57,6 +57,7 @@ Language servers that support LSP inline completion show a grey suggestion at th
|
||||
| **Next Method** / **Previous Method** | `⌃⇧↓` / `⌃⇧↑` | `Alt+Down` / `Alt+Up` |
|
||||
|
||||
- **Go to Declaration or Usages** on a declaration shows its usages instead.
|
||||
- **Go to Implementation(s)** navigates to the symbol's own declaration when it has no implementations, as in IntelliJ IDEA.
|
||||
- Hold `⌘` / `Ctrl` and hover over a name to see it underlined as a link, with brief information about it.
|
||||
- Gutter icons mark types and methods that are implemented or overridden (↓) and methods that implement or override another (↑). Click one to go there.
|
||||
- **Navigate › Test** jumps between a class and its tests by naming convention and offers **Create New Test…** when there is none.
|
||||
|
||||
@@ -23,7 +23,7 @@ Only types you add appear here: choose **Add Service › Run Configuration Type*
|
||||
- Configuration actions: **Run** (or **Rerun**), **Debug**, **Stop**, **Open in Browser**, **Update Application** (for configurations that support it).
|
||||
- Context menu: **Show in Run Tool Window**, **Show in Debug Tool Window**, **Edit Configuration…**, **Remove from Services**.
|
||||
|
||||
A configuration that ran shows its console in the detail pane. Reorder configurations within a group by dragging them or with **Move Up** / **Move Down**; the order is saved per project.
|
||||
A configuration that ran shows its console in the detail pane; one debugged from here shows the whole debugger there (Threads & Variables, Console, Memory), and a breakpoint keeps the Services tool window in front. Reorder configurations within a group by dragging them or with **Move Up** / **Move Down**; the order is saved per project.
|
||||
|
||||
## Docker
|
||||
|
||||
|
||||
@@ -57,6 +57,7 @@ description: "代码补全、导航、查找用法、文档、层次结构与文
|
||||
| **下一个方法** / **上一个方法** | `⌃⇧↓` / `⌃⇧↑` | `Alt+Down` / `Alt+Up` |
|
||||
|
||||
- 在声明本身上执行 **转到声明或用法**,会改为显示它的用法。
|
||||
- 没有任何实现时,**转到实现** 会跳转到符号自身的声明,与 IntelliJ IDEA 一致。
|
||||
- 按住 `⌘` / `Ctrl` 把鼠标悬停在名称上,名称会显示为链接,并附带简要信息。
|
||||
- 装订区域的图标标出被实现或被重写的类型和方法(↓),以及实现或重写了其他方法的方法(↑),单击即可跳转。
|
||||
- **导航 › 测试** 按命名约定在类和它的测试之间跳转;还没有测试时会提供 **创建新测试…**。
|
||||
|
||||
@@ -23,7 +23,7 @@ description: "在服务工具窗口中管理运行配置、Docker 容器、镜
|
||||
- 配置操作:**运行**(或 **重新运行**)、**调试**、**停止**、**在浏览器中打开**、**更新应用**(仅支持的配置)。
|
||||
- 右键菜单:**在运行工具窗口中显示**、**在调试工具窗口中显示**、**编辑配置…**、**从服务中移除**。
|
||||
|
||||
运行过的配置会在详情区显示其控制台。在同一分组内可以拖动或用 **上移** / **下移** 调整顺序,顺序按项目保存。
|
||||
运行过的配置会在详情区显示其控制台;从这里调试的配置在详情区显示完整的调试器(线程和变量、控制台、内存),命中断点时停留在服务工具窗口。在同一分组内可以拖动或用 **上移** / **下移** 调整顺序,顺序按项目保存。
|
||||
|
||||
## Docker
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ for (const [id, selector] of [
|
||||
["general", "[class*='radios'] label"],
|
||||
["notifications", "table tbody td:first-child"],
|
||||
["keymap", "[class*='presetLabel']"],
|
||||
["editor.inspections", "[class*='profileRow'] > span:first-child"],
|
||||
["editor.inspections", "[class*='profileControls'] > span:first-child"],
|
||||
["vcs.issueNavigation", "[class*='pageBody'] button:not([aria-label])"],
|
||||
] as const) {
|
||||
test(`${id} keeps compact labels inside their controls`, async ({ workbench: page }) => {
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Coverage keeps sortable statistics aligned next to the file tree at sidebar widths", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1050, height: 550 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const projectModule = "/src/platform/project.ts";
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const layoutModule = "/src/workbench/toolwindows/store.ts";
|
||||
const { useProject } = await import(/* @vite-ignore */ projectModule);
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
const { setToolWindowSize } = await import(/* @vite-ignore */ layoutModule);
|
||||
const root = useProject.getState().project.root;
|
||||
const files = Array.from({ length: 36 }, (_, i) => ({
|
||||
path: root + (i === 0 ? "/src/Ready.ts" : i === 1 ? "/src/Uncovered.ts" : "/src/settlement/Report" + i + ".ts"),
|
||||
lines: [],
|
||||
linesCovered: i === 0 ? 20 : i,
|
||||
linesTotal: i === 0 ? 20 : 60,
|
||||
branchesCovered: i === 0 ? 4 : 1,
|
||||
branchesTotal: 4,
|
||||
}));
|
||||
window.__ipc.handlers.coverage_import = ({ path }) => ({
|
||||
runner: "lcov",
|
||||
hasBranches: path === "/tmp/coverage.lcov",
|
||||
files,
|
||||
});
|
||||
setToolWindowSize("right", 280);
|
||||
await executeAction("coverage.importReport", "/tmp/coverage.lcov");
|
||||
});
|
||||
|
||||
const coverage = page.getByRole("region", { name: "Coverage", exact: true });
|
||||
const tree = coverage.getByRole("tree", { name: "Coverage" });
|
||||
const line = coverage.getByRole("columnheader", { name: "Line, %" });
|
||||
const branch = coverage.getByRole("columnheader", { name: "Branch, %" });
|
||||
const folder = tree.getByRole("treeitem", { name: /^settlement/ });
|
||||
const ready = tree.getByRole("treeitem", { name: /^Ready\.ts/ });
|
||||
await expect(ready).toBeVisible();
|
||||
await expect(branch).toBeInViewport({ ratio: 1 });
|
||||
await expect.poll(() => tree.evaluate((element) => element.scrollWidth - element.clientWidth)).toBe(0);
|
||||
|
||||
const lineLeft = (await line.boundingBox())!.x;
|
||||
const branchLeft = (await branch.boundingBox())!.x;
|
||||
for (const row of [ready, folder]) {
|
||||
const cells = await row.getByTitle(/% \(/).all();
|
||||
expect(cells).toHaveLength(2);
|
||||
expect((await cells[0]!.boundingBox())!.x).toBeCloseTo(lineLeft, 0);
|
||||
expect((await cells[1]!.boundingBox())!.x).toBeCloseTo(branchLeft, 0);
|
||||
}
|
||||
|
||||
await branch.click();
|
||||
await expect(branch).toHaveAttribute("aria-sort", "descending");
|
||||
await expect(tree.getByRole("treeitem").nth(1)).toHaveAccessibleName(/^Ready\.ts/);
|
||||
await folder.locator("[data-tree-toggle]").click();
|
||||
const nested = tree.getByRole("treeitem", { name: /^Report/ }).first();
|
||||
await expect(nested).toBeVisible();
|
||||
expect(await tree.evaluate((element) => element.scrollHeight)).toBeGreaterThan(
|
||||
await tree.evaluate((element) => element.clientHeight),
|
||||
);
|
||||
expect((await nested.getByTitle("25% (1/4)").boundingBox())!.x).toBeCloseTo((await branch.boundingBox())!.x, 0);
|
||||
expect((await nested.getByTitle(/^Report/).boundingBox())!.width).toBeGreaterThan(30);
|
||||
|
||||
await page.evaluate(async () => {
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
await executeAction("coverage.importReport", "/tmp/lines.lcov");
|
||||
});
|
||||
await expect(branch).toHaveCount(0);
|
||||
await expect(line).toBeVisible();
|
||||
expect((await ready.getByTitle("100% (20/20)").boundingBox())!.x).toBeCloseTo((await line.boundingBox())!.x, 0);
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("long diagnostics and quick fixes wrap within a narrow editor hover", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 520, height: 580 });
|
||||
const path = "/dev/acme-api/Settlement.ts";
|
||||
const identifier = "QuarterlyCrossBorderSettlementProjection".repeat(4);
|
||||
const message = `Cannot resolve ${identifier}.\nCheck the settlement calculation.`;
|
||||
const title = `Replace with ${identifier}Result`;
|
||||
const range = { start: { line: 0, col: 0 }, end: { line: 0, col: 7 } };
|
||||
await page.evaluate(async (path) => {
|
||||
const backend = "/src/editor/core/backend.ts";
|
||||
(await import(/* @vite-ignore */ backend)).docBackend().files.set(path, "pending();\n");
|
||||
const service = "/src/workbench/contributions.ts";
|
||||
await (await import(/* @vite-ignore */ service)).editorService().openFile(path);
|
||||
}, path);
|
||||
await expect(page.locator(".cm-content")).toContainText("pending()");
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ path, message, title, range }) => {
|
||||
window.__ipc.handlers.lsp_hover = () => null;
|
||||
window.__ipc.handlers.lsp_code_actions = () => [
|
||||
{
|
||||
title,
|
||||
kind: "quickfix",
|
||||
isPreferred: true,
|
||||
disabledReason: null,
|
||||
edit: {
|
||||
files: [{ kind: "edit", path, edits: [{ range, new_text: "settled" }] }],
|
||||
},
|
||||
command: null,
|
||||
data: null,
|
||||
server: 1,
|
||||
},
|
||||
];
|
||||
const diagnostic = "/src/editor/lsp/diagnostics.ts";
|
||||
(await import(/* @vite-ignore */ diagnostic)).setFileDiagnostics(path, "settlement-lint", [
|
||||
{ severity: "error", message, range, source: "settlement-lint", code: "missing-model" },
|
||||
{ severity: "hint", message: "Review the reported total.", range, source: "settlement-lint", code: "review" },
|
||||
]);
|
||||
},
|
||||
{ path, message, title, range },
|
||||
);
|
||||
|
||||
await page.locator(".cm-content .cm-lintRange-error").hover();
|
||||
const hover = page.locator(".cm-lsp-hover");
|
||||
await expect(hover).toBeVisible();
|
||||
const fix = hover.getByRole("button", { name: new RegExp(`^${title}`) });
|
||||
await expect(fix).toBeVisible();
|
||||
expect(await hover.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
const messageText = hover.locator(".cm-lsp-diag-message").first();
|
||||
await expect(messageText).toHaveText(message);
|
||||
await expect(messageText).toHaveCSS("font-size", "13px");
|
||||
const shortcut = fix.locator(".cm-lsp-diag-shortcut");
|
||||
await expect(shortcut).toBeVisible();
|
||||
await expect(shortcut).toHaveCSS("font-size", "12px");
|
||||
const more = hover.getByRole("button", { name: "More actions…", exact: true }).first();
|
||||
await expect(more).toBeInViewport({ ratio: 1 });
|
||||
const outer = (await hover.boundingBox())!;
|
||||
const action = (await fix.boundingBox())!;
|
||||
const editor = (await page.locator(".cm-editor").boundingBox())!;
|
||||
expect(outer.x + outer.width).toBeLessThanOrEqual(editor.x + editor.width + 1);
|
||||
expect(action.x + action.width).toBeLessThanOrEqual(outer.x + outer.width);
|
||||
await more.click();
|
||||
const intentions = page.getByRole("dialog", { name: "Intentions", exact: true });
|
||||
await expect(intentions.getByRole("option", { name: title })).toBeVisible();
|
||||
});
|
||||
@@ -406,6 +406,48 @@ test("Markdown preview highlights ⌘F matches, selected words and scales diagra
|
||||
expect(reset.excalidraw).toBeCloseTo(base.excalidraw, 1);
|
||||
});
|
||||
|
||||
test("Markdown preview keeps following find and edits after scrolling the source", async ({ workbench: page }) => {
|
||||
const editor = await openFromTree(page, "README.md");
|
||||
const content = editor.locator(".cm-content");
|
||||
const preview = page.getByRole("document", { name: "Markdown preview" });
|
||||
await content.click();
|
||||
await page.keyboard.press("Meta+a");
|
||||
const spacer = Array.from({ length: 90 }, (_, i) => `Paragraph ${i}.`).join("\n\n");
|
||||
await page.keyboard.insertText(`First needle\n\n${spacer}\n\nSecond needle\n\n${spacer}\n\nThird needle`);
|
||||
await content.press("Control+Home");
|
||||
await expect(preview).toContainText("Third needle");
|
||||
await editor.locator(".cm-scroller").evaluate((el) => (el.scrollTop = 2000));
|
||||
await expect.poll(() => preview.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
|
||||
|
||||
await preview.focus();
|
||||
await page.keyboard.press("Meta+f");
|
||||
const find = page.getByRole("textbox", { name: "Find" });
|
||||
await find.fill("needle");
|
||||
const visibleMatch = () =>
|
||||
preview.evaluate((el) => {
|
||||
const match = (CSS.highlights.get("markdown-find-current") as unknown as Set<Range> | undefined)
|
||||
?.values()
|
||||
.next().value;
|
||||
if (!match) return null;
|
||||
const box = el.getBoundingClientRect();
|
||||
const range = match.getBoundingClientRect();
|
||||
return range.top >= box.top && range.bottom <= box.bottom ? match.startContainer.textContent : null;
|
||||
});
|
||||
await expect.poll(visibleMatch).toBe("First needle");
|
||||
await find.press("ArrowDown");
|
||||
await expect.poll(visibleMatch).toBe("Second needle");
|
||||
await find.press("ArrowDown");
|
||||
await expect.poll(visibleMatch).toBe("Third needle");
|
||||
await find.press("ArrowUp");
|
||||
await expect.poll(visibleMatch).toBe("Second needle");
|
||||
|
||||
await find.press("Escape");
|
||||
await content.focus();
|
||||
await page.keyboard.press("Meta+a");
|
||||
await page.keyboard.insertText("- **$`v_0`$ Flat wings.**");
|
||||
await expect(preview.locator("strong .katex annotation")).toHaveText("v_0");
|
||||
});
|
||||
|
||||
test("Markdown preview aligns Mermaid diagrams to their container align attribute", async ({ workbench: page }) => {
|
||||
const editor = await openFromTree(page, "README.md");
|
||||
const content = editor.locator(".cm-content");
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("an inline change keeps its actions and original code readable at the editor zoom", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 445, height: 520 });
|
||||
await stubDesktop(page);
|
||||
const original = "const routingPolicy = 'use the legacy regional settlement cutoff before reconciliation';";
|
||||
const current = "const routingPolicy = 'use the current policy';";
|
||||
const content = Array.from({ length: 22 }, (_, i) => {
|
||||
if (i === 4) return current;
|
||||
if (i === 11) return "const settlementWindow = 12;";
|
||||
return `// context ${i + 1}`;
|
||||
}).join("\n");
|
||||
|
||||
await page.evaluate(async (text) => {
|
||||
const service = "/src/workbench/contributions.ts";
|
||||
window.__ipc.handlers.fs_probe = () => ({ size: text.length, binary: false, tooLarge: false });
|
||||
window.__ipc.handlers.fs_read_text = () => text;
|
||||
await (await import(/* @vite-ignore */ service)).editorService().openFile("/dev/acme-api/settlement.ts");
|
||||
}, content);
|
||||
const editor = page.locator(".cm-editor");
|
||||
await expect(editor.locator(".cm-content")).toBeVisible();
|
||||
|
||||
await editor.evaluate(
|
||||
async (el, { original, content }) => {
|
||||
const { view } = (el.querySelector(".cm-content") as HTMLElement & { cmTile: { view: EditorView } }).cmTile;
|
||||
view.dom.style.setProperty("--openidea-editor-font-size", "18px");
|
||||
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: content }, selection: { anchor: 0 } });
|
||||
window.__ipc.handlers.vcs_line_hunks = () => [
|
||||
{ kind: "modified", start: 4, lines: 1, oldStart: 4, oldLines: 1, oldText: original + "\n" },
|
||||
{ kind: "added", start: 11, lines: 1, oldStart: 11, oldLines: 0, oldText: "" },
|
||||
{ kind: "deleted", start: 15, lines: 0, oldStart: 14, oldLines: 1, oldText: "// obsolete window\n" },
|
||||
];
|
||||
const storeModule = "/src/features/vcs/store.ts";
|
||||
const { useVcs } = await import(/* @vite-ignore */ storeModule);
|
||||
useVcs.setState({ available: true, version: useVcs.getState().version + 1 });
|
||||
},
|
||||
{ original, content },
|
||||
);
|
||||
await editor.getByTitle("Modified lines (click to show)", { exact: true }).click();
|
||||
const modified = page.getByRole("dialog", { name: "Modified lines" });
|
||||
await expect(modified).toBeVisible();
|
||||
const originalText = modified.getByText(original, { exact: false });
|
||||
await expect(originalText).toHaveCSS("font-size", "18px");
|
||||
await expect(modified.getByText(current, { exact: false })).toHaveCount(0);
|
||||
await expect(editor.getByText(current, { exact: true })).toBeVisible();
|
||||
|
||||
const preview = modified.getByRole("region", { name: "Original text" });
|
||||
await expect(preview.locator(".tok-keyword")).toHaveText("const");
|
||||
const toolbar = modified.getByRole("toolbar", { name: "Change actions" });
|
||||
expect(await preview.evaluate((el) => el.scrollWidth > el.clientWidth)).toBe(true);
|
||||
const previewBox = (await preview.boundingBox())!;
|
||||
const toolbarBox = (await toolbar.boundingBox())!;
|
||||
const currentBox = (await editor.getByText(current, { exact: true }).boundingBox())!;
|
||||
expect(previewBox.y).toBeGreaterThanOrEqual(toolbarBox.y + toolbarBox.height - 1);
|
||||
expect(
|
||||
toolbarBox.y >= currentBox.y + currentBox.height - 1 || previewBox.y + previewBox.height <= currentBox.y + 1,
|
||||
).toBe(true);
|
||||
expect(previewBox.x).toBeGreaterThanOrEqual(0);
|
||||
expect(previewBox.x + previewBox.width).toBeLessThanOrEqual(445);
|
||||
await toolbar.getByRole("button", { name: "Next Change" }).click();
|
||||
const added = page.getByRole("dialog", { name: "Added lines" });
|
||||
await expect(added).toBeVisible();
|
||||
await expect(added.getByRole("region", { name: "Original text" })).toHaveCount(0);
|
||||
await expect(added.getByRole("button", { name: "Copy Original Text" })).toBeDisabled();
|
||||
|
||||
await added.getByRole("button", { name: "Next Change" }).click();
|
||||
const deleted = page.getByRole("dialog", { name: "Deleted lines" });
|
||||
await expect(deleted.getByRole("region", { name: "Original text" })).toHaveText("// obsolete window");
|
||||
await deleted.getByRole("button", { name: "Rollback" }).click();
|
||||
await expect(deleted).toBeHidden();
|
||||
await expect(editor.getByText("// obsolete window", { exact: true })).toBeVisible();
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("the floating navigation list stays beside the visible segment and scrolls to keyboard selection", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 600, height: 560 });
|
||||
const folder = "billing";
|
||||
const parent =
|
||||
"/dev/acme-api/quarterly-settlement-and-reconciliation/merchant-accounts-with-exchange-rate-adjustments";
|
||||
const directory = `${parent}/${folder}`;
|
||||
const filename = "SettlementSummary.ts";
|
||||
const path = `${directory}/${filename}`;
|
||||
const long = "QuarterlyReconciliationForPendingSettlementAndCrossBorderMerchantAdjustments.ts";
|
||||
const last = "YearEndTotals.ts";
|
||||
await page.evaluate(async (path) => {
|
||||
const backend = "/src/editor/core/backend.ts";
|
||||
(await import(/* @vite-ignore */ backend)).docBackend().files.set(path, "export const pending = 1;\n");
|
||||
const service = "/src/workbench/contributions.ts";
|
||||
await (await import(/* @vite-ignore */ service)).editorService().openFile(path);
|
||||
}, path);
|
||||
await expect(page.locator(".cm-content")).toContainText("pending");
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ directory, filename, long, last }) => {
|
||||
window.__ipc.handlers.fs_read_dir = ({ path }) =>
|
||||
path === directory
|
||||
? ["archive", long, ...Array.from({ length: 24 }, (_, i) => `Report-${i + 1}.ts`), filename, last].map(
|
||||
(name) => ({
|
||||
name,
|
||||
path: `${directory}/${name}`,
|
||||
kind: name === "archive" ? "dir" : "file",
|
||||
size: name === "archive" ? 0 : 1,
|
||||
}),
|
||||
)
|
||||
: [];
|
||||
const actions = "/src/platform/actions.ts";
|
||||
await (await import(/* @vite-ignore */ actions)).executeAction("navigate.navigationBar");
|
||||
},
|
||||
{ directory, filename, long, last },
|
||||
);
|
||||
const bar = page.getByRole("toolbar", { name: "Navigation bar" });
|
||||
await expect(bar).toBeVisible();
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
const segment = bar.getByRole("button", { name: folder, exact: true });
|
||||
await expect(segment).toHaveAttribute("aria-current", "location");
|
||||
const barBounds = (await bar.boundingBox())!;
|
||||
await page.keyboard.press("ArrowDown");
|
||||
const list = page.getByRole("listbox", { name: "Children" });
|
||||
await expect(list).toBeVisible();
|
||||
await expect(list.getByRole("option", { name: filename, exact: true })).toHaveAttribute("aria-selected", "true");
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const bounds = (await list.boundingBox())!;
|
||||
return bounds.x >= 5 && bounds.x + bounds.width <= 595;
|
||||
})
|
||||
.toBe(true);
|
||||
expect((await list.boundingBox())!.y).toBeGreaterThanOrEqual(barBounds.y + barBounds.height - 4);
|
||||
expect((await bar.boundingBox())!.height).toBeCloseTo(barBounds.height);
|
||||
|
||||
await page.keyboard.press("Home");
|
||||
const folderRow = list.getByRole("option", { name: "archive" });
|
||||
await expect(folderRow).toHaveAttribute("aria-selected", "true");
|
||||
await expect(folderRow).toBeInViewport({ ratio: 1 });
|
||||
await expect(list.getByRole("option", { name: long, exact: true }).getByTitle(long)).toBeVisible();
|
||||
expect(await list.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
await page.keyboard.press("End");
|
||||
const lastRow = list.getByRole("option", { name: last, exact: true });
|
||||
await expect(lastRow).toHaveAttribute("aria-selected", "true");
|
||||
await expect(lastRow).toBeInViewport({ ratio: 1 });
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(list).toBeHidden();
|
||||
await expect(bar).toBeFocused();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(bar).toBeHidden();
|
||||
});
|
||||
|
||||
for (const position of ["top", "statusBar"] as const) {
|
||||
test(`the ${position} navigation list opens toward the editor and keeps folder navigation`, async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const directory = "/dev/acme-api/src";
|
||||
const path = `${directory}/Overview.ts`;
|
||||
await page.evaluate(async (path) => {
|
||||
const backend = "/src/editor/core/backend.ts";
|
||||
(await import(/* @vite-ignore */ backend)).docBackend().files.set(path, "export const overview = 1;\n");
|
||||
const service = "/src/workbench/contributions.ts";
|
||||
await (await import(/* @vite-ignore */ service)).editorService().openFile(path);
|
||||
}, path);
|
||||
await expect(page.locator(".cm-content")).toContainText("overview");
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ directory, position }) => {
|
||||
const archive = `${directory}/archive`;
|
||||
window.__ipc.handlers.fs_read_dir = ({ path }) =>
|
||||
path === directory
|
||||
? [
|
||||
{ path: archive, name: "archive", kind: "dir", size: 0 },
|
||||
{ path: `${directory}/Overview.ts`, name: "Overview.ts", kind: "file", size: 1 },
|
||||
]
|
||||
: path === archive
|
||||
? [{ path: `${archive}/Previous.ts`, name: "Previous.ts", kind: "file", size: 1 }]
|
||||
: [];
|
||||
const source = await (await fetch("/src/workbench/Workbench.tsx")).text();
|
||||
const project = source.match(/["'](\/src\/platform\/project\.ts(?:\?[^"']+)?)["']/)?.[1];
|
||||
if (!project) throw new Error("Missing project store");
|
||||
const { useProject } = await import(/* @vite-ignore */ project);
|
||||
const settings = useProject.getState().settings;
|
||||
useProject.setState({
|
||||
settings: { ...settings, appearance: { ...settings?.appearance, navigationBar: position } },
|
||||
});
|
||||
},
|
||||
{ directory, position },
|
||||
);
|
||||
const anchor = page
|
||||
.getByRole("navigation", { name: "Breadcrumbs" })
|
||||
.getByRole("button", { name: "src", exact: true });
|
||||
await anchor.click();
|
||||
const list = page.getByRole("listbox", { name: "src", exact: true });
|
||||
const archive = list.getByRole("option", { name: "archive" });
|
||||
await expect(archive).toHaveAttribute("aria-selected", "true");
|
||||
await expect(list).toBeFocused();
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const bounds = (await anchor.boundingBox())!;
|
||||
const popup = (await list.boundingBox())!;
|
||||
return position === "top" ? popup.y >= bounds.y + bounds.height : popup.y + popup.height <= bounds.y;
|
||||
})
|
||||
.toBe(true);
|
||||
await page.keyboard.press("ArrowRight");
|
||||
const nested = page.getByRole("listbox", { name: "archive" });
|
||||
await expect(nested.getByRole("option", { name: "Previous.ts" })).toHaveAttribute("aria-selected", "true");
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
await expect(archive).toHaveAttribute("aria-selected", "true");
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(list).toBeHidden();
|
||||
await expect(anchor).toBeFocused();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
const parent = "/dev/imports/From-vendor/QuarterlySettlementReconciliationAndReportingProjects";
|
||||
const project = `${parent}/settlement-api`;
|
||||
|
||||
test("the trust prompt keeps the folder scope and restricted preview visible in a narrow window", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 420, height: 455 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(() => {
|
||||
const h = window.__ipc.handlers;
|
||||
h.project_trust_status = ({ path }) => ({ root: path, trusted: false, decided: false });
|
||||
h.project_trust_set = () => null;
|
||||
h.open_project = ({ path }) => ({ root: path, name: "settlement-api", trusted: false, isGit: false, settings: {} });
|
||||
h.fs_read_dir = () => [];
|
||||
});
|
||||
const open = () =>
|
||||
page.evaluate(async (path) => {
|
||||
const projectModule = "/src/platform/project.ts";
|
||||
const { openProject } = await import(/* @vite-ignore */ projectModule);
|
||||
void openProject(path).catch(() => undefined);
|
||||
}, project);
|
||||
await open();
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Trust and Open Project?" });
|
||||
const restricted = dialog.getByRole("button", { name: "Preview in Restricted Mode" });
|
||||
const folder = dialog.getByRole("checkbox", { name: /Trust projects in/ });
|
||||
const projectAction = dialog.getByRole("button", { name: "Trust Project", exact: true });
|
||||
const folderAction = dialog.getByRole("button", { name: "Trust Folder", exact: true });
|
||||
await expect(restricted).toBeFocused();
|
||||
await expect(projectAction).toBeVisible();
|
||||
await expect(folder).not.toBeChecked();
|
||||
await expect(dialog.getByTitle(project, { exact: true })).toBeVisible();
|
||||
await expect(dialog.getByTitle(parent, { exact: true })).toBeVisible();
|
||||
await folder.check();
|
||||
await expect(folderAction).toHaveCount(1);
|
||||
await expect(projectAction).toHaveCount(0);
|
||||
for (const selector of ["[data-dialog-body]", "[data-dialog-footer]"]) {
|
||||
expect(await dialog.locator(selector).evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
}
|
||||
await expect(restricted).toBeInViewport({ ratio: 1 });
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(dialog).toBeHidden();
|
||||
expect(await ipcCalls(page, "project_trust_set")).toEqual([]);
|
||||
expect(await ipcCalls(page, "open_project")).toEqual([]);
|
||||
|
||||
await open();
|
||||
await expect(projectAction).toBeVisible();
|
||||
await expect(folder).not.toBeChecked();
|
||||
await folder.check();
|
||||
await restricted.click();
|
||||
await expect(dialog).toBeHidden();
|
||||
expect(await ipcCalls(page, "project_trust_set")).toEqual([{ path: project, trusted: false, folder: false }]);
|
||||
await expect.poll(() => ipcCalls(page, "open_project")).toEqual([{ path: project }]);
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Quick Evaluate opens an object tree that fits the editor and returns focus on Escape", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 445, height: 500 });
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const path = "/dev/acme-api/settlement.py";
|
||||
const h = window.__ipc.handlers;
|
||||
const value = (name: string, text: string, typeName: string, variablesReference = 0) => ({
|
||||
name,
|
||||
value: text,
|
||||
typeName,
|
||||
variablesReference,
|
||||
evaluateName: name,
|
||||
});
|
||||
h.fs_probe = () => ({ size: 48, binary: false, tooLarge: false });
|
||||
h.fs_read_text = () => "summary = {}\nsubtotal = 42\n";
|
||||
h.debug_evaluate_in = ({ expression }) =>
|
||||
expression === "summary" ? value("summary", "{...}", "dict", 101) : value("subtotal", "42", "int");
|
||||
h.debug_variables = ({ reference }) =>
|
||||
reference === 101
|
||||
? [value("audit", "{...}", "dict", 102), value("total", "47.74", "float")]
|
||||
: Array.from({ length: 22 }, (_, i) => value(`entry${i.toString().padStart(2, "0")}`, String(i), "int"));
|
||||
h.debug_scopes = () => [];
|
||||
const servicesModule = "/src/workbench/contributions.ts";
|
||||
const { editorService } = await import(/* @vite-ignore */ servicesModule);
|
||||
await editorService().openFile(path, { focus: true });
|
||||
const debugModule = "/src/features/debugger/state.ts";
|
||||
const { adoptSession, publishContext } = await import(/* @vite-ignore */ debugModule);
|
||||
adoptSession(91, {
|
||||
name: "Checkout",
|
||||
adapter: "debugpy",
|
||||
status: "paused",
|
||||
selectedFrame: 11,
|
||||
frames: [{ id: 11, name: "checkout", path, line: 0, column: 0, presentationHint: null }],
|
||||
});
|
||||
publishContext();
|
||||
});
|
||||
const editor = page.locator(".cm-editor");
|
||||
const content = editor.locator(".cm-content");
|
||||
await expect(content).toBeVisible();
|
||||
await content.evaluate((el) => {
|
||||
const { view } = (el as HTMLElement & { cmTile: { view: EditorView } }).cmTile;
|
||||
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "summary = {}\nsubtotal = 42\n" } });
|
||||
});
|
||||
const evaluate = (line: number) =>
|
||||
content.evaluate(async (el, lineNo) => {
|
||||
const { view } = (el as HTMLElement & { cmTile: { view: EditorView } }).cmTile;
|
||||
view.dispatch({ selection: { anchor: view.state.doc.line(lineNo).from + 2 } });
|
||||
const actionModule = "/src/platform/actions.ts";
|
||||
await (await import(/* @vite-ignore */ actionModule)).executeAction("debug.quickEvaluate");
|
||||
}, line);
|
||||
|
||||
await evaluate(1);
|
||||
const hint = page.locator(".cm-lsp-hint");
|
||||
await expect(hint).toBeVisible();
|
||||
await expect(hint.getByRole("button", { name: "Expand value" })).toHaveCount(0);
|
||||
const tree = hint.getByRole("tree", { name: "summary" });
|
||||
await expect(tree).toBeFocused();
|
||||
await expect(tree.getByText("audit", { exact: true })).toBeVisible();
|
||||
await page.setViewportSize({ width: 400, height: 360 });
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const editorBox = (await editor.boundingBox())!;
|
||||
const hintBox = (await hint.boundingBox())!;
|
||||
return hintBox.x >= editorBox.x - 1 && hintBox.x + hintBox.width <= editorBox.x + editorBox.width + 1;
|
||||
})
|
||||
.toBe(true);
|
||||
|
||||
await tree.getByText("audit", { exact: true }).click();
|
||||
await tree.press("ArrowRight");
|
||||
await expect(tree.getByText("entry00", { exact: true })).toBeVisible();
|
||||
expect(await tree.evaluate((el) => el.scrollHeight > el.clientHeight)).toBe(true);
|
||||
await tree.press("Escape");
|
||||
await expect(hint).toBeHidden();
|
||||
await expect(content).toBeFocused();
|
||||
|
||||
await evaluate(2);
|
||||
await expect(hint.getByRole("tree")).toHaveCount(0);
|
||||
await expect(hint).toHaveText(/subtotal\s*=\s*42/);
|
||||
expect(await ipcCalls(page, "debug_evaluate_in")).toEqual([
|
||||
{ session: 91, frameId: 11, expression: "summary", context: "hover" },
|
||||
{ session: 91, frameId: 11, expression: "subtotal", context: "hover" },
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("Rollback fits a short window and scopes its options to checked files", async ({ workbench: page }) => {
|
||||
await page.setViewportSize({ width: 410, height: 330 });
|
||||
await stubDesktop(page);
|
||||
const root = "/dev/settlement-engine";
|
||||
const added = `${root}/ledger/additional-settlement-schedule.txt`;
|
||||
const deleted = `${root}/ledger/retired-settlement-routing.txt`;
|
||||
const modified = Array.from({ length: 16 }, (_, i) => `${root}/ledger/merchant-settlement-batch-${i + 1}.txt`);
|
||||
|
||||
await page.evaluate(
|
||||
async ({ root, added, deleted, modified }) => {
|
||||
const status = [
|
||||
{ path: added, staged: "added", unstaged: null },
|
||||
{ path: deleted, staged: "deleted", unstaged: null },
|
||||
...modified.map((path) => ({ path, staged: null, unstaged: "modified" })),
|
||||
].map((file) => ({ ...file, relPath: file.path.slice(root.length + 1), renamedFrom: null }));
|
||||
const branch = { head: "main", headCommit: "c1", upstream: null, ahead: 0, behind: 0, operation: null };
|
||||
const h = window.__ipc.handlers;
|
||||
h.vcs_branch_info = () => branch;
|
||||
h.vcs_roots = () => [{ root, ...branch }];
|
||||
h.vcs_status = () => status;
|
||||
h.vcs_unstage = () => null;
|
||||
h.vcs_discard = () => null;
|
||||
|
||||
const storeModule = "/src/features/vcs/store.ts";
|
||||
const { useVcs } = await import(/* @vite-ignore */ storeModule);
|
||||
useVcs.setState({ available: true, root, repo: root, roots: [root], branch, status });
|
||||
const contextModule = "/src/platform/context.ts";
|
||||
const { setContext } = await import(/* @vite-ignore */ contextModule);
|
||||
setContext("vcsAvailable", true);
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
await executeAction("vcs.rollback", [root]);
|
||||
},
|
||||
{ root, added, deleted, modified },
|
||||
);
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "Rollback Changes", exact: true });
|
||||
const tree = dialog.getByRole("tree", { name: "Files to roll back" });
|
||||
const body = dialog.locator("[data-dialog-body]");
|
||||
await expect(tree).toBeVisible();
|
||||
expect(await body.evaluate((el) => el.scrollHeight - el.clientHeight)).toBeLessThanOrEqual(1);
|
||||
expect(await body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
|
||||
expect(await tree.evaluate((el) => el.scrollHeight > el.clientHeight)).toBe(true);
|
||||
await expect(tree).toBeFocused();
|
||||
await expect(tree.getByTitle("ledger/additional-settlement-schedule.txt", { exact: true })).toBeVisible();
|
||||
|
||||
const status = dialog.getByRole("status");
|
||||
const deleteCopies = dialog.getByRole("checkbox", { name: "Delete local copies of added files" });
|
||||
const rollback = dialog.getByRole("button", { name: "Rollback", exact: true });
|
||||
await expect(status).toHaveText("1 added16 modified1 deleted");
|
||||
await expect(deleteCopies).toBeEnabled();
|
||||
await expect(deleteCopies).not.toBeChecked();
|
||||
await deleteCopies.check();
|
||||
await tree.getByRole("checkbox", { name: "Include additional-settlement-schedule.txt" }).uncheck();
|
||||
await expect(deleteCopies).toBeDisabled();
|
||||
await expect(status).toHaveText("16 modified1 deleted");
|
||||
|
||||
const rootCheckbox = tree.getByRole("checkbox", { name: "Include settlement-engine", exact: true });
|
||||
await expect(rootCheckbox).toHaveAttribute("aria-checked", "mixed");
|
||||
await rootCheckbox.click();
|
||||
await rootCheckbox.uncheck();
|
||||
await expect(rollback).toBeDisabled();
|
||||
await expect(status).toHaveText("No files selected");
|
||||
|
||||
await tree.getByRole("checkbox", { name: "Include merchant-settlement-batch-1.txt", exact: true }).check();
|
||||
await expect(status).toHaveText("1 modified");
|
||||
await expect(deleteCopies).toBeDisabled();
|
||||
await rollback.click();
|
||||
await expect(dialog).toBeHidden();
|
||||
await expect.poll(() => ipcCalls(page, "vcs_discard")).toEqual([{ paths: [modified[0]] }]);
|
||||
expect(await ipcCalls(page, "vcs_unstage")).toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import { expect, test } from "./fixtures";
|
||||
|
||||
test("the scratch language chooser fits short windows and keeps recents separate from search results", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 470, height: 400 });
|
||||
const long = "Zebra Configuration Language for Regional Settlement and Reconciliation Pipelines";
|
||||
await page.evaluate(async (long) => {
|
||||
const scratch = "/src/features/scratch/scratches.ts";
|
||||
const store = "/src/features/scratch/store.ts";
|
||||
const actions = "/src/platform/actions.ts";
|
||||
const { setScratchBackend } = await import(/* @vite-ignore */ scratch);
|
||||
const { rememberLanguage } = await import(/* @vite-ignore */ store);
|
||||
setScratchBackend({
|
||||
dataDir: async () => "/test-app-data",
|
||||
listNames: async () => [],
|
||||
createDir: async () => {},
|
||||
createFile: async () => {},
|
||||
languages: async () => [
|
||||
...Array.from({ length: 24 }, (_, i) => {
|
||||
const n = String(i + 1).padStart(2, "0");
|
||||
return { id: `config-${n}`, name: `Configuration ${n}`, ext: `cfg${n}` };
|
||||
}),
|
||||
{ id: "json", name: "JSON", ext: "json" },
|
||||
{ id: "python", name: "Python", ext: "py" },
|
||||
{ id: "zebra", name: long, ext: "zebra" },
|
||||
],
|
||||
open: async (path: string) => localStorage.setItem("scratch-layout-opened", path),
|
||||
});
|
||||
rememberLanguage("json");
|
||||
rememberLanguage("python");
|
||||
await (await import(/* @vite-ignore */ actions)).executeAction("file.newScratchFile");
|
||||
}, long);
|
||||
|
||||
const dialog = page.getByRole("dialog", { name: "New Scratch File", exact: true });
|
||||
const input = dialog.getByRole("textbox", { name: "Filter languages" });
|
||||
await expect(input).toBeFocused();
|
||||
const list = dialog.getByRole("listbox", { name: "Languages" });
|
||||
for (let i = 0; i < 3; i++) await input.press("PageDown");
|
||||
const last = list.getByRole("option", { name: long, exact: true });
|
||||
await expect(last).toHaveAttribute("aria-selected", "true");
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const popup = (await dialog.boundingBox())!;
|
||||
const item = (await last.boundingBox())!;
|
||||
return item.y + item.height - popup.y - popup.height;
|
||||
})
|
||||
.toBeLessThanOrEqual(1);
|
||||
await expect(last).toBeInViewport({ ratio: 0.99 });
|
||||
await expect(last.getByTitle(long)).toBeVisible();
|
||||
await expect(input).toBeInViewport({ ratio: 1 });
|
||||
|
||||
await input.fill("python");
|
||||
const python = list.getByRole("option", { name: "Python", exact: true });
|
||||
await expect(python).toHaveAttribute("aria-selected", "true");
|
||||
await expect(list.getByRole("separator")).toHaveCount(0);
|
||||
await input.fill("");
|
||||
const divider = list.getByRole("separator");
|
||||
await expect(divider).toBeVisible();
|
||||
await expect(python).toHaveAttribute("aria-selected", "true");
|
||||
await input.press("ArrowDown");
|
||||
const json = list.getByRole("option", { name: "JSON", exact: true });
|
||||
await expect(json).toHaveAttribute("aria-selected", "true");
|
||||
await input.press("ArrowDown");
|
||||
const first = list.getByRole("option", { name: "Configuration 01", exact: true });
|
||||
await expect(first).toHaveAttribute("aria-selected", "true");
|
||||
expect((await divider.boundingBox())!.y).toBeLessThan((await first.boundingBox())!.y);
|
||||
expect(await input.getAttribute("aria-activedescendant")).toBe(await first.getAttribute("id"));
|
||||
await page.setViewportSize({ width: 640, height: 520 });
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const bounds = (await dialog.boundingBox())!;
|
||||
return Math.abs(bounds.x + bounds.width / 2 - 320);
|
||||
})
|
||||
.toBeLessThanOrEqual(1);
|
||||
await expect(input).toBeFocused();
|
||||
|
||||
await input.fill("zzz");
|
||||
await expect(dialog.getByText("No matching languages")).toBeVisible();
|
||||
await input.fill("json");
|
||||
await input.press("Enter");
|
||||
await expect(dialog).toBeHidden();
|
||||
await expect
|
||||
.poll(() => page.evaluate(() => localStorage.getItem("scratch-layout-opened")))
|
||||
.toBe("/test-app-data/scratches/scratch.json");
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("selection history keeps a full-width diff above a keyboard-resizable revision table", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1140, height: 740 });
|
||||
const filename = "QuarterlyCrossBorderSettlementReconciliationProjection.ts";
|
||||
const path = `/dev/acme-api/modules/${filename}`;
|
||||
const lastMessage = "Introduce the reconciliation projection for pending cross-border merchant settlements";
|
||||
await page.evaluate(async (path) => {
|
||||
const backend = "/src/editor/core/backend.ts";
|
||||
(await import(/* @vite-ignore */ backend))
|
||||
.docBackend()
|
||||
.files.set(path, "export const pending = 0;\nconst projection = uncommitted;\n");
|
||||
const service = "/src/workbench/contributions.ts";
|
||||
await (await import(/* @vite-ignore */ service)).editorService().openFile(path);
|
||||
}, path);
|
||||
const editor = page.locator(".cm-content");
|
||||
await expect(editor).toContainText("uncommitted");
|
||||
await editor.evaluate((el) => {
|
||||
const view = (el as HTMLElement & { cmTile: { view: EditorView } }).cmTile.view;
|
||||
const line = view.state.doc.line(2);
|
||||
view.dispatch({ selection: { anchor: line.from, head: line.to } });
|
||||
view.focus();
|
||||
});
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ path, lastMessage }) => {
|
||||
window.__ipc.handlers.cancel_request = () => null;
|
||||
window.__ipc.handlers.vcs_block_history = () => ({
|
||||
headLines: [1, 1],
|
||||
revisions: Array.from({ length: 22 }, (_, i) => ({
|
||||
id: (i + 16).toString(16).padStart(40, "0"),
|
||||
shortId: (i + 16).toString(16).padStart(7, "0"),
|
||||
author: "Alexandra Reconciliation Coordinator",
|
||||
email: "[email protected]",
|
||||
timeMs: 1738329600000 - i * 86400000,
|
||||
summary: i === 21 ? lastMessage : `Update reconciliation estimate ${22 - i}`,
|
||||
path,
|
||||
before: `const projection = estimate${21 - i};\n`,
|
||||
after: `const projection = estimate${22 - i};\n`,
|
||||
beforeLine: 1,
|
||||
afterLine: 1,
|
||||
})),
|
||||
});
|
||||
const actions = "/src/platform/actions.ts";
|
||||
await (await import(/* @vite-ignore */ actions)).executeAction("vcs.showHistoryForSelection");
|
||||
},
|
||||
{ path, lastMessage },
|
||||
);
|
||||
|
||||
const diff = page.locator(".cm-mergeView");
|
||||
await expect(diff).toContainText("uncommitted");
|
||||
const revisions = page.getByRole("grid", { name: "Revisions" });
|
||||
const history = revisions.or(page.getByRole("listbox", { name: "Revisions" }));
|
||||
await expect(history).toBeVisible();
|
||||
const preview = (await diff.boundingBox())!;
|
||||
const list = (await history.boundingBox())!;
|
||||
expect(list.y).toBeGreaterThanOrEqual(preview.y + preview.height - 1);
|
||||
expect(preview.width).toBeGreaterThanOrEqual(list.width - 2);
|
||||
|
||||
await expect(revisions.getByRole("columnheader")).toHaveText(["Revision", "Date", "Author", "Message"]);
|
||||
const divider = page.getByRole("separator", { name: "Revisions", exact: true });
|
||||
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
|
||||
const initial = (await divider.boundingBox())!.y;
|
||||
await divider.press("ArrowUp");
|
||||
await expect.poll(async () => (await divider.boundingBox())!.y).toBeLessThan(initial);
|
||||
await expect(revisions.getByRole("row", { selected: true })).toContainText("Local Changes");
|
||||
|
||||
await page.setViewportSize({ width: 490, height: 620 });
|
||||
await expect(divider).toHaveAttribute("aria-orientation", "horizontal");
|
||||
await expect(page.getByTitle(`${filename}:2-2`, { exact: true })).toBeVisible();
|
||||
const body = revisions.getByRole("rowgroup");
|
||||
await body.press("End");
|
||||
const last = revisions.getByRole("row", { selected: true });
|
||||
await expect(last.getByRole("gridcell", { name: lastMessage, exact: true })).toHaveAttribute("title", lastMessage);
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const listBounds = (await body.boundingBox())!;
|
||||
const rowBounds = (await last.boundingBox())!;
|
||||
return Math.max(listBounds.y - rowBounds.y, rowBounds.y + rowBounds.height - listBounds.y - listBounds.height);
|
||||
})
|
||||
.toBeLessThanOrEqual(1);
|
||||
const headers = revisions.getByRole("columnheader");
|
||||
const cells = last.getByRole("gridcell");
|
||||
for (let i = 0; i < 4; i++) {
|
||||
expect(
|
||||
Math.abs((await headers.nth(i).boundingBox())!.x - (await cells.nth(i).boundingBox())!.x),
|
||||
).toBeLessThanOrEqual(1);
|
||||
}
|
||||
expect(await body.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
await expect(diff).toContainText("estimate1");
|
||||
});
|
||||
@@ -2,9 +2,9 @@ import { expect, test } from "./fixtures";
|
||||
|
||||
for (const [id, selector] of [
|
||||
["build.deployment", "[class*='layout'] > [class*='note']"],
|
||||
["editor.inspections", "[class*='split'] > [class*='details']"],
|
||||
["editor.inspections", "[class*='split'] section[class*='details']"],
|
||||
["languages.servers", "[class*='body'] > [class*='language'][aria-label]"],
|
||||
["plugins", "[class*='body'] > [class*='details']"],
|
||||
["plugins", "[class*='body'] [class*='details'][aria-label]"],
|
||||
["agents.list", "section[aria-label='Codex']"],
|
||||
] as const) {
|
||||
test(`${id} keeps its details usable beside the list`, async ({ workbench: page }) => {
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
use ide_core::{EventSink, IdeEvent};
|
||||
use ide_core::{EventSink, IdeEvent, SharedSink};
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tauri::{AppHandle, Emitter, Manager, UserAttentionType};
|
||||
|
||||
/// Name of the single backend → UI event. Payload: [`IdeEvent`].
|
||||
@@ -38,6 +42,103 @@ pub struct TauriSink {
|
||||
pub window: Option<String>,
|
||||
}
|
||||
|
||||
const COALESCE_WINDOW: Duration = Duration::from_millis(16);
|
||||
const MAX_PENDING_DIAGNOSTICS: usize = 4096;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
struct DiagnosticKey {
|
||||
path: ide_core::IpcPath,
|
||||
source: String,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct PendingDiagnostics {
|
||||
order: VecDeque<DiagnosticKey>,
|
||||
events: HashMap<DiagnosticKey, IdeEvent>,
|
||||
scheduled: bool,
|
||||
}
|
||||
|
||||
fn diagnostic_key(event: &IdeEvent) -> Option<DiagnosticKey> {
|
||||
let IdeEvent::Diagnostics { path, source, .. } = event else {
|
||||
return None;
|
||||
};
|
||||
Some(DiagnosticKey { path: path.clone(), source: source.clone() })
|
||||
}
|
||||
|
||||
fn take_pending(state: &mut PendingDiagnostics) -> Vec<IdeEvent> {
|
||||
let mut events = Vec::with_capacity(state.events.len());
|
||||
for key in state.order.drain(..) {
|
||||
if let Some(event) = state.events.remove(&key) {
|
||||
events.push(event);
|
||||
}
|
||||
}
|
||||
events
|
||||
}
|
||||
|
||||
/// Collapses repeated full-replacement diagnostics for one `(path, source)` into the
|
||||
/// latest event in a frame-sized window. Any other event flushes the pending
|
||||
/// diagnostics first so lifecycle and ordered events cannot overtake them.
|
||||
pub fn coalescing_sink(sink: SharedSink, runtime: tokio::runtime::Handle) -> SharedSink {
|
||||
let pending = Arc::new(Mutex::new(PendingDiagnostics::default()));
|
||||
let dispatch = Arc::new(Mutex::new(()));
|
||||
Arc::new(move |event| {
|
||||
let Some(key) = diagnostic_key(&event) else {
|
||||
let _dispatch = dispatch.lock();
|
||||
let events = take_pending(&mut pending.lock());
|
||||
for pending_event in events {
|
||||
sink.emit(pending_event);
|
||||
}
|
||||
sink.emit(event);
|
||||
return;
|
||||
};
|
||||
|
||||
loop {
|
||||
let schedule = {
|
||||
let mut state = pending.lock();
|
||||
if !state.events.contains_key(&key) && state.events.len() >= MAX_PENDING_DIAGNOSTICS {
|
||||
None
|
||||
} else {
|
||||
if !state.events.contains_key(&key) {
|
||||
state.order.push_back(key.clone());
|
||||
}
|
||||
state.events.insert(key.clone(), event.clone());
|
||||
if state.scheduled {
|
||||
return;
|
||||
}
|
||||
state.scheduled = true;
|
||||
Some(())
|
||||
}
|
||||
};
|
||||
|
||||
if schedule.is_none() {
|
||||
let _dispatch = dispatch.lock();
|
||||
let events = take_pending(&mut pending.lock());
|
||||
for pending_event in events {
|
||||
sink.emit(pending_event);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
let pending = pending.clone();
|
||||
let dispatch = dispatch.clone();
|
||||
let sink = sink.clone();
|
||||
runtime.spawn(async move {
|
||||
tokio::time::sleep(COALESCE_WINDOW).await;
|
||||
let _dispatch = dispatch.lock();
|
||||
let events = {
|
||||
let mut state = pending.lock();
|
||||
state.scheduled = false;
|
||||
take_pending(&mut state)
|
||||
};
|
||||
for event in events {
|
||||
sink.emit(event);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// A debug session stopped on a breakpoint: bounce/flash the taskbar icon
|
||||
/// (IDEA) unless the user is already looking at an OpenIDEA window. The focus
|
||||
/// check and the request both touch the windowing system, so they run on the
|
||||
@@ -94,3 +195,205 @@ impl EventSink for TauriSink {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::{Diagnostic, IpcPath, Pos, Range, Severity, TaskId};
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
fn setup() -> (ide_core::SharedSink, Arc<Mutex<Vec<IdeEvent>>>) {
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let saved = events.clone();
|
||||
(coalescing_sink(Arc::new(move |event| saved.lock().push(event)), tokio::runtime::Handle::current()), events)
|
||||
}
|
||||
|
||||
fn diagnostics(path: &str, source: &str, message: &str) -> IdeEvent {
|
||||
IdeEvent::Diagnostics {
|
||||
path: IpcPath::from(path),
|
||||
source: source.into(),
|
||||
items: vec![Diagnostic {
|
||||
range: Range::point(Pos::new(0, 0)),
|
||||
severity: Severity::Error,
|
||||
message: message.into(),
|
||||
source: None,
|
||||
code: None,
|
||||
unnecessary: false,
|
||||
deprecated: false,
|
||||
server: None,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn task(message: &str, done: bool) -> IdeEvent {
|
||||
IdeEvent::Task {
|
||||
id: TaskId(1),
|
||||
title: "Indexing".into(),
|
||||
message: Some(message.into()),
|
||||
fraction: Some(if done { 1.0 } else { 0.5 }),
|
||||
done,
|
||||
cancellable: !done,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn coalesces_diagnostics_by_path_and_source() {
|
||||
let (sink, events) = setup();
|
||||
for index in 0..100 {
|
||||
sink.emit(diagnostics("/p/a.rs", "rust-analyzer", &format!("old {index}")));
|
||||
}
|
||||
sink.emit(diagnostics("/p/a.rs", "eslint", "lint"));
|
||||
sink.emit(diagnostics("/p/b.rs", "rust-analyzer", "other"));
|
||||
|
||||
assert!(events.lock().is_empty());
|
||||
tokio::task::yield_now().await;
|
||||
tokio::time::sleep(Duration::from_millis(30)).await;
|
||||
tokio::task::yield_now().await;
|
||||
|
||||
{
|
||||
let saved_events = events.lock();
|
||||
assert_eq!(saved_events.len(), 3);
|
||||
assert!(matches!(
|
||||
&saved_events[0],
|
||||
IdeEvent::Diagnostics { path, source, items }
|
||||
if path == &IpcPath::from("/p/a.rs")
|
||||
&& source == "rust-analyzer"
|
||||
&& items[0].message == "old 99"
|
||||
));
|
||||
assert!(matches!(
|
||||
&saved_events[1],
|
||||
IdeEvent::Diagnostics { path, source, .. }
|
||||
if path == &IpcPath::from("/p/a.rs") && source == "eslint"
|
||||
));
|
||||
assert!(matches!(
|
||||
&saved_events[2],
|
||||
IdeEvent::Diagnostics { path, source, .. }
|
||||
if path == &IpcPath::from("/p/b.rs") && source == "rust-analyzer"
|
||||
));
|
||||
}
|
||||
|
||||
tokio::time::sleep(Duration::from_millis(30)).await;
|
||||
assert_eq!(events.lock().len(), 3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn immediate_events_flush_pending_events_first() {
|
||||
let (sink, events) = setup();
|
||||
sink.emit(diagnostics("/p/a.rs", "rust-analyzer", "before"));
|
||||
sink.emit(diagnostics("/p/b.rs", "rust-analyzer", "other"));
|
||||
sink.emit(IdeEvent::SettingsChanged { key: "editor.fontSize".into() });
|
||||
|
||||
let events = events.lock();
|
||||
assert_eq!(events.len(), 3);
|
||||
assert!(matches!(&events[0], IdeEvent::Diagnostics { .. }));
|
||||
assert!(matches!(&events[1], IdeEvent::Diagnostics { .. }));
|
||||
assert!(matches!(&events[2], IdeEvent::SettingsChanged { .. }));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn lifecycle_events_remain_immediate() {
|
||||
let (sink, events) = setup();
|
||||
sink.emit(task("complete", true));
|
||||
let events = events.lock();
|
||||
assert_eq!(events.len(), 1);
|
||||
assert!(matches!(
|
||||
&events[0],
|
||||
IdeEvent::Task { message, done, .. }
|
||||
if message.as_deref() == Some("complete") && *done
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn diagnostic_buffer_cap_flushes_without_dropping() {
|
||||
let (sink, events) = setup();
|
||||
for index in 0..=MAX_PENDING_DIAGNOSTICS {
|
||||
sink.emit(diagnostics(&format!("/p/{index}.rs"), "rust-analyzer", "diagnostic"));
|
||||
}
|
||||
assert_eq!(events.lock().len(), MAX_PENDING_DIAGNOSTICS);
|
||||
|
||||
tokio::time::sleep(Duration::from_millis(30)).await;
|
||||
assert_eq!(events.lock().len(), MAX_PENDING_DIAGNOSTICS + 1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[ignore = "run for before/after diagnostics transport measurements"]
|
||||
async fn diagnostics_coalescing_benchmark() {
|
||||
const FILES: usize = 2_000;
|
||||
const ROUNDS: usize = 10;
|
||||
let burst: Vec<IdeEvent> = (0..ROUNDS)
|
||||
.flat_map(|round| {
|
||||
(0..FILES).map(move |file| {
|
||||
diagnostics(&format!("/workspace/src/File{file}.rs"), "rust-analyzer", &format!("round-{round}"))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let raw_events = Arc::new(AtomicUsize::new(0));
|
||||
let raw_count = raw_events.clone();
|
||||
let raw: SharedSink = Arc::new(move |event| {
|
||||
let encoded = serde_json::to_vec(&event).unwrap();
|
||||
raw_count.fetch_add(1, Ordering::Relaxed);
|
||||
std::hint::black_box(encoded.len());
|
||||
});
|
||||
let raw_started = Instant::now();
|
||||
for event in &burst {
|
||||
raw.emit(event.clone());
|
||||
}
|
||||
let raw_elapsed = raw_started.elapsed();
|
||||
assert_eq!(raw_events.load(Ordering::Relaxed), FILES * ROUNDS);
|
||||
|
||||
let coalesced_events = Arc::new(AtomicUsize::new(0));
|
||||
let delivered_state = Arc::new(Mutex::new(HashMap::<IpcPath, String>::new()));
|
||||
let coalesced_count = coalesced_events.clone();
|
||||
let delivered = delivered_state.clone();
|
||||
let target: SharedSink = Arc::new(move |event| {
|
||||
let encoded = serde_json::to_vec(&event).unwrap();
|
||||
coalesced_count.fetch_add(1, Ordering::Relaxed);
|
||||
if let IdeEvent::Diagnostics { path, items, .. } = event {
|
||||
delivered.lock().insert(path, items[0].message.clone());
|
||||
}
|
||||
std::hint::black_box(encoded.len());
|
||||
});
|
||||
let coalesced = coalescing_sink(target, tokio::runtime::Handle::current());
|
||||
let coalesced_started = Instant::now();
|
||||
for event in &burst {
|
||||
coalesced.emit(event.clone());
|
||||
}
|
||||
|
||||
let expected_last_round = format!("round-{}", ROUNDS - 1);
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
loop {
|
||||
let complete = {
|
||||
let delivered_state = delivered_state.lock();
|
||||
delivered_state.len() == FILES
|
||||
&& delivered_state.values().all(|message| message == &expected_last_round)
|
||||
};
|
||||
if complete {
|
||||
break;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "diagnostics did not settle before benchmark timeout");
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
let coalesced_elapsed = coalesced_started.elapsed();
|
||||
|
||||
let coalesced_count = coalesced_events.load(Ordering::Relaxed);
|
||||
assert!(coalesced_count >= FILES);
|
||||
assert!(coalesced_count < FILES * ROUNDS);
|
||||
let delivered_state = delivered_state.lock();
|
||||
assert_eq!(delivered_state.len(), FILES);
|
||||
assert!(delivered_state.values().all(|message| message == &expected_last_round));
|
||||
println!(
|
||||
"diagnostics transport burst: raw_events={} raw_ms={:.2} coalesced_events={} \
|
||||
coalesced_total_ms={:.2} reduction_pct={:.1}",
|
||||
FILES * ROUNDS,
|
||||
raw_elapsed.as_secs_f64() * 1_000.0,
|
||||
coalesced_count,
|
||||
coalesced_elapsed.as_secs_f64() * 1_000.0,
|
||||
(1.0 - coalesced_count as f64 / (FILES * ROUNDS) as f64) * 100.0,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -288,6 +288,12 @@ pub fn run() {
|
||||
window_groups::frame_changed(window.app_handle(), window.label());
|
||||
}
|
||||
tauri::WindowEvent::Destroyed => {
|
||||
// Also release a view that failed during startup, before the parent could watch it.
|
||||
if let Some(state) = window.try_state::<AppState>()
|
||||
&& let Ok(project) = state.host.project(window.label())
|
||||
{
|
||||
project.agents.unsubscribe(window.label());
|
||||
}
|
||||
window_zoom::forget(window.label());
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::events::TauriSink;
|
||||
use crate::events::{TauriSink, coalescing_sink};
|
||||
use ide_core::{EventSink, IdeEvent, IdeResult, SharedSink};
|
||||
use ide_language::{LanguageRegistry, Syntax};
|
||||
use ide_workspace::RecentProjects;
|
||||
@@ -83,9 +83,11 @@ impl AppState {
|
||||
tracing::info!("invalidated caches: {removed:?}");
|
||||
}
|
||||
ide_host::data_dirs::migrate(&data_dir, &local_data_dir);
|
||||
let global_sink: SharedSink = Arc::new(TauriSink { app: app.clone(), window: None });
|
||||
let runtime = tauri::async_runtime::handle().inner().clone();
|
||||
let global_sink = coalescing_sink(Arc::new(TauriSink { app: app.clone(), window: None }), runtime.clone());
|
||||
let languages = Arc::new(LanguageRegistry::load(Some(&config_dir.join("languages")))?);
|
||||
let sink_app = app.clone();
|
||||
let sink_runtime = runtime.clone();
|
||||
let host = Arc::new(Host::new(ide_host::HostConfig {
|
||||
config_dir: config_dir.clone(),
|
||||
data_dir: data_dir.clone(),
|
||||
@@ -93,10 +95,13 @@ impl AppState {
|
||||
languages: languages.clone(),
|
||||
syntax,
|
||||
sink_for: Box::new(move |window| {
|
||||
Arc::new(TauriSink { app: sink_app.clone(), window: Some(window.to_owned()) })
|
||||
coalescing_sink(
|
||||
Arc::new(TauriSink { app: sink_app.clone(), window: Some(window.to_owned()) }),
|
||||
sink_runtime.clone(),
|
||||
)
|
||||
}),
|
||||
owner: Self::owner_window,
|
||||
runtime: tauri::async_runtime::handle().inner().clone(),
|
||||
runtime,
|
||||
project_environment: false,
|
||||
}));
|
||||
let announce = global_sink.clone();
|
||||
|
||||
@@ -84,11 +84,16 @@ pub struct Launch {
|
||||
pub editor: Option<Box<EditorLaunch>>,
|
||||
}
|
||||
|
||||
/// A file opened in a lightweight editor window, with optional caret / selection (0-based).
|
||||
/// What a lightweight editor window shows: a file, with optional caret / selection (0-based), or
|
||||
/// the tab of another editor kind.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct EditorLaunch {
|
||||
pub path: ide_core::IpcPath,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub path: Option<ide_core::IpcPath>,
|
||||
/// The tab's editor input, as JSON.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub input: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub line: Option<u32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -355,6 +360,12 @@ impl WindowsState {
|
||||
|
||||
pub fn take_launch(&self, label: &str) -> Option<Launch> {
|
||||
let mut launches = self.launches.lock();
|
||||
// Lightweight windows need their launch again when their webview reloads.
|
||||
if let Some(launch) = launches.get(label)
|
||||
&& launch.editor.is_some()
|
||||
{
|
||||
return Some(launch.clone());
|
||||
}
|
||||
let launch = launches.remove(label)?;
|
||||
if launch.project.is_some() || launch.remote.is_some() || !launch.files.is_empty() || launch.diff.is_some() {
|
||||
self.opening.lock().insert(label.to_owned(), launch.clone());
|
||||
@@ -2755,6 +2766,27 @@ mod tests {
|
||||
assert_eq!(st.take_launch("project-1"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editor_launch_survives_webview_reload_until_window_closes() {
|
||||
let st = WindowsState::default();
|
||||
let launch = Launch {
|
||||
editor: Some(Box::new(EditorLaunch {
|
||||
path: None,
|
||||
input: Some(r#"{"kind":"agent-session","key":"agent:running-task"}"#.into()),
|
||||
line: None,
|
||||
column: None,
|
||||
end_line: None,
|
||||
end_column: None,
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
st.set_launch("editor-main-3", launch.clone());
|
||||
assert_eq!(st.take_launch("editor-main-3"), Some(launch.clone()));
|
||||
assert_eq!(st.take_launch("editor-main-3"), Some(launch));
|
||||
st.forget("editor-main-3");
|
||||
assert!(st.take_launch("editor-main-3").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_taken_launch_owns_its_window_until_completion() {
|
||||
for launch in [
|
||||
|
||||
@@ -49,6 +49,7 @@ agent_stop_background always project_host bin
|
||||
agent_subscribe always project_host bindings sync
|
||||
agent_unarchive always project_host bindings sync
|
||||
agent_unqueue always project_host bindings sync
|
||||
agent_unsubscribe always project_host bindings sync
|
||||
analysis_locate_duplicates always project_host bindings async
|
||||
android_devices trusted desktop bindings async
|
||||
android_logcat trusted desktop bindings async
|
||||
|
||||
+25
-7
@@ -146,11 +146,16 @@ export const commands = {
|
||||
agentShell: (task: string, command: string, request: RequestId) => typedError<null, IdeError>(__TAURI_INVOKE("agent_shell", { task, command, request })),
|
||||
/** Stops one of the task's background tasks. */
|
||||
agentStopBackground: (task: string, background: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_stop_background", { task, background })),
|
||||
/** Streams the project's agent events to this window; returns every task. */
|
||||
agentSubscribe: (onEvent: Channel<AgentEvent_Deserialize>) => typedError<AgentTask_Serialize[], IdeError>(__TAURI_INVOKE("agent_subscribe", { onEvent })),
|
||||
/**
|
||||
* Streams the project's agent events to `subscriber`, one of the project's windows (a remote
|
||||
* host sees them all as one `window`); returns every task.
|
||||
*/
|
||||
agentSubscribe: (onEvent: Channel<AgentEvent_Deserialize>, subscriber: string) => typedError<AgentTask_Serialize[], IdeError>(__TAURI_INVOKE("agent_subscribe", { onEvent, subscriber })),
|
||||
agentUnarchive: (task: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_unarchive", { task })),
|
||||
/** Drops a queued message and returns it (to edit it). */
|
||||
agentUnqueue: (task: string, queued: string) => typedError<AgentQueued, IdeError>(__TAURI_INVOKE("agent_unqueue", { task, queued })),
|
||||
/** Stops the events of a window that closed. */
|
||||
agentUnsubscribe: (subscriber: string) => typedError<null, IdeError>(__TAURI_INVOKE("agent_unsubscribe", { subscriber })),
|
||||
/** Locate Duplicates over the files of `scope`. */
|
||||
analysisLocateDuplicates: (request: RequestId, scope: SearchScope, options: DuplicateOptions) => typedError<DuplicatesReport, IdeError>(__TAURI_INVOKE("analysis_locate_duplicates", { request, scope, options })),
|
||||
/** Devices `adb` knows about, online ones first. */
|
||||
@@ -5610,21 +5615,34 @@ export type EditorGeneralSettings = {
|
||||
richTextCopy?: boolean,
|
||||
};
|
||||
|
||||
/** A file opened in a lightweight editor window, with optional caret / selection (0-based). */
|
||||
/**
|
||||
* What a lightweight editor window shows: a file, with optional caret / selection (0-based), or
|
||||
* the tab of another editor kind.
|
||||
*/
|
||||
export type EditorLaunch = EditorLaunch_Serialize | EditorLaunch_Deserialize;
|
||||
|
||||
/** A file opened in a lightweight editor window, with optional caret / selection (0-based). */
|
||||
/**
|
||||
* What a lightweight editor window shows: a file, with optional caret / selection (0-based), or
|
||||
* the tab of another editor kind.
|
||||
*/
|
||||
export type EditorLaunch_Deserialize = {
|
||||
path: IpcPath,
|
||||
path?: IpcPath | null,
|
||||
/** The tab's editor input, as JSON. */
|
||||
input?: string | null,
|
||||
line?: number | null,
|
||||
column?: number | null,
|
||||
endLine?: number | null,
|
||||
endColumn?: number | null,
|
||||
};
|
||||
|
||||
/** A file opened in a lightweight editor window, with optional caret / selection (0-based). */
|
||||
/**
|
||||
* What a lightweight editor window shows: a file, with optional caret / selection (0-based), or
|
||||
* the tab of another editor kind.
|
||||
*/
|
||||
export type EditorLaunch_Serialize = {
|
||||
path: IpcPath,
|
||||
path?: IpcPath | null,
|
||||
/** The tab's editor input, as JSON. */
|
||||
input?: string | null,
|
||||
line?: number | null,
|
||||
column?: number | null,
|
||||
endLine?: number | null,
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { EditorInput } from "@/workbench/contributions";
|
||||
import { activateEditorWindow } from "./EditorWindow";
|
||||
|
||||
const boot = vi.hoisted(() => ({
|
||||
emit: vi.fn(async () => {}),
|
||||
prepare: vi.fn(async (input: EditorInput) => input),
|
||||
openInput: vi.fn(async (_input: EditorInput, _options: unknown) => {}),
|
||||
openFile: vi.fn(async () => {}),
|
||||
setProject: vi.fn(),
|
||||
takeLaunch: vi.fn(),
|
||||
}));
|
||||
vi.mock("@tauri-apps/api/event", () => ({ emitTo: boot.emit }));
|
||||
vi.mock("@tauri-apps/api/window", () => ({
|
||||
getCurrentWindow: () => ({
|
||||
label: "editor-main-3",
|
||||
onCloseRequested: async () => () => {},
|
||||
setTitle: async () => {},
|
||||
}),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", () => ({
|
||||
commands: {
|
||||
windowTakeLaunch: boot.takeLaunch,
|
||||
projectCurrent: async () => ({ name: "Project", root: "/project", settings: {} }),
|
||||
},
|
||||
}));
|
||||
vi.mock("@/platform/context", () => ({ setContext: vi.fn() }));
|
||||
vi.mock("@/platform/project", () => ({ basename: (path: string) => path, useProject: { setState: boot.setProject } }));
|
||||
vi.mock("@/platform/remote", () => ({ restoreRemote: async () => {} }));
|
||||
vi.mock("@/platform/platformInfo", () => ({ usePlatform: vi.fn() }));
|
||||
vi.mock("@/ui", () => ({ Spinner: () => null, T: () => null, isPopupOpen: () => false }));
|
||||
vi.mock("@/workbench/contributions", () => ({
|
||||
editorService: () => ({ openInput: boot.openInput, openFile: boot.openFile }),
|
||||
notifications: () => ({ notify: vi.fn() }),
|
||||
useContributions: {
|
||||
getState: () => ({ editorKinds: new Map([["agent-session", { prepareWindowInput: boot.prepare }]]) }),
|
||||
},
|
||||
}));
|
||||
vi.mock("@/workbench/EditorArea", () => ({ EditorArea: () => null }));
|
||||
vi.mock("@/workbench/OverlayHost", () => ({ OverlayHost: () => null }));
|
||||
vi.mock("@/workbench/TitleBar", () => ({ TitleBar: () => null }));
|
||||
vi.mock("@/workbench/WindowResizeHandles", () => ({ WindowResizeHandles: () => null }));
|
||||
vi.mock("@/workbench/theme", () => ({ useApplyTheme: () => {} }));
|
||||
vi.mock("@/workbench/messages", () => ({ ask: vi.fn() }));
|
||||
vi.mock("./controller", () => ({ editorController: vi.fn(), tabTitle: () => "Conversation" }));
|
||||
|
||||
let stop: (() => void) | undefined;
|
||||
const input: EditorInput = { kind: "agent-session", key: "agent:one", data: { task: "one" } };
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
boot.takeLaunch.mockResolvedValue({ editor: { input: JSON.stringify(input) } });
|
||||
});
|
||||
afterEach(() => stop?.());
|
||||
|
||||
describe("lightweight window handoff", () => {
|
||||
it("opens and reports ready only after its kind prepared the input", async () => {
|
||||
let ready!: (input: EditorInput) => void;
|
||||
boot.prepare.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
ready = resolve;
|
||||
}),
|
||||
);
|
||||
stop = activateEditorWindow("main");
|
||||
await vi.waitFor(() => expect(boot.prepare).toHaveBeenCalledWith(input));
|
||||
expect(boot.openInput).not.toHaveBeenCalled();
|
||||
expect(boot.emit).not.toHaveBeenCalled();
|
||||
const recovered = { ...input, data: { task: "one", draft: { text: "Latest draft" } } };
|
||||
ready(recovered);
|
||||
await vi.waitFor(() =>
|
||||
expect(boot.emit).toHaveBeenCalledWith("main", "openidea://editor/ready", {
|
||||
label: "editor-main-3",
|
||||
path: input.key,
|
||||
ok: true,
|
||||
}),
|
||||
);
|
||||
expect(boot.openInput).toHaveBeenCalledWith(recovered, { focus: true });
|
||||
});
|
||||
|
||||
it("reports failure without opening a broken conversation", async () => {
|
||||
boot.prepare.mockRejectedValueOnce(new Error("Cannot load conversation"));
|
||||
stop = activateEditorWindow("main");
|
||||
await vi.waitFor(() =>
|
||||
expect(boot.emit).toHaveBeenCalledWith("main", "openidea://editor/ready", {
|
||||
label: "editor-main-3",
|
||||
path: input.key,
|
||||
ok: false,
|
||||
error: "Error: Cannot load conversation",
|
||||
}),
|
||||
);
|
||||
expect(boot.openInput).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Lightweight editor window (`editor-<parent>-<n>`): one project file in a window of its own
|
||||
* ("Open in New Window" without a second workbench).
|
||||
* Lightweight editor window (`editor-<parent>-<n>`): one project file, or one tab of another
|
||||
* editor kind, in a window of its own ("Open in New Window" without a second workbench).
|
||||
*/
|
||||
import clsx from "clsx";
|
||||
import { create } from "zustand";
|
||||
@@ -15,14 +15,14 @@ import { basename, useProject } from "@/platform/project";
|
||||
import { restoreRemote } from "@/platform/remote";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { Spinner, T, isPopupOpen } from "@/ui";
|
||||
import { editorService, notifications } from "@/workbench/contributions";
|
||||
import { editorService, notifications, useContributions, type EditorInput } from "@/workbench/contributions";
|
||||
import { EditorArea } from "@/workbench/EditorArea";
|
||||
import { OverlayHost } from "@/workbench/OverlayHost";
|
||||
import { TitleBar } from "@/workbench/TitleBar";
|
||||
import { WindowResizeHandles } from "@/workbench/WindowResizeHandles";
|
||||
import { useApplyTheme } from "@/workbench/theme";
|
||||
import { ask } from "@/workbench/messages";
|
||||
import { editorController } from "./controller";
|
||||
import { editorController, tabTitle } from "./controller";
|
||||
import type { DocModel } from "./model/document";
|
||||
import styles from "./EditorWindow.module.css";
|
||||
|
||||
@@ -71,7 +71,7 @@ async function settleUnsaved(models: DocModel[], project: string | null): Promis
|
||||
return answer.button === "save" || answer.button === "discard";
|
||||
}
|
||||
|
||||
/** Loads the launch's file into this window's editor. */
|
||||
/** Loads the launch's file or tab into this window's editor. */
|
||||
export function activateEditorWindow(parent: string): () => void {
|
||||
let projectName: string | null = null;
|
||||
const native = getCurrentWindow();
|
||||
@@ -131,14 +131,20 @@ export function activateEditorWindow(parent: string): () => void {
|
||||
try {
|
||||
await restoreRemote();
|
||||
const launch = (await commands.windowTakeLaunch())?.editor as EditorLaunch | null | undefined;
|
||||
if (!launch?.path) throw new Error(tx("Missing editor request"));
|
||||
path = launch.path;
|
||||
let input = launch?.input ? (JSON.parse(launch.input) as EditorInput) : null;
|
||||
path = launch?.path ?? input?.key ?? "";
|
||||
if (!launch || !path) throw new Error(tx("Missing editor request"));
|
||||
const project = await commands.projectCurrent();
|
||||
if (!project) throw new Error(tx("The editor’s project is no longer open"));
|
||||
projectName = project.name;
|
||||
// Settings only: restoring the project's editor session here would overwrite the main window's tabs.
|
||||
useProject.setState({ settings: project.settings });
|
||||
// Other editor kinds read the project; the controller leaves its saved tabs to the main window.
|
||||
useProject.setState(input ? { project, settings: project.settings } : { settings: project.settings });
|
||||
setContext("projectOpen", true);
|
||||
if (input) {
|
||||
const prepare = useContributions.getState().editorKinds.get(input.kind)?.prepareWindowInput;
|
||||
if (prepare) input = await prepare(input);
|
||||
}
|
||||
if (disposed) return;
|
||||
const selection =
|
||||
launch.line != null && launch.column != null
|
||||
? {
|
||||
@@ -147,9 +153,11 @@ export function activateEditorWindow(parent: string): () => void {
|
||||
...(launch.endLine != null ? { endLine: launch.endLine, endCol: launch.endColumn ?? 0 } : {}),
|
||||
}
|
||||
: undefined;
|
||||
await editorService().openFile(path, { focus: true, selection });
|
||||
if (input) await editorService().openInput(input, { focus: true });
|
||||
else await editorService().openFile(path, { focus: true, selection });
|
||||
useEditorWindow.setState({ path });
|
||||
showCaption(`${project.name} — ${basename(path)}`);
|
||||
const title = input ? tabTitle(input, useContributions.getState().editorKinds) : basename(path);
|
||||
showCaption(`${project.name} — ${title}`);
|
||||
await reportReady(parent, { path, ok: true });
|
||||
} catch (error) {
|
||||
const message = String(error);
|
||||
@@ -171,7 +179,7 @@ export function EditorWindow() {
|
||||
const ownTitleBar = usePlatform((s) => s.overlayTitleBar || s.framelessTitleBar);
|
||||
return (
|
||||
<main className={clsx(styles.window, os === "linux" && styles.edge)}>
|
||||
{ownTitleBar && <TitleBar minimal dialog title={title} />}
|
||||
{ownTitleBar && <TitleBar minimal title={title} />}
|
||||
{error ? (
|
||||
<div className={styles.error} role="alert">
|
||||
{error}
|
||||
|
||||
@@ -54,6 +54,7 @@ import { hoverActionsAt } from "@/platform/hoverActions";
|
||||
import { save as saveFileDialog, type DialogFilter as SaveDialogFilter } from "@/platform/dialog";
|
||||
import { isUntitledUri, untitledTitle } from "@/platform/virtualDocs";
|
||||
import { isRemoteWindow } from "@/platform/remote";
|
||||
import { auxiliaryWindow } from "@/platform/auxWindow";
|
||||
import { fileIconName, showContextMenu, type MenuItem } from "@/ui";
|
||||
import { canOpenWithSystemApp, canRevealInFileManager, fileManagerName } from "@/platform/fileManager";
|
||||
import {
|
||||
@@ -663,6 +664,8 @@ export class EditorController implements SlotHost {
|
||||
|
||||
/** Reopens the tabs, splits and carets saved for `root` (after the project opened). */
|
||||
async restoreSession(root: string) {
|
||||
// The project window owns the saved layout; a lightweight window shows what it was opened for.
|
||||
if (auxiliaryWindow()) return;
|
||||
this.sessionRoot = root;
|
||||
// A window close dropped this session: the next open starts from the tabs opened now.
|
||||
if (this.forgottenSessions.delete(root)) return;
|
||||
@@ -1913,6 +1916,8 @@ export class EditorController implements SlotHost {
|
||||
/** Open a lightweight aux editor (or a full window outside the project), then remove the original tab. */
|
||||
async detachTab(paneId: string, tabId: string): Promise<boolean> {
|
||||
const tab = useTabs.getState().panes[paneId]?.tabs.find((t) => t.id === tabId);
|
||||
const moves = tab && useContributions.getState().editorKinds.get(tab.input.kind)?.openInWindow;
|
||||
if (moves) return moves(tab.input);
|
||||
const path = tab?.input.path;
|
||||
if (
|
||||
!tab ||
|
||||
@@ -1981,6 +1986,11 @@ export class EditorController implements SlotHost {
|
||||
},
|
||||
});
|
||||
}
|
||||
/** Shows `input` in a lightweight window of this project; resolves to the window's label once it is shown. */
|
||||
openInWindow(input: EditorInput): Promise<string> {
|
||||
if (!isTauri() || isRemoteWindow()) return Promise.reject(new Error(t("app.window.desktopOnly")));
|
||||
return openLightweightEditor({ input: JSON.stringify(input) }, windowBackgroundHex(), input.key);
|
||||
}
|
||||
/** IDEA "Open in Opposite Group": the tab stays and a copy opens next door (or in a new split). */
|
||||
openInOpposite(paneId: string, tabId: string) {
|
||||
const s = useTabs.getState();
|
||||
@@ -2294,8 +2304,9 @@ export class EditorController implements SlotHost {
|
||||
{ label: "Unsplit All", run: () => void this.unsplitAll(paneId) },
|
||||
] as MenuItem[])
|
||||
: []),
|
||||
...(tab.input.path &&
|
||||
(tab.input.kind === "file" || documentLifecycle(tab.input, useContributions.getState().editorKinds))
|
||||
...(useContributions.getState().editorKinds.get(tab.input.kind)?.openInWindow ||
|
||||
(tab.input.path &&
|
||||
(tab.input.kind === "file" || documentLifecycle(tab.input, useContributions.getState().editorKinds)))
|
||||
? ([{ label: "Open in New Window", run: () => void this.detachTab(paneId, tab.id) }] as MenuItem[])
|
||||
: []),
|
||||
{ kind: "separator" },
|
||||
|
||||
@@ -39,7 +39,7 @@ beforeEach(() => {
|
||||
status: "ok",
|
||||
data: { kind: "opened", label: "second" },
|
||||
});
|
||||
vi.spyOn(light, "openLightweightEditor").mockResolvedValue();
|
||||
vi.spyOn(light, "openLightweightEditor").mockResolvedValue("editor-main-1");
|
||||
});
|
||||
afterEach(() => {
|
||||
ctrl?.stop();
|
||||
@@ -51,6 +51,24 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("detachTab", () => {
|
||||
it("leaves the move to an editor kind that moves its own tabs", async () => {
|
||||
const openInWindow = vi.fn(async () => true);
|
||||
unregister = registerEditorKind({ kind: "chat", component: () => null, title: () => "Chat", openInWindow });
|
||||
ctrl = new EditorController(createMemoryBackend({}));
|
||||
ctrl.start();
|
||||
await ctrl.openInput({ kind: "chat", key: "chat:1", data: { id: 1 } }, { focus: false });
|
||||
const [pane, id] = current();
|
||||
expect(await ctrl.detachTab(pane, id)).toBe(true);
|
||||
expect(openInWindow).toHaveBeenCalledWith(expect.objectContaining({ key: "chat:1", data: { id: 1 } }));
|
||||
expect(light.openLightweightEditor).not.toHaveBeenCalled();
|
||||
await ctrl.openInWindow({ kind: "chat", key: "chat:1", data: { id: 1 } });
|
||||
expect(light.openLightweightEditor).toHaveBeenCalledWith(
|
||||
{ input: JSON.stringify({ kind: "chat", key: "chat:1", data: { id: 1 } }) },
|
||||
null,
|
||||
"chat:1",
|
||||
);
|
||||
});
|
||||
|
||||
it("moves a project file to a lightweight editor without saving first", async () => {
|
||||
useProject.setState({
|
||||
project: { root: "/p", workspace: { projects: ["/p"] } } as never,
|
||||
|
||||
@@ -45,6 +45,7 @@ export function activate(): void | (() => void) {
|
||||
provideEditorService({
|
||||
openFile: (path, options) => ctrl.openFile(path, options),
|
||||
openInput: (input, options) => ctrl.openInput(input, options),
|
||||
openInWindow: (input) => ctrl.openInWindow(input),
|
||||
openUntitled: (options) => ctrl.openUntitled(options),
|
||||
activePath: () => ctrl.activePath(),
|
||||
activeCursor: () => ctrl.activeCursor(),
|
||||
|
||||
@@ -5,18 +5,23 @@ import { call, commands, type EditorLaunch } from "@/platform/ipc";
|
||||
|
||||
const READY_MS = 30_000;
|
||||
|
||||
/** Opens a project-file aux editor and resolves once it has taken over the document. */
|
||||
export async function openLightweightEditor(launch: EditorLaunch, background: string | null): Promise<void> {
|
||||
/** Opens a lightweight editor window; resolves to its label once it shows the file or tab. */
|
||||
export async function openLightweightEditor(
|
||||
launch: EditorLaunch,
|
||||
background: string | null,
|
||||
/** What the window reports as shown: the file, or the key of the launch's tab. */
|
||||
target = launch.path,
|
||||
): Promise<string> {
|
||||
const parent = getCurrentWindow();
|
||||
let off: (() => void) | undefined;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
return await new Promise<string>((resolve, reject) => {
|
||||
timer = setTimeout(() => reject(new Error(tx("Timed out opening the editor window"))), READY_MS);
|
||||
void parent
|
||||
.listen<EditorReadyResult>(EDITOR_READY, ({ payload }) => {
|
||||
if (payload.path && payload.path !== launch.path) return;
|
||||
if (payload.ok) resolve();
|
||||
if (payload.path && payload.path !== target) return;
|
||||
if (payload.ok) resolve(payload.label);
|
||||
else reject(new Error(payload.error || tx("Could not open the editor window")));
|
||||
})
|
||||
.then((unlisten) => {
|
||||
|
||||
@@ -1,18 +1,22 @@
|
||||
.popup {
|
||||
max-width: min(90vw, 900px);
|
||||
padding: 0;
|
||||
.barPopup,
|
||||
.childPopup {
|
||||
width: max-content;
|
||||
overflow: hidden;
|
||||
font-size: var(--fs-chrome);
|
||||
}
|
||||
.root {
|
||||
outline: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-width: 900px;
|
||||
}
|
||||
.bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0;
|
||||
padding: 3px 4px;
|
||||
min-width: 0;
|
||||
padding: var(--space-1);
|
||||
overflow-x: auto;
|
||||
scrollbar-width: thin;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.segmentWrap {
|
||||
@@ -22,20 +26,20 @@
|
||||
}
|
||||
.sep {
|
||||
color: var(--fg-faint);
|
||||
margin: 0 1px;
|
||||
margin: 0 var(--space-0-5);
|
||||
}
|
||||
.segment {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
gap: var(--space-1);
|
||||
max-width: min(288px, 55vw);
|
||||
height: var(--h-control-small);
|
||||
padding: 0 5px;
|
||||
padding: 0 var(--space-1-5);
|
||||
border: none;
|
||||
border-radius: var(--radius-small);
|
||||
background: transparent;
|
||||
color: var(--fg);
|
||||
font: inherit;
|
||||
font-size: var(--fs-ui);
|
||||
cursor: default;
|
||||
}
|
||||
.segment:hover {
|
||||
@@ -46,22 +50,28 @@
|
||||
background: var(--bg-list-selected);
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
.childPopup {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: min(200px, calc(100vw - 12px));
|
||||
}
|
||||
.list {
|
||||
align-self: flex-start;
|
||||
min-width: 200px;
|
||||
max-height: 360px;
|
||||
overflow-y: auto;
|
||||
margin: 0 4px 4px;
|
||||
padding: 4px;
|
||||
border-top: 1px solid var(--border-popup);
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
max-width: min(480px, calc(100vw - 14px));
|
||||
max-height: min(360px, 62vh);
|
||||
padding: var(--space-1);
|
||||
overflow: auto;
|
||||
overflow-x: hidden;
|
||||
outline: none;
|
||||
}
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: var(--space-1);
|
||||
height: var(--h-list-row);
|
||||
padding: 0 6px;
|
||||
border-radius: var(--radius-row);
|
||||
padding: 0 var(--space-2);
|
||||
border-radius: var(--radius-selection);
|
||||
color: var(--fg);
|
||||
white-space: nowrap;
|
||||
}
|
||||
@@ -70,31 +80,31 @@
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
.rowLabel {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.rowIcon {
|
||||
flex: none;
|
||||
}
|
||||
.empty {
|
||||
padding: 4px 6px;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.childList {
|
||||
min-width: 200px;
|
||||
max-height: 360px;
|
||||
overflow-y: auto;
|
||||
padding: 4px;
|
||||
outline: none;
|
||||
}
|
||||
.childHeader {
|
||||
display: flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
height: var(--h-list-row);
|
||||
padding: 0 6px;
|
||||
margin-bottom: 2px;
|
||||
gap: var(--space-1);
|
||||
max-width: min(480px, calc(100vw - 14px));
|
||||
height: calc(var(--h-list-row) + var(--space-2));
|
||||
padding: 0 var(--space-3);
|
||||
border-bottom: 1px solid var(--border-popup);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.rowChevron {
|
||||
flex: none;
|
||||
margin-left: auto;
|
||||
color: var(--fg-faint);
|
||||
}
|
||||
@@ -4,13 +4,13 @@
|
||||
* (folder contents, file / symbol members); Enter on a child opens it (a
|
||||
* folder becomes the next segment), Escape closes the list, then the bar.
|
||||
*/
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
import { create } from "zustand";
|
||||
import { call, commands, isTauri, type OutlineItem } from "@/platform/ipc";
|
||||
import { projectFolder, useProject } from "@/platform/project";
|
||||
import { useProjectViewLead } from "@/workbench/contributions";
|
||||
import { Icon, Popup, T } from "@/ui";
|
||||
import { Icon, listNavigate, Popup, revealHorizontally, revealVertically, T } from "@/ui";
|
||||
import { editorController, useEditorStatus } from "../controller";
|
||||
import { useOutline } from "../model/document";
|
||||
import { symbolChain } from "./outline";
|
||||
@@ -64,6 +64,74 @@ function anchorPoint(): { x: number; y: number } {
|
||||
return r ? { x: r.left + 8, y: r.top + 4 } : { x: 80, y: 80 };
|
||||
}
|
||||
|
||||
function NavChildList({
|
||||
label,
|
||||
id,
|
||||
items,
|
||||
active,
|
||||
onSelect,
|
||||
onChoose,
|
||||
onKeyDown,
|
||||
}: {
|
||||
label: string;
|
||||
id: string;
|
||||
items: readonly NavChild[] | null;
|
||||
active: number;
|
||||
onSelect: (index: number) => void;
|
||||
onChoose: (child: NavChild) => void;
|
||||
onKeyDown?: (e: KeyboardEvent) => void;
|
||||
}) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useLayoutEffect(() => {
|
||||
const scroller = ref.current;
|
||||
const row = scroller?.querySelector<HTMLElement>('[aria-selected="true"]');
|
||||
if (!scroller || !row) return;
|
||||
const reveal = () => revealVertically(scroller, row);
|
||||
reveal();
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
const resize = new ResizeObserver(reveal);
|
||||
resize.observe(scroller);
|
||||
return () => resize.disconnect();
|
||||
}, [active, items]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
id={id}
|
||||
className={styles.list}
|
||||
role="listbox"
|
||||
aria-label={label}
|
||||
aria-activedescendant={items?.[active] ? `${id}-${active}` : undefined}
|
||||
tabIndex={0}
|
||||
data-autofocus
|
||||
onKeyDown={onKeyDown}
|
||||
>
|
||||
{items?.length === 0 && (
|
||||
<div className={styles.empty}>
|
||||
<T>Nothing here</T>
|
||||
</div>
|
||||
)}
|
||||
{items?.map((child, i) => (
|
||||
<div
|
||||
key={`${child.path}:${child.label}:${i}`}
|
||||
id={`${id}-${i}`}
|
||||
role="option"
|
||||
aria-selected={i === active}
|
||||
className={clsx(styles.row, i === active && styles.rowActive)}
|
||||
onMouseEnter={() => onSelect(i)}
|
||||
onClick={() => onChoose(child)}
|
||||
>
|
||||
<Icon name={iconOf(child)} size={16} className={styles.rowIcon} />
|
||||
<span className={styles.rowLabel} title={child.label}>
|
||||
{child.label}
|
||||
</span>
|
||||
{child.kind === "dir" && <Icon name="chevron-right" size={12} className={styles.rowChevron} />}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NavBar({ path, line, col, directory }: { path: string; line: number; col: number; directory: boolean }) {
|
||||
const project = useProject((s) => s.project);
|
||||
const outline = useOutline((s) => s[path]);
|
||||
@@ -77,11 +145,19 @@ function NavBar({ path, line, col, directory }: { path: string; line: number; co
|
||||
const [active, setActive] = useState(() =>
|
||||
Math.max(0, directory ? initial.length - 1 : initial.findIndex((s) => s.kind === "file")),
|
||||
);
|
||||
const [list, setList] = useState<{ seg: number; items: NavChild[]; active: number; left: number } | null>(null);
|
||||
const [list, setList] = useState<{ seg: number; items: NavChild[]; active: number } | null>(null);
|
||||
const [childAnchor, setChildAnchor] = useState<HTMLButtonElement | null>(null);
|
||||
const listId = useId();
|
||||
const [anchor] = useState(anchorPoint);
|
||||
const strip = useRef<HTMLDivElement>(null);
|
||||
const buttons = useRef<Array<HTMLButtonElement | null>>([]);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const request = useRef(0);
|
||||
const listSegment = list?.seg;
|
||||
|
||||
const closeList = () => {
|
||||
request.current++;
|
||||
setList(null);
|
||||
};
|
||||
|
||||
const openList = async (index: number, segs = segments) => {
|
||||
const seg = segs[index];
|
||||
@@ -92,7 +168,7 @@ function NavBar({ path, line, col, directory }: { path: string; line: number; co
|
||||
// Start on the child that leads to the next segment, like IDEA.
|
||||
const next = segs[index + 1];
|
||||
const at = next ? items.findIndex((c) => c.path === next.path && c.label === next.label) : -1;
|
||||
setList({ seg: index, items, active: Math.max(0, at), left: buttons.current[index]?.offsetLeft ?? 0 });
|
||||
setList({ seg: index, items, active: Math.max(0, at) });
|
||||
};
|
||||
|
||||
const choose = (child: NavChild) => {
|
||||
@@ -125,15 +201,14 @@ function NavBar({ path, line, col, directory }: { path: string; line: number; co
|
||||
let handled = true;
|
||||
if (e.key === "ArrowLeft") move(-1);
|
||||
else if (e.key === "ArrowRight") move(1);
|
||||
else if (e.key === "ArrowDown" && !list) void openList(active);
|
||||
else if (e.key === "ArrowDown" && list)
|
||||
setList({ ...list, active: Math.min(list.items.length - 1, list.active + 1) });
|
||||
else if (e.key === "ArrowUp" && list) setList({ ...list, active: Math.max(0, list.active - 1) });
|
||||
else if (e.key === "Enter" && list) {
|
||||
const child = list.items[list.active];
|
||||
if (child) choose(child);
|
||||
} else if (e.key === "Enter") void openList(active);
|
||||
else if (e.key === "Escape" && list) setList(null);
|
||||
else if (list) {
|
||||
const next = listNavigate(e.key, list);
|
||||
if (next !== null) setList({ ...list, active: next });
|
||||
else if (e.key === "Enter") {
|
||||
const child = list.items[list.active];
|
||||
if (child) choose(child);
|
||||
} else handled = false;
|
||||
} else if (e.key === "ArrowDown" || e.key === "Enter") void openList(active);
|
||||
else handled = false;
|
||||
if (handled) {
|
||||
e.preventDefault();
|
||||
@@ -142,11 +217,19 @@ function NavBar({ path, line, col, directory }: { path: string; line: number; co
|
||||
};
|
||||
|
||||
useLayoutEffect(() => {
|
||||
buttons.current[active]?.scrollIntoView?.({ block: "nearest", inline: "nearest" });
|
||||
}, [active]);
|
||||
useEffect(() => {
|
||||
listRef.current?.querySelector<HTMLElement>('[aria-selected="true"]')?.scrollIntoView?.({ block: "nearest" });
|
||||
}, [list]);
|
||||
const row = strip.current;
|
||||
const current = buttons.current[active];
|
||||
if (!row || !current) return;
|
||||
const reveal = () => revealHorizontally(row, current);
|
||||
reveal();
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
const resize = new ResizeObserver(reveal);
|
||||
resize.observe(row);
|
||||
return () => resize.disconnect();
|
||||
}, [active, segments]);
|
||||
useLayoutEffect(() => {
|
||||
setChildAnchor(listSegment === undefined ? null : (buttons.current[listSegment] ?? null));
|
||||
}, [listSegment, segments]);
|
||||
|
||||
return (
|
||||
<Popup
|
||||
@@ -156,7 +239,7 @@ function NavBar({ path, line, col, directory }: { path: string; line: number; co
|
||||
offset={0}
|
||||
onClose={close}
|
||||
aria-label="Navigation bar"
|
||||
className={styles.popup}
|
||||
className={styles.barPopup}
|
||||
>
|
||||
<div
|
||||
className={styles.root}
|
||||
@@ -166,7 +249,7 @@ function NavBar({ path, line, col, directory }: { path: string; line: number; co
|
||||
role="toolbar"
|
||||
aria-label={tx("Navigation bar")}
|
||||
>
|
||||
<div className={styles.bar}>
|
||||
<div className={styles.bar} ref={strip}>
|
||||
{segments.map((s, i) => (
|
||||
<span key={`${i}:${s.path}:${s.label}`} className={styles.segmentWrap}>
|
||||
{i > 0 && <Icon name="chevron-right" size={12} className={styles.sep} />}
|
||||
@@ -176,44 +259,39 @@ function NavBar({ path, line, col, directory }: { path: string; line: number; co
|
||||
tabIndex={-1}
|
||||
className={clsx(styles.segment, i === active && styles.active)}
|
||||
aria-current={i === active ? "location" : undefined}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={i === listSegment}
|
||||
aria-controls={i === listSegment ? listId : undefined}
|
||||
title={s.label}
|
||||
onClick={() => {
|
||||
setActive(i);
|
||||
void openList(i);
|
||||
}}
|
||||
>
|
||||
<Icon name={iconOf(s)} size={14} />
|
||||
<span>{s.label}</span>
|
||||
<Icon name={iconOf(s)} size={14} className={styles.rowIcon} />
|
||||
<span className={styles.rowLabel}>{s.label}</span>
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
{list && (
|
||||
<div
|
||||
ref={listRef}
|
||||
className={styles.list}
|
||||
style={{ marginLeft: list.left }}
|
||||
role="listbox"
|
||||
{list && childAnchor && (
|
||||
<Popup
|
||||
open
|
||||
anchor={childAnchor}
|
||||
placement="bottom-start"
|
||||
onClose={closeList}
|
||||
aria-label={tx("Children")}
|
||||
className={styles.childPopup}
|
||||
>
|
||||
{list.items.length === 0 && (
|
||||
<div className={styles.empty}>
|
||||
<T>Nothing here</T>
|
||||
</div>
|
||||
)}
|
||||
{list.items.map((c, i) => (
|
||||
<div
|
||||
key={`${c.path}:${c.label}:${i}`}
|
||||
role="option"
|
||||
aria-selected={i === list.active}
|
||||
className={clsx(styles.row, i === list.active && styles.rowActive)}
|
||||
onMouseEnter={() => setList({ ...list, active: i })}
|
||||
onClick={() => choose(c)}
|
||||
>
|
||||
<Icon name={iconOf(c)} size={14} />
|
||||
<span className={styles.rowLabel}>{c.label}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<NavChildList
|
||||
id={listId}
|
||||
label={tx("Children")}
|
||||
items={list.items}
|
||||
active={list.active}
|
||||
onSelect={(i) => setList({ ...list, active: i })}
|
||||
onChoose={choose}
|
||||
/>
|
||||
</Popup>
|
||||
)}
|
||||
</div>
|
||||
</Popup>
|
||||
@@ -228,10 +306,12 @@ function NavBar({ path, line, col, directory }: { path: string; line: number; co
|
||||
export function NavChildrenPopup({
|
||||
segment,
|
||||
anchor,
|
||||
openAbove = true,
|
||||
onClose,
|
||||
}: {
|
||||
segment: NavSegment;
|
||||
anchor: HTMLElement;
|
||||
openAbove?: boolean;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [stack, setStack] = useState<NavSegment[]>([segment]);
|
||||
@@ -239,7 +319,7 @@ export function NavChildrenPopup({
|
||||
const outline = useOutline((s) => s[top.path]);
|
||||
const [loaded, setLoaded] = useState<{ top: NavSegment; items: NavChild[] } | null>(null);
|
||||
const [active, setActive] = useState(0);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const listId = useId();
|
||||
const items = loaded?.top === top ? loaded.items : null;
|
||||
|
||||
useEffect(() => {
|
||||
@@ -255,10 +335,6 @@ export function NavChildrenPopup({
|
||||
alive = false;
|
||||
};
|
||||
}, [top, outline]);
|
||||
useEffect(() => {
|
||||
listRef.current?.querySelector<HTMLElement>('[aria-selected="true"]')?.scrollIntoView?.({ block: "nearest" });
|
||||
}, [active, items]);
|
||||
|
||||
const choose = (child: NavChild) => {
|
||||
if (child.kind === "dir") return setStack((s) => [...s, { kind: "dir", path: child.path, label: child.label }]);
|
||||
onClose();
|
||||
@@ -270,10 +346,9 @@ export function NavChildrenPopup({
|
||||
};
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
const n = items?.length ?? 0;
|
||||
const next = items ? listNavigate(e.key, { items, active, wrap: true }) : null;
|
||||
let handled = true;
|
||||
if (e.key === "ArrowDown" && n) setActive((a) => (a + 1) % n);
|
||||
else if (e.key === "ArrowUp" && n) setActive((a) => (a - 1 + n) % n);
|
||||
if (next !== null) setActive(next);
|
||||
else if (e.key === "Enter" || (e.key === "ArrowRight" && items?.[active]?.kind === "dir")) {
|
||||
const child = items?.[active];
|
||||
if (child) choose(child);
|
||||
@@ -286,44 +361,31 @@ export function NavChildrenPopup({
|
||||
};
|
||||
|
||||
return (
|
||||
<Popup open anchor={anchor} placement="top-start" onClose={onClose} aria-label={top.label} className={styles.popup}>
|
||||
<div
|
||||
ref={listRef}
|
||||
className={styles.childList}
|
||||
role="listbox"
|
||||
aria-label={top.label}
|
||||
tabIndex={0}
|
||||
data-autofocus
|
||||
aria-activedescendant={items?.length ? `navbar-child-${active}` : undefined}
|
||||
<Popup
|
||||
open
|
||||
anchor={anchor}
|
||||
placement={openAbove ? "top-start" : "bottom-start"}
|
||||
onClose={onClose}
|
||||
aria-label={top.label}
|
||||
className={styles.childPopup}
|
||||
>
|
||||
{stack.length > 1 && (
|
||||
<div className={styles.childHeader}>
|
||||
<Icon name={iconOf(top)} size={16} className={styles.rowIcon} />
|
||||
<span className={styles.rowLabel} title={top.label}>
|
||||
{top.label}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<NavChildList
|
||||
id={listId}
|
||||
label={top.label}
|
||||
items={items}
|
||||
active={active}
|
||||
onSelect={setActive}
|
||||
onChoose={choose}
|
||||
onKeyDown={onKeyDown}
|
||||
>
|
||||
{stack.length > 1 && (
|
||||
<div className={styles.childHeader}>
|
||||
<Icon name={iconOf(top)} size={14} />
|
||||
<span className={styles.rowLabel}>{top.label}</span>
|
||||
</div>
|
||||
)}
|
||||
{items?.length === 0 && (
|
||||
<div className={styles.empty}>
|
||||
<T>Nothing here</T>
|
||||
</div>
|
||||
)}
|
||||
{items?.map((c, i) => (
|
||||
<div
|
||||
key={`${c.path}:${c.label}:${i}`}
|
||||
id={`navbar-child-${i}`}
|
||||
role="option"
|
||||
aria-selected={i === active}
|
||||
className={clsx(styles.row, i === active && styles.rowActive)}
|
||||
onMouseEnter={() => setActive(i)}
|
||||
onClick={() => choose(c)}
|
||||
>
|
||||
<Icon name={iconOf(c)} size={14} />
|
||||
<span className={styles.rowLabel}>{c.label}</span>
|
||||
{c.kind === "dir" && <Icon name="chevron-right" size={12} className={styles.rowChevron} />}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
/>
|
||||
</Popup>
|
||||
);
|
||||
}
|
||||
@@ -226,7 +226,15 @@ function BreadcrumbStrip({
|
||||
}
|
||||
|
||||
/** A row of crumbs; a segment with `nav` opens a popup of its children. */
|
||||
function CrumbNav({ segments, className }: { segments: Crumb[]; className?: string }) {
|
||||
function CrumbNav({
|
||||
segments,
|
||||
className,
|
||||
inStatusBar,
|
||||
}: {
|
||||
segments: Crumb[];
|
||||
className?: string;
|
||||
inStatusBar: boolean;
|
||||
}) {
|
||||
const [popup, setPopup] = useState<{ nav: NavSegment; anchor: HTMLElement } | null>(null);
|
||||
return (
|
||||
<BreadcrumbStrip
|
||||
@@ -261,7 +269,15 @@ function CrumbNav({ segments, className }: { segments: Crumb[]; className?: stri
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
{popup && <NavChildrenPopup segment={popup.nav} anchor={popup.anchor} onClose={() => setPopup(null)} />}
|
||||
{popup && (
|
||||
<NavChildrenPopup
|
||||
key={`${popup.nav.kind}:${popup.nav.path}:${popup.nav.label}`}
|
||||
segment={popup.nav}
|
||||
anchor={popup.anchor}
|
||||
openAbove={inStatusBar}
|
||||
onClose={() => setPopup(null)}
|
||||
/>
|
||||
)}
|
||||
</BreadcrumbStrip>
|
||||
);
|
||||
}
|
||||
@@ -311,7 +327,7 @@ export function Breadcrumbs({ className, inStatusBar = false }: { className?: st
|
||||
segments.push(projectCrumb(project ?? currentProject));
|
||||
}
|
||||
if (!segments.length) return null;
|
||||
return <CrumbNav segments={segments} className={className ?? styles.status} />;
|
||||
return <CrumbNav segments={segments} className={className ?? styles.status} inStatusBar={inStatusBar} />;
|
||||
}
|
||||
|
||||
/** The status bar instance of the navigation bar; renders only for `statusBar`. */
|
||||
|
||||
@@ -4,7 +4,15 @@
|
||||
* history, `docs.ts`) and code.quickDefinition (⌥Space, definition source popup).
|
||||
*/
|
||||
import { EditorSelection } from "@codemirror/state";
|
||||
import { closeHoverTooltips, hasHoverTooltips, hoverTooltip, ViewPlugin, type EditorView } from "@codemirror/view";
|
||||
import {
|
||||
closeHoverTooltips,
|
||||
hasHoverTooltips,
|
||||
hoverTooltip,
|
||||
repositionTooltips,
|
||||
ViewPlugin,
|
||||
type EditorView,
|
||||
type TooltipView,
|
||||
} from "@codemirror/view";
|
||||
import type { Extension } from "@codemirror/state";
|
||||
import {
|
||||
commands,
|
||||
@@ -17,6 +25,7 @@ import {
|
||||
type RequestId,
|
||||
} from "@/platform/ipc";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { diagnosticsAt, type PlacedDiagnostic, type EditorDiagnostic } from "./diagnostics";
|
||||
import { isEmptyMarkup, languageForPath } from "./markdown";
|
||||
@@ -38,6 +47,7 @@ import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { CONTRIBUTED_HOVER, contributedAtAll, type ContributedHover } from "@/editor/api";
|
||||
import { navigationModifierHeld, onNavigationModifier, pointerTarget } from "@/platform/navigationModifier";
|
||||
import { languageSemantics } from "./semantic";
|
||||
import { tooltipBounds } from "@/editor/core/cm/setup";
|
||||
|
||||
let hoverRequest: RequestId | null = null;
|
||||
|
||||
@@ -74,6 +84,26 @@ export async function requestHover(view: EditorView, pos: number): Promise<Hover
|
||||
}
|
||||
}
|
||||
|
||||
function diagnosticAction(label: string, shortcut: string | undefined, run: () => void): HTMLButtonElement {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "cm-lsp-link-button";
|
||||
const text = document.createElement("span");
|
||||
text.className = "cm-lsp-diag-action-label";
|
||||
text.textContent = label;
|
||||
button.appendChild(text);
|
||||
if (shortcut) {
|
||||
const keys = document.createElement("span");
|
||||
keys.className = "cm-lsp-diag-shortcut";
|
||||
keys.textContent = shortcut;
|
||||
keys.setAttribute("aria-hidden", "true");
|
||||
button.appendChild(keys);
|
||||
}
|
||||
button.addEventListener("mousedown", (e) => e.preventDefault());
|
||||
button.addEventListener("click", run);
|
||||
return button;
|
||||
}
|
||||
|
||||
function renderDiagnostics(view: EditorView, diags: PlacedDiagnostic[]): HTMLElement {
|
||||
const box = document.createElement("div");
|
||||
box.className = "cm-lsp-hover-diagnostics";
|
||||
@@ -91,58 +121,39 @@ function renderDiagnostics(view: EditorView, diags: PlacedDiagnostic[]): HTMLEle
|
||||
msg.className = "cm-lsp-diag-message";
|
||||
msg.textContent = d.message;
|
||||
row.appendChild(msg);
|
||||
const meta = document.createElement("div");
|
||||
meta.className = "cm-lsp-diag-meta";
|
||||
if (d.source) {
|
||||
const src = document.createElement("span");
|
||||
src.className = "cm-lsp-diag-source";
|
||||
src.textContent = d.source;
|
||||
meta.appendChild(src);
|
||||
row.appendChild(src);
|
||||
}
|
||||
const fix = document.createElement("button");
|
||||
fix.type = "button";
|
||||
fix.className = "cm-lsp-link-button";
|
||||
const keys = shortcutLabel("code.showIntentions");
|
||||
fix.textContent = keys ? `More actions… ${keys}` : "More actions…";
|
||||
if (d.severity !== "hint") offerQuickFix(view, meta, fix, from, to, d);
|
||||
fix.addEventListener("mousedown", (e) => e.preventDefault());
|
||||
fix.addEventListener("click", () => {
|
||||
const actions = document.createElement("div");
|
||||
actions.className = "cm-lsp-diag-actions";
|
||||
const more = diagnosticAction(tx("More actions…"), shortcutLabel("code.showIntentions"), () => {
|
||||
view.dispatch({ selection: EditorSelection.cursor(from) });
|
||||
view.focus();
|
||||
void executeAction("code.showIntentions");
|
||||
});
|
||||
meta.appendChild(fix);
|
||||
row.appendChild(meta);
|
||||
actions.appendChild(more);
|
||||
if (d.severity !== "hint") offerQuickFix(view, more, from, to, d);
|
||||
row.appendChild(actions);
|
||||
box.appendChild(row);
|
||||
}
|
||||
return box;
|
||||
}
|
||||
|
||||
/** IDEA's hover link to the problem's preferred quick fix, shown once the server named one. */
|
||||
function offerQuickFix(
|
||||
view: EditorView,
|
||||
meta: HTMLElement,
|
||||
before: HTMLElement,
|
||||
from: number,
|
||||
to: number,
|
||||
diagnostic: EditorDiagnostic,
|
||||
) {
|
||||
function offerQuickFix(view: EditorView, before: HTMLElement, from: number, to: number, diagnostic: EditorDiagnostic) {
|
||||
const doc = view.state.doc;
|
||||
void quickFixesAt(view, from, to, diagnostic.problem)
|
||||
.then(([action]) => {
|
||||
if (!action || view.state.doc !== doc || !before.isConnected) return;
|
||||
const link = document.createElement("button");
|
||||
link.type = "button";
|
||||
link.className = "cm-lsp-link-button";
|
||||
const keys = shortcutLabel("code.applyQuickFix");
|
||||
link.textContent = keys ? `${action.title} ${keys}` : action.title;
|
||||
link.addEventListener("mousedown", (e) => e.preventDefault());
|
||||
link.addEventListener("click", () => {
|
||||
const link = diagnosticAction(action.title, shortcutLabel("code.applyQuickFix"), () => {
|
||||
view.dispatch({ effects: closeHoverTooltips });
|
||||
view.focus();
|
||||
void applyCodeAction(view, action);
|
||||
});
|
||||
meta.insertBefore(link, before);
|
||||
before.before(link);
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
@@ -186,12 +197,26 @@ export async function hoverSource(view: EditorView, pos: number) {
|
||||
create: () => {
|
||||
const dom = document.createElement("div");
|
||||
dom.className = `cm-lsp-hover ${selectableText}`;
|
||||
if (diags.length) dom.appendChild(renderDiagnostics(view, diags));
|
||||
if (!entry) return { dom };
|
||||
const tooltip: TooltipView = { dom };
|
||||
if (diags.length) {
|
||||
dom.appendChild(renderDiagnostics(view, diags));
|
||||
const fit = ({ left, right }: { left: number; right: number }) => {
|
||||
const width = `${Math.max(0, Math.floor(right - left) - 2)}px`;
|
||||
if (dom.style.getPropertyValue("--cm-diagnostic-hover-width") === width) return false;
|
||||
dom.style.setProperty("--cm-diagnostic-hover-width", width);
|
||||
return true;
|
||||
};
|
||||
tooltip.mount = () => void fit(tooltipBounds(view));
|
||||
tooltip.positioned = (space) => {
|
||||
if (fit(space)) repositionTooltips(view);
|
||||
};
|
||||
}
|
||||
if (!entry) return tooltip;
|
||||
// The same documentation view as F1's popup: links open in place, ← / →, Edit Source.
|
||||
dom.classList.add("cm-lsp-hover-doc");
|
||||
const doc = hoverDoc(entry, () => view.dispatch({ effects: closeHoverTooltips }));
|
||||
return { dom, destroy: mountHoverDoc(dom.appendChild(document.createElement("div")), doc) };
|
||||
tooltip.destroy = mountHoverDoc(dom.appendChild(document.createElement("div")), doc);
|
||||
return tooltip;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -29,6 +29,20 @@ describe("markdown LaTeX math", () => {
|
||||
expect(paras[1]!.textContent).toBe("Prices: $5 and $10, or $5-$10, or $ 5 $, or $x$.");
|
||||
});
|
||||
|
||||
it("renders GitHub-style protected inline math without the backticks", () => {
|
||||
const root = parseSafe("Prices $5 and $10, with **$`v_0`$** ($`\\theta`$) and $`\\text{price \\$10}`$.");
|
||||
const formulas = [...root.querySelectorAll(".katex annotation")].map((el) => el.textContent);
|
||||
expect(formulas).toEqual(["v_0", "\\theta", "\\text{price \\$10}"]);
|
||||
expect(root.querySelector("strong .katex annotation")?.textContent).toBe("v_0");
|
||||
expect(root.querySelector("p")?.textContent?.startsWith("Prices $5 and $10, with ")).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps an unfinished protected delimiter from swallowing a later formula", () => {
|
||||
const root = parseSafe("Unfinished $`x` and $y$.");
|
||||
expect(root.querySelector("p > code")?.textContent).toBe("x");
|
||||
expect(root.querySelector(".katex annotation")?.textContent).toBe("y");
|
||||
});
|
||||
|
||||
it("prevents * and _ inside math from triggering emphasis while allowing emphasis around math", () => {
|
||||
const root = parseSafe("Formula $(a)_1 + (b)_2$ and $a * b$ and $c * d$, plus **$x^2$**.");
|
||||
expect(root.querySelector("em")).toBeNull();
|
||||
|
||||
@@ -39,11 +39,15 @@ function findClosingDelimiter(src: string, from: number, delim: string): number
|
||||
return -1;
|
||||
}
|
||||
|
||||
const PROTECTED_INLINE_DOLLAR = /^\$`([^`\r\n]+)`\$/;
|
||||
// Marked masks code spans as `[aaa]` before calling emStrongMask
|
||||
const MASKED_PROTECTED_INLINE_DOLLAR = /^\$\[(a+)\]\$/;
|
||||
|
||||
/**
|
||||
* Matches inline `$...$` from index 0 using Pandoc-style guards so currency
|
||||
* like `$5 and $10` or `$5-$10` stays plain text while `$x$`, `设$x=1$`, etc. match.
|
||||
*/
|
||||
function matchInlineDollar(src: string): { end: number; text: string } | null {
|
||||
function matchInlineDollar(src: string, protectedDollar: RegExp): { end: number; text: string } | null {
|
||||
if (src[0] !== "$" || src[1] === "$" || !src[1] || /\s/.test(src[1])) return null;
|
||||
for (let i = 1; i < src.length; i++) {
|
||||
const ch = src[i]!;
|
||||
@@ -55,6 +59,7 @@ function matchInlineDollar(src: string): { end: number; text: string } | null {
|
||||
return null;
|
||||
}
|
||||
if (ch === "$") {
|
||||
if (protectedDollar.test(src.slice(i))) return null;
|
||||
if (i <= 1 || /\s/.test(src[i - 1]!)) continue;
|
||||
const next = src[i + 1] ?? "";
|
||||
if (next === "$" || /\d/.test(next)) return null;
|
||||
@@ -67,7 +72,10 @@ function matchInlineDollar(src: string): { end: number; text: string } | null {
|
||||
}
|
||||
|
||||
/** Matches inline `$$...$$`, `$...$`, `\(...\)`, or `\[...\]` starting at index 0 of `src`. */
|
||||
function matchInlineMath(src: string): { raw: string; text: string; display: boolean } | null {
|
||||
function matchInlineMath(
|
||||
src: string,
|
||||
protectedDollar = PROTECTED_INLINE_DOLLAR,
|
||||
): { raw: string; text: string; display: boolean } | null {
|
||||
if (src.startsWith("$$")) {
|
||||
const close = findClosingDelimiter(src, 2, "$$");
|
||||
if (close > 2) {
|
||||
@@ -77,7 +85,13 @@ function matchInlineMath(src: string): { raw: string; text: string; display: boo
|
||||
return null;
|
||||
}
|
||||
if (src[0] === "$") {
|
||||
const m = matchInlineDollar(src);
|
||||
const match = protectedDollar.exec(src);
|
||||
if (match) {
|
||||
const text = match[1]!;
|
||||
return text.trim() ? { raw: match[0], text, display: false } : null;
|
||||
}
|
||||
if (src[1] === "`") return null;
|
||||
const m = matchInlineDollar(src, protectedDollar);
|
||||
return m ? { raw: src.slice(0, m.end), text: m.text, display: false } : null;
|
||||
}
|
||||
if (src.startsWith("\\(")) {
|
||||
@@ -123,7 +137,7 @@ function maskInlineMath(src: string): string {
|
||||
continue;
|
||||
}
|
||||
if (src[i] === "$" || (src[i] === "\\" && (src[i + 1] === "(" || src[i + 1] === "["))) {
|
||||
const m = matchInlineMath(src.slice(i));
|
||||
const m = matchInlineMath(src.slice(i), MASKED_PROTECTED_INLINE_DOLLAR);
|
||||
if (m) {
|
||||
out += m.raw.replace(/[^\r\n]/g, "a");
|
||||
i += m.raw.length;
|
||||
|
||||
@@ -386,6 +386,20 @@ async function pythonImplementations(doc: EditorDocContext, pos: Pos): Promise<D
|
||||
return pythonImplementationTargets(hierarchy, doc.path, pos, outline).catch(() => []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks for the declaration at `offset`, dropping the target under the caret. Called when Go to
|
||||
* Implementation finds nothing: the jump then ends on the declaration, as in IDEA.
|
||||
*/
|
||||
async function implementationFallbackTargets(
|
||||
view: EditorView,
|
||||
offset: number,
|
||||
path: string,
|
||||
pos: Pos,
|
||||
): Promise<readonly DeclarationTarget[]> {
|
||||
const declaration = await requestNavigation(view, offset, "definition").catch(() => []);
|
||||
return declaration.filter((l) => !isSelfTarget([l], path, pos));
|
||||
}
|
||||
|
||||
/** Whether `line` (0-based) of `text` is an import statement. */
|
||||
function isImportLine(text: Text, line: number): boolean {
|
||||
return line < text.lines && /^\s*(from|import)\s/.test(text.line(line + 1).text);
|
||||
@@ -510,7 +524,17 @@ async function gotoResolved(
|
||||
const graph = graphTargets ? await graphTargets : [];
|
||||
if (superseded()) return;
|
||||
if (graph.length) locs = graph;
|
||||
else if (isCancelled(e) || !declaration) {
|
||||
else if (kind === "implementation" && !isCancelled(e) && !isUnavailable(e)) {
|
||||
// Some servers fail the request instead of answering empty (gopls: "no interfaces
|
||||
// implemented by this method"). Treat that as a search that found nothing, not a broken server.
|
||||
const declarationTargets = await implementationFallbackTargets(view, offset, doc.path, pos);
|
||||
if (superseded()) return;
|
||||
if (!declarationTargets.length) {
|
||||
reportLspError(view, e, true);
|
||||
return;
|
||||
}
|
||||
locs = dedupeLocations(declarationTargets);
|
||||
} else if (isCancelled(e) || !declaration) {
|
||||
reportLspError(view, e, true);
|
||||
return;
|
||||
} else {
|
||||
@@ -542,6 +566,12 @@ async function gotoResolved(
|
||||
return;
|
||||
}
|
||||
if (superseded()) return;
|
||||
// Outside `gotoAfterEdits`, whose retries would repeat the extra request.
|
||||
if (!locs.length && kind === "implementation" && !serverDown) {
|
||||
const declarationTargets = await implementationFallbackTargets(view, offset, doc.path, pos);
|
||||
if (superseded()) return;
|
||||
locs = dedupeLocations(declarationTargets);
|
||||
}
|
||||
if (!locs.length) {
|
||||
// The server has no definition here: a link (`href`, `#include`, Markdown) or a file path.
|
||||
if (
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import type { commands, Location } from "@/platform/ipc";
|
||||
|
||||
const { lspGoto, lspGotoImplementation } = vi.hoisted(() => ({
|
||||
lspGoto: vi.fn<typeof commands.lspGoto>(),
|
||||
lspGotoImplementation: vi.fn<typeof commands.lspGotoImplementation>(),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
const real = await orig<typeof import("@/platform/ipc")>();
|
||||
const fsReadText: typeof commands.fsReadText = async () => ({
|
||||
status: "error",
|
||||
error: { kind: "notFound", message: "not found" },
|
||||
});
|
||||
const navInheritance: typeof commands.navInheritance = async () => ({ status: "ok", data: [] });
|
||||
return {
|
||||
...real,
|
||||
isTauri: () => true,
|
||||
commands: { ...real.commands, lspGoto, lspGotoImplementation, fsReadText, navInheritance },
|
||||
};
|
||||
});
|
||||
vi.mock("@tauri-apps/api/core", async (orig) => ({
|
||||
...(await orig<object>()),
|
||||
Channel: class {
|
||||
onmessage = () => {};
|
||||
},
|
||||
}));
|
||||
|
||||
const { gotoTargets } = await import("./navigation");
|
||||
const { lspDoc } = await import("./lsp");
|
||||
const { closePopup } = await import("./popupStore");
|
||||
const { invalidateConfigurationNavigation } = await import("./configurationNavigation");
|
||||
const { provideEditorService } = await import("@/workbench/contributions");
|
||||
const openFile = vi.fn(async (_path: string, _opts: unknown) => {});
|
||||
provideEditorService({ openFile } as never);
|
||||
|
||||
const loc = (path: string, line = 1, col = 2): Location => ({
|
||||
path,
|
||||
uri: null,
|
||||
range: { start: { line, col }, end: { line, col: col + 3 } },
|
||||
});
|
||||
const ok = (data: Location[]) => ({ status: "ok" as const, data });
|
||||
const declared = loc("/p/store.go");
|
||||
const implementation = loc("/p/iface.go");
|
||||
|
||||
const TEXT = "package p\n\nfunc (s *Store) Search() {}\n";
|
||||
const editor = (text: string, language: string, path: string) =>
|
||||
new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: text,
|
||||
extensions: [lspDoc.of({ doc: 1, path, language, uiMode: language, readOnly: false })],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
|
||||
let view: EditorView;
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
invalidateConfigurationNavigation();
|
||||
lspGoto.mockResolvedValue(ok([]));
|
||||
lspGotoImplementation.mockResolvedValue(ok([]));
|
||||
view = editor(TEXT, "go", "/p/store.go");
|
||||
});
|
||||
afterEach(() => {
|
||||
view.destroy();
|
||||
closePopup();
|
||||
document.body.replaceChildren();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
/** Go to Implementation on `Search`, at the method's name. */
|
||||
const gotoSearch = () => gotoTargets(view, "implementation", TEXT.indexOf("Search") + 2);
|
||||
|
||||
describe("Go to Implementation on a symbol nothing implements", () => {
|
||||
it("navigates to the declaration, like IDEA", async () => {
|
||||
lspGoto.mockResolvedValue(ok([declared]));
|
||||
await gotoSearch();
|
||||
expect(openFile.mock.calls.map(([path]) => path)).toEqual(["/p/store.go"]);
|
||||
expect(lspGotoImplementation).toHaveBeenCalledOnce();
|
||||
expect(lspGoto.mock.calls.map(([, , kind]) => kind)).toEqual(["definition"]);
|
||||
});
|
||||
|
||||
it("navigates when the server reports its failed search as an error", async () => {
|
||||
lspGotoImplementation.mockResolvedValue({
|
||||
status: "error",
|
||||
error: { kind: "protocol", message: "no interfaces implemented by this method" },
|
||||
});
|
||||
lspGoto.mockResolvedValue(ok([declared]));
|
||||
await gotoSearch();
|
||||
expect(openFile.mock.calls.map(([path]) => path)).toEqual(["/p/store.go"]);
|
||||
});
|
||||
|
||||
it("still navigates to the implementations when there are some", async () => {
|
||||
lspGotoImplementation.mockResolvedValue(ok([implementation]));
|
||||
await gotoSearch();
|
||||
expect(openFile.mock.calls.map(([path]) => path)).toEqual(["/p/iface.go"]);
|
||||
expect(lspGoto).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not navigate onto the declaration the caret is already on", async () => {
|
||||
const at = TEXT.indexOf("Search");
|
||||
const col = at - (TEXT.lastIndexOf("\n", at) + 1);
|
||||
lspGoto.mockResolvedValue(
|
||||
ok([{ ...declared, range: { start: { line: 2, col }, end: { line: 2, col: col + 6 } } }]),
|
||||
);
|
||||
await gotoSearch();
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("No implementations found");
|
||||
});
|
||||
|
||||
it("keeps the not-found hint when the declaration request fails", async () => {
|
||||
lspGoto.mockRejectedValue(new Error("timeout"));
|
||||
await gotoSearch();
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("No implementations found");
|
||||
});
|
||||
|
||||
it("ignores the caret's own declaration among several targets", async () => {
|
||||
const at = TEXT.indexOf("Search");
|
||||
const col = at - (TEXT.lastIndexOf("\n", at) + 1);
|
||||
const self = { ...declared, range: { start: { line: 2, col }, end: { line: 2, col: col + 6 } } };
|
||||
lspGoto.mockResolvedValue(ok([self, loc("/p/other.go")]));
|
||||
await gotoSearch();
|
||||
expect(openFile.mock.calls.map(([path]) => path)).toEqual(["/p/other.go"]);
|
||||
});
|
||||
|
||||
it("keeps an unavailable server's error instead of inventing a target", async () => {
|
||||
lspGotoImplementation.mockResolvedValue({
|
||||
status: "error",
|
||||
error: { kind: "unavailable", message: "no implementation provider" },
|
||||
});
|
||||
lspGoto.mockResolvedValue(ok([declared]));
|
||||
await gotoSearch();
|
||||
expect(lspGoto).not.toHaveBeenCalled();
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
expect(document.querySelector(".cm-lsp-hint")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("navigates to a type's declaration from a usage", async () => {
|
||||
const text = "package p\n\nvar s Store\n";
|
||||
view.destroy();
|
||||
view = editor(text, "go", "/p/store.go");
|
||||
lspGoto.mockResolvedValue(ok([loc("/p/store.go", 0, 5)]));
|
||||
await gotoTargets(view, "implementation", text.indexOf("Store") + 2);
|
||||
expect(openFile).toHaveBeenCalledWith("/p/store.go", { selection: { line: 0, col: 5 }, focus: true });
|
||||
});
|
||||
|
||||
it("covers Python, whose servers have no type hierarchy", async () => {
|
||||
const text = "class Order:\n pass\n\nuse = Order\n";
|
||||
view.destroy();
|
||||
view = editor(text, "python", "/p/order.py");
|
||||
lspGoto.mockResolvedValue(ok([loc("/p/order.py", 0, 6)]));
|
||||
await gotoTargets(view, "implementation", text.lastIndexOf("Order") + 2);
|
||||
expect(openFile).toHaveBeenCalledWith("/p/order.py", { selection: { line: 0, col: 6 }, focus: true });
|
||||
});
|
||||
});
|
||||
@@ -300,13 +300,14 @@ describe("mouse navigation", () => {
|
||||
expect(lspGoto).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports missing implementations without navigating to the declaration", async () => {
|
||||
it("asks for the declaration before reporting missing implementations", async () => {
|
||||
lspGoto.mockResolvedValue({ status: "ok", data: [] });
|
||||
click({ metaKey: true, altKey: true });
|
||||
await vi.waitFor(() =>
|
||||
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("No implementations found"),
|
||||
);
|
||||
expect(lspGoto).toHaveBeenCalledExactlyOnceWith(1, { line: 0, col: 9 }, "implementation");
|
||||
// IDEA falls back to the declaration when nothing implements the name.
|
||||
expect(lspGoto.mock.calls.map(([, , kind]) => kind)).toEqual(["implementation", "definition"]);
|
||||
expect(openFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
@@ -229,7 +229,12 @@ export const lspTheme = EditorView.theme({
|
||||
// shrink and scroll inside the popup instead of running past its border.
|
||||
".cm-tooltip.cm-tooltip-hover": { ...tooltipSurface, display: "flex", flexDirection: "column" },
|
||||
".cm-tooltip-hover > .cm-tooltip-section": { minHeight: 0, flexShrink: 1 },
|
||||
".cm-lsp-hover": { maxWidth: "580px", maxHeight: "380px", overflow: "auto", padding: "10px 14px" },
|
||||
".cm-lsp-hover": {
|
||||
maxWidth: "min(580px, var(--cm-diagnostic-hover-width, 580px))",
|
||||
maxHeight: "380px",
|
||||
overflow: "auto",
|
||||
padding: "10px 14px",
|
||||
},
|
||||
// With documentation the doc view pads its own body and keeps its toolbar at the bottom.
|
||||
".cm-lsp-hover.cm-lsp-hover-doc": { padding: "0" },
|
||||
".cm-lsp-hover-doc > .cm-lsp-hover-diagnostics": {
|
||||
@@ -237,39 +242,57 @@ export const lspTheme = EditorView.theme({
|
||||
borderBottom: "1px solid var(--border-popup)",
|
||||
},
|
||||
".cm-lsp-diag": {
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
display: "grid",
|
||||
gridTemplateColumns: "16px minmax(0, 1fr)",
|
||||
columnGap: "var(--space-2)",
|
||||
rowGap: "var(--space-1)",
|
||||
fontFamily: "var(--font-ui)",
|
||||
fontSize: "var(--fs-ui)",
|
||||
paddingLeft: "22px",
|
||||
position: "relative",
|
||||
lineHeight: "1.4",
|
||||
},
|
||||
".cm-lsp-diag-icon": { display: "inline-flex", marginTop: "1px", alignSelf: "start" },
|
||||
".cm-lsp-diag + .cm-lsp-diag": {
|
||||
marginTop: "var(--space-2)",
|
||||
paddingTop: "var(--space-2)",
|
||||
borderTop: "1px solid var(--border-popup)",
|
||||
},
|
||||
".cm-lsp-diag-icon": { position: "absolute", left: "0", top: "1px", display: "inline-flex" },
|
||||
".cm-lsp-diag + .cm-lsp-diag": { marginTop: "8px" },
|
||||
".cm-lsp-diag-error .cm-lsp-diag-icon": { color: "var(--danger)" },
|
||||
".cm-lsp-diag-warning .cm-lsp-diag-icon": { color: "var(--warning)" },
|
||||
".cm-lsp-diag-info .cm-lsp-diag-icon, .cm-lsp-diag-hint .cm-lsp-diag-icon": { color: "var(--info)" },
|
||||
".cm-lsp-diag-message": { color: "var(--fg-strong)", whiteSpace: "pre-wrap", lineHeight: "18px" },
|
||||
".cm-lsp-diag-meta": {
|
||||
".cm-lsp-diag-message": { color: "var(--fg-strong)", whiteSpace: "pre-wrap", overflowWrap: "anywhere" },
|
||||
".cm-lsp-diag-actions": {
|
||||
gridColumn: "2",
|
||||
display: "flex",
|
||||
flexWrap: "wrap",
|
||||
columnGap: "12px",
|
||||
rowGap: "2px",
|
||||
marginTop: "6px",
|
||||
columnGap: "var(--space-3)",
|
||||
rowGap: "var(--space-0-5)",
|
||||
alignItems: "baseline",
|
||||
},
|
||||
".cm-lsp-diag-meta > *": { whiteSpace: "nowrap" },
|
||||
".cm-lsp-diag-source": { color: "var(--fg-subtle)", fontSize: "var(--fs-small)" },
|
||||
".cm-lsp-diag-source": {
|
||||
gridColumn: "2",
|
||||
color: "var(--fg-subtle)",
|
||||
fontSize: "var(--fs-small)",
|
||||
overflowWrap: "anywhere",
|
||||
},
|
||||
".cm-lsp-link-button": {
|
||||
display: "inline-flex",
|
||||
flexWrap: "wrap",
|
||||
alignItems: "baseline",
|
||||
columnGap: "var(--space-1)",
|
||||
minWidth: 0,
|
||||
maxWidth: "100%",
|
||||
border: "none",
|
||||
background: "none",
|
||||
padding: "0",
|
||||
font: "inherit",
|
||||
fontSize: "var(--fs-ui)",
|
||||
color: "var(--link)",
|
||||
cursor: "pointer",
|
||||
textAlign: "left",
|
||||
whiteSpace: "normal",
|
||||
},
|
||||
".cm-lsp-link-button:hover": { color: "var(--link-hover)", textDecoration: "underline" },
|
||||
".cm-lsp-diag-action-label": { minWidth: 0, overflowWrap: "anywhere" },
|
||||
".cm-lsp-diag-shortcut": { color: "var(--fg-subtle)", fontSize: "var(--fs-small)", whiteSpace: "nowrap" },
|
||||
".cm-lsp-link-button:hover .cm-lsp-diag-action-label": { color: "var(--link-hover)", textDecoration: "underline" },
|
||||
".cm-tooltip.cm-lsp-signature": {
|
||||
fontFamily: "var(--openidea-editor-font, var(--font-mono))",
|
||||
fontWeight: "var(--fw-code, 400)",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ComponentType } from "react";
|
||||
import { activate as editor } from "./editor/core";
|
||||
import { activate as agents } from "./features/agents";
|
||||
import { activateEditorWindow, EditorWindow } from "./editor/core/EditorWindow";
|
||||
import { installLocaleSync } from "./features/app/locale";
|
||||
import { installMenuBridge } from "./features/app/menuBridge";
|
||||
@@ -8,8 +9,8 @@ import { installKeyboardDispatcher } from "./platform/keymap";
|
||||
import { activateList } from "./windowBoot";
|
||||
|
||||
/**
|
||||
* Lightweight editor window of project window `parent`: one file, sharing the
|
||||
* parent's documents and language servers, with no workbench chrome.
|
||||
* Lightweight editor window of project window `parent`: one file or agent conversation, sharing
|
||||
* the parent's documents, language servers and agents, with no workbench chrome.
|
||||
*/
|
||||
export function bootEditorWindow(parent: string): ComponentType {
|
||||
activateList("editor window", [
|
||||
@@ -17,6 +18,7 @@ export function bootEditorWindow(parent: string): ComponentType {
|
||||
["settings", trackRuntimeSettings],
|
||||
["menu", installMenuBridge],
|
||||
["editor", editor],
|
||||
["agents", agents],
|
||||
["editorWindow", () => activateEditorWindow(parent)],
|
||||
]);
|
||||
installKeyboardDispatcher();
|
||||
|
||||
@@ -42,11 +42,14 @@ import {
|
||||
refreshProviders,
|
||||
refreshTaskModels,
|
||||
releaseClosedTaskCache,
|
||||
trackPromptHistory,
|
||||
useAgents,
|
||||
} from "./store";
|
||||
import { TaskStatusMark } from "./TaskStatusMark";
|
||||
import { taskActions, useAgentsHeaderMenu } from "./taskActions";
|
||||
import { replyActions } from "./replyActions";
|
||||
import { activateTaskWindows, moveTaskToWindow, prepareTaskWindowInput, taskTabClosed } from "./taskWindows";
|
||||
import { auxiliaryWindow } from "@/platform/auxWindow";
|
||||
|
||||
export { activateSettingsPages } from "./settingsPages";
|
||||
|
||||
@@ -62,6 +65,9 @@ function trackAgentButtonSetting(): () => void {
|
||||
};
|
||||
}
|
||||
|
||||
/** A lightweight editor window has agents only once it shows a conversation. */
|
||||
const agentsHere = () => !auxiliaryWindow() || useAgents.getState().loaded;
|
||||
|
||||
export function activate(): () => void {
|
||||
const sync = (root: string | null | undefined) => {
|
||||
disconnect();
|
||||
@@ -69,6 +75,8 @@ export function activate(): () => void {
|
||||
};
|
||||
sync(useProject.getState().project?.root);
|
||||
const disposers = [
|
||||
activateTaskWindows(),
|
||||
trackPromptHistory(),
|
||||
activateSettingsPages(),
|
||||
trackEditorCopies(),
|
||||
registerAgentContextSource({
|
||||
@@ -143,10 +151,16 @@ export function activate(): () => void {
|
||||
// Tabs of tasks deleted meanwhile are closed when the tasks load (`connect`).
|
||||
restorable: true,
|
||||
onTabClose: (tabId) => clearAgentTabFontZoom(tabId),
|
||||
prepareWindowInput: prepareTaskWindowInput,
|
||||
onClose: (input) => {
|
||||
const task = (input.data as { task?: string } | undefined)?.task;
|
||||
if (task) releaseClosedTaskCache(task);
|
||||
if (!task) return;
|
||||
releaseClosedTaskCache(task);
|
||||
taskTabClosed(task);
|
||||
},
|
||||
...(auxiliaryWindow()
|
||||
? {}
|
||||
: { openInWindow: (input) => moveTaskToWindow((input.data as { task: string }).task) }),
|
||||
// Rebuilding a long conversation on every switch back is slow.
|
||||
keepAlive: true,
|
||||
}),
|
||||
@@ -182,7 +196,7 @@ export function activate(): () => void {
|
||||
menus: ["editor", "projectView"],
|
||||
order: 80,
|
||||
items: (menu, { paths, dirs }) =>
|
||||
paths.length && !paths.some(isVirtualUri)
|
||||
paths.length && !paths.some(isVirtualUri) && agentsHere()
|
||||
? [
|
||||
{
|
||||
kind: "action",
|
||||
@@ -193,6 +207,27 @@ export function activate(): () => void {
|
||||
: [],
|
||||
}),
|
||||
registerActions([
|
||||
{
|
||||
id: "agents.moveToNewWindow",
|
||||
title: "Open in New Window",
|
||||
category: "Agents",
|
||||
when: "projectOpen",
|
||||
enabled: ({ arg }) =>
|
||||
!auxiliaryWindow() &&
|
||||
(typeof arg === "string" ||
|
||||
maybeEditorService()?.activeInput?.()?.kind === SESSION_KIND ||
|
||||
!!useAgents.getState().docked),
|
||||
run: async ({ arg }) => {
|
||||
const input = maybeEditorService()?.activeInput?.();
|
||||
const task =
|
||||
typeof arg === "string"
|
||||
? arg
|
||||
: input?.kind === SESSION_KIND
|
||||
? (input.data as { task: string }).task
|
||||
: useAgents.getState().docked;
|
||||
if (task) await moveTaskToWindow(task);
|
||||
},
|
||||
},
|
||||
...taskActions,
|
||||
...replyActions,
|
||||
{
|
||||
@@ -303,6 +338,7 @@ export function activate(): () => void {
|
||||
icon: "toolwindow-agents",
|
||||
when: "projectOpen",
|
||||
keywords: ["agent", "chat", "context", "reference", "selection"],
|
||||
enabled: agentsHere,
|
||||
run: ({ arg }) => {
|
||||
if (Array.isArray(arg)) sendPaths(arg.filter((p): p is string => typeof p === "string"));
|
||||
else sendSelection();
|
||||
|
||||
@@ -4,6 +4,9 @@ import type { AgentTask, ProjectInfo } from "@/bindings";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { sendPaths, sendSelection } from "./references";
|
||||
import { HOME, composerDraft, useAgents } from "./store";
|
||||
import { installTaskWindowRouting } from "./taskWindowRouting";
|
||||
import type { ComposerDraft } from "./composerModel";
|
||||
import { diagnoseTestFailure } from "./testFailure";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ notify: vi.fn(), editor: null as unknown }));
|
||||
vi.mock("@/editor/api", async (original) => ({
|
||||
@@ -51,6 +54,32 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
describe("Send to Agent from the Project view", () => {
|
||||
it("appends references and failed-test context to the draft being edited in another window", () => {
|
||||
setup({ task: task(BACK, BACK, "local") });
|
||||
useAgents.setState({ composers: new Map([["t", { text: "Stale parent draft", files: [], images: [] }]]) });
|
||||
let remote: ComposerDraft = { text: "Typed in the child", files: [], images: [] };
|
||||
const update = vi.fn((key: string, patch: Partial<ComposerDraft>) => {
|
||||
if (key !== "t") return false;
|
||||
remote = { ...remote, ...patch };
|
||||
return true;
|
||||
});
|
||||
const stop = installTaskWindowRouting(() => true, undefined, {
|
||||
read: (key) => (key === "t" ? remote : undefined),
|
||||
update,
|
||||
});
|
||||
try {
|
||||
expect(sendPaths([`${BACK}/pom.xml`])).toBe(true);
|
||||
expect(remote.text).toBe("Typed in the child @pom.xml ");
|
||||
expect(remote.files).toEqual([{ path: `${BACK}/pom.xml`, rel: "pom.xml" }]);
|
||||
diagnoseTestFailure({ name: "example", output: ["Expected success"] });
|
||||
expect(remote.text).toContain("Typed in the child @pom.xml\n\nThe test example failed.");
|
||||
expect(update).toHaveBeenCalledTimes(2);
|
||||
expect(useAgents.getState().composers.get("t")?.text).toBe("Stale parent draft");
|
||||
} finally {
|
||||
stop();
|
||||
}
|
||||
});
|
||||
|
||||
it("single project: files and folders as before", () => {
|
||||
setup({});
|
||||
expect(sendPaths([`${BACK}/pom.xml`, `${BACK}/src/`])).toBe(true);
|
||||
|
||||
@@ -22,6 +22,8 @@ import type {
|
||||
RequestId,
|
||||
} from "@/bindings";
|
||||
import { useChangesOptions } from "./changesOptions";
|
||||
import { auxiliaryWindow, windowLabel } from "@/platform/auxWindow";
|
||||
import { routeToWindow, taskWindowDraft, taskWindowFocused, updateTaskWindowDraft } from "./taskWindowRouting";
|
||||
import { clearAgentTaskFontZoom, resetAllAgentFontZoom } from "./fontZoom";
|
||||
import { clearDismissedAssets } from "./sessionAssetsModel";
|
||||
import { basename, useProject } from "@/platform/project";
|
||||
@@ -321,9 +323,14 @@ export function setDraftOption(id: string, value: string) {
|
||||
}
|
||||
}
|
||||
|
||||
export const composerDraft = (key: string) => useAgents.getState().composers.get(key) ?? emptyDraft();
|
||||
export const composerDraft = (key: string) =>
|
||||
taskWindowDraft(key) ?? useAgents.getState().composers.get(key) ?? emptyDraft();
|
||||
|
||||
export function updateComposer(key: string, patch: Partial<ComposerDraft>) {
|
||||
if (updateTaskWindowDraft(key, patch)) {
|
||||
useAgents.setState({ lastComposer: key });
|
||||
return;
|
||||
}
|
||||
useAgents.setState((s) => ({
|
||||
composers: new Map(s.composers).set(key, {
|
||||
...(s.composers.get(key) ?? emptyDraft()),
|
||||
@@ -345,7 +352,7 @@ function clearSubmittedComposer(key: string, submitted: ComposerDraft, started:
|
||||
/** Session tabs on screen; a task can be shown in more than one split. */
|
||||
const visible = new Map<string, number>();
|
||||
const windowFocused = () => document.visibilityState !== "hidden" && document.hasFocus();
|
||||
const viewing = (task: string) => visible.has(task) && windowFocused();
|
||||
const viewing = (task: string) => (visible.has(task) && windowFocused()) || taskWindowFocused(task);
|
||||
|
||||
function setUnread(task: string, value: boolean) {
|
||||
const s = useAgents.getState();
|
||||
@@ -527,7 +534,7 @@ export async function connect(): Promise<void> {
|
||||
let tasks: AgentTask[], providers: AgentProvider[];
|
||||
try {
|
||||
[tasks, providers] = await Promise.all([
|
||||
call(commands.agentSubscribe(channel)),
|
||||
call(commands.agentSubscribe(channel, windowLabel())),
|
||||
useProject.getState().project?.trusted === false
|
||||
? Promise.resolve([] as AgentProvider[])
|
||||
: call(commands.agentProviders()),
|
||||
@@ -778,7 +785,8 @@ function onEvent(e: AgentEvent) {
|
||||
unread.delete(e.id);
|
||||
// A deleted task leaves its group and the pinned area.
|
||||
const organize = pruneOrganize(s.organize, tasks.values());
|
||||
if (organize !== s.organize) saveOrganize(s.organizeRoot, organize);
|
||||
// The project window saves it: a lightweight window's copy may be older.
|
||||
if (organize !== s.organize && !auxiliaryWindow()) saveOrganize(s.organizeRoot, organize);
|
||||
useAgents.setState({
|
||||
tasks,
|
||||
composers,
|
||||
@@ -845,6 +853,8 @@ function onEvent(e: AgentEvent) {
|
||||
|
||||
/** In-app balloon for an Attention event; OS delivery goes through the general balloon path. */
|
||||
function notifyAttention(taskId: string, reason: "finished" | "input" | "failed") {
|
||||
// The project window remains responsible for task notifications.
|
||||
if (auxiliaryWindow()) return;
|
||||
if (viewing(taskId) || quietTasks.has(taskId)) return;
|
||||
const task = useAgents.getState().tasks.get(taskId);
|
||||
const title = task?.title ?? "Agent";
|
||||
@@ -1047,6 +1057,7 @@ export function useAgentCommands(
|
||||
}
|
||||
|
||||
export function openTask(task: string) {
|
||||
if (routeToWindow(task)) return;
|
||||
forgetClosed(task);
|
||||
if (useAgents.getState().sessionLocation === "toolWindow") {
|
||||
showDockedTask(task);
|
||||
@@ -1150,6 +1161,7 @@ export async function closeAndNewTask() {
|
||||
|
||||
/** Opens the New Task page; `prompt` pre-fills it. */
|
||||
export function openHome(prompt?: string) {
|
||||
if (routeToWindow(null, prompt)) return;
|
||||
const project = useProject.getState().project;
|
||||
useAgents.setState({ lastComposer: HOME });
|
||||
if (project?.workspace) {
|
||||
@@ -1360,6 +1372,15 @@ function remember(text: string) {
|
||||
save(HISTORY_KEY, history);
|
||||
}
|
||||
|
||||
/** Prompts sent from the project's other windows join this window's history. */
|
||||
export function trackPromptHistory(): () => void {
|
||||
const onStorage = (e: StorageEvent) => {
|
||||
if (e.key === HISTORY_KEY) useAgents.setState({ history: load<string[]>(HISTORY_KEY, []) });
|
||||
};
|
||||
window.addEventListener("storage", onStorage);
|
||||
return () => window.removeEventListener("storage", onStorage);
|
||||
}
|
||||
|
||||
/** The `!` commands running per task, so Stop ends them. */
|
||||
const shellRuns = new Map<string, Set<RequestId>>();
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { AgentTask } from "@/bindings";
|
||||
import type { Action } from "@/platform/actions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { auxiliaryWindow } from "@/platform/auxWindow";
|
||||
import { useProject } from "@/platform/project";
|
||||
import type { MenuItem } from "@/ui";
|
||||
import { confirm, showError, confirmChecked } from "@/workbench/messages";
|
||||
@@ -396,6 +397,9 @@ export function taskMenu(tasks: AgentTask[]): MenuItem[] {
|
||||
...(!multiple
|
||||
? ([
|
||||
{ kind: "action", action: "agents.renameTask", label: "Rename…", icon: "edit", arg: task.id },
|
||||
...(!auxiliaryWindow()
|
||||
? ([{ kind: "action", action: "agents.moveToNewWindow", arg: task.id }] satisfies MenuItem[])
|
||||
: []),
|
||||
...(hasTaskTerminal(task, projectRoot)
|
||||
? ([
|
||||
{ kind: "action", action: "terminal.openAt", label: "Terminal", icon: "terminal", arg: task.cwd },
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
/** A task has one interactive conversation view, even when that view lives in another window. */
|
||||
import type { ComposerDraft } from "./composerModel";
|
||||
|
||||
type Route = (task: string | null, prompt?: string) => boolean;
|
||||
type Drafts = {
|
||||
read(task: string): ComposerDraft | undefined;
|
||||
update(task: string, patch: Partial<ComposerDraft>): boolean;
|
||||
};
|
||||
let route: Route | undefined;
|
||||
let focused: ((task: string) => boolean) | undefined;
|
||||
let drafts: Drafts | undefined;
|
||||
|
||||
export function installTaskWindowRouting(
|
||||
open: Route,
|
||||
isFocused?: (task: string) => boolean,
|
||||
composers?: Drafts,
|
||||
): () => void {
|
||||
route = open;
|
||||
focused = isFocused;
|
||||
drafts = composers;
|
||||
return () => {
|
||||
if (route === open) {
|
||||
route = undefined;
|
||||
focused = undefined;
|
||||
drafts = undefined;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export const taskWindowFocused = (task: string): boolean => focused?.(task) ?? false;
|
||||
|
||||
/** Whether another window shows `task` (New Task when null) instead of this one. */
|
||||
export const routeToWindow: Route = (task, prompt) => route?.(task, prompt) ?? false;
|
||||
export const taskWindowDraft = (task: string) => drafts?.read(task);
|
||||
export const updateTaskWindowDraft = (task: string, patch: Partial<ComposerDraft>) =>
|
||||
drafts?.update(task, patch) ?? false;
|
||||
@@ -0,0 +1,396 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { editorService, type EditorInput, type EditorService } from "@/workbench/contributions";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import {
|
||||
activateTaskWindows,
|
||||
moveTaskToWindow,
|
||||
prepareTaskWindowInput,
|
||||
TASK_WINDOW,
|
||||
type TaskWindowMessage,
|
||||
} from "./taskWindows";
|
||||
import { routeToWindow, taskWindowDraft, taskWindowFocused, updateTaskWindowDraft } from "./taskWindowRouting";
|
||||
|
||||
const CHILD = "editor-main-3";
|
||||
const backend = vi.hoisted(() => ({
|
||||
label: "main",
|
||||
serviceOverride: undefined as EditorService | undefined,
|
||||
subscribers: new Set<() => void>(),
|
||||
receive: undefined as ((event: { payload: unknown }) => void) | undefined,
|
||||
destroyed: undefined as (() => void) | undefined,
|
||||
focusChanged: undefined as ((event: { payload: boolean }) => void) | undefined,
|
||||
activeInput: undefined as ((input: EditorInput) => void) | undefined,
|
||||
draft: { text: "Unsent draft", files: [{ path: "/project/a.ts", rel: "a.ts" }], images: [] },
|
||||
state: {
|
||||
loaded: true,
|
||||
error: null as string | null,
|
||||
entries: new Map<string, unknown[]>([["running-task", []]]),
|
||||
entryLoads: new Map<string, { error: string | null }>(),
|
||||
composers: new Map(),
|
||||
tasks: new Map([["running-task", { status: "running", title: "Fix the build" }]]),
|
||||
docked: null as string | null,
|
||||
unread: new Set<string>(),
|
||||
},
|
||||
emit: vi.fn(async () => {}),
|
||||
openInWindow: vi.fn(async (_input: EditorInput) => "editor-main-3"),
|
||||
openInput: vi.fn(async (_input: EditorInput, _options?: unknown) => {}),
|
||||
openFile: vi.fn(async (_path: string, _options?: unknown) => {}),
|
||||
unsubscribe: vi.fn(async () => ({ status: "ok", data: null })),
|
||||
focus: vi.fn(async () => {}),
|
||||
closeInput: vi.fn(async () => true),
|
||||
openTask: vi.fn(),
|
||||
openHome: vi.fn(),
|
||||
updateComposer: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
loadEntries: vi.fn(async () => {}),
|
||||
}));
|
||||
|
||||
vi.mock("@tauri-apps/api/event", () => ({
|
||||
TauriEvent: { WINDOW_DESTROYED: "destroyed" },
|
||||
emitTo: backend.emit,
|
||||
}));
|
||||
vi.mock("@tauri-apps/api/window", () => ({
|
||||
getCurrentWindow: () => ({
|
||||
label: backend.label,
|
||||
listen: async (_event: string, receive: typeof backend.receive) => {
|
||||
backend.receive = receive;
|
||||
return () => {
|
||||
backend.receive = undefined;
|
||||
};
|
||||
},
|
||||
}),
|
||||
getAllWindows: async () => [{ label: "main" }, { label: "settings-main" }, { label: "editor-main-3" }],
|
||||
Window: {
|
||||
getByLabel: async () => ({
|
||||
unminimize: async () => {},
|
||||
show: async () => {},
|
||||
setFocus: backend.focus,
|
||||
isFocused: async () => false,
|
||||
once: async (_event: string, destroyed: () => void) => {
|
||||
backend.destroyed = destroyed;
|
||||
},
|
||||
onFocusChanged: async (changed: typeof backend.focusChanged) => {
|
||||
backend.focusChanged = changed;
|
||||
return async () => {};
|
||||
},
|
||||
}),
|
||||
},
|
||||
}));
|
||||
vi.mock("@/platform/ipc", () => ({
|
||||
isTauri: () => true,
|
||||
call: async (result: Promise<{ data: unknown }>) => (await result).data,
|
||||
commands: { agentUnsubscribe: backend.unsubscribe },
|
||||
}));
|
||||
vi.mock("@/workbench/contributions", () => ({
|
||||
editorService: () =>
|
||||
backend.serviceOverride ?? {
|
||||
openFile: backend.openFile,
|
||||
openInput: backend.openInput,
|
||||
closeInput: backend.closeInput,
|
||||
openInWindow: backend.openInWindow,
|
||||
onActiveInputChange: (listener: typeof backend.activeInput) => {
|
||||
backend.activeInput = listener;
|
||||
return () => {
|
||||
backend.activeInput = undefined;
|
||||
};
|
||||
},
|
||||
},
|
||||
provideEditorService: (service: EditorService) => {
|
||||
backend.serviceOverride = service;
|
||||
},
|
||||
provideToolWindowService: vi.fn(),
|
||||
notifications: () => ({ notify: backend.notify }),
|
||||
}));
|
||||
vi.mock("./store", () => ({
|
||||
composerDraft: () => backend.draft,
|
||||
updateComposer: backend.updateComposer,
|
||||
loadEntries: backend.loadEntries,
|
||||
openTask: backend.openTask,
|
||||
openHome: backend.openHome,
|
||||
useAgents: {
|
||||
subscribe: (fn: () => void) => {
|
||||
backend.subscribers.add(fn);
|
||||
return () => backend.subscribers.delete(fn);
|
||||
},
|
||||
getState: () => backend.state,
|
||||
setState: (patch: Partial<typeof backend.state>) => Object.assign(backend.state, patch),
|
||||
},
|
||||
}));
|
||||
|
||||
let stop: () => void;
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
backend.label = "main";
|
||||
backend.serviceOverride = undefined;
|
||||
backend.subscribers.clear();
|
||||
backend.state.loaded = true;
|
||||
backend.state.error = null;
|
||||
backend.state.entries = new Map([["running-task", []]]);
|
||||
backend.state.entryLoads = new Map();
|
||||
backend.state.docked = null;
|
||||
backend.state.unread = new Set();
|
||||
backend.destroyed = undefined;
|
||||
backend.focusChanged = undefined;
|
||||
stop = activateTaskWindows();
|
||||
await vi.waitFor(() => expect(backend.receive).toBeDefined());
|
||||
});
|
||||
afterEach(() => {
|
||||
stop();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
const receive = (message: TaskWindowMessage) => backend.receive?.({ payload: message });
|
||||
|
||||
async function detach() {
|
||||
expect(await moveTaskToWindow("running-task")).toBe(true);
|
||||
await vi.waitFor(() => expect(backend.focusChanged).toBeDefined());
|
||||
}
|
||||
|
||||
describe("moving a conversation to a lightweight editor window", () => {
|
||||
it("opens the tab there with the unsent draft, then closes it here", async () => {
|
||||
backend.state.docked = "running-task";
|
||||
await detach();
|
||||
expect(backend.openInWindow).toHaveBeenCalledWith({
|
||||
kind: "agent-session",
|
||||
key: "agent:running-task",
|
||||
data: { task: "running-task", title: "Fix the build" },
|
||||
});
|
||||
expect(backend.closeInput).toHaveBeenCalledWith("agent:running-task");
|
||||
expect(backend.state.docked).toBeNull();
|
||||
expect(backend.state.tasks.has("running-task")).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the conversation here when the window cannot open", async () => {
|
||||
backend.openInWindow.mockRejectedValueOnce(new Error("Timed out opening the editor window"));
|
||||
expect(await moveTaskToWindow("running-task")).toBe(false);
|
||||
expect(backend.closeInput).not.toHaveBeenCalled();
|
||||
expect(routeToWindow("running-task")).toBe(false);
|
||||
expect(backend.notify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ body: "Timed out opening the editor window" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("focuses the window instead of opening a second view", async () => {
|
||||
await detach();
|
||||
expect(routeToWindow("running-task")).toBe(true);
|
||||
await vi.waitFor(() => expect(backend.focus).toHaveBeenCalled());
|
||||
expect(await moveTaskToWindow("running-task")).toBe(true);
|
||||
expect(backend.openInWindow).toHaveBeenCalledOnce();
|
||||
expect(routeToWindow("another-task")).toBe(false);
|
||||
expect(routeToWindow(null)).toBe(false);
|
||||
});
|
||||
|
||||
it("closes a tab of the conversation that Back/Forward reopened here", async () => {
|
||||
await detach();
|
||||
backend.closeInput.mockClear();
|
||||
backend.activeInput?.({ kind: "agent-session", key: "agent:running-task", data: { task: "running-task" } });
|
||||
expect(backend.closeInput).toHaveBeenCalledWith("agent:running-task");
|
||||
});
|
||||
|
||||
it("brings the conversation back with what was typed there when the window closes", async () => {
|
||||
await detach();
|
||||
receive({ type: "draft", task: "running-task", label: CHILD, draft: { text: "Typed over there" } });
|
||||
backend.destroyed?.();
|
||||
expect(backend.updateComposer).toHaveBeenCalledWith("running-task", { ...backend.draft, text: "Typed over there" });
|
||||
expect(backend.openTask).toHaveBeenCalledWith("running-task");
|
||||
expect(backend.unsubscribe).toHaveBeenCalledWith(CHILD);
|
||||
expect(routeToWindow("running-task")).toBe(false);
|
||||
});
|
||||
|
||||
it("brings the conversation back when only its tab closes there", async () => {
|
||||
await detach();
|
||||
receive({ type: "closed", task: "running-task", label: "editor-main-9" });
|
||||
expect(backend.openTask).not.toHaveBeenCalled();
|
||||
receive({ type: "closed", task: "running-task", label: CHILD });
|
||||
expect(backend.openTask).toHaveBeenCalledWith("running-task");
|
||||
expect(backend.unsubscribe).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("counts a conversation in a focused window as read", async () => {
|
||||
await detach();
|
||||
backend.state.unread.add("running-task");
|
||||
backend.focusChanged?.({ payload: true });
|
||||
expect(taskWindowFocused("running-task")).toBe(true);
|
||||
expect(backend.state.unread.has("running-task")).toBe(false);
|
||||
backend.focusChanged?.({ payload: false });
|
||||
expect(taskWindowFocused("running-task")).toBe(false);
|
||||
});
|
||||
|
||||
it("finds its windows again after a reload", async () => {
|
||||
expect(backend.emit).toHaveBeenCalledWith(CHILD, TASK_WINDOW, { type: "sync" });
|
||||
expect(backend.emit).toHaveBeenCalledOnce();
|
||||
receive({ type: "draft", task: "running-task", label: "editor-project-2-1", draft: backend.draft });
|
||||
expect(routeToWindow("running-task")).toBe(false);
|
||||
receive({ type: "draft", task: "running-task", label: CHILD, draft: backend.draft });
|
||||
expect(routeToWindow("running-task")).toBe(true);
|
||||
expect(backend.closeInput).toHaveBeenCalledWith("agent:running-task");
|
||||
expect(backend.openInWindow).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows what a lightweight window asks for", () => {
|
||||
receive({ type: "open", task: "another-task" });
|
||||
expect(backend.openTask).toHaveBeenCalledWith("another-task");
|
||||
receive({ type: "open", task: null, prompt: "Review this" });
|
||||
expect(backend.openHome).toHaveBeenCalledWith("Review this");
|
||||
});
|
||||
|
||||
it("returns the latest mirrored draft to a reloading child", async () => {
|
||||
await detach();
|
||||
receive({ type: "draft", task: "running-task", label: CHILD, draft: { text: "Latest draft" } });
|
||||
receive({ type: "requestDraft", task: "running-task", label: CHILD });
|
||||
expect(backend.emit).toHaveBeenLastCalledWith(CHILD, TASK_WINDOW, {
|
||||
type: "draftSnapshot",
|
||||
task: "running-task",
|
||||
draft: { ...backend.draft, text: "Latest draft" },
|
||||
});
|
||||
});
|
||||
|
||||
it("routes edits made in the project to the latest draft in its child", async () => {
|
||||
await detach();
|
||||
receive({ type: "draft", task: "running-task", label: CHILD, draft: { text: "Typed there" } });
|
||||
expect(taskWindowDraft("running-task")?.text).toBe("Typed there");
|
||||
expect(updateTaskWindowDraft("running-task", { text: "Typed there @a.ts" })).toBe(true);
|
||||
expect(backend.emit).toHaveBeenLastCalledWith(CHILD, TASK_WINDOW, {
|
||||
type: "draftSnapshot",
|
||||
task: "running-task",
|
||||
draft: { ...backend.draft, text: "Typed there @a.ts" },
|
||||
});
|
||||
expect(updateTaskWindowDraft("another-task", { text: "Local draft" })).toBe(false);
|
||||
});
|
||||
|
||||
it("does not hide the original view before the child reports success", async () => {
|
||||
let finish!: (label: string) => void;
|
||||
backend.openInWindow.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
finish = resolve;
|
||||
}),
|
||||
);
|
||||
const moving = moveTaskToWindow("running-task");
|
||||
receive({ type: "draft", task: "running-task", label: CHILD, draft: { text: "Already typed there" } });
|
||||
expect(backend.closeInput).not.toHaveBeenCalled();
|
||||
finish(CHILD);
|
||||
expect(await moving).toBe(true);
|
||||
await vi.waitFor(() => expect(backend.destroyed).toBeDefined());
|
||||
backend.destroyed?.();
|
||||
expect(backend.updateComposer).toHaveBeenCalledWith("running-task", {
|
||||
...backend.draft,
|
||||
text: "Already typed there",
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores late draft events from a window that failed to open", async () => {
|
||||
backend.openInWindow.mockRejectedValueOnce(new Error("Cannot load task"));
|
||||
expect(await moveTaskToWindow("running-task")).toBe(false);
|
||||
receive({ type: "draft", task: "running-task", label: "editor-main-99", draft: backend.draft });
|
||||
expect(backend.closeInput).not.toHaveBeenCalled();
|
||||
expect(routeToWindow("running-task")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("preparing the child's conversation", () => {
|
||||
const input: EditorInput = {
|
||||
kind: "agent-session",
|
||||
key: "agent:running-task",
|
||||
data: { task: "running-task", draft: { text: "Old launch draft" } },
|
||||
};
|
||||
async function child() {
|
||||
stop();
|
||||
await Promise.resolve();
|
||||
backend.label = CHILD;
|
||||
}
|
||||
async function reply() {
|
||||
await vi.waitFor(() =>
|
||||
expect(backend.emit).toHaveBeenCalledWith("main", TASK_WINDOW, {
|
||||
type: "requestDraft",
|
||||
task: "running-task",
|
||||
label: CHILD,
|
||||
}),
|
||||
);
|
||||
receive({ type: "draftSnapshot", task: "running-task", draft: { ...backend.draft, text: "Latest draft" } });
|
||||
}
|
||||
|
||||
it("waits for the task and uses the current draft instead of launch data", async () => {
|
||||
await child();
|
||||
backend.state.loaded = false;
|
||||
backend.emit.mockClear();
|
||||
const pending = prepareTaskWindowInput(input);
|
||||
expect(backend.emit).not.toHaveBeenCalled();
|
||||
backend.state.loaded = true;
|
||||
backend.subscribers.forEach((fn) => fn());
|
||||
await reply();
|
||||
expect(await pending).toEqual({
|
||||
...input,
|
||||
data: { task: "running-task", draft: { ...backend.draft, text: "Latest draft" } },
|
||||
});
|
||||
expect(backend.subscribers.size).toBe(0);
|
||||
});
|
||||
|
||||
it("routes files, diffs and workbench actions to the project while keeping its conversation here", async () => {
|
||||
await child();
|
||||
stop = activateTaskWindows();
|
||||
backend.activeInput?.(input);
|
||||
backend.emit.mockClear();
|
||||
await editorService().openFile("/project/a.ts", { focus: true });
|
||||
expect(backend.emit).toHaveBeenLastCalledWith("main", TASK_WINDOW, {
|
||||
type: "openFile",
|
||||
path: "/project/a.ts",
|
||||
options: { focus: true },
|
||||
});
|
||||
const diff = { kind: "diff", key: "diff:one" };
|
||||
await editorService().openInput(diff);
|
||||
expect(backend.emit).toHaveBeenLastCalledWith("main", TASK_WINDOW, {
|
||||
type: "openInput",
|
||||
input: diff,
|
||||
options: undefined,
|
||||
});
|
||||
await editorService().openInput(input);
|
||||
expect(backend.openInput).toHaveBeenCalledWith(input, undefined);
|
||||
await executeAction("file.settings", "agents");
|
||||
expect(backend.emit).toHaveBeenLastCalledWith("main", TASK_WINDOW, {
|
||||
type: "action",
|
||||
action: "file.settings",
|
||||
arg: "agents",
|
||||
});
|
||||
});
|
||||
|
||||
it("applies context appended in the project to the child composer", async () => {
|
||||
await child();
|
||||
stop = activateTaskWindows();
|
||||
backend.activeInput?.(input);
|
||||
backend.emit.mockClear();
|
||||
const draft = { ...backend.draft, text: "Typed in the child @a.ts" };
|
||||
receive({ type: "draftSnapshot", task: "running-task", draft });
|
||||
expect(backend.updateComposer).toHaveBeenCalledWith("running-task", draft);
|
||||
expect(backend.emit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not complete the handoff when connecting fails", async () => {
|
||||
await child();
|
||||
backend.state.error = "Connection failed";
|
||||
backend.emit.mockClear();
|
||||
await expect(prepareTaskWindowInput(input)).rejects.toThrow("Connection failed");
|
||||
expect(backend.emit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("waits for conversation entries and rejects their loading error", async () => {
|
||||
await child();
|
||||
backend.state.entries.clear();
|
||||
const pending = prepareTaskWindowInput(input);
|
||||
const rejected = expect(pending).rejects.toThrow("Cannot read conversation");
|
||||
expect(backend.loadEntries).toHaveBeenCalledWith("running-task");
|
||||
backend.state.entryLoads.set("running-task", { error: "Cannot read conversation" });
|
||||
backend.subscribers.forEach((fn) => fn());
|
||||
await rejected;
|
||||
});
|
||||
|
||||
it("times out without hiding the parent or retaining its store listener", async () => {
|
||||
await child();
|
||||
vi.useFakeTimers();
|
||||
backend.state.loaded = false;
|
||||
const rejected = expect(prepareTaskWindowInput(input)).rejects.toThrow("Loading the conversation timed out");
|
||||
await vi.advanceTimersByTimeAsync(20_000);
|
||||
await rejected;
|
||||
expect(backend.subscribers.size).toBe(0);
|
||||
expect(backend.closeInput).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,390 @@
|
||||
/**
|
||||
* A conversation moved to a lightweight editor window. Only the view moves: the task and its
|
||||
* agent process stay in the project's backend, and the project window keeps the task list, the
|
||||
* unread marks, the notifications and a copy of the unsent draft.
|
||||
*/
|
||||
import { emitTo, TauriEvent, type UnlistenFn } from "@tauri-apps/api/event";
|
||||
import { getAllWindows, getCurrentWindow, Window } from "@tauri-apps/api/window";
|
||||
import { auxiliaryWindow, windowLabel } from "@/platform/auxWindow";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { executeAction, registerActions } from "@/platform/actions";
|
||||
import {
|
||||
editorService,
|
||||
notifications,
|
||||
provideEditorService,
|
||||
provideToolWindowService,
|
||||
toolWindowService,
|
||||
type EditorInput,
|
||||
type OpenOptions,
|
||||
} from "@/workbench/contributions";
|
||||
import type { ComposerDraft } from "./composerModel";
|
||||
import { SESSION_KIND, sessionKey } from "./model";
|
||||
import { composerDraft, loadEntries, openHome, openTask, updateComposer, useAgents } from "./store";
|
||||
import { installTaskWindowRouting } from "./taskWindowRouting";
|
||||
|
||||
export const TASK_WINDOW = "openidea://agents/window";
|
||||
|
||||
export type TaskWindowMessage =
|
||||
| { type: "requestDraft"; task: string; label: string }
|
||||
| { type: "draftSnapshot"; task: string; draft: ComposerDraft }
|
||||
| { type: "openFile"; path: string; options?: OpenOptions }
|
||||
| { type: "openInput"; input: EditorInput; options?: OpenOptions }
|
||||
| { type: "toolWindow"; id: string }
|
||||
| { type: "action"; action: string; arg?: unknown }
|
||||
/** Window `label` shows `task`; `draft` is what changed in its composer. */
|
||||
| { type: "draft"; task: string; label: string; draft: Partial<ComposerDraft> }
|
||||
/** Window `label` closed its tab of `task`. */
|
||||
| { type: "closed"; task: string; label: string }
|
||||
/** A lightweight window asks the project window to show `task`, or New Task. */
|
||||
| { type: "open"; task: string | null; prompt?: string }
|
||||
/** A project window that lost track of its windows (it reloaded) asks them to report again. */
|
||||
| { type: "sync" };
|
||||
|
||||
type TaskData = { task: string; title?: string; draft?: ComposerDraft };
|
||||
const taskInput = (data: TaskData): EditorInput => ({ kind: SESSION_KIND, key: sessionKey(data.task), data });
|
||||
const taskOf = (input: EditorInput | null) => (input?.kind === SESSION_KIND ? (input.data as TaskData).task : null);
|
||||
|
||||
type Detached = { label: string; draft: ComposerDraft; focused: boolean; stop?: UnlistenFn };
|
||||
/** Project window: the conversations shown in its lightweight windows. */
|
||||
const detached = new Map<string, Detached>();
|
||||
const opening = new Map<string, ComposerDraft>();
|
||||
/** Lightweight window: its tab of this task closed. */
|
||||
let tabClosed: ((task: string) => void) | undefined;
|
||||
export const taskTabClosed = (task: string) => tabClosed?.(task);
|
||||
|
||||
/** A reload uses the project's current draft, not the draft in the original launch. */
|
||||
export async function prepareTaskWindowInput(input: EditorInput): Promise<EditorInput> {
|
||||
const task = taskOf(input);
|
||||
const aux = auxiliaryWindow();
|
||||
if (!task || !aux) return input;
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
let loading = false;
|
||||
const finish = (error?: unknown) => {
|
||||
clearTimeout(timer);
|
||||
stop();
|
||||
if (error !== undefined) reject(error);
|
||||
else resolve();
|
||||
};
|
||||
const check = () => {
|
||||
const state = useAgents.getState();
|
||||
if (!state.loaded) return;
|
||||
const error = state.error || state.entryLoads.get(task)?.error;
|
||||
if (error) return finish(new Error(error));
|
||||
if (!state.tasks.has(task)) return finish(new Error(tx("Could not open the editor window")));
|
||||
if (state.entries.has(task)) return finish();
|
||||
if (!loading) {
|
||||
loading = true;
|
||||
void loadEntries(task).catch(finish);
|
||||
}
|
||||
};
|
||||
const stop = useAgents.subscribe(check);
|
||||
const timer = setTimeout(() => finish(new Error(tx("Loading the conversation timed out. Try again."))), 20_000);
|
||||
check();
|
||||
});
|
||||
const self = getCurrentWindow();
|
||||
let receive!: (draft: ComposerDraft) => void;
|
||||
const snapshot = new Promise<ComposerDraft>((resolve) => {
|
||||
receive = resolve;
|
||||
});
|
||||
const stop = await self.listen<TaskWindowMessage>(TASK_WINDOW, ({ payload }) => {
|
||||
if (payload.type === "draftSnapshot" && payload.task === task) receive(payload.draft);
|
||||
});
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
const draft = await Promise.race([
|
||||
emitTo(aux.parent, TASK_WINDOW, {
|
||||
type: "requestDraft",
|
||||
task,
|
||||
label: self.label,
|
||||
} satisfies TaskWindowMessage).then(() => snapshot),
|
||||
new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error(tx("Timed out opening the editor window"))), 5000);
|
||||
}),
|
||||
]);
|
||||
return { ...input, data: { ...(input.data as TaskData), draft } };
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
stop();
|
||||
}
|
||||
}
|
||||
|
||||
async function focusWindow(label: string): Promise<void> {
|
||||
const window = await Window.getByLabel(label);
|
||||
if (!window) return;
|
||||
await window.unminimize();
|
||||
await window.show();
|
||||
await window.setFocus();
|
||||
}
|
||||
|
||||
function markRead(task: string) {
|
||||
const unread = new Set(useAgents.getState().unread);
|
||||
if (unread.delete(task)) useAgents.setState({ unread });
|
||||
}
|
||||
|
||||
async function hide(task: string) {
|
||||
if (useAgents.getState().docked === task) useAgents.setState({ docked: null });
|
||||
await editorService().closeInput?.(sessionKey(task));
|
||||
}
|
||||
|
||||
/** The conversation comes back with what was typed in its window. */
|
||||
function restore(task: string, entry: Detached) {
|
||||
if (detached.get(task) !== entry) return;
|
||||
detached.delete(task);
|
||||
void entry.stop?.();
|
||||
if (!useAgents.getState().tasks.has(task)) return;
|
||||
updateComposer(task, entry.draft);
|
||||
openTask(task);
|
||||
void focusWindow(getCurrentWindow().label);
|
||||
}
|
||||
|
||||
async function watch(task: string, entry: Detached) {
|
||||
const window = await Window.getByLabel(entry.label);
|
||||
if (!window) return restore(task, entry);
|
||||
// Not undone by `restore`: a window that closed the tab still receives agent events until it is gone.
|
||||
void window.once(TauriEvent.WINDOW_DESTROYED, () => {
|
||||
void call(commands.agentUnsubscribe(entry.label)).catch(() => {});
|
||||
restore(task, entry);
|
||||
});
|
||||
const focus = (focused: boolean) => {
|
||||
entry.focused = focused;
|
||||
if (focused) {
|
||||
markRead(task);
|
||||
useAgents.setState({ lastComposer: task });
|
||||
}
|
||||
};
|
||||
const stop = await window.onFocusChanged(({ payload }) => focus(payload));
|
||||
if (detached.get(task) !== entry) return void stop();
|
||||
entry.stop = stop;
|
||||
focus(await window.isFocused());
|
||||
}
|
||||
|
||||
function adopt(task: string, label: string, draft: Partial<ComposerDraft>) {
|
||||
let entry = detached.get(task);
|
||||
if (entry?.label !== label) {
|
||||
void entry?.stop?.();
|
||||
entry = { label, draft: composerDraft(task), focused: false };
|
||||
detached.set(task, entry);
|
||||
void watch(task, entry);
|
||||
void hide(task);
|
||||
}
|
||||
entry.draft = { ...entry.draft, ...draft };
|
||||
}
|
||||
|
||||
function activateProjectWindow(): () => void {
|
||||
const self = getCurrentWindow();
|
||||
const recovering = new Set<string>();
|
||||
const stops = [
|
||||
installTaskWindowRouting(
|
||||
(task) => {
|
||||
const entry = task ? detached.get(task) : undefined;
|
||||
if (entry) void focusWindow(entry.label);
|
||||
return !!entry;
|
||||
},
|
||||
(task) => detached.get(task)?.focused ?? false,
|
||||
{
|
||||
read: (task) => detached.get(task)?.draft,
|
||||
update: (task, patch) => {
|
||||
const entry = detached.get(task);
|
||||
if (!entry) return false;
|
||||
entry.draft = { ...entry.draft, ...patch };
|
||||
void emitTo(entry.label, TASK_WINDOW, {
|
||||
type: "draftSnapshot",
|
||||
task,
|
||||
draft: entry.draft,
|
||||
} satisfies TaskWindowMessage).catch((error) => console.warn("cannot update conversation draft", error));
|
||||
return true;
|
||||
},
|
||||
},
|
||||
),
|
||||
// Back/Forward and a restored layout open tabs without going through `openTask`.
|
||||
editorService().onActiveInputChange?.((input) => {
|
||||
const task = taskOf(input);
|
||||
const entry = task ? detached.get(task) : undefined;
|
||||
if (!task || !entry) return;
|
||||
void hide(task);
|
||||
void focusWindow(entry.label);
|
||||
}),
|
||||
];
|
||||
const listening = self.listen<TaskWindowMessage>(TASK_WINDOW, ({ payload: message }) => {
|
||||
if (message.type === "requestDraft") {
|
||||
const aux = auxiliaryWindow(message.label);
|
||||
const entry = detached.get(message.task);
|
||||
if (aux?.kind === "editor" && aux.parent === self.label && (!entry || entry.label === message.label))
|
||||
void emitTo(message.label, TASK_WINDOW, {
|
||||
type: "draftSnapshot",
|
||||
task: message.task,
|
||||
draft: entry?.draft ?? composerDraft(message.task),
|
||||
} satisfies TaskWindowMessage).catch((error) => console.warn("cannot restore conversation draft", error));
|
||||
} else if (message.type === "draft") {
|
||||
if (auxiliaryWindow(message.label)?.parent !== self.label) return;
|
||||
const pending = opening.get(message.task);
|
||||
if (pending) opening.set(message.task, { ...pending, ...message.draft });
|
||||
else if (detached.get(message.task)?.label === message.label || recovering.has(message.label))
|
||||
adopt(message.task, message.label, message.draft);
|
||||
} else if (message.type === "closed") {
|
||||
const entry = detached.get(message.task);
|
||||
if (entry?.label === message.label) restore(message.task, entry);
|
||||
} else if (message.type === "open") {
|
||||
if (message.task) openTask(message.task);
|
||||
else openHome(message.prompt);
|
||||
void focusWindow(self.label);
|
||||
} else if (message.type === "openFile" || message.type === "openInput") {
|
||||
const editors = editorService();
|
||||
const opened =
|
||||
message.type === "openFile"
|
||||
? editors.openFile(message.path, message.options)
|
||||
: editors.openInput(message.input, message.options);
|
||||
void opened.then(() => focusWindow(self.label)).catch(console.error);
|
||||
} else if (message.type === "toolWindow") {
|
||||
toolWindowService().show(message.id, true);
|
||||
void focusWindow(self.label);
|
||||
} else if (message.type === "action") {
|
||||
void focusWindow(self.label)
|
||||
.then(() => executeAction(message.action, message.arg))
|
||||
.catch(console.error);
|
||||
}
|
||||
});
|
||||
void listening
|
||||
.then(async () => {
|
||||
for (const { label } of await getAllWindows()) {
|
||||
const aux = auxiliaryWindow(label);
|
||||
if (aux?.kind === "editor" && aux.parent === self.label) {
|
||||
recovering.add(label);
|
||||
await emitTo(label, TASK_WINDOW, { type: "sync" } satisfies TaskWindowMessage);
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch((error) => console.warn("cannot look for conversation windows", error));
|
||||
return () => {
|
||||
stops.forEach((stop) => stop?.());
|
||||
void listening.then((stop) => stop()).catch(() => {});
|
||||
for (const entry of detached.values()) void entry.stop?.();
|
||||
detached.clear();
|
||||
};
|
||||
}
|
||||
|
||||
function activateLightweightWindow(parent: string): () => void {
|
||||
const self = getCurrentWindow();
|
||||
/** The conversations shown here, with what the project window last heard of their composers. */
|
||||
const shown = new Map<string, Partial<ComposerDraft>>();
|
||||
const send = (message: TaskWindowMessage) =>
|
||||
void emitTo(parent, TASK_WINDOW, message).catch((error) => console.warn("cannot reach the project window", error));
|
||||
const editors = editorService();
|
||||
// A conversation keeps its view here; its file links and workbench tools open in the project.
|
||||
provideEditorService({
|
||||
...editors,
|
||||
openFile: (path, options) =>
|
||||
shown.size
|
||||
? emitTo(parent, TASK_WINDOW, { type: "openFile", path, options } satisfies TaskWindowMessage)
|
||||
: editors.openFile(path, options),
|
||||
openInput: (input, options) =>
|
||||
shown.size && input.kind !== SESSION_KIND
|
||||
? emitTo(parent, TASK_WINDOW, { type: "openInput", input, options } satisfies TaskWindowMessage)
|
||||
: editors.openInput(input, options),
|
||||
});
|
||||
provideToolWindowService({
|
||||
show: (id) => send({ type: "toolWindow", id }),
|
||||
toggle: (id) => send({ type: "toolWindow", id }),
|
||||
hide: () => {},
|
||||
isVisible: () => false,
|
||||
});
|
||||
const report = (task: string, all = false) => {
|
||||
const draft = composerDraft(task);
|
||||
const known = all ? {} : shown.get(task)!;
|
||||
// Images are base64: only what changed travels with each keystroke.
|
||||
const changed = Object.fromEntries(
|
||||
Object.entries(draft).filter(([field, value]) => value !== known[field as keyof ComposerDraft]),
|
||||
);
|
||||
shown.set(task, draft);
|
||||
if (all || Object.keys(changed).length) send({ type: "draft", task, label: self.label, draft: changed });
|
||||
};
|
||||
const show = (input: EditorInput | null) => {
|
||||
const task = taskOf(input);
|
||||
if (!task || shown.has(task)) return;
|
||||
const { draft } = input!.data as TaskData;
|
||||
// What was being typed in the project window moves along, once.
|
||||
if (draft && !useAgents.getState().composers.has(task)) updateComposer(task, draft);
|
||||
report(task, true);
|
||||
};
|
||||
tabClosed = (task) => {
|
||||
if (!shown.delete(task)) return;
|
||||
send({ type: "closed", task, label: self.label });
|
||||
// A window opened for the conversation has nothing left to show.
|
||||
setTimeout(() => {
|
||||
if (!editorService().openTabs?.().length) void self.close();
|
||||
});
|
||||
};
|
||||
const stops = [
|
||||
registerActions(
|
||||
[
|
||||
{ id: "terminal.openAt", title: "Open in Terminal" },
|
||||
{ id: "file.settings", title: "Settings…" },
|
||||
{ id: "navigate.selectInProjectView", title: "Select in Project View" },
|
||||
].map(({ id, title }) => ({
|
||||
id,
|
||||
title,
|
||||
hidden: true,
|
||||
enabled: () => shown.size > 0,
|
||||
run: ({ arg }) => send({ type: "action", action: id, arg }),
|
||||
})),
|
||||
),
|
||||
installTaskWindowRouting((task, prompt) => {
|
||||
if (task && shown.has(task)) void editorService().openInput(taskInput({ task }), { focus: true });
|
||||
else send({ type: "open", task, prompt });
|
||||
return true;
|
||||
}),
|
||||
editorService().onActiveInputChange?.(show),
|
||||
useAgents.subscribe((state, previous) => {
|
||||
if (state.composers !== previous.composers) for (const task of shown.keys()) report(task);
|
||||
}),
|
||||
];
|
||||
const listening = self.listen<TaskWindowMessage>(TASK_WINDOW, ({ payload: message }) => {
|
||||
if (message.type === "sync") for (const task of shown.keys()) report(task, true);
|
||||
else if (message.type === "draftSnapshot" && shown.has(message.task)) {
|
||||
// This snapshot came from the project (for example, Send to Agent): do not echo it back.
|
||||
shown.set(message.task, message.draft);
|
||||
updateComposer(message.task, message.draft);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
tabClosed = undefined;
|
||||
provideEditorService(editors);
|
||||
stops.forEach((stop) => stop?.());
|
||||
void listening.then((stop) => stop()).catch(() => {});
|
||||
};
|
||||
}
|
||||
|
||||
export function activateTaskWindows(): () => void {
|
||||
if (!isTauri() || !windowLabel()) return () => {};
|
||||
const aux = auxiliaryWindow();
|
||||
return aux ? activateLightweightWindow(aux.parent) : activateProjectWindow();
|
||||
}
|
||||
|
||||
/** Moves the conversation of `task` to a window of its own; false when it stayed here. */
|
||||
export async function moveTaskToWindow(task: string): Promise<boolean> {
|
||||
const open = editorService().openInWindow;
|
||||
if (!open || auxiliaryWindow() || opening.has(task) || !useAgents.getState().tasks.has(task)) return false;
|
||||
const existing = detached.get(task);
|
||||
if (existing) {
|
||||
await focusWindow(existing.label);
|
||||
return true;
|
||||
}
|
||||
const draft = composerDraft(task);
|
||||
opening.set(task, draft);
|
||||
try {
|
||||
const title = useAgents.getState().tasks.get(task)?.title;
|
||||
const label = await open(taskInput({ task, title }));
|
||||
adopt(task, label, opening.get(task) ?? draft);
|
||||
return true;
|
||||
} catch (error) {
|
||||
notifications().notify({
|
||||
level: "error",
|
||||
title: "Could not move conversation to a new window",
|
||||
body: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return false;
|
||||
} finally {
|
||||
opening.delete(task);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,16 @@
|
||||
.view {
|
||||
--coverage-metrics: 2;
|
||||
--coverage-metric-width: min(29cqi, 128px);
|
||||
--coverage-column-gap: var(--space-2);
|
||||
container-type: inline-size;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
.noBranches {
|
||||
--coverage-metrics: 1;
|
||||
}
|
||||
.tabs {
|
||||
min-width: 0;
|
||||
border: 0;
|
||||
@@ -18,19 +25,24 @@
|
||||
.header,
|
||||
.row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(120px, 1fr) 170px 170px;
|
||||
grid-template-columns: minmax(0, 1fr) repeat(var(--coverage-metrics), var(--coverage-metric-width));
|
||||
align-items: center;
|
||||
column-gap: var(--space-2);
|
||||
}
|
||||
.header.noBranches,
|
||||
.row.noBranches {
|
||||
grid-template-columns: minmax(120px, 1fr) 170px;
|
||||
column-gap: var(--coverage-column-gap);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
.header {
|
||||
flex: none;
|
||||
height: 24px;
|
||||
padding: 0 10px 0 28px;
|
||||
padding-inline: 30px 14px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
overflow: hidden;
|
||||
}
|
||||
.header,
|
||||
.tree [role="tree"] {
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
.header::-webkit-scrollbar {
|
||||
width: 10px;
|
||||
}
|
||||
.headerCell {
|
||||
display: inline-flex;
|
||||
@@ -41,7 +53,6 @@
|
||||
border: 0;
|
||||
background: none;
|
||||
font: inherit;
|
||||
font-size: var(--fs-small);
|
||||
color: var(--fg-secondary);
|
||||
text-align: left;
|
||||
cursor: default;
|
||||
@@ -49,15 +60,21 @@
|
||||
.headerCell:hover {
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
.headerCell svg {
|
||||
flex: none;
|
||||
}
|
||||
.tree {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
/* Keep the chevron and icon in the name column at deeper levels. */
|
||||
--coverage-max-row-inset: max(
|
||||
4px,
|
||||
calc(100% - var(--coverage-metrics) * (var(--coverage-metric-width) + var(--coverage-column-gap)) - 72px)
|
||||
);
|
||||
}
|
||||
.row {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding-right: 10px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.name {
|
||||
display: flex;
|
||||
@@ -68,35 +85,31 @@
|
||||
.icon {
|
||||
flex: none;
|
||||
}
|
||||
.label {
|
||||
.label,
|
||||
.value {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.cell {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
min-width: 0;
|
||||
}
|
||||
.bar {
|
||||
flex: none;
|
||||
width: 48px;
|
||||
height: 6px;
|
||||
border-radius: 1px;
|
||||
background: var(--coverage-uncovered);
|
||||
opacity: 0.85;
|
||||
overflow: hidden;
|
||||
}
|
||||
.barFill {
|
||||
display: block;
|
||||
height: 100%;
|
||||
background: var(--coverage-covered);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.value {
|
||||
font-size: var(--fs-small);
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
@container (width < 360px) {
|
||||
.header,
|
||||
.tree {
|
||||
--coverage-metric-width: min(23cqi, 65px);
|
||||
--coverage-column-gap: var(--space-1);
|
||||
}
|
||||
.count {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
}
|
||||
}
|
||||
.link {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { EmptyState, Icon, IconButton, Tabs, Tree, fileIconName, T } from "@/ui";
|
||||
import { editorService } from "@/workbench/contributions";
|
||||
import { coverageTree, formatPercent, percent, sortTree, type CoverageNode, type SortKey } from "./model";
|
||||
import { coverageTree, formatPercent, sortTree, type CoverageNode, type SortKey } from "./model";
|
||||
import { activeSuite, closeSuite, selectSuite, setCoverageVisible, useCoverage } from "./store";
|
||||
import styles from "./Coverage.module.css";
|
||||
|
||||
@@ -49,16 +50,13 @@ export function CoverageHeaderActions() {
|
||||
);
|
||||
}
|
||||
|
||||
function Bar({ covered, total }: { covered: number; total: number }) {
|
||||
const p = percent(covered, total);
|
||||
function Metric({ covered, total }: { covered: number; total: number }) {
|
||||
const value = formatPercent(covered, total);
|
||||
const [percentage, count] = value.split(" ", 2);
|
||||
return (
|
||||
<span className={styles.cell}>
|
||||
{p !== null && (
|
||||
<span className={styles.bar} aria-hidden="true">
|
||||
<span className={styles.barFill} style={{ width: `${p}%` }} />
|
||||
</span>
|
||||
)}
|
||||
<span className={styles.value}>{formatPercent(covered, total)}</span>
|
||||
<span className={styles.value} title={value}>
|
||||
{percentage}
|
||||
{count && <span className={styles.count}> {count}</span>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -70,6 +68,7 @@ const COLUMNS: Array<{ key: SortKey; label: string }> = [
|
||||
];
|
||||
|
||||
export function CoverageView() {
|
||||
const tx = useTx();
|
||||
const suite = useCoverage((s) => activeSuite(s));
|
||||
const visible = useCoverage((s) => s.visible);
|
||||
const root = useProject((s) => s.project?.root ?? "");
|
||||
@@ -108,13 +107,13 @@ export function CoverageView() {
|
||||
setSort((s) => (s.key === key ? { key, ascending: !s.ascending } : { key, ascending: key === "name" }));
|
||||
|
||||
return (
|
||||
<div className={styles.view}>
|
||||
<div className={clsx(styles.view, !branches && styles.noBranches)}>
|
||||
{!visible && (
|
||||
<div className={styles.banner}>
|
||||
<T>Coverage is hidden in editors and the project view.</T>
|
||||
</div>
|
||||
)}
|
||||
<div className={clsx(styles.header, !branches && styles.noBranches)} role="row">
|
||||
<div className={styles.header} role="row">
|
||||
{columns.map((c) => (
|
||||
<button
|
||||
key={c.key}
|
||||
@@ -122,9 +121,10 @@ export function CoverageView() {
|
||||
role="columnheader"
|
||||
aria-sort={sort.key === c.key ? (sort.ascending ? "ascending" : "descending") : "none"}
|
||||
className={styles.headerCell}
|
||||
title={tx(c.label)}
|
||||
onClick={() => toggleSort(c.key)}
|
||||
>
|
||||
{c.label}
|
||||
<span className={styles.label}>{tx(c.label)}</span>
|
||||
{sort.key === c.key && <Icon name={sort.ascending ? "chevron-up" : "chevron-down"} size={12} />}
|
||||
</button>
|
||||
))}
|
||||
@@ -132,6 +132,8 @@ export function CoverageView() {
|
||||
<Tree<CoverageNode>
|
||||
aria-label="Coverage"
|
||||
className={styles.tree}
|
||||
indent={12}
|
||||
maxRowInset="var(--coverage-max-row-inset)"
|
||||
roots={roots}
|
||||
getKey={(n) => n.path}
|
||||
getLabel={(n) => n.name}
|
||||
@@ -143,13 +145,15 @@ export function CoverageView() {
|
||||
if (!n.dir) void editorService().openFile(n.path);
|
||||
}}
|
||||
renderNode={(n) => (
|
||||
<span className={clsx(styles.row, !branches && styles.noBranches)}>
|
||||
<span className={styles.row}>
|
||||
<span className={styles.name}>
|
||||
<Icon name={n.dir ? "folder" : fileIconName(n.name)} size={16} className={styles.icon} />
|
||||
<span className={styles.label}>{n.name}</span>
|
||||
<span className={styles.label} title={n.name}>
|
||||
{n.name}
|
||||
</span>
|
||||
</span>
|
||||
<Bar covered={n.linesCovered} total={n.linesTotal} />
|
||||
{branches && <Bar covered={n.branchesCovered} total={n.branchesTotal} />}
|
||||
<Metric covered={n.linesCovered} total={n.linesTotal} />
|
||||
{branches && <Metric covered={n.branchesCovered} total={n.branchesTotal} />}
|
||||
</span>
|
||||
)}
|
||||
empty={<EmptyState title="The report covers no files" />}
|
||||
|
||||
@@ -91,7 +91,17 @@ interface Shaping {
|
||||
|
||||
export interface DataViewProps extends Pick<
|
||||
GridProps,
|
||||
"rowState" | "isModified" | "editable" | "onEdit" | "onResetCell" | "driver" | "sort" | "onSort" | "rowMenu"
|
||||
| "rowState"
|
||||
| "isModified"
|
||||
| "editable"
|
||||
| "onEdit"
|
||||
| "onResetCell"
|
||||
| "driver"
|
||||
| "sort"
|
||||
| "onSort"
|
||||
| "rowMenu"
|
||||
| "initialScrollLeft"
|
||||
| "onHorizontalScroll"
|
||||
> {
|
||||
columns: readonly GridColumn[];
|
||||
rowCount: number;
|
||||
@@ -238,6 +248,8 @@ export function DataView(props: DataViewProps) {
|
||||
onSelectionChange={setRange}
|
||||
onFilter={(col, anchor) => setFilterAt({ col, anchor })}
|
||||
filtered={(col) => filter.has(col)}
|
||||
initialScrollLeft={props.initialScrollLeft}
|
||||
onHorizontalScroll={props.onHorizontalScroll}
|
||||
/>
|
||||
{filter.size > 0 && (
|
||||
<div className={styles.filterPill} role="status">
|
||||
|
||||
@@ -98,6 +98,10 @@ export interface GridProps {
|
||||
onFind?: () => void;
|
||||
/** Go to Column: a new object selects that column's cell in the current row, scrolls to it and focuses the grid. */
|
||||
revealColumn?: { col: number } | null;
|
||||
/** Horizontal scroll offset to restore on mount, when a caller keeps view state across mounts. */
|
||||
initialScrollLeft?: number;
|
||||
/** Reports horizontal scroll changes to a caller that keeps view state across mounts. */
|
||||
onHorizontalScroll?: (left: number) => void;
|
||||
"aria-label"?: string;
|
||||
}
|
||||
|
||||
@@ -254,6 +258,15 @@ export function Grid(props: GridProps) {
|
||||
}, [revealColumn]);
|
||||
const totalWidth = useMemo(() => numberWidth + widths.reduce((a, b) => a + b, 0), [numberWidth, widths]);
|
||||
const template = `${numberWidth}px ${widths.map((w) => `${w}px`).join(" ")}`;
|
||||
// Retried as columns are measured, until the content is wide enough to reach the offset.
|
||||
const pendingScrollLeft = useRef(props.initialScrollLeft);
|
||||
useLayoutEffect(() => {
|
||||
const el = scrollRef.current;
|
||||
const left = pendingScrollLeft.current;
|
||||
if (!el || !left) return;
|
||||
el.scrollLeft = left;
|
||||
if (el.scrollLeft >= left - 1) pendingScrollLeft.current = undefined;
|
||||
}, [totalWidth]);
|
||||
|
||||
const selected = (r: number, c: number) => {
|
||||
if (!sel) return false;
|
||||
@@ -605,6 +618,7 @@ export function Grid(props: GridProps) {
|
||||
pointerFocus.current = true;
|
||||
setTimeout(() => (pointerFocus.current = false));
|
||||
}}
|
||||
onScroll={(e) => props.onHorizontalScroll?.(e.currentTarget.scrollLeft)}
|
||||
onPaste={onPaste}
|
||||
onContextMenu={onContextMenu}
|
||||
>
|
||||
|
||||
@@ -48,6 +48,7 @@ interface TableViewState {
|
||||
sort: DbSortKey[];
|
||||
filterText: string;
|
||||
filter: string;
|
||||
horizontalScrollLeft: number;
|
||||
}
|
||||
|
||||
const MAX_VIEW_STATES = 100;
|
||||
@@ -72,10 +73,28 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
const [sort, setSort] = useState<DbSortKey[]>(initial?.sort ?? []);
|
||||
const [filterText, setFilterText] = useState(initial?.filterText ?? "");
|
||||
const [filter, setFilter] = useState(initial?.filter ?? "");
|
||||
// A ref, not state: scrolling must not re-render the editor.
|
||||
const scrollLeft = useRef(initial?.horizontalScrollLeft ?? 0);
|
||||
useEffect(
|
||||
() => rememberViewState(input.key, { offset, limit, sort, filterText, filter }),
|
||||
() =>
|
||||
rememberViewState(input.key, {
|
||||
offset,
|
||||
limit,
|
||||
sort,
|
||||
filterText,
|
||||
filter,
|
||||
horizontalScrollLeft: scrollLeft.current,
|
||||
}),
|
||||
[input.key, offset, limit, sort, filterText, filter],
|
||||
);
|
||||
const onHorizontalScroll = useCallback(
|
||||
(left: number) => {
|
||||
scrollLeft.current = left;
|
||||
const state = viewStates.get(input.key);
|
||||
if (state) state.horizontalScrollLeft = left;
|
||||
},
|
||||
[input.key],
|
||||
);
|
||||
const [nonce, setNonce] = useState(0);
|
||||
const [edits, setEdits] = useState<PendingEdits>(emptyEdits);
|
||||
const [panel, setPanel] = useState<DataPanel | null>(null);
|
||||
@@ -432,6 +451,8 @@ export function TableEditor({ input }: { input: EditorInput }) {
|
||||
driver={source?.driver}
|
||||
sort={sort}
|
||||
onSort={onSort}
|
||||
initialScrollLeft={scrollLeft.current}
|
||||
onHorizontalScroll={onHorizontalScroll}
|
||||
pager={
|
||||
<Toolbar className={styles.resultPager} aria-label="Table pages">
|
||||
{!singlePage && (
|
||||
|
||||
@@ -112,6 +112,7 @@ const TEMPLATE_CONTEXT_KEY = "openideaTemplateContexts";
|
||||
|
||||
import { formatElapsed } from "./resultView";
|
||||
import { SQL_LANGUAGE } from "./sqlLanguage";
|
||||
import { jdbcDialect } from "./vendors";
|
||||
export { SQL_LANGUAGE };
|
||||
const ROW_LIMITS = ["100", "500", "1000", "5000", "50000"];
|
||||
|
||||
@@ -1069,6 +1070,9 @@ export function completionSource(path: string, sql: SqlText = WHOLE_FILE): Compl
|
||||
const current = id ? databaseRequest(id) : projectRequest();
|
||||
const source = sourceById(id);
|
||||
const driver: DbDriver = source?.driver ?? "sqlite";
|
||||
// A custom JDBC source (`driver: "jdbc"`) says nothing about how its server folds
|
||||
// identifiers; its URL does (`jdbc:oracle:thin:@…`). Quoting follows that dialect.
|
||||
const dialect = driver === "jdbc" ? jdbcDialect(source?.url) : null;
|
||||
const model = id ? (useDatabase.getState().completion[id] ?? null) : null;
|
||||
if (id && !model) void loadCompletion(id);
|
||||
// Unqualified names resolve in the console's active schema (IDEA's schema dropdown).
|
||||
@@ -1091,6 +1095,7 @@ export function completionSource(path: string, sql: SqlText = WHOLE_FILE): Compl
|
||||
model: scoped,
|
||||
analysis,
|
||||
driver,
|
||||
dialect,
|
||||
sourceName: source?.name ?? undefined,
|
||||
catalog: cataloged ? catalogOf(id) : undefined,
|
||||
});
|
||||
|
||||
@@ -63,20 +63,26 @@ export function shouldAutoCompleteSql(analysis: Analysis): boolean {
|
||||
|
||||
const MAX_ALL_COLUMNS = 3000;
|
||||
|
||||
/** `name`, quoted when the dialect needs it (case, characters, reserved words). */
|
||||
export function quoteIdent(name: string, driver: DbDriver): string {
|
||||
/**
|
||||
* `name`, quoted when the dialect needs it (case, characters, reserved words).
|
||||
* A `jdbc` source quotes by the dialect its URL speaks (`dialect`); without one, only
|
||||
* what is not a plain word is quoted, which is right for the dialects that fold case
|
||||
* neither way.
|
||||
*/
|
||||
export function quoteIdent(name: string, driver: DbDriver, dialect?: DbDriver | null): string {
|
||||
const d = driver === "jdbc" && dialect ? dialect : driver;
|
||||
const plain =
|
||||
driver === "postgres"
|
||||
d === "postgres"
|
||||
? /^[a-z_][a-z0-9_$]*$/
|
||||
: // Oracle and Snowflake fold unquoted names to upper case; a lower-case name must stay quoted.
|
||||
driver === "oracle" || driver === "snowflake"
|
||||
d === "oracle" || d === "snowflake"
|
||||
? /^[A-Z_][A-Z0-9_$]*$/
|
||||
: driver === "clickhouse"
|
||||
: d === "clickhouse"
|
||||
? /^[A-Za-z_][A-Za-z0-9_]*$/
|
||||
: /^[A-Za-z_][A-Za-z0-9_$]*$/;
|
||||
if (plain.test(name) && !isReserved(name, driver)) return name;
|
||||
if (driver === "clickhouse") return `"${name.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
|
||||
const q = driver === "mysql" ? "`" : '"';
|
||||
if (plain.test(name) && !isReserved(name, d)) return name;
|
||||
if (d === "clickhouse") return `"${name.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
|
||||
const q = d === "mysql" ? "`" : '"';
|
||||
return q + name.split(q).join(q + q) + q;
|
||||
}
|
||||
|
||||
@@ -121,11 +127,20 @@ export interface CompletionInput {
|
||||
model: DbCompletion | null;
|
||||
analysis: Analysis;
|
||||
driver: DbDriver;
|
||||
/** The dialect a `jdbc` source speaks, from its URL (`jdbcDialect`); quoting follows it. */
|
||||
dialect?: DbDriver | null;
|
||||
/** Data source name, shown next to tables like IDEA does. */
|
||||
sourceName?: string;
|
||||
}
|
||||
|
||||
export function sqlCandidates({ model, analysis: a, driver, sourceName, catalog }: CompletionInput): SqlCandidate[] {
|
||||
export function sqlCandidates({
|
||||
model,
|
||||
analysis: a,
|
||||
driver,
|
||||
dialect,
|
||||
sourceName,
|
||||
catalog,
|
||||
}: CompletionInput): SqlCandidate[] {
|
||||
const eq = nameMatcher(driver);
|
||||
const ctx = a.context;
|
||||
if (ctx.kind === "none") return [];
|
||||
@@ -135,7 +150,7 @@ export function sqlCandidates({ model, analysis: a, driver, sourceName, catalog
|
||||
const kw = (k: string) => (lower ? k.toLowerCase() : k);
|
||||
const tables = model?.tables ?? [];
|
||||
const defaultSchema = model?.defaultSchema ?? "";
|
||||
const exact = (n: string) => quoteIdent(n, driver);
|
||||
const exact = (n: string) => quoteIdent(n, driver, dialect);
|
||||
// Snowflake folds unquoted names to upper case, so a name typed in lower case may stay lower case.
|
||||
const lowerQualifier = !!a.qualifier?.length && a.qualifier.every((p) => /[a-z]/.test(p) && p === p.toLowerCase());
|
||||
// What is typed decides: the name's own prefix, else the qualifier before it, else the statement's keywords.
|
||||
@@ -270,7 +285,7 @@ export function sqlCandidates({ model, analysis: a, driver, sourceName, catalog
|
||||
|
||||
case "table": {
|
||||
const taken = new Set(a.refs.flatMap((r) => [refName(r).toLowerCase(), r.name.toLowerCase()]));
|
||||
if (ctx.join) out.push(...joinCandidates(a, model, driver, taken, kw));
|
||||
if (ctx.join) out.push(...joinCandidates(a, model, driver, dialect, taken, kw));
|
||||
for (const c of a.ctes) out.push({ label: c.name, kind: "table", tail: "(CTE)", boost: 40 });
|
||||
const schemas = new Set<string>();
|
||||
for (const t of tables) {
|
||||
@@ -472,13 +487,14 @@ function joinCandidates(
|
||||
a: Analysis,
|
||||
model: DbCompletion | null,
|
||||
driver: DbDriver,
|
||||
dialect: DbDriver | null | undefined,
|
||||
taken: Set<string>,
|
||||
kw: Kw,
|
||||
): SqlCandidate[] {
|
||||
if (!model) return [];
|
||||
const eq = nameMatcher(driver);
|
||||
const out: SqlCandidate[] = [];
|
||||
const q = (n: string) => quoteIdent(n, driver);
|
||||
const q = (n: string) => quoteIdent(n, driver, dialect);
|
||||
const seen = new Set<string>();
|
||||
const local = (s: string) => eq(s, model.defaultSchema) || driver === "sqlite";
|
||||
const tableText = (schema: string, name: string) => (local(schema) ? q(name) : `${q(schema)}.${q(name)}`);
|
||||
|
||||
@@ -8,6 +8,7 @@ import { identName, inLiteral, lex } from "./lexer";
|
||||
import { DATA_TYPES, statementStarters } from "./dialect";
|
||||
import { bindParams, findParams } from "./params";
|
||||
import { SqlResolver } from "./resolve";
|
||||
import { jdbcDialect } from "../vendors";
|
||||
|
||||
const col = (name: string, dataType = "INTEGER", primaryKey = false, hasDefault = false) => ({
|
||||
name,
|
||||
@@ -280,6 +281,51 @@ describe("completion candidates", () => {
|
||||
expect(quoteIdent('a"b', "oracle")).toBe('"a""b"');
|
||||
});
|
||||
|
||||
it("quotes a custom JDBC source's names by the dialect its URL speaks", () => {
|
||||
expect(jdbcDialect("jdbc:oracle:thin:@//db.local:1521/ORCL")).toBe("oracle");
|
||||
expect(jdbcDialect("JDBC:Oracle:thin:@db:1521:ORCL")).toBe("oracle");
|
||||
expect(jdbcDialect("jdbc:postgresql://db.local/shop")).toBe("postgres");
|
||||
expect(jdbcDialect("jdbc:MariaDB://db/shop")).toBe("mysql");
|
||||
expect(jdbcDialect("jdbc:sqlserver://db;databaseName=shop")).toBe("sqlServer");
|
||||
expect(jdbcDialect("jdbc:unknown://db/shop")).toBeNull();
|
||||
expect(jdbcDialect("")).toBeNull();
|
||||
expect(jdbcDialect(null)).toBeNull();
|
||||
// Oracle folds unquoted names to upper case, so only an upper-case name stays bare.
|
||||
expect(quoteIdent("MyTable", "jdbc", "oracle")).toBe('"MyTable"');
|
||||
expect(quoteIdent("MYTABLE", "jdbc", "oracle")).toBe("MYTABLE");
|
||||
expect(quoteIdent("mytable", "jdbc", "oracle")).toBe('"mytable"');
|
||||
// Without a dialect, a plain word still stays bare: the source never said which server it is.
|
||||
expect(quoteIdent("MyTable", "jdbc")).toBe("MyTable");
|
||||
expect(quoteIdent("MyTable", "jdbc", null)).toBe("MyTable");
|
||||
const hr: DbCompletion = {
|
||||
defaultSchema: "HR",
|
||||
tables: [
|
||||
{
|
||||
schema: "HR",
|
||||
name: "MyTable",
|
||||
kind: "table",
|
||||
columns: [col("ID", "NUMBER", true), col("fullName", "VARCHAR2")],
|
||||
},
|
||||
],
|
||||
foreignKeys: [],
|
||||
};
|
||||
const tables = sqlCandidates({
|
||||
model: hr,
|
||||
analysis: at("SELECT * FROM |", "jdbc"),
|
||||
driver: "jdbc",
|
||||
dialect: jdbcDialect("jdbc:oracle:thin:@//db.local:1521/ORCL"),
|
||||
});
|
||||
expect(tables.find((c) => c.label === "MyTable")?.insert).toBe('"MyTable"');
|
||||
const columns = sqlCandidates({
|
||||
model: hr,
|
||||
analysis: at("SELECT | FROM MyTable", "jdbc"),
|
||||
driver: "jdbc",
|
||||
dialect: "oracle",
|
||||
});
|
||||
expect(columns.find((c) => c.label === "ID")?.insert).toBe("ID");
|
||||
expect(columns.find((c) => c.label === "fullName")?.insert).toBe('"fullName"');
|
||||
});
|
||||
|
||||
it("offers Snowflake vocabulary and quotes names the server folds to upper case", () => {
|
||||
expect(statementStarters("snowflake")).toEqual(
|
||||
expect.arrayContaining([
|
||||
|
||||
@@ -224,6 +224,22 @@ it("omits a reset inserted cell from Submit instead of writing SQL NULL", async
|
||||
});
|
||||
|
||||
describe("table editor view state", () => {
|
||||
it("restores the grid's horizontal scroll position when its tab mounts again (#4775)", async () => {
|
||||
const input = tableInput("source", "default", "users");
|
||||
let view!: ReturnType<typeof render>;
|
||||
await act(async () => {
|
||||
view = render(<TableEditor input={input} />);
|
||||
});
|
||||
const grid = await screen.findByRole("grid");
|
||||
grid.scrollLeft = 180;
|
||||
fireEvent.scroll(grid);
|
||||
view.unmount();
|
||||
await act(async () => {
|
||||
render(<TableEditor input={input} />);
|
||||
});
|
||||
expect((await screen.findByRole("grid")).scrollLeft).toBe(180);
|
||||
});
|
||||
|
||||
it("queries with the sort it had when its tab mounts again", async () => {
|
||||
const input = tableInput("source", "default", "users");
|
||||
let view!: ReturnType<typeof render>;
|
||||
|
||||
@@ -176,6 +176,15 @@ const SCHEMES: Record<string, string> = {
|
||||
|
||||
export const vendorOfScheme = (scheme: string): DbVendor | undefined => BY_ID.get(SCHEMES[scheme.toLowerCase()] ?? "");
|
||||
|
||||
/**
|
||||
* The dialect a custom JDBC source's URL speaks (`jdbc:oracle:thin:@//db:1521/ORCL` → `oracle`):
|
||||
* its `driver: "jdbc"` says nothing about how the server folds identifiers.
|
||||
*/
|
||||
export function jdbcDialect(url: string | null | undefined): DbDriver | null {
|
||||
const scheme = /^(?:jdbc:)?([a-z][a-z0-9]*):/i.exec((url ?? "").trim())?.[1] ?? "";
|
||||
return vendorOfScheme(scheme)?.driver ?? null;
|
||||
}
|
||||
|
||||
const bracketed = (host: string) => (host.includes(":") && !host.startsWith("[") ? `[${host}]` : host);
|
||||
|
||||
/** The JDBC URL of a data source's fields (the General tab's URL preview). */
|
||||
|
||||
@@ -10,7 +10,15 @@ import {
|
||||
updateBreakpoint,
|
||||
useBreakpoints,
|
||||
} from "../breakpoints/store";
|
||||
import { adoptSession, useExecutionPoint, useDebug, handleDebugEvent, type DebugSession } from "../state";
|
||||
import {
|
||||
adoptSession,
|
||||
selectSession,
|
||||
stopTarget,
|
||||
useExecutionPoint,
|
||||
useDebug,
|
||||
handleDebugEvent,
|
||||
type DebugSession,
|
||||
} from "../state";
|
||||
import { getContext } from "@/platform/context";
|
||||
import styles from "../editor/editor.module.css";
|
||||
|
||||
@@ -314,6 +322,23 @@ describe("session events", () => {
|
||||
expect(getContext().debugSessionActive).toBe(false);
|
||||
});
|
||||
|
||||
it("enables Stop for the selected session tab only (#4738)", () => {
|
||||
adoptSession(80, { name: "server" });
|
||||
adoptSession(81, { name: "client" });
|
||||
selectSession(80);
|
||||
expect(getContext().debugCanStop).toBe(true);
|
||||
expect(stopTarget()?.id).toBe(80);
|
||||
handleDebugEvent(81, { kind: "terminated" });
|
||||
selectSession(81);
|
||||
// The finished session's tab: Stop is off although the server still runs.
|
||||
expect(getContext().debugSessionActive).toBe(true);
|
||||
expect(getContext().debugCanStop).toBe(false);
|
||||
expect(stopTarget()).toBeNull();
|
||||
selectSession(80);
|
||||
expect(getContext().debugCanStop).toBe(true);
|
||||
handleDebugEvent(80, { kind: "terminated" });
|
||||
});
|
||||
|
||||
it("ignores sessions this window did not start, but adopts children of its own", async () => {
|
||||
vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
adoptSession(90, { name: "app", adapter: "js-debug" });
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { expressionAt } from "../editor/valueTooltip";
|
||||
|
||||
/** The expression around the `|` in `line`. */
|
||||
function at(line: string, calls: boolean) {
|
||||
const pos = line.indexOf("|");
|
||||
const view = new EditorView({ state: EditorState.create({ doc: line.replace("|", "") }) });
|
||||
const text = expressionAt(view, pos, { calls })?.text ?? null;
|
||||
view.destroy();
|
||||
return text;
|
||||
}
|
||||
|
||||
describe("expression at the mouse for Quick Evaluate (#4772)", () => {
|
||||
it("takes the call of the clicked method, arguments included", () => {
|
||||
expect(at("String n = vo.getChd|rnum();", true)).toBe("vo.getChdrnum()");
|
||||
expect(at('x = f|(a, g(b), "c)");', true)).toBe('f(a, g(b), "c)")');
|
||||
expect(at("x = list.g|et (i);", true)).toBe("list.get (i)");
|
||||
});
|
||||
|
||||
it("follows member chains through calls and indexing to the clicked member", () => {
|
||||
expect(at("a.getB().c|()", true)).toBe("a.getB().c()");
|
||||
expect(at("a.get|B().c()", true)).toBe("a.getB()");
|
||||
expect(at("items[i + 1].na|me", true)).toBe("items[i + 1].name");
|
||||
expect(at("a.b()[0].c|", true)).toBe("a.b()[0].c");
|
||||
});
|
||||
|
||||
it("leaves an unbalanced call as the bare member", () => {
|
||||
expect(at("vo.getChd|rnum(a,", true)).toBe("vo.getChdrnum");
|
||||
});
|
||||
|
||||
it("keeps plain hovers free of calls", () => {
|
||||
expect(at("String n = vo.getChd|rnum();", false)).toBe("vo.getChdrnum");
|
||||
expect(at("a.getB().c|()", false)).toBe("c");
|
||||
});
|
||||
});
|
||||
@@ -91,7 +91,7 @@ describe("paused editor evaluation", () => {
|
||||
view.dispatch({ selection: { anchor: 0, head: 5 } });
|
||||
expect(click().defaultPrevented).toBe(true);
|
||||
await vi.waitFor(() => expect(document.querySelector(".cm-lsp-hint")?.textContent).toContain("order.items = 42"));
|
||||
expect(ipc.debugEvaluateIn).toHaveBeenCalledExactlyOnceWith(7, 10, "order.items", "hover");
|
||||
expect(ipc.debugEvaluateIn).toHaveBeenCalledExactlyOnceWith(7, 10, "order.items", "watch");
|
||||
expect(view.state.selection.main.head).toBe(16);
|
||||
});
|
||||
|
||||
@@ -101,7 +101,7 @@ describe("paused editor evaluation", () => {
|
||||
session();
|
||||
view.dispatch({ selection: { anchor: 0, head: doc.length } });
|
||||
click();
|
||||
await vi.waitFor(() => expect(ipc.debugEvaluateIn).toHaveBeenCalledWith(7, 10, doc, "hover"));
|
||||
await vi.waitFor(() => expect(ipc.debugEvaluateIn).toHaveBeenCalledWith(7, 10, doc, "watch"));
|
||||
expect(view.state.selection.main.from).toBe(0);
|
||||
expect(view.state.selection.main.to).toBe(doc.length);
|
||||
await vi.waitFor(() =>
|
||||
@@ -114,7 +114,24 @@ describe("paused editor evaluation", () => {
|
||||
const text = "(total +\n order.items)";
|
||||
view.dispatch({ changes: { from: 0, to: doc.length, insert: text }, selection: { anchor: 0, head: text.length } });
|
||||
click();
|
||||
await vi.waitFor(() => expect(ipc.debugEvaluateIn).toHaveBeenCalledWith(7, 10, text, "hover"));
|
||||
await vi.waitFor(() => expect(ipc.debugEvaluateIn).toHaveBeenCalledWith(7, 10, text, "watch"));
|
||||
});
|
||||
|
||||
it("ignores an object response that arrives after the debugger resumes", async () => {
|
||||
session();
|
||||
view.dispatch({ selection: { anchor: 16 } });
|
||||
type Response = Awaited<ReturnType<typeof ipc.debugEvaluateIn>>;
|
||||
let reply!: (result: Response) => void;
|
||||
ipc.debugEvaluateIn.mockImplementationOnce(() => new Promise((resolve) => (reply = resolve)));
|
||||
const evaluating = executeAction("debug.quickEvaluate");
|
||||
await vi.waitFor(() => expect(ipc.debugEvaluateIn).toHaveBeenCalledOnce());
|
||||
useDebug.setState((s) => ({ sessions: { 7: { ...s.sessions[7]!, status: "running" } } }));
|
||||
reply({
|
||||
status: "ok",
|
||||
data: { name: "order.items", value: "Array(2)", typeName: "Array", variablesReference: 5, evaluateName: null },
|
||||
});
|
||||
await evaluating;
|
||||
expect(document.querySelector(".cm-lsp-hint")).toBeNull();
|
||||
});
|
||||
|
||||
it("lets a higher priority custom mouse action win the shared gesture", () => {
|
||||
|
||||
@@ -70,19 +70,35 @@ it.each([undefined, true, false])(
|
||||
);
|
||||
|
||||
it.each(["breakpoint", "function breakpoint", "exception", "pause"])(
|
||||
"reveals an in-place session on suspend (%s)",
|
||||
"reveals an in-place session in Services on suspend (%s)",
|
||||
async (reason) => {
|
||||
const show = vi.fn();
|
||||
provideToolWindowService({ show } as unknown as ToolWindowService);
|
||||
await startSession(config("launch"), { show: false });
|
||||
expect(show).not.toHaveBeenCalled();
|
||||
handleDebugEvent(42, { kind: "stopped", threadId: 1, reason, description: null, allThreadsStopped: true });
|
||||
expect(show).toHaveBeenCalledWith("debug");
|
||||
// Services shows the session's debugger in place (#4773).
|
||||
expect(show).toHaveBeenCalledExactlyOnceWith("services");
|
||||
expect(useDebug.getState().active).toBe(42);
|
||||
expect(useDebug.getState().sessions[42]).toMatchObject({ status: "paused", selectedThread: 1 });
|
||||
},
|
||||
);
|
||||
|
||||
it("reveals a session started elsewhere in the Debug tool window on suspend", async () => {
|
||||
const show = vi.fn();
|
||||
provideToolWindowService({ show } as unknown as ToolWindowService);
|
||||
await startSession(config("launch"));
|
||||
show.mockClear();
|
||||
handleDebugEvent(42, {
|
||||
kind: "stopped",
|
||||
threadId: 1,
|
||||
reason: "breakpoint",
|
||||
description: null,
|
||||
allThreadsStopped: true,
|
||||
});
|
||||
expect(show).toHaveBeenCalledExactlyOnceWith("debug");
|
||||
});
|
||||
|
||||
it.each(["launch", "attach"])("awaits every file before %s can send configurationDone", async (request) => {
|
||||
const completed: string[] = [];
|
||||
const release: Array<() => void> = [];
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Variable } from "@/platform/ipc";
|
||||
import { valueText } from "../valueText";
|
||||
import { stringText, valueText } from "../valueText";
|
||||
|
||||
const v = (name: string, value: string, variablesReference = 0): Variable =>
|
||||
({ name, value, variablesReference, typeName: null, evaluateName: null }) as Variable;
|
||||
@@ -39,3 +39,15 @@ describe("valueText", () => {
|
||||
expect(text).toBe("r\n a: x\n b: y\n …");
|
||||
});
|
||||
});
|
||||
|
||||
describe("stringText (#4747)", () => {
|
||||
it("shows a quoted string as its text, escapes resolved", () => {
|
||||
expect(stringText('"Name: app\\nPort: \\"3306\\"\\tok\\\\"')).toBe('Name: app\nPort: "3306"\tok\\');
|
||||
expect(stringText("'it\\'s'")).toBe("it's");
|
||||
expect(stringText('"caf\\u00e9 \\x41 \\u{1F600}"')).toBe("café A 😀");
|
||||
});
|
||||
|
||||
it("leaves anything that isn't one quoted literal alone", () => {
|
||||
for (const value of ["42", "[]string len: 2", '"a" + "b', "Foo@12"]) expect(stringText(value)).toBe(value);
|
||||
});
|
||||
});
|
||||
@@ -79,12 +79,13 @@ import {
|
||||
startPreparedSession,
|
||||
stopSession,
|
||||
stopAssociatedProcess,
|
||||
stopTarget,
|
||||
useDebug,
|
||||
type DebugSession,
|
||||
} from "./state";
|
||||
import { focusedDebugView } from "./ui/focusedView";
|
||||
import { browseFocusedConsoleHistory } from "./ui/expressionHistory";
|
||||
import { expressionAt, valueHint } from "./editor/valueTooltip";
|
||||
import { expressionAt, showQuickValue } from "./editor/valueTooltip";
|
||||
import { mouseEvaluateTarget } from "./editor/quickEvaluate";
|
||||
import { showHint } from "@/editor/lsp/hint";
|
||||
import { pausedLineTargets, startInlineSmartStep } from "./editor/smartStep";
|
||||
@@ -207,24 +208,37 @@ function evaluateSeed(view: EditorView | undefined = activeEditor()?.view, pos?:
|
||||
const { state } = view;
|
||||
const sel = state.selection.main;
|
||||
if (!sel.empty && (pos == null || (sel.from <= pos && pos <= sel.to))) return state.sliceDoc(sel.from, sel.to);
|
||||
return expressionAt(view, pos ?? sel.head)?.text ?? "";
|
||||
return expressionAt(view, pos ?? sel.head, { calls: true })?.text ?? "";
|
||||
}
|
||||
|
||||
async function quickEvaluate(arg?: unknown) {
|
||||
const target = mouseEvaluateTarget(arg);
|
||||
const view = target?.view ?? activeEditor()?.view;
|
||||
if (!view) return;
|
||||
const sel = view.state.selection.main;
|
||||
const pos = target?.pos ?? sel.from;
|
||||
const { doc, selection } = view.state;
|
||||
const pos = target?.pos ?? selection.main.from;
|
||||
const expression = evaluateSeed(view, target?.pos).trim();
|
||||
if (!expression) return showHint(view, "Nothing to evaluate at the caret");
|
||||
const session = activeSession();
|
||||
const stop = useDebug.getState().stopSeq;
|
||||
const stillCurrent = () => {
|
||||
const current = activeSession();
|
||||
return (
|
||||
view.dom.isConnected &&
|
||||
view.state.doc === doc &&
|
||||
view.state.selection.eq(selection) &&
|
||||
current?.status === "paused" &&
|
||||
current.id === session?.id &&
|
||||
current.selectedFrame === session?.selectedFrame &&
|
||||
useDebug.getState().stopSeq === stop
|
||||
);
|
||||
};
|
||||
try {
|
||||
const value = await evaluate(expression, "hover", session);
|
||||
if (!session) return;
|
||||
showHint(view, () => valueHint(expression, value, session.id), { pos, timeout: 60_000 });
|
||||
// Unlike a plain hover, an explicit Quick Evaluate may call methods (adapters refuse that for "hover").
|
||||
const value = await evaluate(expression, "watch", session);
|
||||
if (session && stillCurrent()) showQuickValue(view, pos, expression, value, session.id);
|
||||
} catch (e) {
|
||||
showHint(view, e instanceof Error ? e.message : String(e), { pos, tone: "error" });
|
||||
if (stillCurrent()) showHint(view, e instanceof Error ? e.message : String(e), { pos, tone: "error" });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -560,9 +574,9 @@ export function registerDebugActions(): () => void {
|
||||
title: "Stop",
|
||||
category: "Debug",
|
||||
icon: "stop",
|
||||
when: "debugSessionActive",
|
||||
when: "debugCanStop",
|
||||
run: () => {
|
||||
const s = activeSession() ?? Object.values(useDebug.getState().sessions).find(isLive);
|
||||
const s = stopTarget();
|
||||
if (s) void stopSession(s.id);
|
||||
},
|
||||
},
|
||||
|
||||
@@ -180,9 +180,22 @@
|
||||
word-break: break-word;
|
||||
}
|
||||
.valueTooltipTree {
|
||||
padding: 2px 0;
|
||||
display: flex;
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
width: min(460px, calc(var(--debug-value-editor-width, 100vw) - var(--space-2)));
|
||||
max-width: 100%;
|
||||
height: min(260px, 50vh);
|
||||
padding: 0;
|
||||
font-family: var(--font-ui);
|
||||
white-space: normal;
|
||||
}
|
||||
:global(.cm-lsp-hint):has(> .valueTooltipTree) {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.valueExpand {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -19,8 +19,45 @@ import styles from "./editor.module.css";
|
||||
const BASE_HOVER = 100;
|
||||
const IDENT = /[\p{L}\p{N}_$]/u;
|
||||
|
||||
/** Identifier (with `a.b.c` member access) around `pos`, or the selection containing it. */
|
||||
export function expressionAt(view: EditorView, pos: number): { from: number; to: number; text: string } | null {
|
||||
const OPEN: Record<string, string> = { ")": "(", "]": "[" };
|
||||
const CLOSE: Record<string, string> = { "(": ")", "[": "]" };
|
||||
|
||||
/** Index just past the bracket group opening at `i` (strings skipped), or -1 when it doesn't close on the line. */
|
||||
function closeOf(t: string, i: number): number {
|
||||
const stack: string[] = [];
|
||||
for (let j = i; j < t.length; j++) {
|
||||
const c = t[j]!;
|
||||
if (c === '"' || c === "'" || c === "`") {
|
||||
j++;
|
||||
while (j < t.length && t[j] !== c) j += t[j] === "\\" ? 2 : 1;
|
||||
if (j >= t.length) return -1;
|
||||
} else if (CLOSE[c]) stack.push(CLOSE[c]);
|
||||
else if (c === ")" || c === "]") {
|
||||
if (stack.pop() !== c) return -1;
|
||||
if (!stack.length) return j + 1;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** Index of the bracket opening the group that closes at `i - 1`, or -1. */
|
||||
function openOf(t: string, i: number): number {
|
||||
for (let start = i - 1; start >= 0; start--) {
|
||||
if (t[start] === OPEN[t[i - 1]!] && closeOf(t, start) === i) return start;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Identifier (with `a.b.c` member access) around `pos`, or the selection containing it. With
|
||||
* `calls`, as for Quick Evaluate: member chains through calls and indexing (`a.getB().c`,
|
||||
* `items[i].name`) and the call of the identifier itself (`o.getX()`, `f(a, b)`).
|
||||
*/
|
||||
export function expressionAt(
|
||||
view: EditorView,
|
||||
pos: number,
|
||||
{ calls = false } = {},
|
||||
): { from: number; to: number; text: string } | null {
|
||||
const { state } = view;
|
||||
const sel = state.selection.main;
|
||||
if (!sel.empty && pos >= sel.from && pos <= sel.to) {
|
||||
@@ -33,7 +70,25 @@ export function expressionAt(view: EditorView, pos: number): { from: number; to:
|
||||
let end = start;
|
||||
if (!IDENT.test(t[end] ?? "") && !IDENT.test(t[start - 1] ?? "")) return null;
|
||||
while (end < t.length && IDENT.test(t[end]!)) end++;
|
||||
while (start > 0 && (IDENT.test(t[start - 1]!) || (t[start - 1] === "." && IDENT.test(t[start - 2] ?? "")))) start--;
|
||||
for (;;) {
|
||||
while (start > 0 && IDENT.test(t[start - 1]!)) start--;
|
||||
if (t[start - 1] === "." && IDENT.test(t[start - 2] ?? "")) start--;
|
||||
else if (calls && t[start - 1] === "." && OPEN[t[start - 2] ?? ""]) {
|
||||
let open = openOf(t, start - 1);
|
||||
// `a.b()[0].c`: walk back over every group, then the name they follow.
|
||||
while (open > 0 && OPEN[t[open - 1]!]) open = openOf(t, open);
|
||||
if (open <= 0 || !IDENT.test(t[open - 1]!)) break;
|
||||
start = open;
|
||||
} else break;
|
||||
}
|
||||
if (calls) {
|
||||
let next = end;
|
||||
while (t[next] === " ") next++;
|
||||
if (t[next] === "(") {
|
||||
const close = closeOf(t, next);
|
||||
if (close > 0) end = close;
|
||||
}
|
||||
}
|
||||
const text = t.slice(start, end);
|
||||
if (!text || /^\d/.test(text)) return null;
|
||||
return { from: line.from + start, to: line.from + end, text };
|
||||
@@ -95,6 +150,17 @@ export function valueHint(
|
||||
return { dom, destroy: () => tree?.unmount() };
|
||||
}
|
||||
|
||||
export function showQuickValue(
|
||||
view: EditorView,
|
||||
pos: number,
|
||||
expression: string,
|
||||
value: Variable,
|
||||
session: DebugSessionId,
|
||||
) {
|
||||
if (value.variablesReference > 0) showValueTree(view, pos, expression, value, session);
|
||||
else showHint(view, () => valueHint(expression, value, session), { pos, timeout: 60_000 });
|
||||
}
|
||||
|
||||
export function valueTooltip(): Extension {
|
||||
return hoverTooltip(
|
||||
async (view, pos) => {
|
||||
@@ -123,13 +189,7 @@ export function valueTooltip(): Extension {
|
||||
// The tree outgrows the hint and may move to the other side of the line, away from the
|
||||
// mouse, which closed the hover tooltip before it could be reached. Like IDEA's value
|
||||
// popup it stays until Escape, a click in the editor or the next step.
|
||||
pin: () => {
|
||||
view.dispatch({ effects: closeHoverTooltips });
|
||||
showHint(view, () => pinnedTree(view, expr.text, value, session.id), {
|
||||
pos: expr.from,
|
||||
timeout: null,
|
||||
});
|
||||
},
|
||||
pin: () => showValueTree(view, expr.from, expr.text, value, session.id),
|
||||
}),
|
||||
};
|
||||
},
|
||||
@@ -137,6 +197,11 @@ export function valueTooltip(): Extension {
|
||||
);
|
||||
}
|
||||
|
||||
function showValueTree(view: EditorView, pos: number, expression: string, value: Variable, session: DebugSessionId) {
|
||||
view.dispatch({ effects: closeHoverTooltips });
|
||||
showHint(view, () => pinnedTree(view, expression, value, session), { pos, timeout: null });
|
||||
}
|
||||
|
||||
/** An expanded value tree, closed when its session leaves the stop it was evaluated in. */
|
||||
function pinnedTree(view: EditorView, expression: string, value: Variable, session: DebugSessionId) {
|
||||
const stop = useDebug.getState().stopSeq;
|
||||
@@ -144,6 +209,20 @@ function pinnedTree(view: EditorView, expression: string, value: Variable, sessi
|
||||
if (s.stopSeq !== stop || s.sessions[session]?.status !== "paused") hideHint(view);
|
||||
});
|
||||
const hint = valueHint(expression, value, session, 400, { expanded: true });
|
||||
let width = 0;
|
||||
let resizeFrame = 0;
|
||||
const updateWidth = () => {
|
||||
const next = view.dom.clientWidth;
|
||||
if (!next || next === width) return;
|
||||
width = next;
|
||||
hint.dom.style.setProperty("--debug-value-editor-width", `${width}px`);
|
||||
};
|
||||
updateWidth();
|
||||
const resize = new ResizeObserver(() => {
|
||||
cancelAnimationFrame(resizeFrame);
|
||||
resizeFrame = requestAnimationFrame(updateWidth);
|
||||
});
|
||||
resize.observe(view.dom);
|
||||
// The tree has the focus, so the editor's Escape doesn't reach the hint.
|
||||
hint.dom.addEventListener("keydown", (e) => {
|
||||
if (e.key !== "Escape" || e.defaultPrevented) return;
|
||||
@@ -154,6 +233,8 @@ function pinnedTree(view: EditorView, expression: string, value: Variable, sessi
|
||||
return {
|
||||
dom: hint.dom,
|
||||
destroy: () => {
|
||||
resize.disconnect();
|
||||
cancelAnimationFrame(resizeFrame);
|
||||
unsubscribe();
|
||||
hint.destroy();
|
||||
},
|
||||
|
||||
@@ -79,6 +79,7 @@ function useLiveSessionCount(): number | null {
|
||||
export function activate(): () => void {
|
||||
useDebugRunSessions.setState({
|
||||
Console: lazyComponent(() => import("./ui/DebugConsole").then((m) => m.DebugServiceConsole)),
|
||||
View: lazyComponent(() => import("./ui/DebugToolWindow").then((m) => m.DebugServiceView)),
|
||||
});
|
||||
loadWatches(useProject.getState().project?.root ?? null);
|
||||
publishContext();
|
||||
@@ -88,7 +89,7 @@ export function activate(): () => void {
|
||||
loadJsBreakpoints(useProject.getState().project?.root ?? null);
|
||||
loadResponseOverrides(useProject.getState().project?.root ?? null);
|
||||
const disposers = [
|
||||
() => useDebugRunSessions.setState({ sessions: [], serviceSessions: [], Console: null }),
|
||||
() => useDebugRunSessions.setState({ sessions: [], serviceSessions: [], Console: null, View: null }),
|
||||
registerDebugActions(),
|
||||
registerDebugTabActions(),
|
||||
registerDevToolsWindows(),
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
maybeEditorService,
|
||||
notifications,
|
||||
runOutput,
|
||||
SERVICES_WINDOW,
|
||||
toolWindowService,
|
||||
useDebugRunSessions,
|
||||
} from "@/workbench/contributions";
|
||||
@@ -77,6 +78,8 @@ export interface DebugSession {
|
||||
process: RunId | null;
|
||||
/** Pinned tab (root sessions): once finished, a later session opens a new tab instead of taking its place. */
|
||||
pinned?: boolean;
|
||||
/** Started in place from the Services tool window (root sessions): its stops show it there, not in the Debug window. */
|
||||
inPlace?: boolean;
|
||||
status: SessionStatus;
|
||||
stoppedThread: number | null;
|
||||
stopReason: string | null;
|
||||
@@ -197,6 +200,13 @@ export function isLive(s: DebugSession | null | undefined): boolean {
|
||||
return !!s && s.status !== "terminated";
|
||||
}
|
||||
|
||||
/** The session the Debug tool window's Stop acts on: the selected one while it runs (any live one when none is selected). */
|
||||
export function stopTarget(): DebugSession | null {
|
||||
const s = activeSession();
|
||||
if (s) return isLive(s) ? s : null;
|
||||
return Object.values(useDebug.getState().sessions).find(isLive) ?? null;
|
||||
}
|
||||
|
||||
/** Whether the session with this id is still there and running, as of now. */
|
||||
export const isLiveSession = (id: DebugSessionId) => isLive(useDebug.getState().sessions[id]);
|
||||
|
||||
@@ -405,6 +415,8 @@ export function publishContext() {
|
||||
});
|
||||
const anyLive = Object.values(useDebug.getState().sessions).some(isLive);
|
||||
setContext("debugSessionActive", anyLive);
|
||||
// Stop acts on the selected session tab, so a finished one doesn't stop another session.
|
||||
setContext("debugCanStop", !!stopTarget());
|
||||
setContext("debugSessionRunning", s?.status === "running");
|
||||
setContext("debugSessionPaused", s?.status === "paused");
|
||||
// Dart and Flutter sessions: Hot Reload / Hot Restart.
|
||||
@@ -711,6 +723,7 @@ export async function startPreparedSession(
|
||||
adapter: config.debugAdapter ?? "",
|
||||
runConfig: config,
|
||||
pinned,
|
||||
inPlace: options.show === false,
|
||||
}),
|
||||
},
|
||||
console: { ...s.console, [id]: [] },
|
||||
@@ -812,6 +825,7 @@ export async function startSession(
|
||||
launch: options.rerunnable === false ? null : launch,
|
||||
process: options.process ?? null,
|
||||
pinned: preparation ? preparation.pinned : pinned,
|
||||
inPlace: options.show === false,
|
||||
status: cur.status === "starting" ? "running" : cur.status,
|
||||
},
|
||||
},
|
||||
@@ -975,13 +989,12 @@ export async function rerunSession(id: DebugSessionId, options: { show?: boolean
|
||||
if (!root.runConfig && !launch) return;
|
||||
if (isLive(root)) await stopSession(root.id);
|
||||
rerunOf = root.id;
|
||||
// A session debugged in place from Services reruns there too.
|
||||
const show = options.show ?? (root.inPlace ? false : undefined);
|
||||
try {
|
||||
if (root.runConfig)
|
||||
await executeAction(
|
||||
"run.debugConfig",
|
||||
options.show === false ? { config: root.runConfig, show: false } : root.runConfig,
|
||||
);
|
||||
else await startSession(launch!, { show: options.show });
|
||||
await executeAction("run.debugConfig", show === false ? { config: root.runConfig, show: false } : root.runConfig);
|
||||
else await startSession(launch!, { show });
|
||||
} finally {
|
||||
rerunOf = null;
|
||||
}
|
||||
@@ -1355,7 +1368,8 @@ export function handleDebugEvent(id: DebugSessionId, event: DebugEvent) {
|
||||
void loadFrames(id, event.threadId, !markTraceStop(id, event.threadId, s.stops + 1));
|
||||
const dbg = workflowSettings().debugger;
|
||||
try {
|
||||
if (dbg.showOnBreakpoint) toolWindowService().show("debug");
|
||||
// A session debugged in place from Services shows its debugger there (#4773).
|
||||
if (dbg.showOnBreakpoint) toolWindowService().show(rootOf(s).inPlace ? SERVICES_WINDOW : "debug");
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
@@ -353,3 +353,15 @@
|
||||
border-bottom: 0;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.serviceView {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.serviceView > * {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Debug tool window: toolbar, Threads & Variables (frames + variables), Console. */
|
||||
import { writeClipboardText } from "@/platform/clipboard";
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { basename, useProject } from "@/platform/project";
|
||||
@@ -173,7 +173,35 @@ export function DebugTabs() {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Services › a configuration being debugged: the same debugger as the Debug tool window, for
|
||||
* that session (#4773). `console` replaces the Console tab, e.g. with the console of the run the
|
||||
* debugger is attached to.
|
||||
*/
|
||||
export function DebugServiceView({ sessionId, console: consolePane }: { sessionId: number; console?: ReactNode }) {
|
||||
const shown = useDebug((s) => {
|
||||
const active = s.active != null ? s.sessions[s.active] : undefined;
|
||||
return !!active && rootOf(active).id === sessionId;
|
||||
});
|
||||
useEffect(() => {
|
||||
if (useDebug.getState().sessions[sessionId]) selectSession(sessionId);
|
||||
}, [sessionId]);
|
||||
// The toolbar acts on the active session: using this view makes its session the active one again.
|
||||
const reselect = () => {
|
||||
if (!shown && useDebug.getState().sessions[sessionId]) selectSession(sessionId);
|
||||
};
|
||||
return (
|
||||
<div className={styles.serviceView} onPointerDownCapture={reselect} onFocusCapture={reselect}>
|
||||
{shown && <DebugView consolePane={consolePane} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DebugToolWindow() {
|
||||
return <DebugView />;
|
||||
}
|
||||
|
||||
function DebugView({ consolePane }: { consolePane?: ReactNode }) {
|
||||
const tx = useTx();
|
||||
const active = useDebug((s) => (s.active != null ? s.sessions[s.active] : undefined));
|
||||
const muted = useBreakpoints((s) => s.muted);
|
||||
@@ -314,7 +342,7 @@ export function DebugToolWindow() {
|
||||
) : tab === "network" ? (
|
||||
<NetworkView key={active.id} session={active.id} />
|
||||
) : (
|
||||
<DebugConsole key={active.id} session={active} />
|
||||
(consolePane ?? <DebugConsole key={active.id} session={active} />)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -175,8 +175,9 @@
|
||||
/* Expanded value hint in the editor. */
|
||||
.hint {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
width: 460px;
|
||||
height: 260px;
|
||||
min-height: 0;
|
||||
padding-block: var(--space-1);
|
||||
}
|
||||
@@ -12,15 +12,17 @@ import { methodAt } from "../breakpoints/symbols";
|
||||
import {
|
||||
activeSession,
|
||||
addWatch,
|
||||
evaluate,
|
||||
removeAllWatches,
|
||||
removeWatch,
|
||||
revealFrame,
|
||||
sessionSupports,
|
||||
setVariableValue,
|
||||
useDebug,
|
||||
} from "../state";
|
||||
import { blurDebugView, focusDebugView } from "./focusedView";
|
||||
import { classifyValue, oneLine, shownValue, sortVariables } from "../values";
|
||||
import { valueText } from "../valueText";
|
||||
import { stringText, valueText } from "../valueText";
|
||||
import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import styles from "./VariablesView.module.css";
|
||||
|
||||
@@ -282,7 +284,14 @@ export function VariablesView({
|
||||
|
||||
const copyValue = async (node: VarNode) => {
|
||||
let text = node.value;
|
||||
if (session != null && node.reference > 0) {
|
||||
const paused = session != null ? useDebug.getState().sessions[session] : undefined;
|
||||
if (paused?.status === "paused" && node.reference <= 0 && node.evaluateName) {
|
||||
// A long string arrives cut short; evaluating it for the clipboard returns all of it.
|
||||
text = await evaluate(node.evaluateName, "clipboard", paused).then(
|
||||
(v) => v.value || text,
|
||||
() => text,
|
||||
);
|
||||
} else if (session != null && node.reference > 0) {
|
||||
try {
|
||||
text = await valueText(node, (ref) => call(commands.debugVariables(session, ref)));
|
||||
} catch (e) {
|
||||
@@ -383,15 +392,44 @@ export function VariablesView({
|
||||
)
|
||||
}
|
||||
/>
|
||||
{valuePopup && <ValueDialog node={valuePopup} onClose={() => setValuePopup(null)} />}
|
||||
{valuePopup && <ValueDialog node={valuePopup} session={session} onClose={() => setValuePopup(null)} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ValueDialog({ node, onClose }: { node: VarNode; onClose: () => void }) {
|
||||
/**
|
||||
* View: the whole value in a popup that a click outside closes. Adapters cut long strings
|
||||
* short in variables; the value is evaluated again as for copying (`clipboard`), which
|
||||
* returns it in full, and a string shows as its text, line breaks included.
|
||||
*/
|
||||
function ValueDialog({
|
||||
node,
|
||||
session,
|
||||
onClose,
|
||||
}: {
|
||||
node: VarNode;
|
||||
session: DebugSessionId | null;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [value, setValue] = useState(node.value);
|
||||
useEffect(() => {
|
||||
const s = session != null ? useDebug.getState().sessions[session] : undefined;
|
||||
if (!s || s.status !== "paused" || !node.evaluateName || node.reference > 0) return;
|
||||
let live = true;
|
||||
evaluate(node.evaluateName, "clipboard", s).then(
|
||||
(v) => live && v.value && setValue(v.value),
|
||||
() => {},
|
||||
);
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [node, session]);
|
||||
const text = classifyValue(value, node.typeName) === "string" ? stringText(value) : value;
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
popup
|
||||
dismissOnBackdrop
|
||||
onClose={onClose}
|
||||
title={`${node.name}${node.typeName ? ` {${node.typeName}}` : ""}`}
|
||||
width={720}
|
||||
@@ -401,7 +439,7 @@ function ValueDialog({ node, onClose }: { node: VarNode; onClose: () => void })
|
||||
aria-label={formatMessage(tx("Value of {label}"), { label: node.name })}
|
||||
>
|
||||
<div className={styles.valuePopupContent}>
|
||||
<pre className={styles.valuePopupValue}>{node.value}</pre>
|
||||
<pre className={styles.valuePopupValue}>{text}</pre>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
@@ -51,3 +51,22 @@ export async function valueText(
|
||||
await walk(root.reference, 1);
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
const ESCAPES: Record<string, string> = { n: "\n", r: "\r", t: "\t", b: "\b", f: "\f", v: "\v", "0": "\0" };
|
||||
|
||||
/**
|
||||
* A string value as its text (the View popup): a quoted literal (`"a\nb"`, Python's `'a'`)
|
||||
* loses its quotes and has its escapes resolved, so line breaks show as lines. Anything
|
||||
* else, or a literal the adapter cut short, is returned as it came.
|
||||
*/
|
||||
export function stringText(value: string): string {
|
||||
const m = /^(["'])([\s\S]*)\1$/.exec(value);
|
||||
if (!m) return value;
|
||||
return m[2]!.replace(/\\(u\{[0-9a-fA-F]+\}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|.)/g, (all, e: string) => {
|
||||
if (e[0] === "u" || e[0] === "x") {
|
||||
const code = parseInt(e.replace(/^[ux]\{?|\}$/g, ""), 16);
|
||||
return Number.isNaN(code) ? all : String.fromCodePoint(code);
|
||||
}
|
||||
return ESCAPES[e] ?? e;
|
||||
});
|
||||
}
|
||||
@@ -39,8 +39,10 @@ function TrustDialog() {
|
||||
return (
|
||||
<Dialog
|
||||
open={!!path}
|
||||
icon="app"
|
||||
width={560}
|
||||
icon="warning"
|
||||
width={600}
|
||||
className={styles.trustDialog}
|
||||
blockWorkbenchShortcuts
|
||||
title="Trust and Open Project?"
|
||||
onClose={() => void executeAction("project.dontOpen")}
|
||||
buttons={[
|
||||
@@ -49,8 +51,12 @@ function TrustDialog() {
|
||||
autoFocus: true,
|
||||
onClick: () => void executeAction("project.previewRestricted"),
|
||||
},
|
||||
{ label: "Don't Open", onClick: () => void executeAction("project.dontOpen") },
|
||||
{ label: "Trust Project", role: "default", onClick: () => void executeAction("project.trust") },
|
||||
{ label: "Don't Open", role: "cancel" },
|
||||
{
|
||||
label: folder ? "Trust Folder" : "Trust Project",
|
||||
role: "default",
|
||||
onClick: () => void executeAction("project.trust"),
|
||||
},
|
||||
]}
|
||||
footerStart={
|
||||
<Checkbox
|
||||
@@ -68,17 +74,17 @@ function TrustDialog() {
|
||||
/>
|
||||
}
|
||||
>
|
||||
<div className={styles.content}>
|
||||
<div className={styles.promptContent}>
|
||||
<PathLine path={path ?? ""} />
|
||||
<p>
|
||||
<T>Loading, running or building a project may execute potentially malicious code from its build scripts.</T>
|
||||
</p>
|
||||
<p className={styles.restrictedPreview}>
|
||||
<T>
|
||||
If you don't trust the source, preview the project in Restricted Mode, where project commands and tools
|
||||
can't run.
|
||||
</T>
|
||||
</p>
|
||||
<p>
|
||||
<T>Loading, running or building a project may execute potentially malicious code from its build scripts.</T>
|
||||
</p>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
|
||||
@@ -6,14 +6,27 @@
|
||||
.content p {
|
||||
margin: 0;
|
||||
}
|
||||
.promptContent {
|
||||
composes: content;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
.promptContent > .pathLine {
|
||||
padding: var(--space-1) var(--space-2);
|
||||
background: var(--bg-elev);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-small);
|
||||
color: var(--fg-secondary);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.restrictedPreview {
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
.pathLine {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.content > .pathLine {
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
.pathHead {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
@@ -26,15 +39,31 @@
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.folderOption {
|
||||
max-width: 100%;
|
||||
align-items: flex-start;
|
||||
width: 100%;
|
||||
}
|
||||
.folderLabel {
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
flex-direction: column;
|
||||
gap: var(--space-0-5);
|
||||
min-width: 0;
|
||||
}
|
||||
.folderPrefix {
|
||||
flex: none;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.folderLabel > .pathLine {
|
||||
color: var(--fg-secondary);
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.trustDialog [data-dialog-footer] button {
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
min-height: var(--h-button);
|
||||
height: auto;
|
||||
padding-block: var(--space-1);
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.banner {
|
||||
display: flex;
|
||||
|
||||
@@ -115,7 +115,7 @@ it("saves the parent-folder choice and reuses a persisted decision", async () =>
|
||||
const opening = confirmProjectTrust("/projects/new");
|
||||
await screen.findByRole("dialog");
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: /Trust projects in/ }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Trust Project" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Trust Folder" }));
|
||||
await act(async () => opening);
|
||||
expect(decide).toHaveBeenCalledWith("/projects/new", true, true);
|
||||
status.mockResolvedValue({ status: "ok", data: { trusted: true, decided: true } });
|
||||
@@ -140,7 +140,7 @@ it("shows and trusts the canonical folder when opening through a symlink", async
|
||||
const opening = confirmProjectTrust("/aliases/new");
|
||||
await screen.findByRole("dialog");
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: /Trust projects in \/real\/projects/ }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Trust Project" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Trust Folder" }));
|
||||
await act(async () => opening);
|
||||
expect(decide).toHaveBeenCalledWith("/real/projects/new", true, true);
|
||||
});
|
||||
|
||||
@@ -757,7 +757,7 @@ function RunDetail({ item }: { item: ServiceTreeItem }) {
|
||||
// Re-render on session changes.
|
||||
useRun((s) => s.sessions);
|
||||
const debugViews = useDebugRunSessions();
|
||||
const Console = debugViews.Console;
|
||||
const { Console, View } = debugViews;
|
||||
const t = useT();
|
||||
const txTemplate = useTxTemplate();
|
||||
const r = resolve(item);
|
||||
@@ -773,11 +773,14 @@ function RunDetail({ item }: { item: ServiceTreeItem }) {
|
||||
);
|
||||
// The configuration ran: its console, as in the Run tool window. Run / Debug / Stop
|
||||
// come from this window's toolbar (the selection), so the console strip leaves them out.
|
||||
if (r.session?.run) {
|
||||
const execution = r.session;
|
||||
return <SessionPanel key={execution.run!.id} session={execution.run!} showLifecycle={false} />;
|
||||
}
|
||||
const execution = r.session?.run;
|
||||
const runConsole = execution && <SessionPanel key={execution.id} session={execution} showLifecycle={false} />;
|
||||
const d = r.session?.debug[0];
|
||||
// Being debugged: the whole debugger in place, as in IDEA's Services (#4773); the console of a
|
||||
// run the debugger is attached to stays its Console tab.
|
||||
if (d && View && (d.status !== "terminated" || !execution))
|
||||
return <View key={d.id} sessionId={d.id} console={runConsole} />;
|
||||
if (runConsole) return runConsole;
|
||||
if (d && Console)
|
||||
return (
|
||||
<div className={styles.debugConsole}>
|
||||
|
||||
@@ -1,31 +1,36 @@
|
||||
.popup {
|
||||
width: 280px;
|
||||
width: 320px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
.body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
outline: none;
|
||||
padding-bottom: 4px;
|
||||
min-height: 0;
|
||||
padding-bottom: var(--space-1);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
.header {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: var(--h-row);
|
||||
padding: 0 10px;
|
||||
font-size: var(--fs-small);
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.title {
|
||||
flex: 1;
|
||||
padding: var(--space-2) var(--space-3) var(--space-1);
|
||||
color: var(--fg-strong);
|
||||
line-height: 1.4;
|
||||
}
|
||||
.search {
|
||||
margin: 0 8px 4px;
|
||||
flex: none;
|
||||
margin: 0 var(--space-2) var(--space-1);
|
||||
border-bottom: 1px solid var(--border-popup);
|
||||
}
|
||||
.list {
|
||||
max-height: 360px;
|
||||
height: auto;
|
||||
max-height: calc(20 * var(--h-list-row) + var(--space-2));
|
||||
}
|
||||
.divider {
|
||||
width: 100%;
|
||||
height: 1px;
|
||||
background: var(--border-popup);
|
||||
}
|
||||
.row {
|
||||
display: flex;
|
||||
@@ -35,11 +40,15 @@
|
||||
flex: 1;
|
||||
}
|
||||
.label {
|
||||
min-width: 0;
|
||||
color: var(--fg-emphasis);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.icon {
|
||||
flex: none;
|
||||
}
|
||||
.active .label {
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import { useId, useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
import { HighlightedText, Icon, List, Popup, SearchField, fileIconName, listNavigate, T } from "@/ui";
|
||||
import { chooserRows, type LanguageRow, type ScratchLanguage } from "./model";
|
||||
@@ -6,6 +6,8 @@ import { closeChooser, rememberLanguage, useScratch } from "./store";
|
||||
import { createScratch } from "./scratches";
|
||||
import styles from "./ScratchChooser.module.css";
|
||||
|
||||
const isDivider = (row: LanguageRow | null) => row === null;
|
||||
|
||||
/** Overlay: IDEA's "New Scratch File" popup — searchable languages, recent first. */
|
||||
export function ScratchChooserHost() {
|
||||
const languages = useScratch((s) => s.languages);
|
||||
@@ -17,13 +19,22 @@ export function ScratchChooserHost() {
|
||||
function ScratchChooser({ languages }: { languages: readonly ScratchLanguage[] }) {
|
||||
const recent = useScratch((s) => s.recent);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const listId = useId();
|
||||
const [filter, setFilter] = useState("");
|
||||
const [active, setActive] = useState(0);
|
||||
const rows = useMemo(() => chooserRows(languages, recent, filter), [languages, recent, filter]);
|
||||
const rows = useMemo(() => {
|
||||
const options = chooserRows(languages, recent, filter);
|
||||
if (filter.trim()) return options;
|
||||
const firstOther = options.findIndex(({ lang }) => !recent.includes(lang.id));
|
||||
return firstOther > 0 ? [...options.slice(0, firstOther), null, ...options.slice(firstOther)] : options;
|
||||
}, [languages, recent, filter]);
|
||||
const current = Math.min(active, rows.length - 1);
|
||||
const anchor = useMemo(() => ({ x: Math.max(16, window.innerWidth / 2 - 140), y: window.innerHeight / 5 }), []);
|
||||
const anchor = useMemo(
|
||||
() => ({ getBoundingClientRect: () => new DOMRect(window.innerWidth / 2, window.innerHeight / 5, 0, 0) }),
|
||||
[],
|
||||
);
|
||||
|
||||
const pick = (row: LanguageRow | undefined) => {
|
||||
const pick = (row: LanguageRow | null | undefined) => {
|
||||
if (!row) return;
|
||||
closeChooser();
|
||||
rememberLanguage(row.lang.id);
|
||||
@@ -35,6 +46,7 @@ function ScratchChooser({ languages }: { languages: readonly ScratchLanguage[] }
|
||||
const next = listNavigate(e.key === "Home" || e.key === "End" ? "" : e.key, {
|
||||
items: rows,
|
||||
active: current,
|
||||
isSection: isDivider,
|
||||
wrap: true,
|
||||
});
|
||||
if (next !== null) {
|
||||
@@ -50,7 +62,7 @@ function ScratchChooser({ languages }: { languages: readonly ScratchLanguage[] }
|
||||
<Popup
|
||||
open
|
||||
anchor={anchor}
|
||||
placement="bottom-start"
|
||||
placement="bottom"
|
||||
onClose={closeChooser}
|
||||
role="dialog"
|
||||
aria-label="New Scratch File"
|
||||
@@ -58,9 +70,7 @@ function ScratchChooser({ languages }: { languages: readonly ScratchLanguage[] }
|
||||
>
|
||||
<div className={styles.body}>
|
||||
<div className={styles.header}>
|
||||
<span className={styles.title}>
|
||||
<T>New Scratch File</T>
|
||||
</span>
|
||||
<T>New Scratch File</T>
|
||||
</div>
|
||||
<SearchField
|
||||
ref={inputRef}
|
||||
@@ -69,6 +79,8 @@ function ScratchChooser({ languages }: { languages: readonly ScratchLanguage[] }
|
||||
value={filter}
|
||||
placeholder="Filter languages"
|
||||
aria-label="Filter languages"
|
||||
aria-controls={listId}
|
||||
aria-activedescendant={rows[current] ? `${listId}-${current}` : undefined}
|
||||
className={styles.search}
|
||||
onChange={(value) => {
|
||||
setFilter(value);
|
||||
@@ -78,11 +90,15 @@ function ScratchChooser({ languages }: { languages: readonly ScratchLanguage[] }
|
||||
onKeyDown={onKeyDown}
|
||||
/>
|
||||
<List
|
||||
id={listId}
|
||||
items={rows}
|
||||
getKey={(r) => r.lang.id}
|
||||
getKey={(r) => (r ? `language:${r.lang.id}` : "recent-divider")}
|
||||
activeIndex={current}
|
||||
onActiveChange={setActive}
|
||||
onActivate={(r) => pick(r)}
|
||||
onActivate={pick}
|
||||
isSection={isDivider}
|
||||
sectionHeight={8}
|
||||
renderSection={() => <span role="separator" className={styles.divider} />}
|
||||
focusable={false}
|
||||
hoverSelects
|
||||
className={styles.list}
|
||||
@@ -92,14 +108,16 @@ function ScratchChooser({ languages }: { languages: readonly ScratchLanguage[] }
|
||||
<T>No matching languages</T>
|
||||
</div>
|
||||
}
|
||||
renderItem={(r, state) => (
|
||||
<div className={clsx(styles.row, state.active && styles.active)} data-language={r.lang.id}>
|
||||
<Icon name={fileIconName(`scratch.${r.lang.ext}`)} size={16} />
|
||||
<span className={styles.label}>
|
||||
<HighlightedText text={r.lang.name} indices={r.matches ?? undefined} />
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
renderItem={(r, state) =>
|
||||
r && (
|
||||
<div className={clsx(styles.row, state.active && styles.active)} data-language={r.lang.id}>
|
||||
<Icon name={fileIconName(`scratch.${r.lang.ext}`)} size={16} className={styles.icon} />
|
||||
<span className={styles.label} title={r.lang.name}>
|
||||
<HighlightedText text={r.lang.name} indices={r.matches ?? undefined} />
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</Popup>
|
||||
|
||||
@@ -14,6 +14,7 @@ import { GlobListEditor, Row, Section, Select, Toggle } from "../components/Form
|
||||
import { choosePath } from "@/platform/choosePath";
|
||||
import { usePageContext, useSetting } from "../components/context";
|
||||
import { SdkField, tildify, useDetected, useJdtlsJdk } from "./components";
|
||||
import { isMavenThreadCount } from "./mavenThreads";
|
||||
import styles from "./Sdk.module.css";
|
||||
|
||||
function PathInput({
|
||||
@@ -566,6 +567,7 @@ export function MavenPage() {
|
||||
const [downloadSources, setDownloadSources] = useSetting<boolean>("languages.java.maven.downloadSources");
|
||||
const [updateSnapshots, setUpdateSnapshots] = useSetting<boolean>("languages.java.maven.updateSnapshots");
|
||||
const [threads, setThreads] = useSetting<string>("languages.java.maven.threads");
|
||||
const threadsInvalid = !!threads?.trim() && !isMavenThreadCount(threads);
|
||||
const [activeProfiles, setActiveProfiles] = useSetting<string>("languages.java.maven.activeProfiles");
|
||||
const id = useId();
|
||||
return (
|
||||
@@ -651,12 +653,24 @@ export function MavenPage() {
|
||||
<Row
|
||||
label="Thread count"
|
||||
htmlFor={id}
|
||||
hint="Passed as -T to Maven builds and run configurations: a thread count (4) or a core multiplier (2C, 2.5C) for parallel builds of multi-module projects. Empty runs Maven serially."
|
||||
hint={
|
||||
threadsInvalid ? (
|
||||
<span className={styles.error} role="alert">
|
||||
<T>
|
||||
Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C,
|
||||
2.5C).
|
||||
</T>
|
||||
</span>
|
||||
) : (
|
||||
"Passed as -T to Maven builds and run configurations: a thread count (4) or a core multiplier (2C, 2.5C) for parallel builds of multi-module projects. Empty runs Maven serially."
|
||||
)
|
||||
}
|
||||
>
|
||||
<span className={styles.pathRow}>
|
||||
<Input
|
||||
id={id}
|
||||
mono
|
||||
invalid={threadsInvalid}
|
||||
className={styles.pathInput}
|
||||
value={threads}
|
||||
placeholder="4, 2C"
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { isMavenThreadCount } from "./mavenThreads";
|
||||
|
||||
it("accepts the -T values Maven takes and nothing else (#4743)", () => {
|
||||
for (const ok of ["4", "1C", "2.5C", "0.5C", " 8 "]) expect(isMavenThreadCount(ok), ok).toBe(true);
|
||||
for (const bad of ["0", "0C", "-2", "2c", "2.C", ".5C", "2.5.1C", "four", "4 threads", "C"])
|
||||
expect(isMavenThreadCount(bad), bad).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Whether Maven accepts `value` as `-T`: a thread count (`4`) or a core multiplier with an
|
||||
* optional decimal fraction (`1C`, `2.5C`). Mirrors `MavenSettings::thread_count`, which
|
||||
* leaves any other value out of the command line.
|
||||
*/
|
||||
export function isMavenThreadCount(value: string): boolean {
|
||||
return /^(?:\d+(?:\.\d+)?)C?$/.test(value.trim()) && parseFloat(value) > 0;
|
||||
}
|
||||
@@ -1,58 +1,56 @@
|
||||
.popup {
|
||||
min-width: 320px;
|
||||
max-width: min(720px, 80vw);
|
||||
--hunk-surface-width: min(720px, var(--hunk-popup-width), calc(100vw - var(--space-4)));
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: max-content;
|
||||
overflow: hidden;
|
||||
}
|
||||
.toolbar {
|
||||
flex: none;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5);
|
||||
height: 28px;
|
||||
padding: 0 4px;
|
||||
border-bottom: 1px solid var(--border-popup);
|
||||
align-self: flex-start;
|
||||
max-width: var(--hunk-surface-width);
|
||||
gap: var(--space-0-5) var(--space-1);
|
||||
padding: var(--space-1) var(--space-2);
|
||||
background: var(--bg-popup);
|
||||
border: 1px solid var(--border-popup);
|
||||
border-radius: var(--radius-small);
|
||||
}
|
||||
.toolbar:has(+ .preview) {
|
||||
border-bottom: 0;
|
||||
border-end-start-radius: 0;
|
||||
border-end-end-radius: 0;
|
||||
}
|
||||
.title {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
padding: 0 8px;
|
||||
min-width: 0;
|
||||
padding-inline: var(--space-1);
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
white-space: nowrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.counter {
|
||||
color: var(--fg-faint);
|
||||
}
|
||||
.body {
|
||||
.preview {
|
||||
max-width: var(--hunk-surface-width);
|
||||
min-height: 0;
|
||||
max-height: 280px;
|
||||
margin: 0;
|
||||
padding: var(--space-1) var(--space-2) var(--space-1) 0;
|
||||
overflow: auto;
|
||||
padding: 4px 0;
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-code);
|
||||
line-height: var(--lh-code);
|
||||
-webkit-user-select: text;
|
||||
user-select: text;
|
||||
}
|
||||
.removed,
|
||||
.added {
|
||||
padding: 0 12px 0 4px;
|
||||
overscroll-behavior: contain;
|
||||
white-space: pre;
|
||||
color: var(--fg);
|
||||
background: color-mix(in srgb, var(--gutter-deleted) 12%, var(--bg-editor));
|
||||
border: 1px solid var(--border-popup);
|
||||
border-radius: 0 var(--radius-small) var(--radius-small) var(--radius-small);
|
||||
}
|
||||
.removed {
|
||||
background: color-mix(in srgb, var(--gutter-deleted) 14%, transparent);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.added {
|
||||
background: color-mix(in srgb, var(--gutter-added) 16%, transparent);
|
||||
}
|
||||
.sign {
|
||||
display: inline-block;
|
||||
width: 16px;
|
||||
color: var(--fg-faint);
|
||||
-webkit-user-select: none;
|
||||
user-select: none;
|
||||
.preview:focus-visible {
|
||||
outline: 2px solid var(--focus-ring);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
/** Inline change popup shown when clicking a gutter change marker. */
|
||||
import { writeClipboardText } from "@/platform/clipboard";
|
||||
import { useState } from "react";
|
||||
import { useEffect, useState, type CSSProperties } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { IconButton, Popup } from "@/ui";
|
||||
import { previewColors, tokenSpans, type CodeToken } from "@/editor/lineTokens";
|
||||
import { IconButton, Popup, selectableText } from "@/ui";
|
||||
import type { PopupAnchor } from "@/ui/Popup";
|
||||
import { editorHunks, gotoChange, setHunkPopupHooks, type EditorHunk } from "./gutter";
|
||||
import styles from "./HunkPopup.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
@@ -14,8 +16,8 @@ interface PopupState {
|
||||
view: EditorView;
|
||||
hunk: EditorHunk;
|
||||
path: string;
|
||||
x: number;
|
||||
y: number;
|
||||
anchor: PopupAnchor;
|
||||
width: number;
|
||||
id: number;
|
||||
}
|
||||
|
||||
@@ -42,13 +44,25 @@ export function closeHunkPopup() {
|
||||
|
||||
export function openHunkPopup(view: EditorView, hunk: EditorHunk, path: string) {
|
||||
const doc = view.state.doc;
|
||||
const endPos = hunk.to > hunk.from ? Math.max(hunk.from, hunk.to - 1) : Math.min(hunk.from, doc.length);
|
||||
const coords = view.coordsAtPos(doc.lineAt(endPos).from);
|
||||
const gutterRect = view.dom.querySelector(".cm-openidea-lane")?.getBoundingClientRect();
|
||||
const x = gutterRect ? gutterRect.right : (coords?.left ?? 0);
|
||||
const y = coords ? (hunk.to > hunk.from ? coords.bottom : coords.top) : 0;
|
||||
const from = Math.min(hunk.from, doc.length);
|
||||
const to = Math.min(Math.max(from, hunk.to - 1), doc.length);
|
||||
const anchor = {
|
||||
contextElement: view.scrollDOM,
|
||||
getBoundingClientRect: () => {
|
||||
const start = view.coordsAtPos(from);
|
||||
const visible = view.scrollDOM.getBoundingClientRect();
|
||||
const gutter = view.dom.querySelector(".cm-openidea-lane")?.getBoundingClientRect();
|
||||
const x = Math.max(start?.left ?? visible.left, gutter?.right ?? visible.left);
|
||||
const top = view.documentTop + view.lineBlockAt(from).top;
|
||||
const bottom = hunk.to > hunk.from ? view.documentTop + view.lineBlockAt(to).bottom : top;
|
||||
const clampY = (y: number) => Math.min(visible.bottom, Math.max(visible.top, y));
|
||||
// Flipping above the change leaves the current lines in the editor visible.
|
||||
return new DOMRect(x, clampY(top), 0, Math.max(0, clampY(bottom) - clampY(top)));
|
||||
},
|
||||
};
|
||||
const width = Math.max(240, view.scrollDOM.getBoundingClientRect().right - anchor.getBoundingClientRect().left);
|
||||
openFor = view;
|
||||
render({ view, hunk, path, x, y, id: ++seq });
|
||||
render({ view, hunk, path, anchor, width, id: ++seq });
|
||||
}
|
||||
|
||||
export function installHunkPopup(): () => void {
|
||||
@@ -67,21 +81,40 @@ export function installHunkPopup(): () => void {
|
||||
};
|
||||
}
|
||||
|
||||
function splitLines(text: string): string[] {
|
||||
if (!text) return [];
|
||||
const lines = text.split("\n");
|
||||
if (lines[lines.length - 1] === "") lines.pop();
|
||||
return lines;
|
||||
}
|
||||
|
||||
const KIND_TITLE = { added: "Added lines", modified: "Modified lines", deleted: "Deleted lines" } as const;
|
||||
|
||||
function OriginalText({ view, path, text }: { view: EditorView; path: string; text: string }) {
|
||||
const [tokens, setTokens] = useState<CodeToken[] | null>(null);
|
||||
const [font] = useState(() => {
|
||||
const { fontFamily, fontSize, fontWeight, lineHeight, fontVariantLigatures } = getComputedStyle(view.contentDOM);
|
||||
return { fontFamily, fontSize, fontWeight, lineHeight, fontVariantLigatures, tabSize: view.state.tabSize };
|
||||
});
|
||||
useEffect(() => {
|
||||
if (text.length > 100_000) return;
|
||||
let alive = true;
|
||||
void previewColors(text, path).then((colorize) => {
|
||||
if (alive && colorize) setTokens(colorize(0, text.length));
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [text, path]);
|
||||
return (
|
||||
<pre
|
||||
role="region"
|
||||
aria-label={tx("Original text")}
|
||||
tabIndex={0}
|
||||
className={`${styles.preview} ${selectableText}`}
|
||||
style={font}
|
||||
>
|
||||
{tokenSpans(text, 0, text.length, tokens)}
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
|
||||
function HunkPopupView({ state }: { state: PopupState }) {
|
||||
const { view, hunk, path } = state;
|
||||
const [copied, setCopied] = useState(false);
|
||||
const current = view.state.sliceDoc(hunk.from, hunk.to);
|
||||
const oldLines = splitLines(hunk.oldText);
|
||||
const newLines = splitLines(current);
|
||||
const all = editorHunks(view.state);
|
||||
const index = all.findIndex((h) => h.start === hunk.start && h.oldStart === hunk.oldStart);
|
||||
|
||||
@@ -97,7 +130,7 @@ function HunkPopupView({ state }: { state: PopupState }) {
|
||||
};
|
||||
|
||||
const step = (dir: 1 | -1) => {
|
||||
const target = gotoChange(view, dir);
|
||||
const target = gotoChange(view, dir, hunk.from);
|
||||
if (target) requestAnimationFrame(() => openHunkPopup(view, target, path));
|
||||
else closeHunkPopup();
|
||||
};
|
||||
@@ -105,12 +138,14 @@ function HunkPopupView({ state }: { state: PopupState }) {
|
||||
return (
|
||||
<Popup
|
||||
open
|
||||
anchor={{ x: state.x, y: state.y }}
|
||||
anchor={state.anchor}
|
||||
placement="bottom-start"
|
||||
offset={2}
|
||||
onClose={closeHunkPopup}
|
||||
aria-label={KIND_TITLE[hunk.kind]}
|
||||
aria-label={tx(KIND_TITLE[hunk.kind])}
|
||||
className={styles.popup}
|
||||
style={{ "--hunk-popup-width": `${state.width}px` } as CSSProperties}
|
||||
unstyled
|
||||
>
|
||||
<div className={styles.toolbar} role="toolbar" aria-label={tx("Change actions")}>
|
||||
<IconButton
|
||||
@@ -152,26 +187,7 @@ function HunkPopupView({ state }: { state: PopupState }) {
|
||||
</span>
|
||||
<IconButton icon="close" title="Close" size="small" onClick={closeHunkPopup} />
|
||||
</div>
|
||||
{(oldLines.length > 0 || newLines.length > 0) && (
|
||||
<div className={styles.body}>
|
||||
{oldLines.map((l, i) => (
|
||||
<div key={`o${i}`} className={styles.removed}>
|
||||
<span className={styles.sign} aria-hidden>
|
||||
-
|
||||
</span>
|
||||
{l || " "}
|
||||
</div>
|
||||
))}
|
||||
{newLines.map((l, i) => (
|
||||
<div key={`n${i}`} className={styles.added}>
|
||||
<span className={styles.sign} aria-hidden>
|
||||
+
|
||||
</span>
|
||||
{l || " "}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{hunk.oldText && <OriginalText view={view} path={path} text={hunk.oldText} />}
|
||||
</Popup>
|
||||
);
|
||||
}
|
||||
@@ -8,13 +8,6 @@
|
||||
.resizable {
|
||||
min-width: 0;
|
||||
}
|
||||
.sidebar {
|
||||
flex: none;
|
||||
width: 260px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-right: 1px solid var(--border);
|
||||
}
|
||||
.header {
|
||||
flex: none;
|
||||
height: var(--h-header);
|
||||
@@ -77,12 +70,6 @@
|
||||
.deletedPath {
|
||||
text-decoration: line-through;
|
||||
}
|
||||
.diff {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.message {
|
||||
padding: var(--space-4);
|
||||
color: var(--fg-faint);
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
.dialog [data-dialog-body] {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.content {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
min-height: 0;
|
||||
padding: var(--space-2) var(--space-4) 0;
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
|
||||
.content .tree {
|
||||
flex: 1 1 260px;
|
||||
height: auto;
|
||||
min-height: var(--h-row);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.summary {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1) var(--space-3);
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
|
||||
.added {
|
||||
color: var(--vcs-added);
|
||||
}
|
||||
|
||||
.modified {
|
||||
color: var(--vcs-modified);
|
||||
}
|
||||
|
||||
.deleted {
|
||||
color: var(--vcs-deleted);
|
||||
}
|
||||
|
||||
.warning {
|
||||
margin: 0;
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
@@ -1,18 +1,56 @@
|
||||
.range {
|
||||
flex: none;
|
||||
min-width: 0;
|
||||
max-width: min(60%, 52ch);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.summary,
|
||||
.meta {
|
||||
.table {
|
||||
--list-inset: var(--space-1);
|
||||
--history-columns: minmax(56px, 9%) minmax(68px, 18%) minmax(56px, 18%) minmax(0, 1fr);
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.columns {
|
||||
display: grid;
|
||||
grid-template-columns: var(--history-columns);
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
.heading {
|
||||
flex: none;
|
||||
min-height: var(--h-row);
|
||||
padding-inline: calc(var(--list-inset) + var(--space-2));
|
||||
border-bottom: 1px solid var(--border);
|
||||
color: var(--fg-muted);
|
||||
font-size: var(--fs-small);
|
||||
overflow: hidden;
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
.heading::-webkit-scrollbar {
|
||||
width: 10px;
|
||||
}
|
||||
.list {
|
||||
flex: 1;
|
||||
scrollbar-gutter: stable;
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
.cell {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.summary {
|
||||
color: var(--fg-emphasis);
|
||||
}
|
||||
.meta {
|
||||
.cell[role="gridcell"]:not(:last-child) {
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.cell[role="gridcell"]:nth-child(-n + 2) {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { BlockHistory, BlockRevision } from "@/bindings";
|
||||
import { call, commands, isCancelled, nextRequestId } from "@/platform/ipc";
|
||||
import { List, Spinner, T } from "@/ui";
|
||||
import { List, Spinner, SplitGroup, SplitHandle, SplitPanel, T } from "@/ui";
|
||||
import type { EditorInput } from "@/workbench/contributions";
|
||||
import { DiffEditor } from "./DiffEditor";
|
||||
import { diffInput, type DiffSide } from "./diffInput";
|
||||
@@ -23,6 +23,7 @@ export type HistoryRow =
|
||||
| { kind: "revision"; revision: BlockRevision };
|
||||
|
||||
const HEAD = "HEAD";
|
||||
const COLUMNS = ["Revision", "Date", "Author", "Message"] as const;
|
||||
|
||||
/** Lines `from..=to` of `text`, each ending with a line break (as Git prints a block). */
|
||||
export function blockOf(text: string, [from, to]: readonly [number, number]): string {
|
||||
@@ -78,6 +79,7 @@ export function SelectionHistoryEditor({ input }: { input: EditorInput }) {
|
||||
const rows = history ? historyRows(history, blockOf(data.text, data.lines)) : [];
|
||||
const current = rows[Math.min(active, rows.length - 1)];
|
||||
const [from, to] = data.lines;
|
||||
const range = `${baseName(data.path)}:${from + 1}-${to + 1}`;
|
||||
|
||||
let detail;
|
||||
if (!current)
|
||||
@@ -97,13 +99,23 @@ export function SelectionHistoryEditor({ input }: { input: EditorInput }) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={layout.root}>
|
||||
<div className={layout.sidebar}>
|
||||
<SplitGroup
|
||||
className={`${layout.root} ${layout.resizable}`}
|
||||
orientation="vertical"
|
||||
storageKey="openidea.selectionHistory.layout"
|
||||
>
|
||||
<SplitPanel id="selection-preview" defaultSize="50%" minSize="25%">
|
||||
{detail}
|
||||
</SplitPanel>
|
||||
<SplitHandle aria-label={tx("Revisions")} />
|
||||
<SplitPanel id="selection-revisions" defaultSize="50%" minSize="25%">
|
||||
<div className={layout.header}>
|
||||
<span className={layout.title}>
|
||||
<T>History for Selection</T>
|
||||
</span>
|
||||
<span className={styles.range}>{`${baseName(data.path)}:${from + 1}-${to + 1}`}</span>
|
||||
<span className={styles.range} title={range}>
|
||||
{range}
|
||||
</span>
|
||||
</div>
|
||||
{error ? (
|
||||
<div className={layout.message}>{error}</div>
|
||||
@@ -112,43 +124,60 @@ export function SelectionHistoryEditor({ input }: { input: EditorInput }) {
|
||||
<Spinner size={14} />
|
||||
</div>
|
||||
) : (
|
||||
<List
|
||||
items={rows}
|
||||
getKey={(row) => (row.kind === "local" ? "local" : row.revision.id)}
|
||||
activeIndex={Math.min(active, rows.length - 1)}
|
||||
onActiveChange={setActive}
|
||||
onActivate={(_row, i) => setActive(i)}
|
||||
rowHeight={38}
|
||||
aria-label="Revisions"
|
||||
className={layout.list}
|
||||
empty={
|
||||
<span className={layout.message}>
|
||||
{history.headLines ? tx`No commits changed these lines` : tx`These lines are not committed yet`}
|
||||
</span>
|
||||
}
|
||||
renderItem={(row) =>
|
||||
row.kind === "local" ? (
|
||||
<span className={layout.entry}>
|
||||
<span className={styles.summary}>
|
||||
<T>Local Changes</T>
|
||||
</span>
|
||||
<span className={styles.meta}>
|
||||
<T>Not Committed Yet</T>
|
||||
</span>
|
||||
<div
|
||||
className={styles.table}
|
||||
role="grid"
|
||||
aria-label={tx("Revisions")}
|
||||
aria-colcount={COLUMNS.length}
|
||||
aria-rowcount={rows.length + 1}
|
||||
>
|
||||
<div role="row" aria-rowindex={1} className={`${styles.columns} ${styles.heading}`}>
|
||||
{COLUMNS.map((label) => (
|
||||
<span key={label} role="columnheader" className={styles.cell}>
|
||||
<T>{label}</T>
|
||||
</span>
|
||||
) : (
|
||||
<span className={layout.entry}>
|
||||
<span className={styles.summary}>{row.revision.summary}</span>
|
||||
<span className={styles.meta}>
|
||||
{`${row.revision.shortId} · ${row.revision.author} · ${formatTime(row.revision.timeMs)}`}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<List
|
||||
items={rows}
|
||||
getKey={(row) => (row.kind === "local" ? "local" : row.revision.id)}
|
||||
activeIndex={Math.min(active, rows.length - 1)}
|
||||
onActiveChange={setActive}
|
||||
onActivate={(_row, i) => setActive(i)}
|
||||
tableBody={{ headerRows: 1 }}
|
||||
className={styles.list}
|
||||
empty={
|
||||
<span className={layout.message}>
|
||||
{history.headLines ? tx`No commits changed these lines` : tx`These lines are not committed yet`}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
/>
|
||||
}
|
||||
renderItem={(row) => {
|
||||
const revision = row.kind === "revision" ? row.revision : null;
|
||||
const cells = [
|
||||
revision?.shortId ?? "",
|
||||
formatTime(revision?.timeMs),
|
||||
revision?.author ?? "",
|
||||
revision?.summary ?? tx("Local Changes"),
|
||||
];
|
||||
return (
|
||||
<span role="none" className={styles.columns}>
|
||||
{cells.map((value, i) => (
|
||||
<span
|
||||
key={COLUMNS[i]}
|
||||
role="gridcell"
|
||||
className={styles.cell}
|
||||
title={value && (!revision ? tx("Not Committed Yet") : value)}
|
||||
>
|
||||
{value}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className={layout.diff}>{detail}</div>
|
||||
</div>
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import type { BlockHistory, BlockRevision } from "@/bindings";
|
||||
|
||||
@@ -108,7 +108,12 @@ describe("History for Selection tab", () => {
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId("diff").textContent).toBe("bbbbbbb^: two\nthree\n| bbbbbbb: TWO\nthree\n"),
|
||||
);
|
||||
expect(screen.getByText(/^bbbbbbb · Ada · /)).toBeTruthy();
|
||||
const row = screen.getByRole("row", { name: /bbbbbbb.*Ada.*Shout two/ });
|
||||
expect(
|
||||
within(row)
|
||||
.getAllByRole("gridcell")
|
||||
.map((cell) => cell.textContent),
|
||||
).toEqual(["bbbbbbb", expect.any(String), "Ada", "Shout two"]);
|
||||
});
|
||||
|
||||
it("says why there is nothing to show", async () => {
|
||||
|
||||
@@ -19,6 +19,7 @@ import { showCompareRevisions } from "./operations";
|
||||
import { FileChecklist } from "./shelf";
|
||||
import { currentRepo, loadStashes, refreshNow, useVcs } from "./store";
|
||||
import styles from "./common.module.css";
|
||||
import rollbackStyles from "./RollbackDialog.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
export function firstLine(message: string): string {
|
||||
@@ -219,9 +220,14 @@ export function showRollbackDialog(files: FileStatus[]) {
|
||||
function RollbackDialog({ files, onClose }: { files: FileStatus[]; onClose: () => void }) {
|
||||
const [selected, setSelected] = useState(() => new Set(files.map((f) => f.path)));
|
||||
const [deleteAdded, setDeleteAdded] = useState(false);
|
||||
const hasAdded = files.some((f) => f.staged === "added");
|
||||
const chosen = files.filter((f) => selected.has(f.path));
|
||||
const counts = { added: 0, modified: 0, deleted: 0 };
|
||||
for (const file of chosen) {
|
||||
const kind = effectiveKind(file);
|
||||
counts[kind === "added" || kind === "deleted" ? kind : "modified"]++;
|
||||
}
|
||||
const { added, modified, deleted } = counts;
|
||||
const run = async () => {
|
||||
const chosen = files.filter((f) => selected.has(f.path));
|
||||
onClose();
|
||||
if (!chosen.length) return;
|
||||
await saveAll();
|
||||
@@ -240,24 +246,40 @@ function RollbackDialog({ files, onClose }: { files: FileStatus[]; onClose: () =
|
||||
open
|
||||
title="Rollback Changes"
|
||||
onClose={onClose}
|
||||
width={520}
|
||||
footerStart={
|
||||
hasAdded && (
|
||||
<Checkbox checked={deleteAdded} onChange={setDeleteAdded} label="Delete local copies of added files" />
|
||||
)
|
||||
}
|
||||
className={rollbackStyles.dialog}
|
||||
width={540}
|
||||
minWidth={320}
|
||||
minHeight={240}
|
||||
resizable="both"
|
||||
buttons={[
|
||||
{ label: "Rollback", role: "default", autoFocus: true, disabled: !selected.size, onClick: () => void run() },
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
{ label: "Rollback", role: "default", disabled: !chosen.length, onClick: () => void run() },
|
||||
{ label: "Close", role: "cancel" },
|
||||
]}
|
||||
>
|
||||
<div className={styles.section}>
|
||||
{files.length === 1
|
||||
? tx`${selected.size} of ${files.length} file will be reverted to their last committed state. Uncommitted changes are lost.`
|
||||
: tx`${selected.size} of ${files.length} files will be reverted to their last committed state. Uncommitted changes are lost.`}
|
||||
<div className={rollbackStyles.content}>
|
||||
<FileChecklist
|
||||
files={files}
|
||||
selected={selected}
|
||||
onChange={setSelected}
|
||||
label="Files to roll back"
|
||||
className={rollbackStyles.tree}
|
||||
/>
|
||||
<div className={rollbackStyles.summary} role="status">
|
||||
{!chosen.length && <T>No files selected</T>}
|
||||
{added > 0 && <span className={rollbackStyles.added}>{tx`${added} added`}</span>}
|
||||
{modified > 0 && <span className={rollbackStyles.modified}>{tx`${modified} modified`}</span>}
|
||||
{deleted > 0 && <span className={rollbackStyles.deleted}>{tx`${deleted} deleted`}</span>}
|
||||
</div>
|
||||
<Checkbox
|
||||
checked={added > 0 && deleteAdded}
|
||||
disabled={!added}
|
||||
onChange={setDeleteAdded}
|
||||
label="Delete local copies of added files"
|
||||
/>
|
||||
<p className={rollbackStyles.warning}>
|
||||
<T>Rollback discards uncommitted changes in the selected files.</T>
|
||||
</p>
|
||||
</div>
|
||||
<FileChecklist files={files} selected={selected} onChange={setSelected} label="Files to roll back" />
|
||||
<div style={{ height: 12 }} />
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -278,11 +278,14 @@ export function changeMarkers(ctx: EditorDocContext): Extension {
|
||||
}
|
||||
|
||||
/** Moves the caret to the next / previous change in `view`. Returns whether it moved. */
|
||||
export function gotoChange(view: EditorView, dir: 1 | -1): EditorHunk | undefined {
|
||||
export function gotoChange(
|
||||
view: EditorView,
|
||||
dir: 1 | -1,
|
||||
from = view.state.selection.main.head,
|
||||
): EditorHunk | undefined {
|
||||
const hunks = editorHunks(view.state);
|
||||
if (!hunks.length) return undefined;
|
||||
const head = view.state.selection.main.head;
|
||||
const lineFrom = view.state.doc.lineAt(head).from;
|
||||
const lineFrom = view.state.doc.lineAt(from).from;
|
||||
const sorted = [...hunks].sort((a, b) => a.from - b.from);
|
||||
let target: EditorHunk | undefined;
|
||||
if (dir === 1) target = sorted.find((h) => h.from > lineFrom && view.state.doc.lineAt(h.from).from > lineFrom);
|
||||
@@ -292,7 +295,7 @@ export function gotoChange(view: EditorView, dir: 1 | -1): EditorHunk | undefine
|
||||
.find(
|
||||
(h) =>
|
||||
view.state.doc.lineAt(Math.min(h.from, view.state.doc.length)).from < lineFrom &&
|
||||
!(h.from <= head && head < h.to),
|
||||
!(h.from <= from && from < h.to),
|
||||
);
|
||||
target ??= dir === 1 ? sorted[0] : sorted[sorted.length - 1];
|
||||
if (!target) return undefined;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { isMacHost } from "@/platform/keymap";
|
||||
import { Icon, IconButton, SearchField, type MenuItem } from "@/ui";
|
||||
import clsx from "clsx";
|
||||
import { useContext, useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
@@ -251,11 +252,18 @@ export function FilterBar() {
|
||||
onOpen: (anchor: HTMLElement) =>
|
||||
menuBelow(
|
||||
anchor,
|
||||
repositories.map((repo) => ({
|
||||
label: repoName(repo),
|
||||
checked: filters.repositories?.includes(repo) ?? false,
|
||||
run: () => setLogFilters({ repositories: toggleRepository(filters.repositories, repo) }),
|
||||
})),
|
||||
repositories.map((repo) => {
|
||||
const name = repoName(repo);
|
||||
const modifier = isMacHost() ? "⌘" : "Ctrl";
|
||||
return {
|
||||
label: name,
|
||||
verbatim: true,
|
||||
checked: filters.repositories?.includes(repo) ?? false,
|
||||
run: () => setLogFilters({ repositories: toggleRepository(filters.repositories, repo) }),
|
||||
runWithModifier: () => setLogFilters({ repositories: [repo] }),
|
||||
hint: tx`${modifier}+Click to only see "${name}"`,
|
||||
};
|
||||
}),
|
||||
),
|
||||
onClear: () => setLogFilters({ repositories: [] }),
|
||||
},
|
||||
|
||||
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача