дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
330eae539f | ||
|
|
5fe061bedd |
No files matched your search
Створено
+47
-46
@@ -2637,6 +2637,7 @@ version = "1.4.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "337d46834ee672ab3e48caca2cb0c78cc174fb12b3a68d0d88f99a0519a5e36e"
|
||||
dependencies = [
|
||||
"generic-array 0.14.7",
|
||||
"rustversion",
|
||||
"typenum",
|
||||
]
|
||||
@@ -4144,7 +4145,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4168,7 +4169,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4182,7 +4183,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4193,7 +4194,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4211,7 +4212,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4225,7 +4226,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4235,7 +4236,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4252,7 +4253,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4266,7 +4267,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4292,7 +4293,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"bb8",
|
||||
"blake3",
|
||||
@@ -4323,7 +4324,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4336,7 +4337,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4357,7 +4358,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4369,7 +4370,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4382,7 +4383,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4400,7 +4401,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4470,7 +4471,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
@@ -4489,7 +4490,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4511,7 +4512,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4523,7 +4524,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"futures",
|
||||
@@ -4540,7 +4541,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4549,7 +4550,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4560,7 +4561,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4616,7 +4617,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4644,7 +4645,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4663,7 +4664,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4686,7 +4687,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4709,7 +4710,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4723,7 +4724,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"globset",
|
||||
@@ -4742,7 +4743,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4766,7 +4767,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4782,7 +4783,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
@@ -4803,7 +4804,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4824,7 +4825,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4837,7 +4838,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4862,7 +4863,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4877,7 +4878,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4890,7 +4891,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4903,7 +4904,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4924,7 +4925,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4945,7 +4946,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -4969,7 +4970,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -4985,7 +4986,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6586,7 +6587,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -7711,9 +7712,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "russh"
|
||||
version = "0.65.1"
|
||||
version = "0.64.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94be3d86c71b9ed220a675c405e35c7a02565a009bf8da2e9cc13a700320a5c5"
|
||||
checksum = "ba61e87b9ec9a39a59a6bbed4c0b8ff7fb07073405b24a767a1f2c8560ac8f58"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"bitflags 2.13.2",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.43"
|
||||
version = "0.1.42"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -1368,20 +1368,12 @@ impl AgentManager {
|
||||
let restamped = blocking(move || {
|
||||
let changes = at.changes(&before)?;
|
||||
let rev = at.rev()?;
|
||||
let sources = match rev.as_deref() {
|
||||
Some(rev) => worktree::rename_sources(at.cwd(), rev)?,
|
||||
None => Default::default(),
|
||||
};
|
||||
let mut restamped = Vec::new();
|
||||
for change in changes.iter().filter(|c| rel_paths.as_ref().is_none_or(|p| p.contains(&c.rel_path))) {
|
||||
// A rename goes back to its old path too; the new one is taken away first, so a
|
||||
// case-only rename on a case-insensitive disk ends as the old file.
|
||||
for change in std::iter::once(change).chain(sources.get(&change.rel_path)) {
|
||||
worktree::restore(at.cwd(), rev.as_deref(), change, &before, saved.as_deref())?;
|
||||
// Back to the user's own edits: not a change of the task any more.
|
||||
if before.contains_key(&change.rel_path) {
|
||||
restamped.push((change.rel_path.clone(), worktree::stamp(&change.path.0)));
|
||||
}
|
||||
worktree::restore(at.cwd(), rev.as_deref(), change, &before, saved.as_deref())?;
|
||||
// Back to the user's own edits: not a change of the task any more.
|
||||
if before.contains_key(&change.rel_path) {
|
||||
restamped.push((change.rel_path.clone(), worktree::stamp(&change.path.0)));
|
||||
}
|
||||
}
|
||||
Ok(restamped)
|
||||
|
||||
@@ -3055,33 +3055,6 @@ async fn commits_made_during_a_local_task_are_kept_by_its_rollback() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn rolling_back_a_rename_brings_the_old_file_back() {
|
||||
for eol in EOLS {
|
||||
let repo = Checkout::new(eol);
|
||||
repo.write("Old.java", "class Old {}\n");
|
||||
repo.write("Case.java", "class Case {}\n");
|
||||
repo.commit("init");
|
||||
let (mgr, task) = repo.task().await;
|
||||
repo.git(&["mv", "Old.java", "New.java"]);
|
||||
repo.git(&["mv", "Case.java", "CASE.java"]);
|
||||
// Renames list their new path only.
|
||||
let listed = changed(&mgr, &task.id).await;
|
||||
assert_eq!(listed, ["CASE.java", "New.java"], "{eol:?}");
|
||||
|
||||
mgr.rollback_changes(&task.id, Some(listed)).await.unwrap();
|
||||
assert_eq!(repo.read("Old.java"), "class Old {}\n", "{eol:?}");
|
||||
assert!(!repo.dir.join("New.java").exists(), "{eol:?}");
|
||||
assert_eq!(repo.read("Case.java"), "class Case {}\n", "{eol:?}");
|
||||
let names: Vec<String> = std::fs::read_dir(&repo.dir)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.filter(|n| n.ends_with(".java"))
|
||||
.collect();
|
||||
assert!(!names.contains(&"CASE.java".to_owned()), "{eol:?}: {names:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_local_task_in_a_repository_without_commits_lists_and_rolls_back_its_changes() {
|
||||
for eol in EOLS {
|
||||
|
||||
@@ -124,28 +124,6 @@ pub(crate) fn changes(cwd: &Path, base: &str) -> IdeResult<Vec<AgentChange>> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Files renamed since `rev`, by their new repository-relative path: the old path, as a deletion
|
||||
/// to roll back along with the rename.
|
||||
pub(crate) fn rename_sources(cwd: &Path, rev: &str) -> IdeResult<BTreeMap<String, AgentChange>> {
|
||||
let Some(repo) = discover(cwd)? else { return Ok(BTreeMap::new()) };
|
||||
let root = repo.root().to_path_buf();
|
||||
Ok(repo
|
||||
.diff_with_worktree(rev)?
|
||||
.into_iter()
|
||||
.filter_map(|f| {
|
||||
let old = f.old_path.filter(|old| *old != f.path)?;
|
||||
let source = AgentChange {
|
||||
path: IpcPath(root.join(&old)),
|
||||
rel_path: old,
|
||||
kind: ChangeKind::Deleted,
|
||||
added: 0,
|
||||
removed: 0,
|
||||
};
|
||||
Some((f.path, source))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn added(path: IpcPath, rel_path: String) -> AgentChange {
|
||||
let added = std::fs::read_to_string(&*path).map_or(0, |t| t.lines().count() as u32);
|
||||
AgentChange { path, rel_path, kind: ChangeKind::Added, added, removed: 0 }
|
||||
|
||||
@@ -105,12 +105,9 @@ fn builtin(adapter: &str) -> Option<DebuggerConfig> {
|
||||
"stdio",
|
||||
"Install netcoredbg (.NET debugger) in Settings › Languages & Frameworks › Language Servers",
|
||||
),
|
||||
"lldb-dap" => cfg(
|
||||
"lldb-dap",
|
||||
&[],
|
||||
"stdio",
|
||||
"Install LLVM's lldb-dap (brew install llvm), or on macOS use the one found by xcrun -f lldb-dap",
|
||||
),
|
||||
"lldb-dap" => {
|
||||
cfg("lldb-dap", &[], "stdio", "Install LLVM's lldb-dap (brew install llvm; on macOS `xcrun -f lldb-dap`)")
|
||||
}
|
||||
// GDB's own DAP interpreter, stdio transport. The DAP support it needs shipped in GDB 14
|
||||
// (`prepare_gdb` refuses older ones with the required version in the message).
|
||||
"gdb" => cfg(
|
||||
|
||||
@@ -773,7 +773,7 @@ impl LspManager {
|
||||
Err(LaunchError::Missing) => {
|
||||
let cfg = server.effective_config();
|
||||
let message =
|
||||
cfg.install_hint.clone().unwrap_or_else(|| format!("{} was not found on PATH", cfg.command));
|
||||
cfg.install_hint.clone().unwrap_or_else(|| format!("`{}` was not found on PATH", cfg.command));
|
||||
if server.fail_start(
|
||||
generation,
|
||||
Conn::Missing,
|
||||
|
||||
@@ -153,24 +153,6 @@ impl Deployment<'_> {
|
||||
self.exclude.local(local.strip_prefix(self.map.project_root()).unwrap_or(local))
|
||||
}
|
||||
|
||||
/// Fails when writing or deleting `local` would go through a symbolic link that
|
||||
/// leaves its mapped folder.
|
||||
async fn confined(&self, local: &Path) -> IdeResult<()> {
|
||||
let Some(root) = self.map.local_root(local) else {
|
||||
return Err(IdeError::invalid(format!("{} is not under a mapped folder", local.display())));
|
||||
};
|
||||
// A missing mapped folder has nothing inside it to follow.
|
||||
let Ok(root) = tokio::fs::canonicalize(root).await else { return Ok(()) };
|
||||
if crate::service::stays_inside(&root, local).await {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(IdeError::invalid(format!(
|
||||
"{} leads outside the mapped folder through a symbolic link",
|
||||
local.display()
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Local files under `paths` (folders recursively), excluded names left out.
|
||||
fn local_files(&self, paths: &[PathBuf], report: &mut TransferReport) -> Vec<PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
@@ -283,10 +265,6 @@ impl Deployment<'_> {
|
||||
}
|
||||
let rel = self.rel(local);
|
||||
progress(&rel, i, jobs.len());
|
||||
if let Err(e) = self.confined(local).await {
|
||||
report.fail(rel, e);
|
||||
continue;
|
||||
}
|
||||
match self.fs.download(remote, local).await {
|
||||
Ok(()) => report.files += 1,
|
||||
Err(e) => report.fail(rel, e),
|
||||
@@ -387,15 +365,9 @@ impl Deployment<'_> {
|
||||
progress(&step.path, i, steps.len());
|
||||
let r = match step.action {
|
||||
SyncAction::Upload => self.fs.upload(&local, &remote, self.preserve_time).await,
|
||||
SyncAction::Download => match self.confined(&local).await {
|
||||
Ok(()) => self.fs.download(&remote, &local).await,
|
||||
Err(e) => Err(e),
|
||||
},
|
||||
SyncAction::Download => self.fs.download(&remote, &local).await,
|
||||
SyncAction::DeleteRemote => self.fs.remove(&remote).await,
|
||||
SyncAction::DeleteLocal => match self.confined(&local).await {
|
||||
Ok(()) => tokio::fs::remove_file(&local).await.map_err(IdeError::from),
|
||||
Err(e) => Err(e),
|
||||
},
|
||||
SyncAction::DeleteLocal => std::fs::remove_file(&local).map_err(IdeError::from),
|
||||
};
|
||||
match r {
|
||||
Ok(()) => report.files += 1,
|
||||
|
||||
@@ -104,11 +104,6 @@ impl Mappings {
|
||||
&self.root
|
||||
}
|
||||
|
||||
/// The local folder of the mapping that holds `local`.
|
||||
pub fn local_root(&self, local: &Path) -> Option<&Path> {
|
||||
self.entries.iter().find_map(|(l, _, _)| local.starts_with(l).then_some(l.as_path()))
|
||||
}
|
||||
|
||||
/// The remote path of a local file or folder (`None`: not under any mapping).
|
||||
pub fn remote(&self, local: &Path) -> Option<String> {
|
||||
self.entries.iter().find_map(|(l, r, _)| {
|
||||
|
||||
@@ -605,7 +605,7 @@ async fn remote_tree(
|
||||
/// Whether writing `path` stays in the download folder `root` (canonical): its closest
|
||||
/// existing ancestor resolves inside it, and `path` itself is not a symbolic link, so a link
|
||||
/// already in the folder can't send a download elsewhere.
|
||||
pub(crate) async fn stays_inside(root: &Path, path: &Path) -> bool {
|
||||
async fn stays_inside(root: &Path, path: &Path) -> bool {
|
||||
if tokio::fs::symlink_metadata(path).await.is_ok_and(|m| m.file_type().is_symlink()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -320,44 +320,6 @@ async fn browser_mappings_resolve_symlinks_and_download_to_the_project() {
|
||||
assert_eq!(std::fs::read_to_string(local).unwrap(), "from the server");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn deployment_downloads_never_write_through_links_out_of_the_mapping() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("project");
|
||||
let target = tmp.path().join("mounted");
|
||||
let outside = tmp.path().join("outside");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::create_dir_all(target.join("app/config")).unwrap();
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
std::fs::write(target.join("app/config/keys"), "from the server").unwrap();
|
||||
std::fs::write(target.join("app/note.txt"), "from the server").unwrap();
|
||||
std::fs::write(outside.join("keys"), "kept").unwrap();
|
||||
std::fs::write(outside.join("other"), "kept").unwrap();
|
||||
std::os::unix::fs::symlink(&outside, root.join("config")).unwrap();
|
||||
std::os::unix::fs::symlink(outside.join("other"), root.join("note.txt")).unwrap();
|
||||
let service = service(tmp.path());
|
||||
let settings = settings(&target);
|
||||
let cancel = CancellationToken::new();
|
||||
|
||||
let report = service
|
||||
.download(&settings, &root, None, std::slice::from_ref(&root), cancel.clone(), &mut |_, _, _| {})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(report.files, 0, "{report:?}");
|
||||
assert_eq!(report.errors.len(), 2, "{report:?}");
|
||||
let steps = [
|
||||
SyncStep { path: "config/keys".into(), action: SyncAction::Download },
|
||||
SyncStep { path: "note.txt".into(), action: SyncAction::Download },
|
||||
SyncStep { path: "config/keys".into(), action: SyncAction::DeleteLocal },
|
||||
];
|
||||
let report = service.sync(&settings, &root, None, &steps, cancel, &mut |_, _, _| {}).await.unwrap();
|
||||
assert_eq!(report.files, 0, "{report:?}");
|
||||
assert_eq!(report.errors.len(), 3, "{report:?}");
|
||||
assert_eq!(std::fs::read_to_string(outside.join("keys")).unwrap(), "kept");
|
||||
assert_eq!(std::fs::read_to_string(outside.join("other")).unwrap(), "kept");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_into_copies_only_the_selected_items() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -18,7 +18,7 @@ dirs.workspace = true
|
||||
uuid.workspace = true
|
||||
keyring.workspace = true
|
||||
keyring-core.workspace = true
|
||||
russh = { version = "0.65", default-features = false, features = ["ring", "rsa", "flate2"] }
|
||||
russh = { version = "0.64", default-features = false, features = ["ring", "rsa", "flate2"] }
|
||||
russh-sftp = "2.4"
|
||||
flate2 = "1"
|
||||
suppaftp = { version = "12.2.1", default-features = false, features = ["tokio-rustls-ring"] }
|
||||
|
||||
@@ -44,9 +44,8 @@ impl server::Handler for Sshd {
|
||||
Ok(if user == "dev" && password == "secret" { Auth::Accept } else { Auth::reject() })
|
||||
}
|
||||
|
||||
async fn auth_publickey(&mut self, user: &str, key: server::VerifiedPublicKey<'_>) -> Result<Auth, Self::Error> {
|
||||
let accept = user == "dev" && key.public_key.key_data() == self.client_key.key_data();
|
||||
Ok(if accept { Auth::Accept } else { Auth::reject() })
|
||||
async fn auth_publickey(&mut self, user: &str, key: &PublicKey) -> Result<Auth, Self::Error> {
|
||||
Ok(if user == "dev" && key.key_data() == self.client_key.key_data() { Auth::Accept } else { Auth::reject() })
|
||||
}
|
||||
|
||||
async fn channel_open_session(
|
||||
|
||||
@@ -781,12 +781,14 @@ impl Repo {
|
||||
) -> IdeResult<Option<String>> {
|
||||
let encoding = encoding.into();
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
Ok(self.blob_of(path, rev.unwrap_or("HEAD"))?.map(|b| text_encoding::decode(&b, encoding).into_owned()))
|
||||
let rel = self.rel_path(path)?;
|
||||
let repo = self.gix()?;
|
||||
Ok(repo::blob_at(&repo, &rel, rev.unwrap_or("HEAD"))?.map(|b| text_encoding::decode(&b, encoding).into_owned()))
|
||||
}
|
||||
/// Raw revision bytes, for encoding detection when the working file is absent.
|
||||
pub fn file_bytes_at(&self, path: &Path, rev: Option<&str>) -> IdeResult<Option<Vec<u8>>> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
self.blob_of(path, rev.unwrap_or("HEAD"))
|
||||
repo::blob_at(&self.gix()?, &self.rel_path(path)?, rev.unwrap_or("HEAD"))
|
||||
}
|
||||
/// Stage selected decoded hunks, retaining the index encoding, BOM and line endings.
|
||||
pub fn stage_hunks(
|
||||
|
||||
@@ -128,27 +128,6 @@ impl Repo {
|
||||
/// worktree or paths already relative to it.
|
||||
pub(crate) fn rel_path(&self, path: &Path) -> IdeResult<String> {
|
||||
let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire));
|
||||
Ok(self.index_spelling(self.given_rel_path(path)?))
|
||||
}
|
||||
|
||||
/// The blob of `path` at `rev`. A revision may spell a file differently from the index (a
|
||||
/// case-only rename staged or made since it): the spelling given wins when the revision has
|
||||
/// it, the index's spelling is the fallback.
|
||||
pub(crate) fn blob_of(&self, path: &Path, rev: &str) -> IdeResult<Option<Vec<u8>>> {
|
||||
let repo = self.gix()?;
|
||||
let given = self.given_rel_path(path)?;
|
||||
let indexed = self.index_spelling(given.clone());
|
||||
if !rev.starts_with(':')
|
||||
&& indexed != given
|
||||
&& let Some(bytes) = blob_at(&repo, &given, rev)?
|
||||
{
|
||||
return Ok(Some(bytes));
|
||||
}
|
||||
blob_at(&repo, &indexed, rev)
|
||||
}
|
||||
|
||||
/// `path` relative to the worktree, spelled as given.
|
||||
fn given_rel_path(&self, path: &Path) -> IdeResult<String> {
|
||||
let rel = if path.is_absolute() {
|
||||
self.strip_root(path)
|
||||
.ok_or_else(|| IdeError::invalid(format!("{} is outside the repository", path.display())))?
|
||||
@@ -168,7 +147,7 @@ impl Repo {
|
||||
_ => return Err(IdeError::invalid(format!("invalid path {}", path.display()))),
|
||||
}
|
||||
}
|
||||
Ok(parts.join("/"))
|
||||
Ok(self.index_spelling(parts.join("/")))
|
||||
}
|
||||
|
||||
/// `rel` as the index spells it. On a case-insensitive worktree (`core.ignoreCase`) the
|
||||
|
||||
@@ -23,7 +23,7 @@ Themes from installed plugins appear in the same list, under the plugin's name.
|
||||
|
||||
The same page also has:
|
||||
|
||||
- **Accent color**: the UI's accent color.
|
||||
- **Accent colour**: the UI's accent colour.
|
||||
- **Different tool window background**: set tool windows apart from the editor.
|
||||
- **Accessibility**: **Use contrast scrollbars** and **Adjust colors for red-green vision deficiency** (for protanopia and deuteranopia).
|
||||
- **Compact mode** under **UI Options**.
|
||||
|
||||
@@ -99,7 +99,7 @@ The selected theme is injected as one stylesheet on `:root` that outranks the bu
|
||||
theme blocks, and `data-theme` is switched to the theme's `kind`. Three things still layer on
|
||||
top of it:
|
||||
|
||||
- an **Accent color** picked in **Settings › Appearance & Behavior › Appearance** (other
|
||||
- an **Accent colour** picked in **Settings › Appearance & Behavior › Appearance** (other
|
||||
than the default),
|
||||
- an explicit scheme or attribute overrides in **Settings › Editor › Color Scheme**,
|
||||
- the appearance options that change only metrics (compact mode).
|
||||
|
||||
@@ -99,7 +99,7 @@ Settings › Appearance & Behavior › Appearance, unless noted.
|
||||
| `theme` | `"light"` | `light` (Islands Light), `dark` (Islands Dark), `dark-hc` (High Contrast), `solarized-light`, `solarized-dark`, `one-light`, `one-dark`, or a plugin theme as `plugin:<plugin-id>/<theme-id>`. |
|
||||
| `syncWithOs` | `false` | **Sync with OS**. |
|
||||
| `preferredLightTheme` / `preferredDarkTheme` | `"light"` / `"dark"` | Themes used with **Sync with OS**. |
|
||||
| `accent` | `"#3871e1"` | **Accent color**. |
|
||||
| `accent` | `"#3871e1"` | **Accent colour**. |
|
||||
| `fileIconTheme` | `""` | A plugin's file icon theme as `<plugin-id>/<theme-id>`; empty uses the built-in icons. |
|
||||
| `zoom` | `100` | **Zoom**, in percent (50 to 300). |
|
||||
| `useCustomFont` | `false` | **Use custom font:** apply `uiFontFamily` and `uiFontSize`. |
|
||||
|
||||
@@ -103,70 +103,3 @@ test("Select All takes the whole buffer, not just the mounted rows", async ({ pa
|
||||
expect(copied).toContain("output 0\n");
|
||||
expect(copied).toMatch(/output 499$/);
|
||||
});
|
||||
|
||||
/** Mount the real console over the given output, wrapped or not. */
|
||||
async function consoleOf(page: Page, text: string, softWrap: boolean) {
|
||||
await page.goto("/");
|
||||
await page.evaluate(
|
||||
async ({ text, softWrap }) => {
|
||||
const reactPath = "/node_modules/.vite/deps/react.js";
|
||||
const domPath = "/node_modules/.vite/deps/react-dom_client.js";
|
||||
const viewPath = "/src/features/run/ConsoleView.tsx";
|
||||
const modelPath = "/src/features/run/console.ts";
|
||||
const react = await import(reactPath);
|
||||
const dom = await import(domPath);
|
||||
const { createElement, useState } = react.default ?? react;
|
||||
const { createRoot } = dom.default ?? dom;
|
||||
const { ConsoleView } = await import(viewPath);
|
||||
const { ConsoleModel } = await import(modelPath);
|
||||
const model = new ConsoleModel();
|
||||
model.append({ kind: "stdout", text });
|
||||
const host = document.createElement("div");
|
||||
host.style.cssText = "position:fixed;inset:0;z-index:99999;display:flex;height:300px;background:white";
|
||||
document.body.append(host);
|
||||
function Console() {
|
||||
const [following, setFollowing] = useState(false);
|
||||
return createElement(ConsoleView, {
|
||||
model,
|
||||
version: 1,
|
||||
softWrap,
|
||||
follow: following,
|
||||
onFollowChange: setFollowing,
|
||||
cwd: "/",
|
||||
});
|
||||
}
|
||||
createRoot(host).render(createElement(Console));
|
||||
},
|
||||
{ text, softWrap },
|
||||
);
|
||||
const log = page.getByRole("log", { name: "Console", exact: true });
|
||||
await expect(log.locator("[data-index]").first()).toBeVisible();
|
||||
return log;
|
||||
}
|
||||
|
||||
for (const softWrap of [false, true]) {
|
||||
test(`takes a blank output line as a line break, not a zero-width space (soft wrap ${softWrap ? "on" : "off"})`, async ({
|
||||
page,
|
||||
}) => {
|
||||
const log = await consoleOf(page, "first\n\nsecond\n", softWrap);
|
||||
// A blank line is still a whole row: stripping the character must not shrink it.
|
||||
const heights = await log.evaluate((el) =>
|
||||
[...el.querySelectorAll("[data-index]")].map((row) => Math.round(row.getBoundingClientRect().height)),
|
||||
);
|
||||
expect(heights).toHaveLength(3);
|
||||
expect(new Set(heights).size).toBe(1);
|
||||
expect(heights[0]).toBeGreaterThan(0);
|
||||
|
||||
const selected = await log.evaluate((el) => {
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el.firstElementChild!);
|
||||
const selection = window.getSelection()!;
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
return selection.toString();
|
||||
});
|
||||
expect(selected).not.toContain("\u200b");
|
||||
// Chromium drops the trailing break of a selection; the blank line in the middle stays one.
|
||||
expect(selected.split("\n")).toEqual(["first", "", "second"]);
|
||||
});
|
||||
}
|
||||
@@ -25,4 +25,4 @@ install-hint = "Install clangd (LLVM): brew install llvm, apt install clangd, or
|
||||
[debugger]
|
||||
adapter = "lldb-dap"
|
||||
command = "lldb-dap"
|
||||
install-hint = "Install LLVM's lldb-dap (brew install llvm), or on macOS use the one found by xcrun -f lldb-dap"
|
||||
install-hint = "Install LLVM's lldb-dap (brew install llvm; on macOS also `xcrun -f lldb-dap`)"
|
||||
@@ -25,4 +25,4 @@ install-hint = "Install clangd (LLVM): brew install llvm, apt install clangd, or
|
||||
[debugger]
|
||||
adapter = "lldb-dap"
|
||||
command = "lldb-dap"
|
||||
install-hint = "Install LLVM's lldb-dap (brew install llvm), or on macOS use the one found by xcrun -f lldb-dap"
|
||||
install-hint = "Install LLVM's lldb-dap (brew install llvm; on macOS also `xcrun -f lldb-dap`)"
|
||||
@@ -10,4 +10,4 @@ ui-mode = "D"
|
||||
name = "serve-d"
|
||||
command = "serve-d"
|
||||
root-markers = ["dub.json", "dub.sdl", "dub.selections.json"]
|
||||
install-hint = "Install serve-d (https://github.com/symmetryinvestments/serve-d) and put serve-d on PATH"
|
||||
install-hint = "Install serve-d (https://github.com/symmetryinvestments/serve-d) and expose it as `serve-d`"
|
||||
@@ -11,9 +11,9 @@ tree-sitter = "elixir"
|
||||
name = "elixir-ls"
|
||||
command = "elixir-ls"
|
||||
root-markers = ["mix.exs"]
|
||||
install-hint = "Install ElixirLS (https://github.com/elixir-lsp/elixir-ls/releases) and put language_server.sh on PATH as elixir-ls"
|
||||
install-hint = "Install ElixirLS (https://github.com/elixir-lsp/elixir-ls/releases) and expose language_server.sh as `elixir-ls`"
|
||||
|
||||
[debugger]
|
||||
adapter = "elixir-ls-debugger"
|
||||
command = "elixir-ls-debugger"
|
||||
install-hint = "Install ElixirLS and put debug_adapter.sh on PATH as elixir-ls-debugger"
|
||||
install-hint = "Install ElixirLS and expose debug_adapter.sh as `elixir-ls-debugger`"
|
||||
@@ -12,4 +12,4 @@ ui-mode = "Groovy"
|
||||
name = "groovy-language-server"
|
||||
command = "groovy-language-server"
|
||||
root-markers = ["build.gradle", "settings.gradle", "pom.xml"]
|
||||
install-hint = "Build https://github.com/GroovyLanguageServer/groovy-language-server and put it on PATH as groovy-language-server"
|
||||
install-hint = "Build https://github.com/GroovyLanguageServer/groovy-language-server and expose it as `groovy-language-server`"
|
||||
@@ -16,4 +16,4 @@ install-hint = "Install clangd (LLVM): brew install llvm"
|
||||
[debugger]
|
||||
adapter = "lldb-dap"
|
||||
command = "lldb-dap"
|
||||
install-hint = "Install LLVM's lldb-dap (brew install llvm), or on macOS use the one found by xcrun -f lldb-dap"
|
||||
install-hint = "Install LLVM's lldb-dap (brew install llvm; on macOS also `xcrun -f lldb-dap`)"
|
||||
@@ -16,4 +16,4 @@ install-hint = "Install clangd (LLVM): brew install llvm"
|
||||
[debugger]
|
||||
adapter = "lldb-dap"
|
||||
command = "lldb-dap"
|
||||
install-hint = "Install LLVM's lldb-dap (brew install llvm), or on macOS use the one found by xcrun -f lldb-dap"
|
||||
install-hint = "Install LLVM's lldb-dap (brew install llvm; on macOS also `xcrun -f lldb-dap`)"
|
||||
@@ -16,4 +16,4 @@ install-hint = "Ships with the Swift toolchain / Xcode (xcrun sourcekit-lsp); ht
|
||||
[debugger]
|
||||
adapter = "lldb-dap"
|
||||
command = "lldb-dap"
|
||||
install-hint = "Ships with the Swift toolchain (swift 6+) or LLVM; on macOS it is found by xcrun -f lldb-dap"
|
||||
install-hint = "Ships with the Swift toolchain (swift 6+) or LLVM; on macOS `xcrun -f lldb-dap`"
|
||||
@@ -11,4 +11,4 @@ tree-sitter = "xml"
|
||||
[[language-servers]]
|
||||
name = "lemminx"
|
||||
command = "lemminx"
|
||||
install-hint = "Install Eclipse LemMinX (https://github.com/redhat-developer/vscode-xml/releases) and put the lemminx binary on PATH"
|
||||
install-hint = "Install Eclipse LemMinX (https://github.com/redhat-developer/vscode-xml/releases, binary `lemminx`)"
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "openidea",
|
||||
"private": true,
|
||||
"description": "An open-source IDE inspired by IntelliJ IDEA",
|
||||
"version": "0.1.43",
|
||||
"version": "0.1.42",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
d70fb4fbd91208bfda4b937a599a5dd478400f1bbc99c24c15b316813c7c7593
|
||||
af1b3dd1227337f3983e4bc41816efb07be8604f7a736a48a41f241d0eabc93b
|
||||
@@ -1,10 +1,10 @@
|
||||
id = "openidea.mybatis"
|
||||
name = "MyBatis Navigator"
|
||||
version = "0.4.1"
|
||||
version = "0.5.0"
|
||||
description = "Jumps between MyBatis mapper interfaces and their XML statements, resultMaps, sql/include fragments, namespaces or annotation SQL (gutter arrows and Go to Definition), completes statement and sql ids and #{parameters}."
|
||||
authors = ["OpenIDEA contributors"]
|
||||
license = "Apache-2.0"
|
||||
change-notes = "0.4.1 — the XML for a mapper interface is found by a search, so gutter arrows no longer time out on projects with many XML files. 0.4.0 — result maps: @ResultMap navigates to @Results(id)/XML resultMap and completes ids; resultMap= in XML jumps too. 0.3.0 — annotation SQL: #{…}/${…} in @Select/@Insert/@Update/@Delete navigates to @Param/parameters and completes them; pure-annotation mappers need no XML. 0.2.0 — namespace, resultMap/extends and sql/include navigation, refid completion; 0.1.0 — first release: navigation both ways, line markers, id and parameter completion."
|
||||
change-notes = "0.5.0 — resultType/parameterType/type/javaType/ofType values navigate to the Java class (Go to Definition + gutter); plain `class` files resolve alongside mapper interfaces. 0.4.1 — the XML for a mapper interface is found by a search, so gutter arrows no longer time out on projects with many XML files. 0.4.0 — result maps: @ResultMap navigates to @Results(id)/XML resultMap and completes ids; resultMap= in XML jumps too. 0.3.0 — annotation SQL: #{…}/${…} in @Select/@Insert/@Update/@Delete navigates to @Param/parameters and completes them; pure-annotation mappers need no XML. 0.2.0 — namespace, resultMap/extends and sql/include navigation, refid completion; 0.1.0 — first release: navigation both ways, line markers, id and parameter completion."
|
||||
categories = ["frameworks"]
|
||||
engines.openidea = "^1.4"
|
||||
wasm = "dist/plugin.wasm"
|
||||
|
||||
@@ -42,6 +42,9 @@ pub struct MapperXml {
|
||||
pub extends_refs: Vec<Named>,
|
||||
/// `<include refid="…">` values.
|
||||
pub include_refs: Vec<Named>,
|
||||
/// `resultType` / `parameterType` / `type` / `javaType` / `ofType` values —
|
||||
/// Java class or type-alias references.
|
||||
pub type_refs: Vec<Named>,
|
||||
}
|
||||
|
||||
/// A method parameter: its effective name (`@Param("…")` wins) and where that
|
||||
@@ -140,6 +143,21 @@ pub fn parse_xml(text: &str) -> MapperXml {
|
||||
{
|
||||
out.include_refs.push(r);
|
||||
}
|
||||
// Java-class references, on any tag that carries them.
|
||||
for attr_name in ["resultType", "parameterType", "javaType", "ofType"] {
|
||||
if let Some(r) = named(attr_name) {
|
||||
out.type_refs.push(r);
|
||||
}
|
||||
}
|
||||
// `type="…"` means a Java type on `<resultMap>`, `<id>`/`<result>`,
|
||||
// `<association>`/`<collection>` and `<cache>`.
|
||||
if matches!(
|
||||
name.as_str(),
|
||||
"resultMap" | "id" | "result" | "association" | "collection" | "cache" | "arg" | "idArg"
|
||||
) && let Some(r) = named("type")
|
||||
{
|
||||
out.type_refs.push(r);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -540,16 +558,27 @@ fn result_map_of(head: &str) -> (Vec<LitSpan>, Vec<LitSpan>) {
|
||||
pub fn parse_java(text: &str) -> MapperJava {
|
||||
let package =
|
||||
text.lines().find_map(|l| l.trim().strip_prefix("package ").map(|p| p.trim_end_matches(';').trim().to_owned()));
|
||||
let Some(i) = text.find("interface ") else { return MapperJava::default() };
|
||||
let rest = &text[i + 10..];
|
||||
// Mapper files are interfaces; `resultType`/`javaType` targets are usually
|
||||
// classes — accept either so class navigation resolves a declaration.
|
||||
let (i, kw) = ["interface ", "class "]
|
||||
.iter()
|
||||
.filter_map(|kw| text.find(kw).map(|i| (i, *kw)))
|
||||
.min_by_key(|(i, _)| *i)
|
||||
.unwrap_or((usize::MAX, "interface "));
|
||||
if i == usize::MAX {
|
||||
return MapperJava::default();
|
||||
}
|
||||
let rest = &text[i + kw.len()..];
|
||||
let indent = rest.len() - rest.trim_start().len();
|
||||
let simple: String = rest[indent..].chars().take_while(|c| ident(*c)).collect();
|
||||
let name = Some(match package {
|
||||
Some(p) => format!("{p}.{simple}"),
|
||||
None => simple.clone(),
|
||||
});
|
||||
let decl =
|
||||
Some(Named { name: simple.clone(), range: range_of(text, i + 10 + indent, i + 10 + indent + simple.len()) });
|
||||
let decl = Some(Named {
|
||||
name: simple.clone(),
|
||||
range: range_of(text, i + kw.len() + indent, i + kw.len() + indent + simple.len()),
|
||||
});
|
||||
let body_start = text[i..].find('{').map_or(text.len(), |b| i + b + 1);
|
||||
let mut methods = Vec::new();
|
||||
let mut annotation_sql = Vec::new();
|
||||
@@ -702,6 +731,33 @@ impl Navigator {
|
||||
(java.name.as_deref() == Some(namespace)).then_some((path, java))
|
||||
}
|
||||
|
||||
/// The Java class a `resultType`/`type`/`javaType`/`ofType` value names.
|
||||
/// A fully-qualified name maps straight to a path; a simple name (or a
|
||||
/// MyBatis type alias, which is a simple name) is tried in the mapper's own
|
||||
/// package first, then anywhere in the project by file name.
|
||||
fn class_for(project: &Project, namespace: &str, type_name: &str) -> Option<(String, MapperJava)> {
|
||||
let candidate = |fqn: &str| -> Option<(String, MapperJava)> {
|
||||
let rel = format!("**/{}.java", fqn.replace('.', "/"));
|
||||
let path = project.find_files(&rel, 1).ok()?.into_iter().next()?;
|
||||
let java = parse_java(&project.read_file(&path).ok()?);
|
||||
(java.name.as_deref() == Some(fqn)).then_some((path, java))
|
||||
};
|
||||
if type_name.contains('.') {
|
||||
return candidate(type_name);
|
||||
}
|
||||
let package = namespace.rsplit_once('.').map(|(p, _)| p).unwrap_or("");
|
||||
if !package.is_empty()
|
||||
&& let Some(hit) = candidate(&format!("{package}.{type_name}"))
|
||||
{
|
||||
return Some(hit);
|
||||
}
|
||||
// Simple name or alias: any class file of that simple name.
|
||||
let rel = format!("**/{type_name}.java");
|
||||
let path = project.find_files(&rel, 1).ok()?.into_iter().next()?;
|
||||
let java = parse_java(&project.read_file(&path).ok()?);
|
||||
java.name.is_some().then_some((path, java))
|
||||
}
|
||||
|
||||
/// Where `resultMap="…"` / `<include refid="…">` points: a `<resultMap id>` /
|
||||
/// `<sql id>` in this file, or in the mapper a `namespace.id` prefix names
|
||||
/// (ids never hold dots, so the last segment is the id).
|
||||
@@ -806,6 +862,15 @@ impl Navigator {
|
||||
out.push((r.clone(), target, format!("sql {}", r.name)));
|
||||
}
|
||||
}
|
||||
// `resultType`/`type`/`javaType`/`ofType` → the Java class.
|
||||
for r in &xml.type_refs {
|
||||
if let Some((path, java)) = Self::class_for(&project, &ns.name, &r.name)
|
||||
&& let Some(decl) = java.decl
|
||||
{
|
||||
let simple = r.name.rsplit('.').next().unwrap_or(&r.name);
|
||||
out.push((r.clone(), Location { path, range: decl.range }, format!("class {simple}")));
|
||||
}
|
||||
}
|
||||
// Gutter arrows read top-down: the namespace marker precedes the statements'.
|
||||
out.sort_by_key(|a| a.0.range.start);
|
||||
out
|
||||
@@ -1387,6 +1452,75 @@ mod tests {
|
||||
host
|
||||
}
|
||||
|
||||
const TYPE_XML: &str = concat!(
|
||||
"<?xml version=\"1.0\"?>\n",
|
||||
"<mapper namespace=\"com.acme.UserMapper\">\n",
|
||||
" <resultMap id=\"userMap\" type=\"User\">\n",
|
||||
" <id property=\"id\" column=\"user_id\"/>\n",
|
||||
" <association property=\"order\" javaType=\"com.acme.Order\" ofType=\"Order\"/>\n",
|
||||
" </resultMap>\n",
|
||||
" <select id=\"findById\" resultType=\"com.acme.User\" parameterType=\"long\">\n",
|
||||
" select * from users\n",
|
||||
" </select>\n",
|
||||
"</mapper>\n"
|
||||
);
|
||||
|
||||
#[test]
|
||||
fn parses_type_refs() {
|
||||
let xml = parse_xml(TYPE_XML);
|
||||
let names: Vec<_> = xml.type_refs.iter().map(|n| n.name.as_str()).collect();
|
||||
assert_eq!(names, ["User", "com.acme.Order", "Order", "com.acme.User", "long"]);
|
||||
// `type="User"` range covers the value, not the quotes.
|
||||
assert_eq!(xml.type_refs[0].range, Range::new(Position::new(2, 32), Position::new(2, 36)));
|
||||
}
|
||||
|
||||
fn type_setup() -> MockHost {
|
||||
let host = MockHost::install();
|
||||
host.add_file(
|
||||
"src/main/java/com/acme/UserMapper.java",
|
||||
"package com.acme;\npublic interface UserMapper {\n User findById(Long id);\n}\n",
|
||||
);
|
||||
host.add_file("src/main/java/com/acme/User.java", "package com.acme;\npublic class User {\n Long id;\n}\n");
|
||||
host.add_file(
|
||||
"src/main/java/com/acme/Order.java",
|
||||
"package com.acme;\npublic class Order {\n Long id;\n}\n",
|
||||
);
|
||||
add_mapper(&host, "src/main/resources/mapper/UserMapper.xml", TYPE_XML);
|
||||
host.add_file("pom.xml", "<project/>");
|
||||
host
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn navigates_type_refs_to_java_classes() {
|
||||
let _host = type_setup();
|
||||
let mut n = Navigator::default();
|
||||
let xml = doc("/project/src/main/resources/mapper/UserMapper.xml", "xml", TYPE_XML);
|
||||
let user_class = parse_java("package com.acme;\npublic class User {\n Long id;\n}\n");
|
||||
|
||||
// `type="User"` (simple name) → User.java in the mapper's package.
|
||||
let got = n.definition(&xml, Position::new(2, 33));
|
||||
assert_eq!(
|
||||
got,
|
||||
vec![Location {
|
||||
path: "/project/src/main/java/com/acme/User.java".into(),
|
||||
range: user_class.decl.unwrap().range
|
||||
}]
|
||||
);
|
||||
|
||||
// `resultType="com.acme.User"` (fq name) → the same class.
|
||||
let got = n.definition(&xml, Position::new(6, 40));
|
||||
assert_eq!(got.len(), 1);
|
||||
assert!(got[0].path.ends_with("User.java"));
|
||||
|
||||
// `ofType="Order"` → Order.java.
|
||||
let got = n.definition(&xml, Position::new(4, 69));
|
||||
assert_eq!(got.len(), 1);
|
||||
assert!(got[0].path.ends_with("Order.java"));
|
||||
|
||||
// `parameterType="long"` (primitive, no such class) resolves nowhere.
|
||||
assert!(n.definition(&xml, Position::new(6, 67)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_result_map_refs_and_ids() {
|
||||
let java = parse_java(RESULT_JAVA);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// The commit being prepared in the window the current command or event came
|
||||
/// from (the Commit tool window, or the Commit dialog while it is open): the
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// Plugin-owned project data sources. Requires database.sources and project trust.
|
||||
/// Runs on the Database subsystem's host, including on remote project servers.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// Project-scoped decorations (API 1.4). Requires project.read; paths must be inside
|
||||
/// an open project. Sets belong to the plugin and disappear when it stops.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// What the pane beside the Services tree shows for a plugin's node.
|
||||
interface detail-types {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// Optional export (world `plugin-diagnostics`): problems in the current,
|
||||
/// possibly unsaved document, for the languages declared with the
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// HTTP endpoints found in a project (`[[contributes.endpoints]]`).
|
||||
interface endpoints-provider {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// Workbench events, delivered in batches to `event-handler.handle`.
|
||||
interface events {
|
||||
@@ -35,9 +35,7 @@ interface events {
|
||||
/// API 1.5 also delivers `extensions-changed` (JSON array of the extension
|
||||
/// points this plugin declares whose contributions changed) through `other`,
|
||||
/// to the declaring plugin only and without a capability.
|
||||
/// Kinds: `file-opened`, `file-saved`, `document-changed` (versioned UTF-16
|
||||
/// replacements from explicit path subscriptions), `websocket-ready`
|
||||
/// (a host-owned connection has messages to drain), `files-changed` (batched disk changes
|
||||
/// Kinds: `file-opened`, `file-saved`, `files-changed` (batched disk changes
|
||||
/// as `other`, with created/modified/removed path lists in JSON), `editor-focused` (the focused editor
|
||||
/// changed), `vcs-changed` (a repository's state changed: commit,
|
||||
/// checkout, fetch…), `action-performed` (an IDE action ran) and
|
||||
@@ -47,7 +45,7 @@ interface events {
|
||||
subscribe: func(kind: string) -> result<_, error>;
|
||||
/// Replaces this kind's subscription with project-relative globs (OR).
|
||||
/// Empty globs pause delivery; `subscribe` restores unfiltered delivery.
|
||||
/// Kinds: file-opened, file-saved, document-changed, files-changed. Requires `events`.
|
||||
/// Kinds: file-opened, file-saved, files-changed. Requires `events`.
|
||||
subscribe-paths: func(kind: string, globs: list<string>) -> result<_, error>;
|
||||
unsubscribe: func(kind: string);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
interface lifecycle {
|
||||
use types.{context, error};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// What other plugins contributed to the extension points this plugin declares
|
||||
/// (`[[extension-points]]` in `plugin.toml`; the contributors list this plugin
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// Optional export (world `plugin-file-actions`): quick fixes and
|
||||
/// refactorings that create, rename or delete files, next to the text edits
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// Files outside the open projects: the configuration of the program a
|
||||
/// plugin integrates with, a tool installed elsewhere, a licence file.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// Writes to the IDE log, tagged with the plugin id.
|
||||
interface log {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// Optional export (world `plugin-hover`): Markdown added to the hover of
|
||||
/// documents of the languages declared with the `hover` provider kind,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// Cross-file associations a plugin publishes for the files it declares under
|
||||
/// `[[contributes.documentIndexers]]`. The host calls `index` in cancellable
|
||||
@@ -29,9 +29,6 @@ interface document-indexer {
|
||||
|
||||
/// A range of the document tied to a key the plugin chooses
|
||||
/// (`com.example.UserMapper#findById`, say). Keys are compared as is.
|
||||
/// Ranges lie inside the document; an empty one marks a position (a
|
||||
/// definition that is the whole file, at its start): Go to Declaration
|
||||
/// lands there, Find Usages and Rename skip it.
|
||||
record anchor {
|
||||
key: string,
|
||||
range: range,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// Embedded languages. The host routes plugin providers and configured language
|
||||
/// servers inside these ranges, preserving host-document UTF-16 coordinates.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// Optional export (world `plugin-inlay-hints`): inline hints in documents of
|
||||
/// the languages declared with the `inlay-hints` provider kind, including
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// Problems in files, shown in the editor and the Problems view.
|
||||
interface diagnostics {
|
||||
@@ -43,7 +43,6 @@ interface diagnostics {
|
||||
/// HTTPS with `net:<host>`; unencrypted HTTP with `net.http:<host>`.
|
||||
interface net {
|
||||
use types.{error};
|
||||
use workspace.{project};
|
||||
|
||||
record header {
|
||||
name: string,
|
||||
@@ -70,41 +69,9 @@ interface net {
|
||||
body: list<u8>,
|
||||
}
|
||||
|
||||
record websocket-request {
|
||||
/// `wss://` requires `net:<host>`; loopback `ws://` is allowed for tests.
|
||||
url: string,
|
||||
/// Secret placeholders are expanded by the host as for HTTP requests.
|
||||
/// `host`, `connection`, `upgrade` and `sec-websocket-*` belong to the
|
||||
/// handshake and are rejected.
|
||||
headers: list<header>,
|
||||
/// Empty for none; otherwise the server must accept this subprotocol.
|
||||
subprotocol: string,
|
||||
}
|
||||
|
||||
record websocket-batch {
|
||||
messages: list<list<u8>>,
|
||||
/// The transport has ended. Any returned messages are still valid and
|
||||
/// this connection is removed after this final drain.
|
||||
closed: bool,
|
||||
}
|
||||
|
||||
/// Fails with `denied` for a host the plugin may not reach, `cancelled`
|
||||
/// when a newer request replaced the call or the user cancelled.
|
||||
fetch: func(req: request) -> result<response, error>;
|
||||
/// A project-bound background WebSocket. At most eight may be open for a
|
||||
/// plugin. Dropping this resource closes the transport and releases it.
|
||||
resource websocket {
|
||||
/// Stable connection identifier used by `websocket-ready` events.
|
||||
id: func() -> u64;
|
||||
send: func(bytes: list<u8>) -> result<_, error>;
|
||||
drain: func(limit: u32) -> result<websocket-batch, error>;
|
||||
close: func() -> result<_, error>;
|
||||
}
|
||||
|
||||
/// Creates a project-bound WebSocket resource. The host retains the
|
||||
/// project binding, so resource methods cannot be redirected to another
|
||||
/// project.
|
||||
websocket-connect: func(project: borrow<project>, req: websocket-request) -> result<websocket, error>;
|
||||
}
|
||||
|
||||
/// Secrets the user stored for the plugin (Settings › Plugins, kept in the
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// Additional language features, called only for declared API 1.4 provider kinds.
|
||||
/// Editor calls have a 50 ms soft / 500 ms hard budget; formatting has 5 seconds.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// Discovery of the IDE's built-in MCP server; never exposes its URL or token.
|
||||
interface mcp {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
/// `fs` and `workspace`, and everything else goes through the imports below,
|
||||
/// gated by the capabilities granted in `plugin.toml` (a missing one returns
|
||||
/// `error::denied`).
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
world plugin {
|
||||
import log;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// Editor features a plugin provides for the languages it declares under
|
||||
/// `[[contributes.providers]]` (the host calls only declared kinds). They run
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// Project-scoped targets owned by the registering plugin (API 1.4).
|
||||
interface run-targets {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// Launches this plugin's configurations in the invoking window's Run tool window.
|
||||
interface run {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// Optional export (world `plugin-semantic-tokens`): semantic colouring of
|
||||
/// documents of the languages declared with the `semantic-tokens` provider
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// Shared types. Positions are 0-based lines and UTF-16 code unit columns,
|
||||
/// as in the editor and LSP.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
/// Declarative views: tool windows declared
|
||||
/// under `[[contributes.views]]` and custom editors under
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:plugin@1.6.0;
|
||||
package openidea:plugin@1.5.0;
|
||||
|
||||
interface workspace {
|
||||
use types.{error, location};
|
||||
@@ -111,7 +111,6 @@ interface workspace {
|
||||
|
||||
interface editor {
|
||||
use types.{error, range, text-edit};
|
||||
use workspace.{project};
|
||||
|
||||
record document {
|
||||
/// Grows with every change; edits name the version they were made for.
|
||||
@@ -127,19 +126,6 @@ interface editor {
|
||||
/// Only from commands/events of a window. Paths follow views.open-location.
|
||||
open: func(path: string, selection: option<range>) -> result<_, error>;
|
||||
|
||||
/// Current version and text of an open project document. Unlike
|
||||
/// `text-editor.document`, this is available to background events.
|
||||
/// The path is project-relative and requires `project.read` and
|
||||
/// `editor.read`.
|
||||
document-at: func(project: borrow<project>, path: string) -> result<document, error>;
|
||||
|
||||
/// Applies versioned edits to an open project document from a background
|
||||
/// event. The path is project-relative and requires `project.read` and
|
||||
/// `editor.write`. Stale versions are rejected without changing text.
|
||||
/// These background edits are non-undoable and are not re-emitted as
|
||||
/// `document-changed` events.
|
||||
apply-edits-at: func(project: borrow<project>, path: string, version: u64, edits: list<text-edit>) -> result<u64, error>;
|
||||
|
||||
/// A file open in an editor.
|
||||
resource text-editor {
|
||||
/// Absolute path of the file.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "OpenIDEA",
|
||||
"version": "0.1.43",
|
||||
"version": "0.1.42",
|
||||
"identifier": "ai.l0ng.openidea",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
||||
@@ -11,12 +11,4 @@
|
||||
/>
|
||||
</dependentAssembly>
|
||||
</dependency>
|
||||
<!-- Win32 calls in dependencies (gitoxide's ownership check of a submodule's
|
||||
`<worktree>/../../.git/modules/…` path) accept paths past MAX_PATH when
|
||||
the system enables long paths. -->
|
||||
<application xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<windowsSettings>
|
||||
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
|
||||
</windowsSettings>
|
||||
</application>
|
||||
</assembly>
|
||||
@@ -56,7 +56,7 @@ async function applyEdit(view: EditorView, edit: WorkspaceEdit) {
|
||||
async function prepareIndexes(view: EditorView, path: string): Promise<boolean> {
|
||||
const before = view.state.doc;
|
||||
try {
|
||||
await synchronizeDocumentIndexes(path, "refactor");
|
||||
await synchronizeDocumentIndexes(path);
|
||||
return view.state.doc === before;
|
||||
} catch (e) {
|
||||
reportLspError(view, e, true);
|
||||
@@ -269,7 +269,7 @@ async function finishRename(view: EditorView, doc: EditorDocContext, pos: Pos, o
|
||||
let renamed;
|
||||
const before = view.state.doc;
|
||||
try {
|
||||
await synchronizeDocumentIndexes(doc.path, "refactor");
|
||||
await synchronizeDocumentIndexes(doc.path);
|
||||
if (renameRequest !== request || view.state.doc !== before) return;
|
||||
renamed = await lspRequest(() => commands.lspRename(request, doc.doc, pos, newName));
|
||||
if (renameRequest !== request) return;
|
||||
|
||||
@@ -428,6 +428,33 @@ export function Composer(props: ComposerProps) {
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (composing.current || isImeKey(e.nativeEvent)) return;
|
||||
const el = e.currentTarget;
|
||||
if (!e.altKey && !e.metaKey && !e.ctrlKey && el.selectionStart === el.selectionEnd) {
|
||||
const backward = e.key === "Backspace" || e.key === "ArrowLeft";
|
||||
const forward = e.key === "Delete" || e.key === "ArrowRight";
|
||||
if (backward || forward) {
|
||||
let offset = 0;
|
||||
for (const token of tokens) {
|
||||
const end = offset + token.value.length;
|
||||
const caret = el.selectionStart;
|
||||
if (token.kind !== "text" && (backward ? caret > offset && caret <= end : caret >= offset && caret < end)) {
|
||||
e.preventDefault();
|
||||
if (e.key === "Backspace" || e.key === "Delete") {
|
||||
setText(text.slice(0, offset) + text.slice(end), offset);
|
||||
} else {
|
||||
const next = backward ? offset : end;
|
||||
el.setSelectionRange(
|
||||
e.shiftKey ? Math.min(caret, next) : next,
|
||||
e.shiftKey ? Math.max(caret, next) : next,
|
||||
);
|
||||
}
|
||||
setCompletion(null);
|
||||
return;
|
||||
}
|
||||
offset = end;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (open) {
|
||||
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
@@ -603,10 +630,7 @@ export function Composer(props: ComposerProps) {
|
||||
onChange={(e) => setText(e.target.value, e.target.selectionStart, false)}
|
||||
// The controlled text, not the event's value: closing the completion popup can emit a
|
||||
// stale select event with the old text.
|
||||
onSelect={(e) => {
|
||||
const caret = e.currentTarget.selectionStart;
|
||||
setCompletion(composing.current ? null : completionAt(text, caret));
|
||||
}}
|
||||
onSelect={(e) => setCompletion(composing.current ? null : completionAt(text, e.currentTarget.selectionStart))}
|
||||
onCompositionStart={() => {
|
||||
composing.current = true;
|
||||
setCompletion(null);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { FILES_DRAG, dragSession } from "@/ui";
|
||||
|
||||
@@ -150,77 +150,29 @@ describe("Composer @ folders", () => {
|
||||
});
|
||||
|
||||
describe("Composer tag editing", () => {
|
||||
it.each(["@src/ag", "/rev"])("deletes %s character by character while it is typed", async (tag) => {
|
||||
const box = renderComposer();
|
||||
const user = userEvent.setup();
|
||||
await user.type(box, `see ${tag}`);
|
||||
await user.keyboard("{Backspace}");
|
||||
expect(box.value).toBe(`see ${tag.slice(0, -1)}`);
|
||||
await user.keyboard("{Backspace}");
|
||||
expect(box.value).toBe(`see ${tag.slice(0, -2)}`);
|
||||
});
|
||||
|
||||
it("deletes inside a folder entered with Tab character by character", async () => {
|
||||
const box = renderComposer();
|
||||
const user = userEvent.setup();
|
||||
await user.type(box, "@agen");
|
||||
await screen.findAllByRole("option");
|
||||
await user.keyboard("{Tab}");
|
||||
expect(box.value).toBe("@src/agents/");
|
||||
await user.keyboard("{Backspace}");
|
||||
expect(box.value).toBe("@src/agents");
|
||||
});
|
||||
|
||||
it("edits a completed reference character by character after its space", async () => {
|
||||
const box = renderComposer();
|
||||
const user = userEvent.setup();
|
||||
await user.type(box, "see @agen");
|
||||
await screen.findAllByRole("option");
|
||||
await user.keyboard("{Enter}");
|
||||
expect(box.value).toBe("see @src/agents/ ");
|
||||
await user.keyboard("{Backspace}{Backspace}");
|
||||
expect(box.value).toBe("see @src/agents");
|
||||
});
|
||||
|
||||
it.each(["@src/a.ts", "/review"])("edits %s after moving away and returning", async (tag) => {
|
||||
it.each(["@src/a.ts", "/review"])("deletes %s as a unit", async (tag) => {
|
||||
const box = renderComposer();
|
||||
const user = userEvent.setup();
|
||||
fireEvent.change(box, { target: { value: `see ${tag} next` } });
|
||||
box.focus();
|
||||
box.setSelectionRange(0, 0);
|
||||
fireEvent.select(box);
|
||||
box.blur();
|
||||
box.focus();
|
||||
box.setSelectionRange(4 + tag.length, 4 + tag.length);
|
||||
fireEvent.select(box);
|
||||
await user.keyboard("{Backspace}");
|
||||
expect(box.value).toBe(`see ${tag.slice(0, -1)} next`);
|
||||
expect(box.selectionStart).toBe(3 + tag.length);
|
||||
expect(box.value).toBe("see next");
|
||||
await waitFor(() => expect(box.selectionStart).toBe(4));
|
||||
});
|
||||
|
||||
it.each(["@src/a.ts", "/review"])("moves within %s with the arrow keys", async (tag) => {
|
||||
it.each(["@src/a.ts", "/review"])("moves across %s with the arrow keys", async (tag) => {
|
||||
const box = renderComposer();
|
||||
const user = userEvent.setup();
|
||||
fireEvent.change(box, { target: { value: `see ${tag} next` } });
|
||||
box.focus();
|
||||
box.setSelectionRange(4, 4);
|
||||
await user.keyboard("{ArrowRight}");
|
||||
expect(box.selectionStart).toBe(5);
|
||||
expect(box.selectionStart).toBe(4 + tag.length);
|
||||
await user.keyboard("{ArrowLeft}");
|
||||
expect(box.selectionStart).toBe(4);
|
||||
await user.keyboard("{Delete}");
|
||||
expect(box.value).toBe(`see ${tag.slice(1)} next`);
|
||||
});
|
||||
|
||||
it.each(["@src/a.ts", "/review"])("selects and deletes only part of %s", async (tag) => {
|
||||
const box = renderComposer();
|
||||
const user = userEvent.setup();
|
||||
fireEvent.change(box, { target: { value: `see ${tag} next` } });
|
||||
box.focus();
|
||||
box.setSelectionRange(5, 7);
|
||||
fireEvent.select(box);
|
||||
await user.keyboard("{Backspace}");
|
||||
expect(box.value).toBe(`see ${tag.slice(0, 1)}${tag.slice(3)} next`);
|
||||
expect(box.value).toBe("see next");
|
||||
});
|
||||
|
||||
it("leaves IME keys and composition text to the input method", () => {
|
||||
|
||||
@@ -160,7 +160,7 @@ describe("findUsages", () => {
|
||||
const pending = findUsages();
|
||||
const at = (line: number) => ({ path: "/p/b.rs", range: { start: { line, col: 4 }, end: { line, col: 8 } } });
|
||||
try {
|
||||
await vi.waitFor(() => expect(sync).toHaveBeenCalledWith("/p/a.rs", "usages"));
|
||||
await vi.waitFor(() => expect(sync).toHaveBeenCalledWith("/p/a.rs"));
|
||||
expect(lspReferences).not.toHaveBeenCalled();
|
||||
expect(channels).toHaveLength(allocated);
|
||||
release();
|
||||
@@ -181,23 +181,6 @@ describe("findUsages", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("findUsages with a contributed index that is not up to date", () => {
|
||||
it("still searches, and says plugin usages may be missing", async () => {
|
||||
const off = registerDocumentIndexSync(async () => false);
|
||||
const at = { path: "/p/b.rs", range: { start: { line: 1, col: 4 }, end: { line: 1, col: 8 } } };
|
||||
referenceResponse.mockResolvedValueOnce({ locations: [at], incomplete: null });
|
||||
try {
|
||||
await findUsages();
|
||||
const search = activeUsageSearch(useUsages.getState())!;
|
||||
expect(search.groups).toHaveLength(1);
|
||||
expect(search.note).toBe("May be incomplete: plugin indexes are still updating");
|
||||
} finally {
|
||||
off();
|
||||
resetUsages();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("usage tabs", () => {
|
||||
const search = (id: number) => ({
|
||||
id,
|
||||
|
||||
@@ -6,7 +6,6 @@ import { clearLineTokens } from "@/editor/lineTokens";
|
||||
import { showPendingHint } from "@/editor/lsp/hint";
|
||||
import { incompleteNote } from "@/editor/lsp/lsp";
|
||||
import { commands, IpcError, isCancelled, nextRequestId } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { synchronizeDocumentIndexes, toolWindowService } from "@/workbench/contributions";
|
||||
import {
|
||||
@@ -231,7 +230,7 @@ export async function fetchUsages(
|
||||
let note: string | null = null;
|
||||
let librariesSkipped = false;
|
||||
await caretSynced(c);
|
||||
const indexed = await synchronizeDocumentIndexes(c.path, "usages");
|
||||
await synchronizeDocumentIndexes(c.path);
|
||||
if (c.view && c.view.state.doc !== before) throw new IpcError({ kind: "cancelled", message: "", data: null });
|
||||
let settled = false;
|
||||
const channel = new Channel<References>();
|
||||
@@ -269,7 +268,6 @@ export async function fetchUsages(
|
||||
locs = fb.locs;
|
||||
note = fb.note;
|
||||
}
|
||||
if (!indexed) note ??= tx("May be incomplete: plugin indexes are still updating");
|
||||
const files = await readManyFileLines(pathsToRead(locs, classified));
|
||||
return { groups: groupUsages(locs, files, classified), note, librariesSkipped };
|
||||
}
|
||||
|
||||
@@ -135,7 +135,7 @@ it("flushes pending changes before usages or rename without waiting for the debo
|
||||
await vi.advanceTimersByTimeAsync(250);
|
||||
mocks.index.mockClear();
|
||||
mocks.events.get("fsChanged")?.({ created: [], modified: ["/project/A.xml"], removed: [] });
|
||||
await synchronizeDocumentIndexes("/project/A.xml", "refactor");
|
||||
await synchronizeDocumentIndexes("/project/A.xml");
|
||||
expect(mocks.index).toHaveBeenCalledExactlyOnceWith(["/project/A.xml"], expect.any(Number));
|
||||
});
|
||||
|
||||
@@ -153,7 +153,7 @@ it("waits for an active batch, then indexes changes queued while it was running"
|
||||
await vi.advanceTimersByTimeAsync(40);
|
||||
mocks.events.get("fsChanged")?.({ created: [], modified: ["/project/A.java"], removed: [] });
|
||||
let settled = false;
|
||||
const waiting = synchronizeDocumentIndexes("/project/A.xml", "refactor").then(() => {
|
||||
const waiting = synchronizeDocumentIndexes("/project/A.xml").then(() => {
|
||||
settled = true;
|
||||
});
|
||||
await Promise.resolve();
|
||||
@@ -168,33 +168,7 @@ it("refuses refactoring if a queued index batch failed", async () => {
|
||||
await vi.advanceTimersByTimeAsync(250);
|
||||
mocks.index.mockResolvedValueOnce({ status: "error", error: { kind: "unavailable", message: "indexer failed" } });
|
||||
mocks.events.get("fsChanged")?.({ created: [], modified: ["/project/A.xml"], removed: [] });
|
||||
await expect(synchronizeDocumentIndexes("/project/A.xml", "refactor")).rejects.toThrow(
|
||||
"Plugin indexes could not be updated",
|
||||
);
|
||||
});
|
||||
|
||||
it("lets usages go ahead, marked incomplete, while a failed batch keeps failing", async () => {
|
||||
off = startPluginNavigation();
|
||||
await vi.advanceTimersByTimeAsync(250);
|
||||
const failure = { status: "error", error: { kind: "unavailable", message: "indexer failed" } };
|
||||
mocks.index.mockResolvedValue(failure);
|
||||
mocks.events.get("fsChanged")?.({ created: [], modified: ["/project/A.xml"], removed: [] });
|
||||
await vi.advanceTimersByTimeAsync(40);
|
||||
// Every later search used to fail with "still updating" although nothing was running.
|
||||
await expect(synchronizeDocumentIndexes("/project/A.java", "usages")).resolves.toBe(false);
|
||||
await expect(synchronizeDocumentIndexes("/project/A.java", "usages")).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it("retries a failed batch before the next usages or refactoring", async () => {
|
||||
off = startPluginNavigation();
|
||||
await vi.advanceTimersByTimeAsync(250);
|
||||
mocks.index.mockResolvedValueOnce({ status: "error", error: { kind: "unavailable", message: "indexer failed" } });
|
||||
mocks.events.get("fsChanged")?.({ created: [], modified: ["/project/A.xml"], removed: [] });
|
||||
await vi.advanceTimersByTimeAsync(40);
|
||||
mocks.index.mockClear();
|
||||
await expect(synchronizeDocumentIndexes("/project/A.java", "refactor")).resolves.toBe(true);
|
||||
expect(mocks.index).toHaveBeenCalledWith(["/project/A.xml"], expect.any(Number));
|
||||
await expect(synchronizeDocumentIndexes("/project/A.java", "usages")).resolves.toBe(true);
|
||||
await expect(synchronizeDocumentIndexes("/project/A.xml")).rejects.toThrow("Plugin indexes are still updating");
|
||||
});
|
||||
|
||||
it.each(["/project/notes.txt", "/external/Other.xml", "jdt://contents/Other.xml"])(
|
||||
@@ -205,13 +179,13 @@ it.each(["/project/notes.txt", "/external/Other.xml", "jdt://contents/Other.xml"
|
||||
mocks.index.mockImplementationOnce(() => new Promise(() => {}));
|
||||
mocks.events.get("fsChanged")?.({ created: [], modified: ["/project/A.xml"], removed: [] });
|
||||
await vi.advanceTimersByTimeAsync(40);
|
||||
await synchronizeDocumentIndexes(path, "refactor");
|
||||
await synchronizeDocumentIndexes(path);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps unrelated language-server queries available when plugin discovery fails", async () => {
|
||||
mocks.files.mockRejectedValue(new Error("Plugin file inventory is unavailable"));
|
||||
off = startPluginNavigation();
|
||||
await expect(synchronizeDocumentIndexes("/project/notes.txt", "refactor")).resolves.toBe(true);
|
||||
await expect(synchronizeDocumentIndexes("/project/notes.txt")).resolves.toBeUndefined();
|
||||
expect(mocks.index).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -22,12 +22,9 @@ export function startPluginNavigation(): () => void {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let pending = new Set<string>();
|
||||
const dirty = new Set<string>();
|
||||
/** Paths whose last index batch failed: retried on the next usages or refactoring. */
|
||||
const failed = new Set<string>();
|
||||
const views = new Map<EditorView, string>();
|
||||
let discovered = false;
|
||||
let discovering = false;
|
||||
let discoveryFailed = false;
|
||||
const known = new Set<string>();
|
||||
let signature = "";
|
||||
let reportedError = false;
|
||||
@@ -82,22 +79,13 @@ export function startPluginNavigation(): () => void {
|
||||
await call(commands.pluginNavigationIndex(paths, id));
|
||||
if (at === generation) {
|
||||
paths.forEach((p) => {
|
||||
failed.delete(p);
|
||||
if (!pending.has(p)) dirty.delete(p);
|
||||
});
|
||||
notify();
|
||||
}
|
||||
} catch (error) {
|
||||
if (at === generation && isCancelled(error)) paths.forEach((p) => pending.add(p));
|
||||
else if (at === generation) {
|
||||
// Not "still updating": the batch is done, its paths just have no fresh index.
|
||||
paths.forEach((p) => {
|
||||
if (pending.has(p)) return;
|
||||
dirty.delete(p);
|
||||
failed.add(p);
|
||||
});
|
||||
report(error);
|
||||
}
|
||||
else if (at === generation) report(error);
|
||||
} finally {
|
||||
request = null;
|
||||
running = false;
|
||||
@@ -132,14 +120,12 @@ export function startPluginNavigation(): () => void {
|
||||
if (at !== generation) return;
|
||||
fileExtensions = new Set(inventory.extensions);
|
||||
discovered = !inventory.indexing;
|
||||
discoveryFailed = false;
|
||||
const fresh = inventory.paths.filter((p) => !known.has(p));
|
||||
inventory.paths.forEach((p) => known.add(p));
|
||||
queue(fresh);
|
||||
queue([...views.values()], true);
|
||||
} catch (error) {
|
||||
discovered = false;
|
||||
discoveryFailed = true;
|
||||
report(error);
|
||||
} finally {
|
||||
if (at === generation) discovering = false;
|
||||
@@ -153,11 +139,9 @@ export function startPluginNavigation(): () => void {
|
||||
clearTimeout(timer);
|
||||
pending.clear();
|
||||
dirty.clear();
|
||||
failed.clear();
|
||||
known.clear();
|
||||
discovered = false;
|
||||
discovering = false;
|
||||
discoveryFailed = false;
|
||||
discovery = null;
|
||||
reportedError = false;
|
||||
notify();
|
||||
@@ -167,41 +151,32 @@ export function startPluginNavigation(): () => void {
|
||||
.catch(() => {});
|
||||
}
|
||||
const offs = [
|
||||
registerDocumentIndexSync(async (path, purpose) => {
|
||||
registerDocumentIndexSync(async (path) => {
|
||||
if (!ready()) return;
|
||||
const root = useProject.getState().project!.root;
|
||||
if (!path.startsWith(root.endsWith("/") ? root : `${root}/`)) return;
|
||||
const at = generation;
|
||||
await discover();
|
||||
if (!eligible(path)) return;
|
||||
if (failed.size) queue([...failed]);
|
||||
while (ready() && at === generation && (pending.size || flushing)) {
|
||||
clearTimeout(timer);
|
||||
await flush();
|
||||
}
|
||||
const complete = at === generation && discovered && !dirty.size && !failed.size;
|
||||
if (complete) return true;
|
||||
if (purpose === "usages") return false;
|
||||
if (at === generation && (failed.size || discoveryFailed)) {
|
||||
throw new Error(tx`Plugin indexes could not be updated; see the plugin notification`);
|
||||
if (at !== generation || !discovered || dirty.size) {
|
||||
throw new Error(tx`Plugin indexes are still updating; try again shortly`);
|
||||
}
|
||||
throw new Error(tx`Plugin indexes are still updating; try again shortly`);
|
||||
}),
|
||||
pluginsBackend().onEvent((event) => {
|
||||
if (event.type === "documentIndexesChanged") reset();
|
||||
}),
|
||||
registerNavigationProvider(async (view, offset) => {
|
||||
const doc = docOf(view);
|
||||
if (!ready() || !doc || doc.virtual || !eligible(doc.path) || dirty.has(doc.path) || failed.has(doc.path))
|
||||
return null;
|
||||
if (!ready() || !doc || doc.virtual || !eligible(doc.path) || dirty.has(doc.path)) return null;
|
||||
const before = view.state.doc;
|
||||
await whenSynced(view);
|
||||
const result = await call(commands.pluginNavigationGoto(doc.doc, offsetToPos(before, offset)));
|
||||
if (!result || view.state.doc !== before) return null;
|
||||
return {
|
||||
...rangeToOffsets(before, result.range),
|
||||
targets: result.targets.filter((t) => !dirty.has(t.path) && !failed.has(t.path)),
|
||||
};
|
||||
return { ...rangeToOffsets(before, result.range), targets: result.targets.filter((t) => !dirty.has(t.path)) };
|
||||
}),
|
||||
registerEditorContribution({
|
||||
id: "plugins.navigation",
|
||||
|
||||
@@ -51,8 +51,7 @@ const Line = memo(
|
||||
if (link.kind === "url") void openUrl(link.url);
|
||||
else void openTarget(link.target, cwd);
|
||||
};
|
||||
// A blank line is an empty row: its height comes from CSS, never from a character in the text.
|
||||
if (segments.length === 0) return null;
|
||||
if (segments.length === 0) return <>{""}</>;
|
||||
return (
|
||||
<>
|
||||
{segments.map((seg, i) => {
|
||||
@@ -189,12 +188,6 @@ export function ConsoleView({
|
||||
const editorFont = useProject((s) => s.settings?.editor);
|
||||
const consoleFont = resolveMonoFont(terminalFont, editorFont);
|
||||
const rowHeight = Math.max(16, Math.round(consoleFont.size * 1.5));
|
||||
/** A row's box: at its virtual offset, and never shorter than one line — a blank line has no text. */
|
||||
const rowStyle = (start: number) => ({
|
||||
transform: `translateY(${start}px)`,
|
||||
height: softWrap ? undefined : rowHeight,
|
||||
minHeight: rowHeight,
|
||||
});
|
||||
const [expanded, setExpanded] = useState<ReadonlySet<number>>(() => new Set());
|
||||
const [internalFindOpen, setInternalFindOpen] = useState(false);
|
||||
const findOpen = controlledFindOpen ?? internalFindOpen;
|
||||
@@ -574,7 +567,7 @@ export function ConsoleView({
|
||||
data-index={item.index}
|
||||
ref={softWrap ? virtualizer.measureElement : undefined}
|
||||
className={styles.line}
|
||||
style={rowStyle(item.start)}
|
||||
style={{ transform: `translateY(${item.start}px)`, height: softWrap ? undefined : rowHeight }}
|
||||
>
|
||||
{pendingInput}
|
||||
</div>
|
||||
@@ -587,7 +580,7 @@ export function ConsoleView({
|
||||
data-index={item.index}
|
||||
ref={softWrap ? virtualizer.measureElement : undefined}
|
||||
className={styles.line}
|
||||
style={rowStyle(item.start)}
|
||||
style={{ transform: `translateY(${item.start}px)`, height: softWrap ? undefined : rowHeight }}
|
||||
>
|
||||
{foldButton(row.fold, false)}
|
||||
</div>
|
||||
@@ -601,7 +594,7 @@ export function ConsoleView({
|
||||
data-index={item.index}
|
||||
ref={softWrap ? virtualizer.measureElement : undefined}
|
||||
className={clsx(styles.line, styles[line.kind])}
|
||||
style={rowStyle(item.start)}
|
||||
style={{ transform: `translateY(${item.start}px)`, height: softWrap ? undefined : rowHeight }}
|
||||
>
|
||||
<Line line={line} marks={marksByLine.get(row.index)} length={line.text.length} cwd={cwd} />
|
||||
{row.fold && foldButton(row.fold, true)}
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { ConsoleModel } from "./console";
|
||||
import { ConsoleView } from "./ConsoleView";
|
||||
|
||||
const clipboard = vi.hoisted(() => ({ writeText: vi.fn(async (_text: string) => {}) }));
|
||||
|
||||
vi.mock("@tanstack/react-virtual", () => ({
|
||||
useVirtualizer: ({ count }: { count: number }) => ({
|
||||
getTotalSize: () => count * 20,
|
||||
getVirtualItems: () => Array.from({ length: count }, (_, index) => ({ index, start: index * 20, key: index })),
|
||||
scrollToIndex: () => {},
|
||||
measureElement: () => {},
|
||||
measure: () => {},
|
||||
}),
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
usePlatform.setState({ os: "macos" });
|
||||
clipboard.writeText.mockClear();
|
||||
Object.defineProperty(navigator, "clipboard", { configurable: true, value: clipboard });
|
||||
window.getSelection()?.removeAllRanges();
|
||||
});
|
||||
|
||||
function setup(text: string, softWrap = false) {
|
||||
const model = new ConsoleModel();
|
||||
model.append({ kind: "stdout", text });
|
||||
model.flush();
|
||||
const view = render(
|
||||
<ConsoleView model={model} version={1} softWrap={softWrap} follow={false} onFollowChange={() => {}} cwd="/" />,
|
||||
);
|
||||
return { model, log: screen.getByRole("log"), view };
|
||||
}
|
||||
|
||||
/** The text a Select All + Copy takes: every mounted row, in order. */
|
||||
function selectedText(log: HTMLElement) {
|
||||
const inner = log.firstElementChild!;
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(inner);
|
||||
const selection = window.getSelection()!;
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
return selection.toString();
|
||||
}
|
||||
|
||||
describe("Copying run output", () => {
|
||||
it("takes blank lines from the buffer, adding no zero-width space", () => {
|
||||
const { model, log } = setup("first\n\nsecond\n");
|
||||
expect(model.text()).toBe("first\n\nsecond");
|
||||
// A blank line is one empty row: it may only contribute its own line break.
|
||||
expect(selectedText(log).split("\n")).toEqual(["first", "", "second", ""]);
|
||||
expect(log.textContent).not.toContain("\u200b");
|
||||
});
|
||||
|
||||
it("keeps the zero-width space out of soft-wrapped output too", () => {
|
||||
const { log } = setup("first\n\nsecond\n", true);
|
||||
expect(selectedText(log).split("\n")).toEqual(["first", "", "second", ""]);
|
||||
expect(log.textContent).not.toContain("\u200b");
|
||||
});
|
||||
|
||||
it("still renders a row for every line, blank ones included", () => {
|
||||
const { model, log } = setup("first\n\n\nsecond\n");
|
||||
expect(model.lines).toHaveLength(4);
|
||||
expect(log.querySelectorAll("[data-index]")).toHaveLength(model.lines.length);
|
||||
expect(log.textContent?.replace(/\n/g, "")).toBe("first" + "second");
|
||||
});
|
||||
|
||||
it("puts the same text on the clipboard when a selection is copied with ⌘C", async () => {
|
||||
const { log } = setup("first\n\nsecond\n");
|
||||
// A selection of the rows, not Select All: that path copies the model and would hide a character
|
||||
// the DOM adds.
|
||||
const rows = log.querySelectorAll("[data-index]");
|
||||
const range = document.createRange();
|
||||
range.setStart(rows[0]!, 0);
|
||||
range.setEnd(rows[2]!, rows[2]!.childNodes.length);
|
||||
const selection = window.getSelection()!;
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
fireEvent.keyDown(log, { key: "c", code: "KeyC", metaKey: true });
|
||||
await waitFor(() => expect(clipboard.writeText).toHaveBeenCalledTimes(1));
|
||||
// Three rows, each ending in its own break: the blank one contributes nothing else.
|
||||
expect(clipboard.writeText.mock.calls[0]![0]).toBe("first\n\nsecond\n");
|
||||
});
|
||||
});
|
||||
@@ -121,43 +121,6 @@ describe("SeController", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("lists scratch files with the indexed files, ranked by name", async () => {
|
||||
const outsideFiles = vi.fn(async () => [
|
||||
{ path: "/data/scratches/scratch_3.md", relPath: "Scratches/scratch_3.md" },
|
||||
{ path: "/data/scratches/notes.txt", relPath: "Scratches/notes.txt" },
|
||||
]);
|
||||
const { c, last } = setup({
|
||||
findFiles: async () => [{ ...fm("tests/test_scratch_dir.py"), score: (1 << 20) + 50 }],
|
||||
outsideFiles,
|
||||
inFileSet: (set, path) => path.startsWith("/p/") && (set === "all" || set === "test"),
|
||||
});
|
||||
c.run({ query: "scratch_3", tab: "files", includeNonProject: false, extra: {} });
|
||||
await flush();
|
||||
expect(last().sections.get("files")!.items[0]).toMatchObject({
|
||||
key: "f:/data/scratches/scratch_3.md",
|
||||
name: "scratch_3.md",
|
||||
dir: "Scratches",
|
||||
nameIndices: [0, 1, 2, 3, 4, 5, 6, 7, 8],
|
||||
});
|
||||
|
||||
c.run({ query: "scratch", tab: "files", includeNonProject: false, extra: {} });
|
||||
await flush();
|
||||
expect(
|
||||
last()
|
||||
.sections.get("files")!
|
||||
.items.map((i) => i.key),
|
||||
).toEqual(["f:/data/scratches/scratch_3.md", "f:/p/tests/test_scratch_dir.py"]);
|
||||
|
||||
// Production / test file sets are project scopes.
|
||||
c.run({ query: "scratch", tab: "files", includeNonProject: false, fileSet: "test", extra: {} });
|
||||
await flush();
|
||||
expect(
|
||||
last()
|
||||
.sections.get("files")!
|
||||
.items.map((i) => i.key),
|
||||
).not.toContain("f:/data/scratches/scratch_3.md");
|
||||
});
|
||||
|
||||
it("parses File.kt:42 and opens files at the line", async () => {
|
||||
const findFiles = vi.fn(async () => [fm("File.kt")]);
|
||||
const { c, last } = setup({ findFiles });
|
||||
|
||||
@@ -28,13 +28,11 @@ import {
|
||||
fileItem,
|
||||
folderItem,
|
||||
matchActions,
|
||||
matchOutsideFiles,
|
||||
matchSettings,
|
||||
mergeActionResults,
|
||||
mergeSymbols,
|
||||
sectionsFor,
|
||||
textItems,
|
||||
type OutsideFile,
|
||||
type SeItem,
|
||||
type SeTab,
|
||||
type SectionId,
|
||||
@@ -45,8 +43,6 @@ export interface SeDeps {
|
||||
findFiles(query: string, limit: number): Promise<FileMatch[]>;
|
||||
/** Directories by name or path (`relPath` ending in `/`), listed with the files. */
|
||||
findDirs?(query: string, limit: number): Promise<FileMatch[]>;
|
||||
/** Files outside the project index listed with its matches (Scratches). */
|
||||
outsideFiles?(): Promise<OutsideFile[]>;
|
||||
findSymbols(query: string, filter: SymbolFilter, limit: number): Promise<SymbolMatch[]>;
|
||||
/** Optional language-server symbols; rejects with `unavailable` when no server. */
|
||||
workspaceSymbols?(request: RequestId, query: string): Promise<WorkspaceSymbol[]>;
|
||||
@@ -264,18 +260,15 @@ export class SeController {
|
||||
// Directories rank with the files (equal scores: the file first); a file type filter
|
||||
// and a `File.kt:42` query ask for files only.
|
||||
const withDirs = !!this.deps.findDirs && !!text && !filter && q.line === null;
|
||||
const [indexed, dirs, outside] = await Promise.all([
|
||||
const [fetched, dirs] = await Promise.all([
|
||||
this.deps.findFiles(text, want),
|
||||
withDirs ? this.deps.findDirs!(text, want).catch(() => []) : [],
|
||||
text && this.deps.outsideFiles ? this.deps.outsideFiles().catch(() => []) : [],
|
||||
]);
|
||||
const fetched = outside.length ? [...indexed, ...matchOutsideFiles(outside, text)] : indexed;
|
||||
const merged =
|
||||
dirs.length || outside.length
|
||||
? [...fetched.map((m) => ({ m, folder: false })), ...dirs.map((m) => ({ m, folder: true }))].sort(
|
||||
(a, b) => b.m.score - a.m.score || Number(a.folder) - Number(b.folder),
|
||||
)
|
||||
: fetched.map((m) => ({ m, folder: false }));
|
||||
const merged = dirs.length
|
||||
? [...fetched.map((m) => ({ m, folder: false })), ...dirs.map((m) => ({ m, folder: true }))].sort(
|
||||
(a, b) => b.m.score - a.m.score || Number(a.folder) - Number(b.folder),
|
||||
)
|
||||
: fetched.map((m) => ({ m, folder: false }));
|
||||
const matches = keep ? merged.filter(({ m }) => keep(m.path)) : merged;
|
||||
this.set(
|
||||
id,
|
||||
|
||||
@@ -2,21 +2,17 @@ import { allActions, type Action } from "@/platform/actions";
|
||||
import { evaluateWhen, type ContextKeys } from "@/platform/context";
|
||||
import { call, commands, nextRequestId, type LanguageInfo } from "@/platform/ipc";
|
||||
import { inFileSet } from "@/platform/projectRoots";
|
||||
import { searchEndpoints, searchableSettings, useProjectViewRoots } from "@/workbench/contributions";
|
||||
import { searchEndpoints, searchableSettings } from "@/workbench/contributions";
|
||||
import { projectRoot } from "../common/open";
|
||||
import { cancelRequest, streamSearch } from "@/platform/textSearch";
|
||||
import type { SeDeps } from "./controller";
|
||||
import type { OutsideFile } from "./model";
|
||||
import { recentActions } from "./store";
|
||||
|
||||
/** Backend-backed sources; action enablement is judged against `ctx` (captured on open). */
|
||||
export function ipcDeps(ctx: ContextKeys): SeDeps {
|
||||
let outside: Promise<OutsideFile[]> | null = null;
|
||||
return {
|
||||
findFiles: (q, limit) => call(commands.findFiles(q, limit)),
|
||||
findDirs: (q, limit) => call(commands.findDirs(q, limit)),
|
||||
// Listed once per popup: scratch files are few and change only through the IDE.
|
||||
outsideFiles: () => (outside ??= listScratchFiles()),
|
||||
findSymbols: (q, filter, limit) => call(commands.findSymbols(q, filter, limit)),
|
||||
workspaceSymbols: (request, q) => call(commands.lspWorkspaceSymbols(request, q)),
|
||||
searchText: async (request, query, onFile) => {
|
||||
@@ -51,24 +47,3 @@ export function loadLanguages(): Promise<LanguageInfo[]> {
|
||||
return [];
|
||||
}));
|
||||
}
|
||||
|
||||
const MAX_OUTSIDE_FILES = 2000;
|
||||
const MAX_OUTSIDE_DEPTH = 4;
|
||||
|
||||
/** Files under the project view's Scratches roots, as `<root label>/<relative path>`. */
|
||||
async function listScratchFiles(): Promise<OutsideFile[]> {
|
||||
const out: OutsideFile[] = [];
|
||||
const walk = async (dir: string, rel: string, depth: number) => {
|
||||
const entries = await call(commands.fsReadDir(dir)).catch(() => []);
|
||||
for (const e of entries) {
|
||||
if (out.length >= MAX_OUTSIDE_FILES) return;
|
||||
const path = e.path;
|
||||
if (e.kind === "dir") {
|
||||
if (depth < MAX_OUTSIDE_DEPTH) await walk(path, `${rel}/${e.name}`, depth + 1);
|
||||
} else out.push({ path, relPath: `${rel}/${e.name}` });
|
||||
}
|
||||
};
|
||||
for (const root of useProjectViewRoots.getState().roots.values())
|
||||
if (root.scope === "scratches" && root.path) await walk(root.path, root.label, 0);
|
||||
return out;
|
||||
}
|
||||
@@ -8,7 +8,6 @@ import type { SettingsSearchEntry } from "@/workbench/contributions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { basename, isTypeKind, relDir, symbolDisplayName } from "../common/open";
|
||||
import { byScore, matchText } from "../common/rank";
|
||||
import { wordMatch } from "@/ui";
|
||||
|
||||
export type SeTab = "all" | "classes" | "files" | "symbols" | "actions" | "text";
|
||||
export type SectionId = "recent" | "recentActions" | "classes" | "files" | "symbols" | "endpoints" | "actions" | "text";
|
||||
@@ -172,51 +171,6 @@ export function fileItem(
|
||||
};
|
||||
}
|
||||
|
||||
/** File outside the project index (a scratch file); `relPath` is shown under its root label. */
|
||||
export interface OutsideFile {
|
||||
path: string;
|
||||
relPath: string;
|
||||
}
|
||||
|
||||
// The project index's file scores (`ide-index` matching.rs): a name match ranks in a tier
|
||||
// above path-only matches, with exact / exact-stem / prefix boosts.
|
||||
const NAME_TIER = 1 << 20;
|
||||
|
||||
function nameBoost(name: string, q: string): number {
|
||||
const n = name.toLowerCase();
|
||||
if (n === q) return 4000;
|
||||
const dot = n.indexOf(".");
|
||||
if (dot >= 0 && n.slice(0, dot) === q) return 3000;
|
||||
return n.startsWith(q) ? 600 : 0;
|
||||
}
|
||||
|
||||
/** Files outside the index matching a Files query by name (or by path for `dir/name`), scored like the index's. */
|
||||
export function matchOutsideFiles(files: readonly OutsideFile[], query: string): FileMatch[] {
|
||||
const q = query
|
||||
.trim()
|
||||
.replace(/\\/g, "/")
|
||||
.replace(/^\.?\/+/, "")
|
||||
.replace(/\s+/g, "")
|
||||
.toLowerCase();
|
||||
if (!q) return [];
|
||||
const byPath = q.includes("/");
|
||||
const out: FileMatch[] = [];
|
||||
for (const f of files) {
|
||||
const name = basename(f.relPath);
|
||||
const nameStart = f.relPath.length - name.length;
|
||||
const m = byPath ? wordMatch(f.relPath, q) : wordMatch(name, q);
|
||||
if (!m) continue;
|
||||
const boost = nameBoost(name, byPath ? q.slice(q.lastIndexOf("/") + 1) : q);
|
||||
out.push({
|
||||
path: f.path,
|
||||
relPath: f.relPath,
|
||||
score: (byPath ? 0 : NAME_TIER) + boost,
|
||||
indices: byPath ? m : m.map((i) => i + nameStart),
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A directory match (`relPath` ends in `/`), listed with the files as IDEA's Go to File does. */
|
||||
export function folderItem(m: Pick<FileMatch, "path" | "relPath" | "indices">): FileItem {
|
||||
const rel = m.relPath.replace(/\/$/, "");
|
||||
|
||||
@@ -79,7 +79,14 @@ describe("page tree", () => {
|
||||
);
|
||||
const appearance = BEHAVIOR_PAGES.find((p) => p.id === "appearance")!;
|
||||
expect(specLabels(appearance)).toEqual(
|
||||
expect.arrayContaining(["Accent color", "High Contrast", "UI font size", "Zoom", "Compact mode", "Antialiasing"]),
|
||||
expect.arrayContaining([
|
||||
"Accent colour",
|
||||
"High Contrast",
|
||||
"UI font size",
|
||||
"Zoom",
|
||||
"Compact mode",
|
||||
"Antialiasing",
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -196,8 +196,8 @@ function AccentRow() {
|
||||
const [accent, setAccent] = useSetting<string>("appearance.accent");
|
||||
return (
|
||||
<Indented>
|
||||
<Row label="Accent color">
|
||||
<ColorSwatches value={accent} presets={ACCENT_PRESETS} onChange={setAccent} aria-label="Accent color" />
|
||||
<Row label="Accent colour">
|
||||
<ColorSwatches value={accent} presets={ACCENT_PRESETS} onChange={setAccent} aria-label="Accent colour" />
|
||||
</Row>
|
||||
</Indented>
|
||||
);
|
||||
@@ -745,7 +745,7 @@ export const BEHAVIOR_PAGES: PageSpec[] = [
|
||||
keywords: ["icons", "file icons", "icon theme"],
|
||||
component: FileIconThemeRow,
|
||||
},
|
||||
{ kind: "custom", label: "Accent color", keywords: ["accent colour", "highlight"], component: AccentRow },
|
||||
{ kind: "custom", label: "Accent colour", keywords: ["accent color", "highlight"], component: AccentRow },
|
||||
{ kind: "custom", label: "Different tool window background", component: ToolWindowBackgroundRow },
|
||||
],
|
||||
},
|
||||
|
||||
@@ -241,9 +241,7 @@ const SAMPLES: Record<string, CodeSample> = {
|
||||
["black ", "ansiBlack"],
|
||||
["red ", "ansiRed"],
|
||||
["green ", "ansiGreen"],
|
||||
["yellow", "ansiYellow"],
|
||||
],
|
||||
[
|
||||
["yellow ", "ansiYellow"],
|
||||
["blue ", "ansiBlue"],
|
||||
["magenta ", "ansiMagenta"],
|
||||
["cyan ", "ansiCyan"],
|
||||
@@ -253,9 +251,7 @@ const SAMPLES: Record<string, CodeSample> = {
|
||||
["dark ", "ansiBrightBlack"],
|
||||
["bright-red ", "ansiBrightRed"],
|
||||
["bright-green ", "ansiBrightGreen"],
|
||||
["bright-yellow", "ansiBrightYellow"],
|
||||
],
|
||||
[
|
||||
["bright-yellow ", "ansiBrightYellow"],
|
||||
["bright-blue ", "ansiBrightBlue"],
|
||||
["bright-magenta ", "ansiBrightMagenta"],
|
||||
["bright-cyan ", "ansiBrightCyan"],
|
||||
|
||||
@@ -160,8 +160,6 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
/* A narrow panel moves Commit and Push… to its own row rather than cutting its label. */
|
||||
flex-wrap: wrap;
|
||||
padding: 8px 6px 10px 10px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
@@ -1167,7 +1167,7 @@ function CommitPanel({ included }: { included: number }) {
|
||||
className={styles.pushButton}
|
||||
disabled={!canCommit || !!remoteBusy}
|
||||
onClick={() => void runner.run(true)}
|
||||
title={`${tx(commitAndPushLabel(amend))} (⌥⌘↩)`}
|
||||
title="⌥⌘↩"
|
||||
>
|
||||
<span>
|
||||
<T>{commitAndPushLabel(amend)}</T>
|
||||
|
||||
@@ -287,8 +287,6 @@ describe("catalogs", () => {
|
||||
"CMake",
|
||||
"f-string",
|
||||
"Tailwind CSS",
|
||||
"Bun",
|
||||
"bun-dap (Bun)",
|
||||
]);
|
||||
const translated = SUPPORTED_LOCALES.filter((locale) => locale !== "en").sort();
|
||||
|
||||
|
||||
@@ -1344,7 +1344,5 @@
|
||||
"Close Agent Task": "Close Agent Task",
|
||||
"Close and New Agent Task": "Close and New Agent Task",
|
||||
"Closes the agent task tab in the editor; the task keeps running in the Agents tool window.": "Closes the agent task tab in the editor; the task keeps running in the Agents tool window.",
|
||||
"Closes the agent task tab in the editor, then opens the New Task page.": "Closes the agent task tab in the editor, then opens the New Task page.",
|
||||
"May be incomplete: plugin indexes are still updating": "May be incomplete: plugin indexes are still updating",
|
||||
"Plugin indexes could not be updated; see the plugin notification": "Plugin indexes could not be updated; see the plugin notification"
|
||||
"Closes the agent task tab in the editor, then opens the New Task page.": "Closes the agent task tab in the editor, then opens the New Task page."
|
||||
}
|
||||
@@ -169,6 +169,7 @@
|
||||
"Absolute Path": "Ruta absoluta",
|
||||
"Absolute path of the current file": "Ruta absoluta del archivo actual",
|
||||
"Accent color": "Color de acento",
|
||||
"Accent colour": "Color de acento",
|
||||
"Accept Both (Conflict at Caret)": "Aceptar ambos (conflicto en el cursor)",
|
||||
"Accept Theirs": "Aceptar los suyos",
|
||||
"Accept Theirs (Conflict at Caret)": "Aceptar los suyos (conflicto en el cursor)",
|
||||
|
||||
@@ -123,6 +123,7 @@
|
||||
"Absolute Path": "Chemin absolu",
|
||||
"Absolute path of the current file": "Chemin absolu du fichier actuel",
|
||||
"Accent color": "Couleur d'accentuation",
|
||||
"Accent colour": "Couleur d'accentuation",
|
||||
"Accept Both (Conflict at Caret)": "Accepter les deux (conflit au curseur)",
|
||||
"Accept Theirs": "Accepter leur version",
|
||||
"Accept Theirs (Conflict at Caret)": "Accepter leur version (conflit au curseur)",
|
||||
|
||||
@@ -204,6 +204,7 @@
|
||||
"Absolute Path": "절대 경로",
|
||||
"Absolute path of the current file": "현재 파일의 절대 경로",
|
||||
"Accent color": "강조 색상",
|
||||
"Accent colour": "강조 색상",
|
||||
"Accept Both (Conflict at Caret)": "둘 다 수락(캐럿 위치의 충돌)",
|
||||
"Accept Theirs": "다른 이의 변경 사항 수락",
|
||||
"Accept Theirs (Conflict at Caret)": "다른 이의 변경 사항 수락(캐럿 위치의 충돌)",
|
||||
|
||||
@@ -161,6 +161,7 @@
|
||||
"Absolute Path": "Ścieżka bezwzględna",
|
||||
"Absolute path of the current file": "Ścieżka bezwzględna bieżącego pliku",
|
||||
"Accent color": "Kolor akcentu",
|
||||
"Accent colour": "Kolor akcentu",
|
||||
"Accept Both (Conflict at Caret)": "Zaakceptuj oba (konflikt przy kursorze)",
|
||||
"Accept Theirs": "Zaakceptuj ich (ze zmian)",
|
||||
"Accept Theirs (Conflict at Caret)": "Zaakceptuj ich (konflikt przy kursorze)",
|
||||
|
||||
@@ -161,6 +161,7 @@
|
||||
"Absolute Path": "Caminho absoluto",
|
||||
"Absolute path of the current file": "Caminho absoluto do arquivo atual",
|
||||
"Accent color": "Cor de destaque",
|
||||
"Accent colour": "Cor de destaque",
|
||||
"Accept Both (Conflict at Caret)": "Aceitar ambos (conflito no cursor)",
|
||||
"Accept Theirs": "Aceitar deles",
|
||||
"Accept Theirs (Conflict at Caret)": "Aceitar deles (conflito no cursor)",
|
||||
|
||||
@@ -534,6 +534,7 @@
|
||||
"Absolute Path": "绝对路径",
|
||||
"Absolute path of the current file": "当前文件的绝对路径",
|
||||
"Accent color": "强调色",
|
||||
"Accent colour": "强调色",
|
||||
"Accept Both (Conflict at Caret)": "全部接受(光标处的冲突)",
|
||||
"Accept Theirs": "接受他们的",
|
||||
"Accept Theirs (Conflict at Caret)": "接受他们的(光标处的冲突)",
|
||||
@@ -7731,7 +7732,5 @@
|
||||
"Download Remote Files Into Folder": "将远程文件下载到文件夹",
|
||||
"Download Remote Host files into a local folder (arg: { server, paths, target })": "将远程主机中的文件下载到本地文件夹(参数:{ server, paths, target })",
|
||||
"Delegate IDE build/run actions to Maven": "将 IDE 构建/运行操作委托给 Maven",
|
||||
"Run and Debug build Maven modules with Maven (the project's javac) instead of the Java language server. Editor problems still come from the language server.": "运行和调试时用 Maven(项目的 javac)构建 Maven 模块,而不是用 Java 语言服务器。编辑器中的问题仍来自语言服务器。",
|
||||
"May be incomplete: plugin indexes are still updating": "可能不完整:插件索引仍在更新",
|
||||
"Plugin indexes could not be updated; see the plugin notification": "插件索引更新失败,详见插件通知"
|
||||
"Run and Debug build Maven modules with Maven (the project's javac) instead of the Java language server. Editor problems still come from the language server.": "运行和调试时用 Maven(项目的 javac)构建 Maven 模块,而不是用 Java 语言服务器。编辑器中的问题仍来自语言服务器。"
|
||||
}
|
||||
+2
-43
@@ -455,15 +455,7 @@ export function Menu({ open, onClose, anchor, items, placement = "bottom-start",
|
||||
// Context menus
|
||||
|
||||
interface ContextMenuState {
|
||||
menu: {
|
||||
x: number;
|
||||
y: number;
|
||||
items: MenuItem[];
|
||||
numbers: boolean;
|
||||
id: number;
|
||||
/** The text selection the menu was opened on (see `restoreSelection`). */
|
||||
selection: Range[] | null;
|
||||
} | null;
|
||||
menu: { x: number; y: number; items: MenuItem[]; numbers: boolean; id: number } | null;
|
||||
}
|
||||
|
||||
export const useContextMenuStore = create<ContextMenuState>(() => ({ menu: null }));
|
||||
@@ -476,32 +468,7 @@ export function showContextMenu(
|
||||
) {
|
||||
const x = "clientX" in at ? at.clientX : at.x;
|
||||
const y = "clientY" in at ? at.clientY : at.y;
|
||||
useContextMenuStore.setState({
|
||||
menu: { x, y, items, numbers: !!options?.numbers, id: ++menuSeq, selection: textSelection() },
|
||||
});
|
||||
}
|
||||
|
||||
/** The page's text selection, unless it is in an editable element (editors keep their own). */
|
||||
function textSelection(): Range[] | null {
|
||||
const sel = document.getSelection();
|
||||
if (!sel || sel.isCollapsed || !sel.rangeCount) return null;
|
||||
const node = sel.anchorNode;
|
||||
const el = node instanceof Element ? node : node?.parentElement;
|
||||
if (!el || el.closest("input, textarea, [contenteditable]:not([contenteditable='false'])")) return null;
|
||||
return Array.from({ length: sel.rangeCount }, (_, i) => sel.getRangeAt(i).cloneRange());
|
||||
}
|
||||
|
||||
/**
|
||||
* WebKit drops a page's text selection when focus moves to another element, as when the menu
|
||||
* focuses its first row and when it gives focus back: put the selection the menu was opened on
|
||||
* back, so it stays highlighted while its Copy / Quote apply to it.
|
||||
*/
|
||||
function restoreSelection(ranges: readonly Range[]) {
|
||||
const sel = document.getSelection();
|
||||
if (!sel || !sel.isCollapsed) return;
|
||||
if (!ranges.every((r) => r.startContainer.isConnected && r.endContainer.isConnected)) return;
|
||||
sel.removeAllRanges();
|
||||
for (const r of ranges) sel.addRange(r);
|
||||
useContextMenuStore.setState({ menu: { x, y, items, numbers: !!options?.numbers, id: ++menuSeq } });
|
||||
}
|
||||
|
||||
export function hideContextMenu() {
|
||||
@@ -511,14 +478,6 @@ export function hideContextMenu() {
|
||||
/** Renders the active context menu; mount once (the workbench does). */
|
||||
export function ContextMenuHost() {
|
||||
const menu = useContextMenuStore((s) => s.menu);
|
||||
const selection = menu?.selection ?? null;
|
||||
// After the rows' layout effects: the first row has taken focus.
|
||||
useLayoutEffect(() => {
|
||||
if (!selection) return;
|
||||
restoreSelection(selection);
|
||||
// After the popup has given focus back; a click elsewhere selects afresh after this.
|
||||
return () => queueMicrotask(() => restoreSelection(selection));
|
||||
}, [selection]);
|
||||
if (!menu) return null;
|
||||
return (
|
||||
<Popup
|
||||
|
||||
@@ -193,31 +193,6 @@ describe("Menu action enablement", () => {
|
||||
expect(input).toHaveFocus();
|
||||
});
|
||||
|
||||
it("keeps the text selection a context menu was opened on", async () => {
|
||||
render(
|
||||
<>
|
||||
<p>Selected text</p>
|
||||
<ContextMenuHost />
|
||||
</>,
|
||||
);
|
||||
// WebKit drops the page's selection whenever focus moves.
|
||||
const drop = () => document.getSelection()!.removeAllRanges();
|
||||
document.addEventListener("focusin", drop);
|
||||
try {
|
||||
const text = screen.getByText("Selected text").firstChild!;
|
||||
document.getSelection()!.setBaseAndExtent(text, 0, text, 8);
|
||||
act(() => showContextMenu({ x: 0, y: 0 }, [{ label: "Copy", run: () => undefined }]));
|
||||
expect(screen.getByRole("menuitem", { name: /Copy/ })).toHaveFocus();
|
||||
expect(document.getSelection()!.toString()).toBe("Selected");
|
||||
act(() => hideContextMenu());
|
||||
await act(async () => {});
|
||||
expect(document.getSelection()!.toString()).toBe("Selected");
|
||||
} finally {
|
||||
document.removeEventListener("focusin", drop);
|
||||
document.getSelection()!.removeAllRanges();
|
||||
}
|
||||
});
|
||||
|
||||
it("highlights the row under the pointer without moving focus", () => {
|
||||
render(
|
||||
<MenuList
|
||||
|
||||
@@ -7,26 +7,12 @@ export function useSelectionBoundary(ref: RefObject<HTMLElement | null>): void {
|
||||
const root = ref.current;
|
||||
if (!root) return;
|
||||
const doc = root.ownerDocument;
|
||||
// WebKit's repaint of a shrinking selection misses the gap fills between blocks by a device
|
||||
// pixel at fractional positions, leaving a stripe; repaint the pane once per frame instead.
|
||||
let frame = 0;
|
||||
const repaint = () => {
|
||||
if (frame) return;
|
||||
frame = requestAnimationFrame(() => {
|
||||
root.style.opacity = "0.9999";
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = 0;
|
||||
root.style.removeProperty("opacity");
|
||||
});
|
||||
});
|
||||
};
|
||||
const clamp = () => {
|
||||
const selection = doc.getSelection();
|
||||
if (!selection?.anchorNode || !selection.focusNode) return;
|
||||
if (!selection?.anchorNode || !selection.focusNode || selection.isCollapsed) return;
|
||||
const anchorIn = root.contains(selection.anchorNode);
|
||||
const focusIn = root.contains(selection.focusNode);
|
||||
if (anchorIn || focusIn) repaint();
|
||||
if (selection.isCollapsed || anchorIn === focusIn) return;
|
||||
if (anchorIn === focusIn) return;
|
||||
|
||||
const bounds = doc.createRange();
|
||||
bounds.selectNodeContents(root);
|
||||
@@ -40,24 +26,10 @@ export function useSelectionBoundary(ref: RefObject<HTMLElement | null>): void {
|
||||
// While a drag starts in the pane, make everything outside it unselectable so the
|
||||
// browser never extends the selection there (see global.css).
|
||||
const html = doc.documentElement;
|
||||
// A double or triple click selects a word or line at once and can reach past the pane's
|
||||
// last text into the next field (the composer). `selectionchange` comes after a paint, which
|
||||
// flashes that selection; a frame callback clamps it before.
|
||||
let clampFrame = 0;
|
||||
const clampBeforePaint = () => {
|
||||
cancelAnimationFrame(clampFrame);
|
||||
clampFrame = requestAnimationFrame(clamp);
|
||||
};
|
||||
const lock = (e: MouseEvent) => {
|
||||
if (e.button !== 0) return;
|
||||
html.setAttribute("data-selection-lock", "");
|
||||
clampBeforePaint();
|
||||
};
|
||||
const unlock = () => {
|
||||
if (!html.hasAttribute("data-selection-lock")) return;
|
||||
html.removeAttribute("data-selection-lock");
|
||||
clampBeforePaint();
|
||||
if (e.button === 0) html.setAttribute("data-selection-lock", "");
|
||||
};
|
||||
const unlock = () => html.removeAttribute("data-selection-lock");
|
||||
// Select All in the pane selects its text; the browser's would select across the whole
|
||||
// window (Ctrl+A reaches the webview directly; ⌘A goes to the native Select All).
|
||||
const selectAll = (e: KeyboardEvent) => {
|
||||
@@ -79,9 +51,6 @@ export function useSelectionBoundary(ref: RefObject<HTMLElement | null>): void {
|
||||
doc.removeEventListener("mouseup", unlock, true);
|
||||
doc.removeEventListener("dragend", unlock, true);
|
||||
doc.removeEventListener("selectionchange", clamp);
|
||||
cancelAnimationFrame(frame);
|
||||
cancelAnimationFrame(clampFrame);
|
||||
root.style.removeProperty("opacity");
|
||||
unlock();
|
||||
};
|
||||
}, [ref]);
|
||||
|
||||
@@ -1825,23 +1825,16 @@ export function addContributedFileTemplate(t: import("@/platform/fileTemplates")
|
||||
return () => useContributedFileTemplates.setState((s) => ({ templates: s.templates.filter((x) => x !== t) }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush contributed document indexes before workspace usages or refactoring. A refactoring
|
||||
* refuses (throws) while an index is incomplete; usages go ahead and resolve `false`, so the
|
||||
* results can say they may be incomplete.
|
||||
*/
|
||||
export type DocumentIndexPurpose = "usages" | "refactor";
|
||||
type DocumentIndexSync = (path: string, purpose: DocumentIndexPurpose) => Promise<boolean | void>;
|
||||
const documentIndexSync = new Set<DocumentIndexSync>();
|
||||
export function registerDocumentIndexSync(sync: DocumentIndexSync): () => void {
|
||||
/** Flush contributed document indexes before workspace usages or refactoring. */
|
||||
const documentIndexSync = new Set<(path: string) => Promise<void>>();
|
||||
export function registerDocumentIndexSync(sync: (path: string) => Promise<void>): () => void {
|
||||
documentIndexSync.add(sync);
|
||||
return () => {
|
||||
documentIndexSync.delete(sync);
|
||||
};
|
||||
}
|
||||
export async function synchronizeDocumentIndexes(path: string, purpose: DocumentIndexPurpose): Promise<boolean> {
|
||||
const complete = await Promise.all([...documentIndexSync].map((sync) => sync(path, purpose)));
|
||||
return complete.every((c) => c !== false);
|
||||
export async function synchronizeDocumentIndexes(path: string): Promise<void> {
|
||||
await Promise.all([...documentIndexSync].map((sync) => sync(path)));
|
||||
}
|
||||
|
||||
/** Font zoom for non-CodeMirror surfaces, owned and released by their features. */
|
||||
|
||||
Reference in new issue
Заблокувати користувача