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

..
Автор SHA1 Повідомлення Дата
l0ng-ai 5fb2988f69 fix(agents): anchor composer completions below the caret 2026-10-29 19:42:26 +08:00
65 змінених файлів з 403 додано та 7880 видалено

No files matched your search

Створено
-2
Переглянути файл
@@ -4516,7 +4516,6 @@ dependencies = [
"dunce",
"gix",
"ide-core",
"ignore",
"libc",
"regex-lite",
"serde",
@@ -4534,7 +4533,6 @@ dependencies = [
"chardetng",
"dunce",
"encoding_rs",
"gix",
"globset",
"ide-core",
"ignore",
-13
Переглянути файл
@@ -28,19 +28,6 @@ icon set, copied unmodified (some renamed) from JetBrains' open-source repositor
At render time `src/ui/icons.tsx` may recolour monochrome icons to `currentColor`.
## JetBrains IntelliJ Platform diff algorithm
`src/features/vcs/comparison/**` is a TypeScript port of the text comparison of
[intellij-community](https://github.com/JetBrains/intellij-community) (Apache-2.0):
`platform/util/diff` (`com.intellij.util.diff`: Diff, Reindexer, MyersLCS,
PatienceIntLCS, UniqueLCS; `com.intellij.diff.comparison`: ByLineRt, ByWordRt,
ByCharRt, ChunkOptimizer, ChangeCorrector, LineFragmentSplitter, TrimUtil,
ComparisonUtil, iterables) and `platform/diff-impl` (ComparisonManagerImpl's
`compareLinesInner` and `processBlocks`). `__tests__/ideaCases.json` is converted
from its tests (`LineComparisonUtilTest`, `WordComparisonUtilTest`,
`SplitComparisonUtilTest`). Modified from the originals. Copyright 2000-2026
JetBrains s.r.o. and contributors. Apache License 2.0 (below).
`src/ui/openidea/**` holds OpenIDEA's own file-type icons drawn in the expui style for
languages whose JetBrains icons are not open source (Go, Rust, Ruby, Dart, Lua, Zig,
Svelte, …). Those using the page-with-corner-badge layout (`goMod`, `goWork`,
-30
Переглянути файл
@@ -242,33 +242,6 @@ pub async fn vcs_stage(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeRes
blocking(move || per_repo(&project, &paths, None, |r, paths| r.stage(paths))).await
}
/// Project-host operation (also registered with the remote dispatcher).
pub async fn vcs_add_to_ignore(
host: &Host,
window: &str,
paths: Vec<PathBuf>,
destination: IgnoreDestination,
) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || {
for path in &paths {
if path == &project.root || !path.starts_with(&project.root) {
return Err(ide_core::IdeError::invalid("Ignore selection is outside the project"));
}
}
apply_git_executable(&project.settings.effective());
let result = ide_vcs::add_to_ignore(&paths, destination);
// Exclude may live outside a worktree's watched directory. Refresh filters and UI explicitly.
project.watcher.reload_ignore_rules();
for (_, watcher) in project.content_watchers.lock().iter() {
watcher.reload_ignore_rules();
}
project.sink.emit(ide_core::IdeEvent::VcsChanged { root: project.root.clone().into() });
result.map(|_| ())
})
.await
}
pub async fn vcs_unstage(host: &Host, window: &str, paths: Vec<PathBuf>) -> IdeResult<()> {
let project = host.project(window)?;
blocking(move || per_repo(&project, &paths, None, |r, paths| r.unstage(paths))).await
@@ -827,9 +800,6 @@ pub(crate) fn register(d: &mut Dispatcher) {
d.add("vcs_branches", |c| async move { vcs_branches(&c.host, &c.window, c.arg("repo")?).await });
d.add("vcs_stashes", |c| async move { vcs_stashes(&c.host, &c.window, c.arg("repo")?).await });
d.add("vcs_stage", |c| async move { vcs_stage(&c.host, &c.window, c.arg("paths")?).await });
d.add("vcs_add_to_ignore", |c| async move {
vcs_add_to_ignore(&c.host, &c.window, c.arg("paths")?, c.arg("destination")?).await
});
d.add("vcs_unstage", |c| async move { vcs_unstage(&c.host, &c.window, c.arg("paths")?).await });
d.add("vcs_stage_patch", |c| async move { vcs_stage_patch(&c.host, &c.window, c.arg("patch")?).await });
d.add("vcs_discard", |c| async move { vcs_discard(&c.host, &c.window, c.arg("paths")?).await });
-20
Переглянути файл
@@ -108,26 +108,6 @@ async fn serves_projects_files_documents_search_and_runs() {
invoke(&peer, "vcs_init", json!({ "dir": project })).await.unwrap();
until("git repository", || project.join(".git").is_dir()).await;
// Real project-host ignore writes travel through the remote command dispatcher.
assert!(Dispatcher::standard().commands().contains(&"vcs_add_to_ignore"));
let ignore_root = dunce::canonicalize(&project).unwrap();
for (name, destination) in [("shared.tmp", "gitignore"), ("private.tmp", "localExclude")] {
let path = ignore_root.join(name);
std::fs::write(&path, "temporary").unwrap();
invoke(&peer, "vcs_add_to_ignore", json!({ "paths": [path], "destination": destination })).await.unwrap();
let entries = invoke(&peer, "fs_read_dir", json!({ "path": ignore_root })).await.unwrap();
let entry = entries.as_array().unwrap().iter().find(|e| e["name"] == name).unwrap();
assert_eq!(entry["ignored"], true);
assert_eq!(entry["excluded"], false);
}
assert!(std::fs::read_to_string(project.join(".gitignore")).unwrap().contains("/shared.tmp"));
assert!(std::fs::read_to_string(project.join(".git/info/exclude")).unwrap().contains("/private.tmp"));
let outside = tmp.path().join("outside.tmp");
std::fs::write(&outside, "keep").unwrap();
assert!(
invoke(&peer, "vcs_add_to_ignore", json!({ "paths": [outside], "destination": "gitignore" })).await.is_err()
);
// Unknown commands and bad arguments come back as IdeErrors.
let e = invoke(&peer, "window_minimize", json!({})).await.unwrap_err();
assert!(e.message.contains("not available remotely"), "{e:?}");
-2
Переглянути файл
@@ -8,13 +8,11 @@ license.workspace = true
[dependencies]
dunce.workspace = true
ide-core.workspace = true
ignore.workspace = true
serde.workspace = true
serde_json.workspace = true
specta.workspace = true
gix = { workspace = true, features = ["sha1", "status", "blob-diff", "revision", "index", "dirwalk", "parallel"] }
tracing.workspace = true
tempfile.workspace = true
which = "8"
regex-lite = "0.1"
-318
Переглянути файл
@@ -1,318 +0,0 @@
//! Literal ignore rules for Project view's Git › Add to .gitignore.
use crate::{Repo, cli};
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
use std::collections::{BTreeMap, HashSet};
use std::fs;
use std::io::{Read, Write};
use std::path::{Component, Path, PathBuf};
#[derive(Clone, Copy, Debug, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum IgnoreDestination {
Gitignore,
LocalExclude,
}
struct IgnoreRule {
pattern: String,
relative: PathBuf,
directory: bool,
}
/// Validate the whole selection before writing. Each destination is replaced atomically;
/// a failure in a later repository may leave earlier destinations updated (safe to retry).
/// Never modifies the index or a selected file.
pub fn add_to_ignore(paths: &[PathBuf], destination: IgnoreDestination) -> IdeResult<Vec<PathBuf>> {
let mut edits: BTreeMap<PathBuf, Vec<IgnoreRule>> = BTreeMap::new();
let mut verify = Vec::new();
for path in paths {
// Validate before filesystem access: APFS cannot even stat invalid UTF-8 names.
path.to_str().ok_or_else(|| IdeError::invalid("Path is not UTF-8"))?;
if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
return Err(IdeError::invalid("Select an absolute path without '..'"));
}
no_symlinks(path)?;
let meta = fs::symlink_metadata(path)?;
if !meta.is_file() && !meta.is_dir() {
return Err(IdeError::invalid("Only regular files and directories can be ignored"));
}
// A selected nested repository directory is an entry of its enclosing repository.
let start = path.parent().ok_or_else(|| IdeError::invalid("Cannot ignore a filesystem root"))?;
let repo = Repo::discover(start)?.ok_or_else(|| IdeError::invalid("Selection is not in a Git repository"))?;
let rel =
path.strip_prefix(repo.root()).map_err(|_| IdeError::invalid("Selection is outside its repository"))?;
let literal = pattern(rel, meta.is_dir())?;
if rel.components().any(|c| c.as_os_str() == ".git") {
return Err(IdeError::invalid("Git administration files cannot be ignored"));
}
let rel_str = rel.to_str().ok_or_else(|| IdeError::invalid("Path is not UTF-8"))?;
let tracked = cli::run(repo.root(), &["--literal-pathspecs", "ls-files", "-z", "--", rel_str], None)?;
if !tracked.stdout.is_empty() {
return Err(IdeError::invalid(format!(
"{} contains tracked files. Ignore rules only affect unversioned files; no files were untracked.",
path.display()
)));
}
// check-ignore rejects --literal-pathspecs; a ./ prefix prevents pathspec
// magic in valid filenames such as :(top)private from being interpreted.
let literal_query = format!("./{rel_str}");
let ignored = cli::run_raw(repo.root(), &["check-ignore", "-q", "--", &literal_query], None)?;
match ignored.code {
Some(0) => continue,
Some(1) => {}
_ => return Err(IdeError::invalid(ignored.stdout_str() + &String::from_utf8_lossy(&ignored.stderr))),
}
verify.push((repo.root().to_path_buf(), rel_str.to_owned()));
let (file, rule, base) = match destination {
IgnoreDestination::LocalExclude => {
let output = cli::run(
repo.root(),
&["rev-parse", "--path-format=absolute", "--git-path", "info/exclude"],
None,
)?;
// Strip only Git's output terminator; spaces are valid in the path.
let raw = output.stdout_str();
let file = crate::repo::absolute(Path::new(
raw.strip_suffix("\r\n").or_else(|| raw.strip_suffix('\n')).unwrap_or(&raw),
))?;
let common = crate::repo::absolute(repo.gix()?.common_dir())?;
if file != common.join("info/exclude") {
return Err(IdeError::invalid("Git returned an unexpected exclude path"));
}
(file, literal, repo.root())
}
IgnoreDestination::Gitignore => {
let base = start
.ancestors()
.take_while(|p| p.starts_with(repo.root()))
.find(|p| p.join(".gitignore").symlink_metadata().is_ok())
.unwrap_or(repo.root());
(base.join(".gitignore"), pattern(path.strip_prefix(base).unwrap(), meta.is_dir())?, base)
}
};
no_symlinks(file.parent().unwrap())?;
validate_file(&file)?;
edits.entry(file).or_default().push(IgnoreRule {
pattern: rule,
relative: path.strip_prefix(base).unwrap().to_path_buf(),
directory: meta.is_dir(),
});
}
let mut changed = Vec::new();
for (file, rules) in edits {
append(&file, &rules).map_err(|e| {
IdeError::new(
e.kind,
format!(
"Could not update {}: {}. Earlier destinations may have succeeded; refresh and retry.",
file.display(),
e.message
),
)
})?;
changed.push(file);
}
for (root, rel) in verify {
if cli::run_raw(&root, &["check-ignore", "-q", "--", &format!("./{rel}")], None)?.code != Some(0) {
return Err(IdeError::invalid(format!(
"Rule saved, but {rel} is still visible to Git. A higher-priority .gitignore rule may override it; edit that file and retry."
)));
}
}
Ok(changed)
}
fn pattern(path: &Path, directory: bool) -> IdeResult<String> {
let mut rule = String::from("/");
for (i, part) in path.components().enumerate() {
let Component::Normal(part) = part else { return Err(IdeError::invalid("Unsafe ignore path")) };
let part = part.to_str().ok_or_else(|| IdeError::invalid("Path is not UTF-8"))?;
if part.contains(['\n', '\r', '\0']) {
return Err(IdeError::invalid(
"Paths containing a newline or NUL cannot be represented safely in an ignore file",
));
}
if i > 0 {
rule.push('/');
}
for ch in part.chars() {
if matches!(ch, '\\' | '*' | '?' | '[' | ']' | '#' | '!' | ' ') {
rule.push('\\');
}
rule.push(ch);
}
}
if rule == "/" {
return Err(IdeError::invalid("Cannot ignore a repository root"));
}
if directory {
rule.push('/');
}
Ok(rule)
}
/// Refuse symlinked ancestors too: writing through them could affect another repository.
fn no_symlinks(path: &Path) -> IdeResult<()> {
for part in path.ancestors() {
match fs::symlink_metadata(part) {
Ok(m) if m.file_type().is_symlink() => {
return Err(IdeError::invalid(format!("Refusing symlink path: {}", part.display())));
}
Ok(_) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => return Err(e.into()),
}
}
Ok(())
}
fn validate_file(file: &Path) -> IdeResult<()> {
match fs::symlink_metadata(file) {
Ok(m) if !m.is_file() || m.file_type().is_symlink() => {
Err(IdeError::invalid("Ignore destination must be a regular file, not a symlink"))
}
Ok(m) if m.permissions().readonly() => {
Err(IdeError::invalid(format!("{} is read-only; make it writable and retry", file.display())))
}
Ok(_) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e.into()),
}
}
#[derive(PartialEq, Eq)]
struct Snapshot {
bytes: Vec<u8>,
modified: Option<std::time::SystemTime>,
permissions: fs::Permissions,
}
fn snapshot(file: &Path) -> IdeResult<Option<Snapshot>> {
validate_file(file)?;
let mut options = fs::OpenOptions::new();
options.read(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.custom_flags(libc::O_NOFOLLOW);
}
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
// Open the reparse point itself rather than following a last-component link.
options.custom_flags(0x0020_0000); // FILE_FLAG_OPEN_REPARSE_POINT
}
match options.open(file) {
Ok(mut handle) => {
let metadata = handle.metadata()?;
if !metadata.is_file() || metadata.file_type().is_symlink() {
return Err(IdeError::invalid("Ignore destination must be a regular file"));
}
let mut bytes = Vec::new();
handle.read_to_end(&mut bytes)?;
Ok(Some(Snapshot { bytes, modified: metadata.modified().ok(), permissions: metadata.permissions() }))
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
fn append(file: &Path, rules: &[IgnoreRule]) -> IdeResult<()> {
no_symlinks(file.parent().unwrap())?;
fs::create_dir_all(file.parent().unwrap())?;
// Conventional sibling lock: create_new never follows a preexisting symlink.
let lock_path = file.with_file_name(format!("{}.lock", file.file_name().unwrap().to_string_lossy()));
let lock = fs::OpenOptions::new().write(true).create_new(true).open(&lock_path);
// Keep lock cleanup scoped to successfully acquired locks only.
let _lock = Lock {
file: lock.map_err(|_| {
IdeError::invalid(format!("{} is locked or not writable; close other writers and retry", file.display()))
})?,
path: lock_path,
};
let before = snapshot(file)?;
let bytes = before.as_ref().map(|s| s.bytes.as_slice()).unwrap_or_default();
let text =
std::str::from_utf8(bytes).map_err(|_| IdeError::invalid("Ignore file is not UTF-8; edit it manually"))?;
if text.contains('\0') {
return Err(IdeError::invalid("Ignore file contains NUL; edit it manually"));
}
let newline = if text.contains("\r\n") { "\r\n" } else { "\n" };
// Identical text earlier in the file may have been overridden by a later
// negation. Deduplicate only rules that this file still applies to the path.
let mut builder = ignore::gitignore::GitignoreBuilder::new("");
for (index, line) in text.lines().enumerate() {
let line = if index == 0 { line.trim_start_matches('\u{feff}') } else { line };
if let Err(error) = builder.add_line(None, line) {
tracing::debug!("{}: {error}", file.display());
}
}
let existing = builder.build().map_err(|e| IdeError::invalid(format!("Cannot parse ignore rules: {e}")))?;
let mut requested = HashSet::new();
let mut updated = bytes.to_vec();
for rule in rules {
if !requested.insert(rule.pattern.as_str())
|| existing.matched_path_or_any_parents(&rule.relative, rule.directory).is_ignore()
{
continue;
}
if !updated.is_empty() && !updated.ends_with(b"\n") {
updated.extend_from_slice(newline.as_bytes());
}
updated.extend_from_slice(rule.pattern.as_bytes());
updated.extend_from_slice(newline.as_bytes());
}
if updated == bytes {
return Ok(());
}
let mut temp = tempfile::NamedTempFile::new_in(file.parent().unwrap())?;
let permissions = match fs::metadata(file) {
Ok(meta) => meta.permissions(),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => _lock.file.metadata()?.permissions(),
Err(e) => return Err(e.into()),
};
temp.as_file().set_permissions(permissions)?;
temp.write_all(&updated)?;
temp.as_file().sync_all()?;
replace_if_unchanged(file, before, temp)
}
fn replace_if_unchanged(file: &Path, before: Option<Snapshot>, temp: tempfile::NamedTempFile) -> IdeResult<()> {
no_symlinks(file.parent().unwrap())?;
if snapshot(file)? != before {
return Err(IdeError::invalid("Ignore file changed while preparing the update; retry"));
}
temp.persist(file).map_err(|e| IdeError::from(e.error))?;
Ok(())
}
struct Lock {
file: fs::File,
path: PathBuf,
}
impl Drop for Lock {
fn drop(&mut self) {
let _ = &self.file;
let _ = fs::remove_file(&self.path);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn concurrent_writer_is_detected_without_overwriting_it() {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
let file = root.join(".gitignore");
fs::write(&file, "before\n").unwrap();
let before = snapshot(&file).unwrap();
let mut temp = tempfile::NamedTempFile::new_in(&root).unwrap();
temp.write_all(b"before\n/new\n").unwrap();
fs::write(&file, "external writer\n").unwrap();
assert!(replace_if_unchanged(&file, before, temp).unwrap_err().message.contains("changed"));
assert_eq!(fs::read_to_string(file).unwrap(), "external writer\n");
}
}
-2
Переглянути файл
@@ -441,7 +441,6 @@ pub mod changelists;
mod cli;
mod diff;
mod history;
mod ignore;
mod manage;
mod ops;
mod patch;
@@ -455,7 +454,6 @@ mod write;
pub use cli::{detected_git_executable, git_version, set_askpass_env, set_git_executable};
pub use diff::build_partial_patch;
pub use ignore::{IgnoreDestination, add_to_ignore};
pub use manage::{MergeOptions, RebaseOptions, RemoteEdit, Worktree};
pub use remotes::Remote;
pub use roots::Repos;
+1 -1
Переглянути файл
@@ -50,7 +50,7 @@ pub(crate) fn discover(path: &Path) -> IdeResult<Option<Repo>> {
Ok(Some(Repo { root, git_dir, inner: std::sync::Mutex::new(cache), ignored: Default::default() }))
}
pub(crate) fn absolute(p: &Path) -> IdeResult<PathBuf> {
fn absolute(p: &Path) -> IdeResult<PathBuf> {
let p = if p.is_absolute() { p.to_path_buf() } else { std::env::current_dir()?.join(p) };
// Lexically clean `.`/`..` without resolving symlinks, keeping the caller's spelling.
let mut out = PathBuf::new();
-311
Переглянути файл
@@ -1,311 +0,0 @@
//! Runtime tests against real temporary repositories and the Git executable.
use ide_vcs::{IgnoreDestination::*, add_to_ignore};
use std::path::{Path, PathBuf};
use std::process::Command;
fn git(root: &Path, args: &[&str]) -> String {
let output = Command::new("git")
.current_dir(root)
.args(args)
.env_remove("GIT_DIR")
.env_remove("GIT_WORK_TREE")
.env_remove("GIT_INDEX_FILE")
.env("GIT_CONFIG_NOSYSTEM", "1")
.env("GIT_CONFIG_GLOBAL", if cfg!(windows) { "NUL" } else { "/dev/null" })
.output()
.unwrap();
assert!(output.status.success(), "{args:?}: {}", String::from_utf8_lossy(&output.stderr));
String::from_utf8(output.stdout).unwrap()
}
struct Fixture {
_tmp: tempfile::TempDir,
root: PathBuf,
}
impl Fixture {
fn new() -> Self {
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("repo");
std::fs::create_dir(&root).unwrap();
git(&root, &["init", "-q"]);
git(&root, &["config", "core.excludesFile", if cfg!(windows) { "NUL" } else { "/dev/null" }]);
Self { _tmp: tmp, root }
}
fn file(&self, name: &str) -> PathBuf {
let path = self.root.join(name);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(&path, "data\n").unwrap();
path
}
fn ignored(&self, rel: &str) {
assert!(!git(&self.root, &["check-ignore", "--", &format!("./{rel}")]).is_empty());
assert!(
git(&self.root, &["--literal-pathspecs", "status", "--porcelain", "--untracked-files=all", "--", rel])
.is_empty()
);
}
}
#[test]
fn shared_literals_multiselect_and_directory_are_anchored() {
let fx = Fixture::new();
let mut names = vec!["has space", "#hash", "!bang", "[ab].txt", "-dash", "中文.txt"];
// Win32 filenames cannot contain wildcard characters or end in a space.
if cfg!(unix) {
names.extend(["has space ", "[ab]*?.txt", ":(top)literal", ":!literal", ":(glob)*"]);
}
let mut paths: Vec<_> = names.iter().map(|n| fx.file(n)).collect();
fx.file("literal");
fx.file("cache/a.txt");
fx.file("other/cache/a.txt");
paths.push(fx.root.join("cache"));
for name in &names {
fx.file(&format!("other/{name}"));
}
add_to_ignore(&paths, Gitignore).unwrap();
for name in &names {
fx.ignored(name);
}
fx.ignored("cache/a.txt");
let status = git(&fx.root, &["status", "--porcelain", "--untracked-files=all"]);
assert!(status.contains("other/cache/a.txt"));
assert!(status.contains("other/!bang"));
assert!(status.lines().any(|line| line == "?? literal"));
let text = std::fs::read_to_string(fx.root.join(".gitignore")).unwrap();
assert!(text.contains("/cache/\n"));
assert!(text.contains("/\\[ab\\].txt\n"));
if cfg!(unix) {
assert!(text.contains("/\\[ab\\]\\*\\?.txt\n"));
}
}
#[test]
fn local_exclude_is_local_preserves_comments_crlf_and_deduplicates() {
let fx = Fixture::new();
let path = fx.file("private.txt");
let exclude = fx.root.join(".git/info/exclude");
std::fs::write(&exclude, "# keep this\r\n/other\r\n# no final newline").unwrap();
add_to_ignore(&[path.clone(), path.clone()], LocalExclude).unwrap();
let once = std::fs::read(&exclude).unwrap();
assert_eq!(
String::from_utf8(once.clone()).unwrap(),
"# keep this\r\n/other\r\n# no final newline\r\n/private.txt\r\n"
);
add_to_ignore(&[path], LocalExclude).unwrap();
assert_eq!(std::fs::read(&exclude).unwrap(), once);
fx.ignored("private.txt");
assert!(git(&fx.root, &["status", "--porcelain"]).is_empty());
assert!(!fx.root.join(".gitignore").exists());
}
#[test]
fn nearest_existing_ignore_and_nested_repositories_use_correct_bases() {
let fx = Fixture::new();
let a = fx.file("pkg/deep/a.txt");
std::fs::write(fx.root.join("pkg/.gitignore"), "# nested\n").unwrap();
add_to_ignore(&[a], Gitignore).unwrap();
fx.ignored("pkg/deep/a.txt");
assert_eq!(std::fs::read_to_string(fx.root.join("pkg/.gitignore")).unwrap(), "# nested\n/deep/a.txt\n");
assert!(!fx.root.join(".gitignore").exists());
let b = fx.file("nested/b.txt");
git(&fx.root.join("nested"), &["init", "-q"]);
add_to_ignore(&[b], Gitignore).unwrap();
assert_eq!(std::fs::read_to_string(fx.root.join("nested/.gitignore")).unwrap(), "/b.txt\n");
assert!(!fx.root.join(".gitignore").exists());
}
#[test]
fn tracked_files_and_directories_fail_before_any_write() {
let fx = Fixture::new();
let tracked = fx.file("dir/tracked");
let new = fx.file("new");
git(&fx.root, &["add", "dir/tracked"]);
for path in [tracked, fx.root.join("dir")] {
let error = add_to_ignore(&[new.clone(), path], Gitignore).unwrap_err();
assert!(error.message.contains("tracked files"));
assert!(!fx.root.join(".gitignore").exists());
}
assert!(git(&fx.root, &["diff", "--cached", "--name-only"]).contains("dir/tracked"));
}
#[test]
fn worktree_and_submodule_git_files_resolve_common_exclude() {
let fx = Fixture::new();
fx.file("initial");
git(&fx.root, &["add", "initial"]);
git(
&fx.root,
&[
"-c",
"user.name=Test",
"-c",
"[email protected]",
"-c",
"commit.gpgsign=false",
"commit",
"-qm",
"initial",
],
);
let worktree = fx.root.parent().unwrap().join("linked");
git(&fx.root, &["worktree", "add", "-qb", "linked", worktree.to_str().unwrap()]);
let p = worktree.join("private");
std::fs::write(&p, "x").unwrap();
add_to_ignore(&[p], LocalExclude).unwrap();
assert!(std::fs::read_to_string(fx.root.join(".git/info/exclude")).unwrap().contains("/private\n"));
assert_eq!(git(&worktree, &["check-ignore", "private"]), "private\n");
assert!(git(&worktree, &["status", "--porcelain"]).is_empty());
// A real gitfile layout like a submodule, with metadata outside its worktree.
let sub = fx.root.join("sub");
std::fs::create_dir(&sub).unwrap();
let metadata = fx.root.join(".git/modules/sub");
std::fs::create_dir_all(metadata.parent().unwrap()).unwrap();
git(&sub, &["init", "-q", "--separate-git-dir", metadata.to_str().unwrap()]);
std::fs::write(sub.join("tracked"), "x").unwrap();
git(&sub, &["add", "tracked"]);
git(
&sub,
&[
"-c",
"user.name=Test",
"-c",
"[email protected]",
"-c",
"commit.gpgsign=false",
"commit",
"-qm",
"submodule initial",
],
);
let commit = git(&sub, &["rev-parse", "HEAD"]);
std::fs::write(
fx.root.join(".gitmodules"),
"[submodule \"sub\"]\n\tpath = sub\n\turl = https://example.invalid/sub.git\n",
)
.unwrap();
git(&fx.root, &["update-index", "--add", "--cacheinfo", "160000", commit.trim(), "sub"]);
assert!(add_to_ignore(std::slice::from_ref(&sub), LocalExclude).unwrap_err().message.contains("tracked files"));
std::fs::write(sub.join("private"), "x").unwrap();
add_to_ignore(&[sub.join("private")], LocalExclude).unwrap();
assert!(std::fs::read_to_string(metadata.join("info/exclude")).unwrap().contains("/private\n"));
assert_eq!(git(&sub, &["check-ignore", "private"]), "private\n");
}
#[test]
fn lock_failure_invalid_destination_and_traversal_preserve_data() {
let fx = Fixture::new();
let path = fx.file("new");
let file = fx.root.join(".gitignore");
std::fs::write(&file, "# original\n").unwrap();
std::fs::write(fx.root.join(".gitignore.lock"), "another writer").unwrap();
assert!(add_to_ignore(std::slice::from_ref(&path), Gitignore).unwrap_err().message.contains("locked"));
assert_eq!(std::fs::read_to_string(&file).unwrap(), "# original\n");
assert_eq!(std::fs::read_to_string(fx.root.join(".gitignore.lock")).unwrap(), "another writer");
assert!(add_to_ignore(&[fx.root.join("dir/../new")], Gitignore).is_err());
std::fs::remove_file(fx.root.join(".gitignore.lock")).unwrap();
std::fs::write(&file, b"# invalid\xff").unwrap();
assert!(add_to_ignore(&[path], Gitignore).is_err());
assert_eq!(std::fs::read(file).unwrap(), b"# invalid\xff");
assert!(!fx.root.join(".gitignore.lock").exists());
}
#[cfg(unix)]
#[test]
fn backslash_is_literal_newlines_and_symlinks_are_rejected() {
use std::os::unix::fs::symlink;
let fx = Fixture::new();
let backslash = fx.file("back\\slash");
add_to_ignore(&[backslash], Gitignore).unwrap();
fx.ignored("back\\slash");
let original = std::fs::read(fx.root.join(".gitignore")).unwrap();
for name in ["line\nname", "line\rname"] {
let path = fx.file(name);
assert!(add_to_ignore(&[path], Gitignore).is_err());
}
let outside = fx.root.parent().unwrap().join("outside");
std::fs::write(&outside, "safe").unwrap();
std::fs::remove_file(fx.root.join(".gitignore")).unwrap();
symlink(&outside, fx.root.join(".gitignore")).unwrap();
assert!(add_to_ignore(&[fx.file("new")], Gitignore).is_err());
assert_eq!(std::fs::read_to_string(&outside).unwrap(), "safe");
std::fs::remove_file(fx.root.join(".gitignore")).unwrap();
std::fs::write(fx.root.join(".gitignore"), &original).unwrap();
symlink(fx.root.parent().unwrap(), fx.root.join("link")).unwrap();
assert!(add_to_ignore(&[fx.root.join("link/outside")], LocalExclude).is_err());
assert_eq!(std::fs::read(fx.root.join(".gitignore")).unwrap(), original);
}
#[test]
fn overridden_local_rule_is_not_duplicated_and_explains_precedence() {
let fx = Fixture::new();
let path = fx.file("private");
std::fs::write(fx.root.join(".gitignore"), "!/private\n").unwrap();
let error = add_to_ignore(std::slice::from_ref(&path), LocalExclude).unwrap_err();
assert!(error.message.contains("higher-priority"));
let exclude = fx.root.join(".git/info/exclude");
let once = std::fs::read(&exclude).unwrap();
assert!(add_to_ignore(&[path], LocalExclude).is_err());
assert_eq!(std::fs::read(exclude).unwrap(), once);
}
#[test]
fn readonly_and_nonfile_destinations_remain_untouched() {
let fx = Fixture::new();
let path = fx.file("new");
let file = fx.root.join(".gitignore");
std::fs::create_dir(&file).unwrap();
assert!(add_to_ignore(std::slice::from_ref(&path), Gitignore).is_err());
std::fs::remove_dir(&file).unwrap();
std::fs::write(&file, "# original\n").unwrap();
let original = std::fs::metadata(&file).unwrap().permissions();
let mut permissions = original.clone();
permissions.set_readonly(true);
std::fs::set_permissions(&file, permissions).unwrap();
let result = add_to_ignore(&[path], Gitignore);
std::fs::set_permissions(&file, original).unwrap();
assert!(result.unwrap_err().message.contains("read-only"));
assert_eq!(std::fs::read_to_string(file).unwrap(), "# original\n");
}
#[test]
fn existing_bytes_are_preserved_for_newline_and_bom_variants() {
for original in [b"# comment".as_slice(), b"unrelated\\", b"\xef\xbb\xbf# BOM\r\n", b"# LF\n", b""] {
let fx = Fixture::new();
let path = fx.file("new");
let file = fx.root.join(".gitignore");
std::fs::write(&file, original).unwrap();
add_to_ignore(&[path], Gitignore).unwrap();
assert!(std::fs::read(file).unwrap().starts_with(original));
fx.ignored("new");
}
}
#[cfg(unix)]
#[test]
fn non_utf8_paths_are_rejected_without_creating_ignore_files() {
use std::os::unix::ffi::OsStringExt;
let fx = Fixture::new();
let path = fx.root.join(std::ffi::OsString::from_vec(b"invalid\xff".to_vec()));
// APFS rejects creation of this filename; the request must fail clearly before I/O.
assert!(add_to_ignore(&[path], Gitignore).unwrap_err().message.contains("UTF-8"));
assert!(!fx.root.join(".gitignore").exists());
}
#[test]
fn later_negations_allow_reignoring_shared_and_local_paths_without_batch_duplicates() {
for destination in [Gitignore, LocalExclude] {
let fx = Fixture::new();
let path = fx.file("private");
let file = match destination {
Gitignore => fx.root.join(".gitignore"),
LocalExclude => fx.root.join(".git/info/exclude"),
};
std::fs::write(&file, "/private\n!/private\n").unwrap();
assert!(git(&fx.root, &["status", "--porcelain", "--untracked-files=all"]).contains("private"));
add_to_ignore(&[path.clone(), path.clone()], destination).unwrap();
assert_eq!(std::fs::read_to_string(&file).unwrap(), "/private\n!/private\n/private\n");
fx.ignored("private");
let once = std::fs::read(&file).unwrap();
add_to_ignore(&[path], destination).unwrap();
assert_eq!(std::fs::read(file).unwrap(), once);
}
}
-1
Переглянути файл
@@ -7,7 +7,6 @@ license.workspace = true
[dependencies]
dunce.workspace = true
gix = { workspace = true, features = ["sha1"] }
ide-core.workspace = true
serde.workspace = true
specta.workspace = true
+2 -26
Переглянути файл
@@ -80,24 +80,20 @@ pub(crate) struct GitignoreStack {
/// `.git/info/exclude` and the global excludes file, rooted at the repo root.
repo_level: RwLock<Vec<Gitignore>>,
cache: Mutex<HashMap<PathBuf, Option<Arc<Gitignore>>>>,
nested: Mutex<HashMap<PathBuf, Option<Arc<GitignoreStack>>>>,
}
impl GitignoreStack {
pub fn new(near: &Path) -> Self {
let repo_root = find_repo_root(near);
let repo_level = RwLock::new(Self::load_repo_level(repo_root.as_deref()));
Self { repo_root, repo_level, cache: Mutex::default(), nested: Mutex::default() }
Self { repo_root, repo_level, cache: Mutex::default() }
}
fn load_repo_level(repo_root: Option<&Path>) -> Vec<Gitignore> {
let mut repo_level = Vec::new();
if let Some(root) = repo_root {
let mut builder = GitignoreBuilder::new(root);
let exclude = gix::discover(root)
.ok()
.map(|r| r.common_dir().join("info/exclude"))
.unwrap_or_else(|| root.join(".git/info/exclude"));
let exclude = root.join(".git").join("info").join("exclude");
if exclude.is_file() {
builder.add(exclude);
}
@@ -119,13 +115,11 @@ impl GitignoreStack {
/// Re-reads `.git/info/exclude` and the global excludes file.
pub fn reload_repo_level(&self) {
self.nested.lock().clear();
*self.repo_level.write() = Self::load_repo_level(self.repo_root.as_deref());
}
/// Forgets the cached rules of `dir` and every directory below it.
pub fn invalidate_tree(&self, dir: &Path) {
self.nested.lock().clear();
let mut cache = self.cache.lock();
// Lookups always populate every ancestor, so no key below `dir` exists without `dir`.
if cache.contains_key(dir) {
@@ -139,7 +133,6 @@ impl GitignoreStack {
/// Forgets the cached rules of `dir` (after its `.gitignore` changed).
pub fn invalidate(&self, dir: &Path) {
self.nested.lock().clear();
self.cache.lock().remove(dir);
}
@@ -176,23 +169,6 @@ impl GitignoreStack {
/// Whether `path` (absolute) is ignored. `is_dir` refers to `path` itself.
pub fn is_ignored(&self, path: &Path, is_dir: bool) -> bool {
// A project's watcher can span independent nested repositories. Their local
// excludes and ignore ancestry must stop at their own repository boundary.
if let Some(parent) = path.parent() {
let nested = self
.nested
.lock()
.entry(parent.to_path_buf())
.or_insert_with(|| {
find_repo_root(parent)
.filter(|root| self.repo_root.as_ref() != Some(root))
.map(|_| Arc::new(Self::new(parent)))
})
.clone();
if let Some(nested) = nested {
return nested.is_ignored(path, is_dir);
}
}
if self.repo_root.as_deref() == Some(path) {
return false;
}
+3 -11
Переглянути файл
@@ -50,7 +50,6 @@ type OnChange = Box<dyn Fn(&FsBatch) + Send + Sync>;
pub struct Watcher {
inner: Inner,
excludes: SharedExcludes,
rules: Arc<GitignoreStack>,
}
type SharedExcludes = Arc<RwLock<ExcludeMatcher>>;
@@ -75,7 +74,6 @@ impl Watcher {
let root = dunce::canonicalize(root)?;
let filter = EventFilter::new(root.clone(), &excludes);
let shared = filter.excludes.clone();
let rules = filter.gitignore.clone();
let emit = move |batch: &FsBatch| {
sink.emit(IdeEvent::FsChanged {
created: batch.created.iter().map(Into::into).collect(),
@@ -89,7 +87,7 @@ impl Watcher {
WatchMode::Flat => Self::start_recursive(root, filter, emit, RecursiveMode::NonRecursive),
WatchMode::PerDirectory => Self::start_per_directory(root, filter, emit),
}?;
Ok(Self { inner, excludes: shared, rules })
Ok(Self { inner, excludes: shared })
}
/// Replaces the exclude globs (Settings › Project Structure / File Types
@@ -99,12 +97,6 @@ impl Watcher {
*self.excludes.write() = ExcludeMatcher::new(excludes);
}
/// Explicit refresh for writes to Git common metadata outside the watched root.
pub fn reload_ignore_rules(&self) {
self.rules.reload_repo_level();
self.rules.invalidate_tree(self.rules.repo_root().unwrap_or(Path::new("/")));
}
/// Number of OS-level watches (1 in recursive and flat mode).
pub fn watch_count(&self) -> usize {
match &self.inner {
@@ -382,13 +374,13 @@ fn merge(prev: Option<Change>, next: Change) -> Change {
pub(crate) struct EventFilter {
root: PathBuf,
excludes: SharedExcludes,
gitignore: Arc<GitignoreStack>,
gitignore: GitignoreStack,
}
impl EventFilter {
pub fn new(root: PathBuf, excludes: &[String]) -> Self {
Self {
gitignore: Arc::new(GitignoreStack::new(&root)),
gitignore: GitignoreStack::new(&root),
excludes: Arc::new(RwLock::new(ExcludeMatcher::new(excludes))),
root,
}
-44
Переглянути файл
@@ -321,47 +321,3 @@ fn watcher_reports_changes() {
std::thread::sleep(Duration::from_millis(500));
assert_eq!(batches.lock().len(), n, "no events after drop");
}
#[test]
fn worktree_and_nested_repository_local_excludes_are_reflected_in_listings() {
fn git(root: &std::path::Path, args: &[&str]) {
let out = std::process::Command::new("git").current_dir(root).args(args).output().unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
}
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("repo");
std::fs::create_dir(&root).unwrap();
git(&root, &["init", "-q"]);
std::fs::write(root.join("initial"), "x").unwrap();
git(&root, &["add", "initial"]);
git(
&root,
&[
"-c",
"user.name=Test",
"-c",
"[email protected]",
"-c",
"commit.gpgsign=false",
"commit",
"-qm",
"initial",
],
);
let linked = root.parent().unwrap().join("linked");
git(&root, &["worktree", "add", "-qb", "linked", linked.to_str().unwrap()]);
std::fs::write(linked.join("private"), "x").unwrap();
std::fs::write(root.join(".git/info/exclude"), "/private\n").unwrap();
let entries = ide_vfs::read_dir(&linked, &[]).unwrap();
assert!(entries.iter().find(|e| e.name == "private").unwrap().ignored);
assert!(!entries.iter().find(|e| e.name == "private").unwrap().excluded);
let nested = linked.join("nested");
std::fs::create_dir(&nested).unwrap();
git(&nested, &["init", "-q"]);
std::fs::write(nested.join("private"), "x").unwrap();
let entries = ide_vfs::read_dir(&nested, &[]).unwrap();
assert!(!entries.iter().find(|e| e.name == "private").unwrap().ignored);
std::fs::write(nested.join(".git/info/exclude"), "/private\n").unwrap();
let entries = ide_vfs::read_dir(&nested, &[]).unwrap();
assert!(entries.iter().find(|e| e.name == "private").unwrap().ignored);
}
+1 -4
Переглянути файл
@@ -295,7 +295,7 @@ a token.
<!-- BEGIN GENERATED TOKEN REFERENCE: pnpm gen:theme-docs -->
222 themeable tokens: 116 in the UI theme file, 106 in the editor colour scheme file.
219 themeable tokens: 113 in the UI theme file, 106 in the editor colour scheme file.
### Surfaces (UI theme)
@@ -374,9 +374,6 @@ a token.
| `--gutter-modified` | `#375fad` | `#88adf7` |
| `--gutter-added` | `#549159` | `#7fc784` |
| `--gutter-deleted` | `#868a91` | `#767a8a` |
| `--diff-modified` | `#385570` | `#c2d8f2` |
| `--diff-inserted` | `#294436` | `#bee6be` |
| `--diff-deleted` | `#484a4a` | `#d6d6d6` |
### Syntax (editor scheme)
-336
Переглянути файл
@@ -1,336 +0,0 @@
/**
* The diff viewer over a real git repository (`diffRepo.ts`): each case opens
* HEAD against the working copy and checks the IDEA-style change types of
* lines and words, the difference count against `git diff`, and that the
* 10,000-line files open, scroll and navigate in every viewer mode.
*/
import { rmSync } from "node:fs";
import { dirname } from "node:path";
import type { Page } from "@playwright/test";
import { gitHunks, readSides, tempDiffRepo } from "./diffRepo";
import { expect, test } from "./fixtures";
type Kind = "modified" | "inserted" | "deleted";
interface Opts {
mode?: "split" | "unified";
/** Padded panes (true), or panes joined by a curved divider (false, the default). */
alignChanges?: boolean;
syncScroll?: boolean;
collapse?: boolean;
ignore?: "none" | "trim" | "whitespace" | "whitespaceAndLines";
}
let repo = "";
test.beforeAll(() => {
repo = tempDiffRepo();
});
test.afterAll(() => rmSync(dirname(repo), { recursive: true, force: true }));
const toolbar = (page: Page) => page.getByRole("toolbar", { name: "Diff" });
const counter = (page: Page) =>
toolbar(page)
.locator("span")
.filter({ hasText: /differen|identical/ });
/** Opens HEAD ↔ working tree of `path` and waits until the difference count shows; returns the time it took. */
async function openCase(page: Page, path: string, opts: Opts = {}): Promise<number> {
const { left, right } = readSides(repo, path);
const options = {
mode: "split",
ignore: "none",
highlight: "words",
collapse: false,
alignChanges: true,
syncScroll: true,
...opts,
};
const started = Date.now();
await page.evaluate(
async ({ path, left, right, options }) => {
localStorage.setItem("openidea.vcs.diffOptions", JSON.stringify(options));
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction("diff.compareTexts", {
path,
title: path,
left: { text: left, label: "HEAD" },
right: { text: right, label: "Working tree" },
});
},
{ path, left, right, options },
);
await expect(counter(page)).toBeVisible({ timeout: 20_000 });
const elapsed = Date.now() - started;
// Word highlights land a microtask after both panes exist.
await page.evaluate(() => new Promise(requestAnimationFrame));
return elapsed;
}
interface Side {
lines: Kind[];
words: [string, Kind][];
}
/** Change types of the rendered lines and words of each pane (`a` / `b`; unified: `b` only). */
async function rendered(page: Page): Promise<{ a: Side; b: Side; deletedChunks: number }> {
return page
.locator(".cm-mergeView, .cm-editor.cm-merge-b")
.first()
.evaluate((el) => {
const root = el.closest("[role=region]") ?? el;
const kind = (e: Element, prefix: string) =>
(e.className.match(new RegExp(`${prefix}-(modified|inserted|deleted)`))?.[1] ?? null) as Kind | null;
const side = (cls: string) => {
const ed = root.querySelector(`.cm-editor.cm-merge-${cls}`);
const lines = [...(ed?.querySelectorAll(".cm-content > .cm-line") ?? [])]
.map((l) => kind(l, "cm-diffLine"))
.filter((k): k is Kind => !!k);
const words = [...(ed?.querySelectorAll(".cm-diffWord") ?? [])].map(
(w) => [w.textContent ?? "", kind(w, "cm-diffWord")!] as [string, Kind],
);
return { lines, words };
};
return { a: side("a"), b: side("b"), deletedChunks: root.querySelectorAll(".cm-deletedChunk").length };
});
}
const differences = (n: number) => (n === 1 ? "1 difference" : `${n} differences`);
async function expectCount(page: Page, path: string, n = gitHunks(repo, path)) {
await expect(counter(page)).toHaveText(new RegExp(`^(${differences(n)}|\\d+ of ${n} differences)$`));
}
const all = (n: number, k: Kind) => Array<Kind>(n).fill(k);
async function shot(page: Page, name: string) {
const path = test.info().outputPath(`${name}.png`);
await page.getByRole("region").last().screenshot({ path, animations: "disabled" });
await test.info().attach(name, { path, contentType: "image/png" });
}
test.describe("small cases (side-by-side, Highlight words)", () => {
const cases: {
path: string;
a: Kind[];
b: Kind[];
wordsA?: [string, Kind][];
wordsB?: [string, Kind][];
}[] = [
{
path: "src/words.ts",
a: all(2, "modified"),
b: all(2, "modified"),
wordsA: [["true", "modified"]],
wordsB: [
["false", "modified"],
[" x,", "inserted"],
],
},
{ path: "src/insert.ts", a: [], b: all(5, "inserted"), wordsA: [], wordsB: [] },
{ path: "src/delete.ts", a: all(4, "deleted"), b: [], wordsA: [], wordsB: [] },
{
path: "docs/readme-zh.md",
a: ["modified"],
b: ["modified"],
wordsA: [["测试", "modified"]],
wordsB: [["示例", "modified"]],
},
{
path: "docs/emoji.md",
a: ["modified"],
b: ["modified"],
wordsA: [["👋", "modified"]],
wordsB: [["🌍", "modified"]],
},
{
path: "data/no-eol.txt",
a: ["modified"],
b: ["modified"],
wordsA: [["beta", "modified"]],
wordsB: [["gamma", "modified"]],
},
{ path: "src/indent.py", a: all(3, "modified"), b: all(3, "modified") },
{ path: "src/moved.ts", a: all(5, "deleted"), b: all(5, "inserted"), wordsA: [], wordsB: [] },
{ path: "src/new-file.ts", a: [], b: all(6, "inserted"), wordsA: [], wordsB: [] },
{ path: "src/deleted-file.ts", a: all(6, "deleted"), b: [], wordsA: [], wordsB: [] },
];
for (const c of cases)
test(c.path, async ({ workbench: page }) => {
await openCase(page, c.path);
await expectCount(page, c.path);
const { a, b } = await rendered(page);
expect(a.lines, "left lines").toEqual(c.a);
expect(b.lines, "right lines").toEqual(c.b);
if (c.wordsA) expect(a.words, "left words").toEqual(c.wordsA);
if (c.wordsB) expect(b.words, "right words").toEqual(c.wordsB);
});
test("a renamed field with a comment added reads as one modified block", async ({ workbench: page }) => {
await openCase(page, "src/options.ts");
await expectCount(page, "src/options.ts", 1);
const { a, b } = await rendered(page);
expect(a.lines).toEqual(["modified"]);
expect(b.lines).toEqual(all(6, "modified"));
expect(a.words).toEqual([["syncScroll", "modified"]]);
expect(b.words.every(([, k]) => k === "modified")).toBe(true);
const text = b.words.map(([t]) => t).join("\n");
expect(text).toMatch(/^\/\*\*\n/);
expect(text).toMatch(/syncScrolling$/);
await shot(page, "options");
});
test("an edit in the middle of a 44,000-character minified line", async ({ workbench: page }) => {
const path = "dist/app.min.js";
await openCase(page, path);
await expectCount(page, path);
// Long lines render only around the horizontal viewport: scroll to the edit.
const { left } = readSides(repo, path);
const at = left.indexOf("f(1000,") / left.length;
for (const side of ["a", "b"])
await page
.locator(`.cm-editor.cm-merge-${side} .cm-scroller`)
.evaluate((s, at) => (s.scrollLeft = at * s.scrollWidth - s.clientWidth / 2), at);
await expect.poll(async () => (await rendered(page)).a.words).toEqual([["f", "modified"]]);
const { a, b } = await rendered(page);
expect(a.lines).toEqual(["modified"]);
expect(b.lines).toEqual(["modified"]);
expect(b.words).toEqual([["g", "modified"]]);
await shot(page, "minified");
});
test("a final newline added", async ({ workbench: page }) => {
await openCase(page, "data/add-eol.txt");
await expectCount(page, "data/add-eol.txt");
const { a, b } = await rendered(page);
// IDEA compares lines without their breaks: an empty line inserted, "beta" unchanged.
expect(a.lines).toEqual([]);
expect(b.lines).toEqual(["inserted"]);
await shot(page, "add-eol");
});
test("ignoring whitespace hides an indentation-only change", async ({ workbench: page }) => {
await openCase(page, "src/indent.py", { ignore: "whitespace" });
await expect(counter(page)).toHaveText("No differences");
expect((await rendered(page)).b.lines).toEqual([]);
});
test("unified viewer shows old lines deleted and new lines inserted", async ({ workbench: page }) => {
await openCase(page, "src/options.ts", { mode: "unified" });
await expectCount(page, "src/options.ts", 1);
const { b, deletedChunks } = await rendered(page);
expect(deletedChunks).toBe(1);
expect(b.lines).toEqual(all(6, "inserted"));
await shot(page, "options-unified");
});
});
test.describe("10,000-line files", () => {
test.describe.configure({ timeout: 60_000 });
const modes: [string, Opts][] = [
["padded", {}],
["sync scrolling", { alignChanges: false }],
["unified", { mode: "unified" }],
["collapsed", { collapse: true }],
];
/** Scrolls the diff to the end: the padded panes scroll together, the others from the right (or unified) pane. */
async function scrollToEnd(page: Page) {
await page
.locator(".cm-editor.cm-merge-b")
.first()
.evaluate((ed) => {
const merge = ed.closest<HTMLElement>(".cm-mergeView");
const s =
merge && merge.scrollHeight > merge.clientHeight ? merge : ed.querySelector<HTMLElement>(".cm-scroller")!;
s.scrollTop = s.scrollHeight;
});
await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))));
}
/** Text of the first line fully shown in each pane. */
async function topLines(page: Page) {
return page
.locator(".cm-mergeView")
.first()
.evaluate((mv) => {
const top = (side: string) => {
const ed = mv.querySelector(`.cm-editor.cm-merge-${side}`)!;
const r = mv.getBoundingClientRect();
const s = ed.querySelector(".cm-scroller")!.getBoundingClientRect();
const y = Math.max(r.top, s.top);
return [...ed.querySelectorAll(".cm-content > .cm-line")].find((l) => l.getBoundingClientRect().top >= y)
?.textContent;
};
return [top("a"), top("b")];
});
}
for (const [mode, opts] of modes) {
test(`scattered edits, inserts and deletes (${mode})`, async ({ workbench: page }) => {
const path = "big/scattered.ts";
const ms = await openCase(page, path, opts);
test.info().annotations.push({ type: "open", description: `${ms} ms` });
expect(ms, "time to open").toBeLessThan(8_000);
await expectCount(page, path, 42);
// The first change is a single edited identifier.
await page.locator(".cm-editor.cm-merge-b .cm-content").first().click();
await page.keyboard.press("Meta+ArrowUp");
await page.keyboard.press("F7");
await expect(counter(page)).toHaveText("1 of 42 differences");
const first = await rendered(page);
if (opts.mode !== "unified") {
expect(first.a.words).toContainEqual(["compute", "modified"]);
expect(first.b.words).toContainEqual(["computeFast", "modified"]);
}
// The last difference is reachable and still highlighted.
await page.keyboard.press("Meta+ArrowDown");
await page.keyboard.press("Shift+F7");
await expect(counter(page)).toHaveText("42 of 42 differences");
const last = await rendered(page);
if (opts.mode === "unified") expect(last.b.lines).toContain("inserted");
else expect(last.b.words).toContainEqual(["computeFast", "modified"]);
await scrollToEnd(page);
if (opts.mode !== "unified") {
const [a, b] = await topLines(page);
expect(a, "panes line up at the end").toBe(b);
// Collapsed, the unchanged tail folds away.
if (!opts.collapse) expect(b).toMatch(/value99\d\d/);
}
await shot(page, `scattered-${mode.replace(" ", "-")}`);
});
}
test("every tenth line edited: 1,000 differences", async ({ workbench: page }) => {
const path = "big/every-tenth.ts";
const ms = await openCase(page, path, { alignChanges: false });
test.info().annotations.push({ type: "open", description: `${ms} ms` });
expect(ms, "time to open").toBeLessThan(8_000);
await expectCount(page, path, 1_000);
await scrollToEnd(page);
const { a, b } = await rendered(page);
expect(b.words.length).toBeGreaterThan(0);
expect(b.words.every(([t, k]) => t === "entry" && k === "modified")).toBe(true);
expect(a.words.every(([t, k]) => t === "item" && k === "modified")).toBe(true);
await shot(page, "every-tenth");
});
for (const [mode, opts] of modes.slice(0, 3))
test(`every line edited: one 10,000-line block (${mode})`, async ({ workbench: page }) => {
const path = "big/rewrite.ts";
const ms = await openCase(page, path, opts);
test.info().annotations.push({ type: "open", description: `${ms} ms` });
expect(ms, "time to open").toBeLessThan(8_000);
await expectCount(page, path, 1);
await scrollToEnd(page);
const { b } = await rendered(page);
if (opts.mode === "unified") expect(b.lines.every((k) => k === "inserted")).toBe(true);
else {
expect(b.lines.length).toBeGreaterThan(10);
expect(b.lines.every((k) => k === "modified")).toBe(true);
expect(b.words).toContainEqual(["let", "modified"]);
}
await shot(page, `rewrite-${mode.replace(" ", "-")}`);
});
});
-189
Переглянути файл
@@ -1,189 +0,0 @@
/**
* A git repository of diff viewer cases: each file is committed, then changed
* in the working tree (or added / deleted), covering word edits, pure inserts
* and deletes, whitespace, CJK, missing final newlines, moves, a minified line
* and 10,000-line files. The e2e specs open HEAD against the working copy; run
* `node e2e/diffRepo.ts <dir>` to build it for manual QA in the app.
*/
import { execFileSync } from "node:child_process";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
export interface DiffCase {
path: string;
/** Committed content; null for a file added in the working tree. */
before: string | null;
/** Working-tree content; null for a deleted file. */
after: string | null;
}
const lines = (n: number, line: (i: number) => string) => Array.from({ length: n }, (_, i) => line(i) + "\n").join("");
/** A 10,000-line source file; `edit(i)` may replace line `i` (or return null to drop it). */
function bigFile(edit: (i: number, line: string) => string | string[] | null = (_, l) => l) {
const out: string[] = [];
for (let i = 0; i < 10_000; i++) {
const line = i % 50 === 0 ? `// section ${i / 50}` : `export const value${i} = compute(${i}, "item-${i}");`;
const e = edit(i, line);
if (e !== null) out.push(...(Array.isArray(e) ? e : [e]));
}
return out.map((l) => l + "\n").join("");
}
const OPTIONS_BEFORE = `export interface DiffViewOptions {
mode: DiffMode;
ignore: IgnorePolicy;
highlight: HighlightPolicy;
collapse: boolean;
syncScroll: boolean;
}
`;
const OPTIONS_AFTER = `export interface DiffViewOptions {
mode: DiffMode;
ignore: IgnorePolicy;
highlight: HighlightPolicy;
collapse: boolean;
/**
* IDEA's synchronized scrolling of the side-by-side panes: unpadded panes
* that carry each other along, with a curved divider. Off, the panes are
* padded so unchanged lines line up and scroll together.
*/
syncScrolling: boolean;
}
`;
const FUNCS = ["parse", "format", "validate", "render", "save"].map(
(name) => `function ${name}(input) {\n const result = ${name}Impl(input);\n return result;\n}\n`,
);
const MINIFIED = Array.from({ length: 2_000 }, (_, i) => `var a${i}=f(${i},"k${i}");`).join("");
export const CASES: readonly DiffCase[] = [
// A word edited and a comment added: one modified block (the reported case).
{ path: "src/options.ts", before: OPTIONS_BEFORE, after: OPTIONS_AFTER },
{
path: "src/words.ts",
before: "const flag = true;\ncall(a, b);\nconst keep = 1;\n",
after: "const flag = false;\ncall(a, x, b);\nconst keep = 1;\n",
},
{
path: "src/insert.ts",
before: lines(10, (i) => `line ${i}`),
after: lines(10, (i) => `line ${i}`).replace("line 5\n", "line 5\n" + lines(5, (i) => `added ${i}`)),
},
{
path: "src/delete.ts",
before: lines(12, (i) => `line ${i}`),
after: lines(12, (i) => `line ${i}`).replace(
lines(4, (i) => `line ${i + 4}`),
"",
),
},
{
path: "src/indent.py",
before: "def f():\n if x:\n return 1\n return 0\n",
after: "def f():\n if x:\n return 1\n return 0\n",
},
{ path: "docs/readme-zh.md", before: "# 说明\n\n这是一个测试文件。\n", after: "# 说明\n\n这是一个示例文件。\n" },
{ path: "docs/emoji.md", before: "Hello 👋 world\n", after: "Hello 🌍 world\n" },
{ path: "data/no-eol.txt", before: "alpha\nkeep\nbeta", after: "alpha\nkeep\ngamma" },
{ path: "data/add-eol.txt", before: "alpha\nbeta", after: "alpha\nbeta\n" },
{ path: "src/moved.ts", before: FUNCS.join("\n"), after: [...FUNCS.slice(1), FUNCS[0]!].join("\n") },
{ path: "src/new-file.ts", before: null, after: lines(6, (i) => `export const n${i} = ${i};`) },
{ path: "src/deleted-file.ts", before: lines(6, (i) => `export const d${i} = ${i};`), after: null },
{
path: "dist/app.min.js",
before: MINIFIED + "\n",
after: MINIFIED.replace('f(1000,"k1000")', 'g(1000,"k1000")') + "\n",
},
// 10,000 lines: 40 scattered word edits, a 200-line insert and a 100-line delete.
{
path: "big/scattered.ts",
before: bigFile(),
after: bigFile((i, l) =>
i === 5_000
? [l, ...Array.from({ length: 200 }, (_, k) => `export const inserted${k} = ${k};`)]
: i >= 8_000 && i < 8_100
? null
: i % 250 === 125
? l.replace("compute(", "computeFast(")
: l,
),
},
// 10,000 lines, every tenth one edited: 1,000 differences.
{
path: "big/every-tenth.ts",
before: bigFile(),
after: bigFile((i, l) => (i % 10 === 5 ? l.replace('"item-', '"entry-') : l)),
},
// 10,000 lines, every line edited: one 10,000-line modified block.
{
path: "big/rewrite.ts",
before: bigFile(),
after: bigFile((_, l) => l.replace("export const", "export let").replace("// section", "// part")),
},
];
const git = (cwd: string, ...args: string[]) =>
execFileSync("git", args, { cwd, encoding: "utf8", maxBuffer: 64 << 20, stdio: ["ignore", "pipe", "pipe"] });
/** Builds the repository in `dir` (created, or emptied first). */
export function buildDiffRepo(dir: string): string {
rmSync(dir, { recursive: true, force: true });
mkdirSync(dir, { recursive: true });
const write = (path: string, text: string) => {
mkdirSync(dirname(join(dir, path)), { recursive: true });
writeFileSync(join(dir, path), text);
};
git(dir, "init", "-q", "-b", "main");
git(dir, "config", "user.email", "[email protected]");
git(dir, "config", "user.name", "e2e");
git(dir, "config", "core.autocrlf", "false");
for (const c of CASES) if (c.before !== null) write(c.path, c.before);
git(dir, "add", "-A");
git(dir, "commit", "-qm", "initial");
for (const c of CASES) {
if (c.after === null) rmSync(join(dir, c.path));
else write(c.path, c.after);
}
// Intent-to-add, so `git diff HEAD` lists the new files too.
const added = CASES.filter((c) => c.before === null).map((c) => c.path);
if (added.length) git(dir, "add", "-N", "--", ...added);
return dir;
}
export function tempDiffRepo(): string {
return buildDiffRepo(join(mkdtempSync(join(tmpdir(), "openidea-diff-")), "repo"));
}
/** HEAD and working-tree texts of `path` ("" when missing on that side). */
export function readSides(dir: string, path: string): { left: string; right: string } {
let left = "";
try {
left = git(dir, "show", `HEAD:${path}`);
} catch {
// added in the working tree
}
let right = "";
try {
right = readFileSync(join(dir, path), "utf8");
} catch {
// deleted in the working tree
}
return { left, right };
}
/** Hunks of `git diff -U0` for `path`, the reference count of line differences. */
export function gitHunks(dir: string, path: string): number {
const out = git(dir, "diff", "-U0", "--no-color", "--diff-algorithm=patience", "HEAD", "--", path);
return out.split("\n").filter((l) => l.startsWith("@@")).length;
}
if (import.meta.url === `file://${process.argv[1]}`) {
const dir = resolve(process.argv[2] ?? "diff-repo");
buildDiffRepo(dir);
console.log(`Built ${CASES.length} diff cases in ${dir}`);
console.log(git(dir, "status", "--short"));
}
-113
Переглянути файл
@@ -1,113 +0,0 @@
/** Linux browser acceptance: synthetic MemoryFs + mocked native IPC, real menu/action/refresh UI. */
import { expect, test } from "./fixtures";
for (const destination of ["gitignore", "localExclude"] as const) {
test(`ignore ${destination}: menu dispatch and immediate tree/status refresh`, async ({ workbench: page }) => {
await page.evaluate(async (destination) => {
const fsModule = "/src/features/project-tree/fs.ts";
const storeModule = "/src/features/project-tree/store.ts";
const ipcModule = "/src/platform/ipc.ts";
const { projectFs } = await import(fsModule);
const { reloadAll } = await import(storeModule);
const { commands } = await import(ipcModule);
const root = "/dev/acme-api";
const path = `${root}/scratch.log`;
const fs = projectFs(root);
await fs.createFile(path);
let written = false;
commands.vcsAddToIgnore = async (paths: string[], actual: string) => {
if (actual !== destination || paths.length !== 1 || paths[0] !== path)
throw new Error("Wrong ignore destination or paths");
written = true;
fs.ignored.add(path);
return { status: "ok", data: null };
};
commands.vcsStatus = async () => {
document.body.dataset.ignoreStatusRefresh = written ? "after-write" : "before-write";
return {
status: "ok",
data: written
? []
: [{ path, relPath: "scratch.log", staged: null, unstaged: "untracked", renamedFrom: null }],
};
};
commands.vcsRoots = async () => ({
status: "ok",
data: [{ root, operation: null, head: "main", headCommit: null }],
});
commands.vcsBranchInfo = async () => ({
status: "ok",
data: { head: "main", headCommit: null, upstream: null, ahead: 0, behind: 0, operation: null },
});
const vcsModule = "/src/features/vcs/store.ts";
const { useVcs } = await import(vcsModule);
useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false });
await reloadAll();
const banner = document.createElement("div");
banner.textContent = "LINUX BROWSER E2E · SYNTHETIC FIXTURE · NATIVE IPC MOCKED";
Object.assign(banner.style, {
position: "fixed",
bottom: "28px",
right: "18px",
zIndex: "999999",
padding: "10px 14px",
background: "#fff4ce",
color: "#362a00",
font: "bold 12px sans-serif",
border: "1px solid #9e8500",
borderRadius: "5px",
});
document.body.append(banner);
}, destination);
await page.getByRole("treeitem", { name: "scratch.log", exact: true }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Git", exact: true }).hover();
await page.getByRole("menuitem", { name: "Add to .gitignore", exact: true }).hover();
await expect(page.getByRole("menuitem", { name: ".gitignore", exact: true })).toBeVisible();
await expect(page.getByRole("menuitem", { name: ".git/info/exclude", exact: true })).toBeVisible();
const captureDir = process.env.OPENIDEA_ACCEPTANCE_DIR;
if (captureDir && destination === "gitignore")
await page.screenshot({ path: `${captureDir}/01-ignore-destinations.png` });
await page
.getByRole("menuitem", { name: destination === "gitignore" ? ".gitignore" : ".git/info/exclude", exact: true })
.click();
await expect
.poll(async () =>
page.evaluate(async () => {
const module = "/src/features/project-tree/store.ts";
const { useProjectTree } = await import(module);
return useProjectTree
.getState()
.listings.get("/dev/acme-api")
?.find((entry: { name: string }) => entry.name === "scratch.log")?.ignored;
}),
)
.toBe(true);
await expect
.poll(async () =>
page.evaluate(async () => {
const module = "/src/features/vcs/store.ts";
const { useVcs } = await import(module);
return useVcs.getState().status.length;
}),
)
.toBe(0);
await expect(page.locator("body")).toHaveAttribute("data-ignore-status-refresh", "after-write");
// Display fixture rule text in the actual editor. This is browser memory, not a native disk read.
await page.evaluate(async (destination) => {
const module = "/src/workbench/contributions.ts";
const { editorService } = await import(module);
await editorService().openFile(
`/dev/acme-api/${destination === "gitignore" ? ".gitignore" : ".git/info/exclude"}`,
{ focus: true },
);
}, destination);
const content = page.locator(".cm-editor .cm-content").first();
await content.fill(
`# Synthetic acceptance fixture: ${destination === "gitignore" ? "shared repository rules" : ".git/info/exclude: local rules (common to linked worktrees)"}\n/scratch.log\n`,
);
if (captureDir)
await page.screenshot({
path: `${captureDir}/${destination === "gitignore" ? "02-shared-ignore-effect" : "03-local-exclude-effect"}.png`,
});
});
}
-13
Переглянути файл
@@ -35,16 +35,3 @@ test("type-ahead jumps to a matching node", async ({ workbench: page }) => {
await page.keyboard.type("READ");
await expect(tree.locator('[role="treeitem"][aria-selected="true"]')).toHaveText("README.md");
});
test("Git ignore submenu offers shared and local destinations for files and folders", async ({ workbench: page }) => {
for (const name of ["README.md", "src"]) {
await page.getByRole("treeitem", { name, exact: true }).click({ button: "right" });
await page.getByRole("menuitem", { name: "Git", exact: true }).hover();
await page.getByRole("menuitem", { name: "Add to .gitignore", exact: true }).hover();
await expect(page.getByRole("menuitem", { name: ".gitignore", exact: true })).toBeVisible();
await expect(page.getByRole("menuitem", { name: ".git/info/exclude", exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
await page.keyboard.press("Escape");
}
});
-3
Переглянути файл
@@ -111,9 +111,6 @@ export const ICLS_ATTRIBUTES: Record<string, Array<[Part, string]>> = {
["FOREGROUND", "--fg-editor"],
["BACKGROUND", "--bg-editor"],
],
DIFF_MODIFIED: [["BACKGROUND", "--diff-modified"]],
DIFF_INSERTED: [["BACKGROUND", "--diff-inserted"]],
DIFF_DELETED: [["BACKGROUND", "--diff-deleted"]],
DEFAULT_KEYWORD: [["FOREGROUND", "--syn-keyword"]],
DEFAULT_STRING: [["FOREGROUND", "--syn-string"]],
DEFAULT_NUMBER: [["FOREGROUND", "--syn-number"]],
-1
Переглянути файл
@@ -201,7 +201,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
vcs::vcs_branches,
vcs::vcs_stashes,
vcs::vcs_stage,
vcs::vcs_add_to_ignore,
vcs::vcs_unstage,
vcs::vcs_stage_patch,
vcs::vcs_discard,
-11
Переглянути файл
@@ -108,17 +108,6 @@ pub async fn vcs_stage(window: Window, state: State<'_, AppState>, paths: Vec<Pa
ide_host::ops::vcs::vcs_stage(&state.host, window.label(), paths).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_add_to_ignore(
window: Window,
state: State<'_, AppState>,
paths: Vec<PathBuf>,
destination: IgnoreDestination,
) -> IdeResult<()> {
ide_host::ops::vcs::vcs_add_to_ignore(&state.host, window.label(), paths, destination).await
}
#[tauri::command]
#[specta::specta]
pub async fn vcs_unstage(window: Window, state: State<'_, AppState>, paths: Vec<PathBuf>) -> IdeResult<()> {
-3
Переглянути файл
@@ -404,7 +404,6 @@ export const commands = {
vcsBranches: (repo: string | null) => typedError<Branch[], IdeError>(__TAURI_INVOKE("vcs_branches", { repo })),
vcsStashes: (repo: string | null) => typedError<Stash[], IdeError>(__TAURI_INVOKE("vcs_stashes", { repo })),
vcsStage: (paths: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stage", { paths })),
vcsAddToIgnore: (paths: string[], destination: IgnoreDestination) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_add_to_ignore", { paths, destination })),
vcsUnstage: (paths: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_unstage", { paths })),
vcsStagePatch: (patch: string) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_stage_patch", { patch })),
vcsDiscard: (paths: string[]) => typedError<null, IdeError>(__TAURI_INVOKE("vcs_discard", { paths })),
@@ -3339,8 +3338,6 @@ export type IdentifierOccurrence = {
qualified: boolean,
};
export type IgnoreDestination = "gitignore" | "localExclude";
export type IndentConfig = IndentConfig_Serialize | IndentConfig_Deserialize;
export type IndentConfig_Deserialize = {
+3 -189
Переглянути файл
@@ -1,72 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { OutlineItem, References } from "@/platform/ipc";
import { _addEditor, _removeEditor, codeLenses, documentSynced } from "@/editor/api";
const ipc = vi.hoisted(() => ({
docOutline: vi.fn(),
lspReferences: vi.fn(),
cancelRequest: vi.fn<(id: number) => Promise<void>>(async () => {}),
}));
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
});
const executeAction = vi.hoisted(() => vi.fn(async () => true));
vi.mock("@/platform/actions", () => ({ executeAction }));
const { lensTargets, usagesLensExtension } = await import("./codeLens");
const { lspDoc } = await import("./lsp");
const { useProject } = await import("@/platform/project");
const { emitLocalIdeEvent } = await import("@/platform/ipc");
const ctx = { doc: 7, path: "/p/a.rs", language: "rust", uiMode: "Rust", readOnly: false };
const views: EditorView[] = [];
const ok = <T>(data: T) => ({ status: "ok" as const, data });
const refs = (n: number, incomplete: References["incomplete"] = null) =>
ok({
locations: Array.from({ length: n }, () => ({ path: "/p/b.rs", range: item("x", "function", 0).range })),
incomplete,
});
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((r) => (resolve = r));
return { promise, resolve };
}
function editor(count = 1, sync?: () => Promise<void>) {
const view = new EditorView({
state: EditorState.create({
doc: Array.from({ length: count }, (_, i) => `fn f${i}() {}`).join("\n"),
extensions: [lspDoc.of(ctx), usagesLensExtension(), ...(sync ? [documentSynced.of(sync)] : [])],
}),
parent: document.body,
});
views.push(view);
return view;
}
const titles = (view: EditorView) => view.state.facet(codeLenses).map((l) => l.title);
const settle = () => vi.advanceTimersByTimeAsync(1000);
beforeEach(() => {
vi.useFakeTimers();
ipc.docOutline.mockReset().mockResolvedValue(ok([item("f0", "function", 0)]));
ipc.lspReferences.mockReset().mockResolvedValue(refs(2));
ipc.cancelRequest.mockClear();
executeAction.mockClear();
useProject.setState({
settings: { editor: { inlay: { codeVisionUsages: true, codeVisionAuthor: false } } } as never,
});
});
afterEach(() => {
views.splice(0).forEach((v) => v.destroy());
useProject.setState({ settings: null });
vi.useRealTimers();
});
import { describe, expect, it } from "vitest";
import type { OutlineItem } from "@/platform/ipc";
import { lensTargets } from "./codeLens";
const item = (name: string, kind: OutlineItem["kind"], line: number, children: OutlineItem[] = []): OutlineItem => {
const r = { start: { line, col: 0 }, end: { line, col: 1 } };
@@ -84,123 +18,3 @@ describe("usages lens targets", () => {
expect(lensTargets(items).map((t) => t.name)).toEqual(["Cart", "count"]);
});
});
describe("background usage counts", () => {
it("uses the server's existing scope and leaves full searches to the explicit action", async () => {
const view = editor();
await settle();
expect(ipc.lspReferences).toHaveBeenCalledWith(expect.any(Number), 7, { line: 0, col: 0 }, false, false);
expect(titles(view)).toEqual(["2 usages"]);
view.state.facet(codeLenses)[0]!.run!(view, new MouseEvent("click"));
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
});
it("allows a full search even when the server's current scope has no usages", async () => {
ipc.lspReferences.mockResolvedValue(refs(0));
const view = editor();
await settle();
expect(titles(view)).toEqual(["no usages"]);
view.state.facet(codeLenses)[0]!.run!(view, new MouseEvent("click"));
expect(executeAction).toHaveBeenCalledWith("find.showUsages");
});
it("does not cache an incomplete count while indexing, and retries on server refresh", async () => {
ipc.lspReferences.mockResolvedValueOnce(refs(0, "indexing"));
const view = editor();
await settle();
expect(titles(view)).toEqual([]);
emitLocalIdeEvent({ type: "lspRefresh", kind: "codeLens", server: 1 });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2);
expect(titles(view)).toEqual(["2 usages"]);
});
it("cancels obsolete requests immediately on edits and ignores their late replies", async () => {
const old = deferred<ReturnType<typeof refs>>();
ipc.lspReferences.mockReturnValueOnce(old.promise);
const view = editor();
await settle();
const request = ipc.lspReferences.mock.calls[0]![0];
view.dispatch({ changes: { from: view.state.doc.length, insert: " " } });
expect(ipc.cancelRequest).toHaveBeenCalledWith(request);
await settle();
expect(titles(view)).toEqual(["2 usages"]);
old.resolve(refs(99));
await settle();
expect(titles(view)).toEqual(["2 usages"]);
});
it("retries incomplete counts when indexing ends without a code-lens refresh", async () => {
ipc.lspReferences.mockResolvedValueOnce(refs(0, "indexing"));
const view = editor();
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "rust-analyzer", status: "busy", message: null });
await settle();
expect(titles(view)).toEqual([]);
await settle();
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "rust-analyzer", status: "ready", message: null });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(2);
expect(titles(view)).toEqual(["2 usages"]);
});
it("does not repeat complete counts when the server finishes other work", async () => {
const view = editor();
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "rust-analyzer", status: "busy", message: null });
await settle();
await settle();
emitLocalIdeEvent({ type: "languageServer", server: 1, name: "rust-analyzer", status: "ready", message: null });
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(1);
expect(titles(view)).toEqual(["2 usages"]);
});
it("cancels all in-flight requests on destroy without starting the next batch", async () => {
const pending = deferred<ReturnType<typeof refs>>();
ipc.docOutline.mockResolvedValue(ok(Array.from({ length: 8 }, (_, i) => item(`f${i}`, "function", i))));
ipc.lspReferences.mockReturnValue(pending.promise);
const view = editor(8);
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(4);
const requests = ipc.lspReferences.mock.calls.map(([id]) => id);
view.destroy();
views.splice(views.indexOf(view), 1);
expect(ipc.cancelRequest.mock.calls.map(([id]) => id)).toEqual(requests);
pending.resolve(refs(1));
await settle();
expect(ipc.lspReferences).toHaveBeenCalledTimes(4);
});
it("cancels pending counts when the feature is disabled", async () => {
const pending = deferred<ReturnType<typeof refs>>();
ipc.lspReferences.mockReturnValue(pending.promise);
const view = editor();
await settle();
useProject.setState({
settings: { editor: { inlay: { codeVisionUsages: false, codeVisionAuthor: false } } } as never,
});
expect(ipc.cancelRequest).toHaveBeenCalledWith(ipc.lspReferences.mock.calls[0]![0]);
pending.resolve(refs(2));
await settle();
expect(titles(view)).toEqual([]);
});
it("does not send obsolete requests after waiting for document synchronization", async () => {
const synced = deferred<void>();
const view = editor(1, () => synced.promise);
const handle = { view, ctx };
_addEditor(handle);
try {
await settle();
expect(ipc.docOutline).not.toHaveBeenCalled();
view.destroy();
views.splice(views.indexOf(view), 1);
synced.resolve();
await settle();
expect(ipc.docOutline).not.toHaveBeenCalled();
expect(ipc.lspReferences).not.toHaveBeenCalled();
expect(ipc.cancelRequest).not.toHaveBeenCalled();
} finally {
_removeEditor(handle);
}
});
});
+18 -47
Переглянути файл
@@ -9,11 +9,11 @@ import { EditorSelection, MapMode, StateEffect, StateField, type Extension, type
import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
import { codeLenses, type CodeLens } from "@/editor/api";
import { executeAction } from "@/platform/actions";
import { commands, nextRequestId, type OutlineItem, type RequestId, type SymbolKind } from "@/platform/ipc";
import { commands, nextRequestId, type OutlineItem, type SymbolKind } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { debounce, docOf, isUnavailable, lspRequest } from "./lsp";
import { posToOffset } from "./positions";
import { featureBackoff, onLspRefresh, onServerSettled } from "./availability";
import { featureBackoff, onLspRefresh } from "./availability";
import { editorPrefs } from "@/platform/editorSettings";
import { authorLabel, authorSummary, authorTooltip, blameFor, onBlameInvalidated } from "./authorLens";
import { tx } from "@/platform/i18n";
@@ -106,17 +106,14 @@ function openUsages(view: EditorView, offset: number) {
}
class UsagesLensPlugin {
private schedule = debounce(() => void this.run(), 900);
private refresh = debounce(() => void this.run(), 900);
/** `${line}:${col}:${name}` → count, valid for `cacheDoc`. */
private cache = new Map<string, number>();
private cacheDoc: Text | null = null;
private outline: { doc: Text; targets: LensTarget[] } | null = null;
private generation = 0;
private pending = new Set<RequestId>();
private incomplete = false;
private unsubscribe: () => void;
private offReady: () => void;
private offSettled: () => void;
private offBlame: () => void;
constructor(private view: EditorView) {
@@ -129,9 +126,6 @@ class UsagesLensPlugin {
this.cache.clear();
this.refresh();
});
this.offSettled = onServerSettled(() => {
if (this.incomplete) this.refresh();
});
this.offBlame = onBlameInvalidated(() => this.refresh());
}
@@ -139,23 +133,12 @@ class UsagesLensPlugin {
if (u.docChanged || u.viewportChanged) this.refresh();
}
private cancel() {
this.generation++;
for (const id of this.pending) void commands.cancelRequest(id).catch(() => {});
this.pending.clear();
}
private refresh() {
this.cancel();
this.schedule();
}
private async run() {
const view = this.view;
if (!view.dom.isConnected) return;
const doc = docOf(view);
if (!doc) return;
const gen = this.generation;
const gen = ++this.generation;
const usages = usagesEnabled() && !usagesBackoff.active(doc.doc);
const authors = authorEnabled() && !doc.virtual;
if (!usages && !authors) {
@@ -163,8 +146,6 @@ class UsagesLensPlugin {
return;
}
const text = view.state.doc;
const wanted = () => gen === this.generation && view.state.doc === text;
this.incomplete = false;
// Blame runs beside the reference requests; it never holds up the counts.
const blame = authors ? blameFor(doc.path, text) : Promise.resolve(null);
if (this.cacheDoc !== text) {
@@ -173,8 +154,8 @@ class UsagesLensPlugin {
}
try {
if (this.outline?.doc !== text) {
const items = await lspRequest(() => commands.docOutline(doc.doc), wanted);
if (!wanted()) return;
const items = await lspRequest(() => commands.docOutline(doc.doc));
if (gen !== this.generation || view.state.doc !== text) return;
this.outline = { doc: text, targets: lensTargets(items) };
}
const { from, to } = view.viewport;
@@ -189,30 +170,21 @@ class UsagesLensPlugin {
for (let i = 0; i < todo.length && !unavailable; i += CONCURRENCY) {
await Promise.all(
todo.slice(i, i + CONCURRENCY).map(async (t) => {
const request = nextRequestId();
try {
const { locations: refs, incomplete } = await lspRequest(() => {
this.pending.add(request);
// Opening candidate files for each count triggers expensive server analysis.
// Only an explicit Find Usages should widen the server's scope.
return commands.lspReferences(request, doc.doc, { line: t.line, col: t.col }, false, false);
}, wanted);
if (wanted()) {
if (incomplete) this.incomplete = true;
else this.cache.set(key(t), refs.length);
}
const { locations: refs } = await lspRequest(() =>
commands.lspReferences(nextRequestId(), doc.doc, { line: t.line, col: t.col }, false, true),
);
this.cache.set(key(t), refs.length);
} catch (e) {
if (wanted() && isUnavailable(e)) unavailable = true;
} finally {
this.pending.delete(request);
if (isUnavailable(e)) unavailable = true;
}
}),
);
if (!wanted()) return;
if (gen !== this.generation || view.state.doc !== text) return;
}
if (unavailable) usagesBackoff.mark(doc.doc);
const lines = await blame;
if (!wanted()) return;
if (gen !== this.generation || view.state.doc !== text) return;
const lenses: CodeLens[] = [];
for (const t of visible) {
const offset = posToOffset(text, { line: t.line, col: t.col });
@@ -224,24 +196,23 @@ class UsagesLensPlugin {
lenses.push({
pos: offset,
title: usagesLabel(n),
tooltip: tx`Show usages of ${t.name}`,
tooltip: n ? tx`Show usages of ${t.name}` : undefined,
order: 10,
run: (v) => openUsages(v, Math.min(offset, v.state.doc.length)),
run: n ? (v) => openUsages(v, Math.min(offset, v.state.doc.length)) : undefined,
});
}
if (!sameLenses(view.state.field(lensField), lenses)) view.dispatch({ effects: setLenses.of(lenses) });
} catch (e) {
if (wanted() && isUnavailable(e)) usagesBackoff.mark(doc.doc);
if (isUnavailable(e)) usagesBackoff.mark(doc.doc);
}
}
destroy() {
this.schedule.cancel();
this.refresh.cancel();
this.unsubscribe();
this.offReady();
this.offSettled();
this.offBlame();
this.cancel();
this.generation++;
}
}
-62
Переглянути файл
@@ -1,62 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { showHint, showPendingHint } from "./hint";
let view: EditorView;
const hint = () => document.querySelector(".cm-lsp-hint")?.textContent ?? null;
beforeEach(() => {
vi.useFakeTimers();
view = new EditorView({ state: EditorState.create({ doc: "foo()" }), parent: document.body });
});
afterEach(() => {
view.destroy();
vi.useRealTimers();
});
describe("pending hints", () => {
it("does not flash for fast requests", () => {
const done = showPendingHint(view, "Waiting…");
vi.advanceTimersByTime(100);
done();
vi.advanceTimersByTime(1000);
expect(hint()).toBeNull();
});
it("shows a slow request and removes its hint on completion", () => {
const done = showPendingHint(view, "Waiting…");
vi.advanceTimersByTime(250);
expect(hint()).toBe("Waiting…");
done();
expect(hint()).toBeNull();
});
it("does not dismiss a newer hint when an old request finishes", () => {
const done = showPendingHint(view, "Waiting…");
vi.advanceTimersByTime(250);
showHint(view, "New error", { tone: "error" });
done();
expect(hint()).toBe("New error");
});
it("does not overwrite a newer hint while waiting to show progress", () => {
const done = showPendingHint(view, "Waiting…");
vi.advanceTimersByTime(100);
showHint(view, "New error", { tone: "error" });
vi.advanceTimersByTime(150);
expect(hint()).toBe("New error");
done();
expect(hint()).toBe("New error");
});
it.each(["edit", "move", "destroy"])("does not show stale progress after %s", (change) => {
const done = showPendingHint(view, "Waiting…");
if (change === "edit") view.dispatch({ changes: { from: 0, insert: "x" } });
if (change === "move") view.dispatch({ selection: { anchor: 3 } });
if (change === "destroy") view.destroy();
vi.advanceTimersByTime(250);
done();
expect(hint()).toBeNull();
});
});
+1 -26
Переглянути файл
@@ -67,36 +67,11 @@ export function showHint(
timers.set(
view,
setTimeout(() => {
if (view.dom.isConnected && view.state.field(hintField, false)) view.dispatch({ effects: setHint.of(null) });
if (view.state.field(hintField, false)) view.dispatch({ effects: setHint.of(null) });
}, opts.timeout ?? 4000),
);
}
/** Show progress only for slow requests; the disposer removes only its own hint. */
export function showPendingHint(view: EditorView, content: string): () => void {
const { doc, selection } = view.state;
const previous = view.state.field(hintField, false);
let shown: Hint | null = null;
const timer = setTimeout(() => {
if (
!view.dom.isConnected ||
view.state.doc !== doc ||
!view.state.selection.eq(selection) ||
view.state.field(hintField, false) !== previous
)
return;
showHint(view, content, { timeout: 30_000 });
shown = view.state.field(hintField);
}, 250);
return () => {
clearTimeout(timer);
if (shown && view.state.field(hintField, false) === shown) {
clearTimeout(timers.get(view));
if (view.dom.isConnected) hideHint(view);
}
};
}
export function hideHint(view: EditorView): boolean {
if (!view.state.field(hintField, false)) return false;
view.dispatch({ effects: setHint.of(null) });
+2 -7
Переглянути файл
@@ -46,7 +46,7 @@ import {
localHighlights,
type DeclarationTarget,
} from "./syntaxFallback";
import { showHint, showPendingHint } from "./hint";
import { showHint } from "./hint";
import { caretAnchor, openPopup, type ListPopupItem } from "./popupStore";
import { identifierAt, readManyFileLines } from "./files";
import { documentLinks, followReference, knownLinks, linkReference, referenceAt, textReference } from "./links";
@@ -166,12 +166,7 @@ export async function gotoTargets(view: EditorView, kind: GotoKind, at?: number)
const declaration = kind === "definition" || kind === "declaration";
let serverDown = false;
try {
const done = showPendingHint(view, tx`Finding navigation target…`);
try {
locs = dedupeLocations(await gotoAfterEdits(view, () => lspRequest(() => commands.lspGoto(doc.doc, pos, kind))));
} finally {
done();
}
locs = dedupeLocations(await gotoAfterEdits(view, () => lspRequest(() => commands.lspGoto(doc.doc, pos, kind))));
} catch (e) {
if (isCancelled(e) || !declaration) {
reportLspError(view, e, true);
-62
Переглянути файл
@@ -1,62 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import type { commands } from "@/platform/ipc";
const lspGoto = vi.hoisted(() => vi.fn<typeof commands.lspGoto>());
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return { ...real, isTauri: () => true, commands: { ...real.commands, lspGoto } };
});
const { gotoTargets } = await import("./navigation");
const { lspDoc } = await import("./lsp");
const { provideEditorService } = await import("@/workbench/contributions");
const openFile = vi.fn(async () => {});
provideEditorService({ openFile } as never);
let view: EditorView;
beforeEach(() => {
vi.useFakeTimers();
openFile.mockClear();
view = new EditorView({
state: EditorState.create({
doc: "run()",
extensions: [lspDoc.of({ doc: 1, path: "/p/main.rs", language: "rust", uiMode: "Rust", readOnly: false })],
}),
parent: document.body,
});
});
afterEach(() => {
view.destroy();
vi.useRealTimers();
});
describe("slow navigation feedback", () => {
it("shows progress while finding a definition, then opens the target and clears the hint", async () => {
let resolve!: (result: Awaited<ReturnType<typeof commands.lspGoto>>) => void;
lspGoto.mockImplementationOnce(() => new Promise((r) => (resolve = r)));
const pending = gotoTargets(view, "definition");
await vi.advanceTimersByTimeAsync(250);
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("Finding navigation target…");
expect(openFile).not.toHaveBeenCalled();
resolve({
status: "ok",
data: [{ path: "/p/lib.rs", range: { start: { line: 3, col: 4 }, end: { line: 3, col: 7 } }, uri: null }],
});
await pending;
expect(openFile).toHaveBeenCalledWith("/p/lib.rs", { selection: { line: 3, col: 4 }, focus: true });
expect(document.querySelector(".cm-lsp-hint")).toBeNull();
});
it("replaces progress with the server error", async () => {
let resolve!: (result: Awaited<ReturnType<typeof commands.lspGoto>>) => void;
lspGoto.mockImplementationOnce(() => new Promise((r) => (resolve = r)));
const pending = gotoTargets(view, "implementation");
await vi.advanceTimersByTimeAsync(250);
resolve({ status: "error", error: { kind: "protocol", message: "Server timed out" } });
await pending;
expect(document.querySelector(".cm-lsp-hint")?.textContent).toBe("Server timed out");
expect(openFile).not.toHaveBeenCalled();
});
});
-11
Переглянути файл
@@ -39,17 +39,6 @@
text-overflow: ellipsis;
white-space: nowrap;
}
.title[data-unread] {
color: var(--fg-strong);
font-weight: 600;
}
.unreadDot {
flex: none;
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--accent);
}
.detail {
flex: 1 1 0;
min-width: 0;
+2 -10
Переглянути файл
@@ -5,13 +5,11 @@ import styles from "./Agents.module.css";
export function AgentsStatus() {
const tasks = useAgents((s) => s.tasks);
const unread = useAgents((s) => s.unread);
const list = [...tasks.values()];
const unseen = list.filter((t) => unread.has(t.id)).sort((a, b) => (b.updatedMs ?? 0) - (a.updatedMs ?? 0));
const input = list.filter((t) => t.status === "needsInput");
const running = list.filter((t) => t.status === "running" || t.status === "starting").length;
if (!input.length && !running && !unseen.length) return null;
const target = input[0] ?? unseen[0] ?? list.find((t) => t.status === "running" || t.status === "starting");
if (!input.length && !running) return null;
const target = input[0] ?? list.find((t) => t.status === "running");
return (
<button type="button" className={styles.statusItem} onClick={() => target && openTask(target.id)}>
{input.length > 0 && (
@@ -26,12 +24,6 @@ export function AgentsStatus() {
{running} <T>running</T>
</span>
)}
{unseen.length > 0 && (
<span className={styles.statusPart}>
<span className={styles.unreadDot} aria-hidden="true" />
{unseen.length} <T>unread</T>
</span>
)}
</button>
);
}
-209
Переглянути файл
@@ -1,209 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { AgentTask } from "@/bindings";
import { registerActions } from "@/platform/actions";
import type { EditorInput } from "@/workbench/contributions";
import { confirmChecked, showError } from "@/workbench/messages";
import { ContextMenuHost, hideContextMenu } from "@/ui";
import { AgentsView } from "./AgentsView";
import { SESSION_KIND } from "./model";
import { archiveTask, deleteTask, openTask, useAgents } from "./store";
import { taskActions } from "./taskActions";
const editor = vi.hoisted(() => ({
active: undefined as EditorInput | undefined,
listener: undefined as ((input: EditorInput) => void) | undefined,
}));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
maybeEditorService: () => ({
activeInput: () => editor.active,
onActiveInputChange: (listener: typeof editor.listener) => {
editor.listener = listener;
return () => {
editor.listener = undefined;
};
},
}),
}));
vi.mock("./store", async (original) => ({
...(await original<typeof import("./store")>()),
openTask: vi.fn((id: string) => editor.listener?.({ kind: "agent-session", key: id, data: { task: id } })),
archiveTask: vi.fn(async () => {}),
deleteTask: vi.fn(async () => {}),
}));
vi.mock("@/workbench/messages", () => ({
confirmChecked: vi.fn(async () => ({ checked: false })),
showError: vi.fn(async () => {}),
}));
function task(
id: string,
status: AgentTask["status"] = "ready",
isolation: AgentTask["isolation"] = "local",
): AgentTask {
return {
id,
title: id,
status,
isolation,
provider: "codex",
model: null,
cwd: "/project",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
};
}
const row = (id: string) => screen.getByText(id).closest('[role="treeitem"]')!;
const select = (id: string, modifiers: MouseEventInit = {}) =>
fireEvent.mouseDown(row(id), { button: 0, ...modifiers });
const selectedTasks = () =>
screen
.queryAllByRole("treeitem", { selected: true })
.filter((item) => item.getAttribute("aria-level") === "2")
.map((item) => item.querySelector("[title]")?.getAttribute("title"));
const context = (id: string) => {
fireEvent.mouseDown(row(id), { button: 2 });
fireEvent.contextMenu(row(id));
};
let dispose: () => void;
beforeEach(() => {
vi.clearAllMocks();
editor.active = undefined;
vi.mocked(confirmChecked).mockResolvedValue({ checked: false });
useAgents.setState({
loaded: true,
error: null,
tasks: new Map([task("one"), task("two"), task("three"), task("four")].map((t) => [t.id, t])),
});
dispose = registerActions(taskActions);
});
afterEach(() => {
dispose();
hideContextMenu();
});
function setup() {
render(
<>
<AgentsView />
<ContextMenuHost />
</>,
);
}
describe("Agents selection", () => {
it("extends and shrinks a range without opening its lead or losing selection to an editor echo", () => {
setup();
select("one");
select("three", { shiftKey: true });
expect(selectedTasks()).toEqual(["one", "two", "three"]);
expect(openTask).toHaveBeenCalledTimes(1);
act(() => editor.listener?.({ kind: SESSION_KIND, key: "one", data: { task: "one" } }));
expect(selectedTasks()).toEqual(["one", "two", "three"]);
select("two", { shiftKey: true });
expect(selectedTasks()).toEqual(["one", "two"]);
select("four");
expect(selectedTasks()).toEqual(["four"]);
});
it("keeps the initial active task as the anchor for repeated keyboard extension", () => {
editor.active = { kind: SESSION_KIND, key: "one", data: { task: "one" } };
setup();
const tree = screen.getByRole("tree");
fireEvent.keyDown(tree, { key: "ArrowDown", shiftKey: true });
fireEvent.keyDown(tree, { key: "ArrowDown", shiftKey: true });
expect(selectedTasks()).toEqual(["one", "two", "three"]);
expect(openTask).not.toHaveBeenCalled();
});
it.each(["metaKey", "ctrlKey"])("toggles individual tasks with %s", (modifier) => {
setup();
select("one");
select("three", { [modifier]: true });
expect(selectedTasks()).toEqual(["one", "three"]);
select("three", { [modifier]: true });
expect(selectedTasks()).toEqual(["one"]);
expect(openTask).toHaveBeenCalledTimes(1);
});
});
describe("Agents bulk actions", () => {
it("deletes the right-clicked selection after one confirmation, excluding group headers", async () => {
const tasks = [task("one", "running"), task("two"), task("three")];
useAgents.setState({ tasks: new Map(tasks.map((t) => [t.id, t])) });
setup();
select("one");
select("three", { shiftKey: true });
context("two");
fireEvent.click(screen.getByRole("menuitem", { name: "Delete (3)…" }));
await waitFor(() => expect(deleteTask).toHaveBeenCalledTimes(3));
expect(confirmChecked).toHaveBeenCalledTimes(1);
expect(confirmChecked).toHaveBeenCalledWith(
expect.objectContaining({ message: expect.stringContaining("3 agent tasks") }),
);
expect(vi.mocked(deleteTask).mock.calls).toEqual([
["one", false],
["two", false],
["three", false],
]);
});
it("right-clicking outside the selection targets only that task", async () => {
setup();
select("one");
select("two", { shiftKey: true });
context("four");
fireEvent.click(screen.getByRole("menuitem", { name: "Delete…" }));
await waitFor(() => expect(deleteTask).toHaveBeenCalledExactlyOnceWith("four", false));
});
it("archives only eligible tasks in a mixed selection", async () => {
const tasks = [task("one", "running"), task("two"), task("three", "archived")];
useAgents.setState({ tasks: new Map(tasks.map((t) => [t.id, t])) });
setup();
fireEvent.doubleClick(screen.getByText("Archived"));
select("one");
select("three", { shiftKey: true });
context("two");
fireEvent.click(screen.getByRole("menuitem", { name: "Archive (1)" }));
await waitFor(() => expect(archiveTask).toHaveBeenCalledExactlyOnceWith("two"));
});
it("cancels the whole batch", async () => {
vi.mocked(confirmChecked).mockResolvedValue(null);
await taskActions.find((action) => action.id === "agents.deleteTasks")!.run({ ctx: {}, arg: ["one", "two"] });
expect(deleteTask).not.toHaveBeenCalled();
});
it.each([false, true])("applies worktree cleanup (%s) only to worktree tasks", async (checked) => {
const tasks = [task("one"), task("two", "ready", "worktree")];
useAgents.setState({ tasks: new Map(tasks.map((t) => [t.id, t])) });
vi.mocked(confirmChecked).mockResolvedValue({ checked });
await taskActions.find((action) => action.id === "agents.deleteTasks")!.run({ ctx: {}, arg: ["one", "two"] });
expect(vi.mocked(deleteTask).mock.calls).toEqual([
["one", false],
["two", checked],
]);
});
it("continues after an error and reports the failed task", async () => {
vi.mocked(deleteTask).mockRejectedValueOnce(new Error("Cannot remove worktree"));
await taskActions.find((action) => action.id === "agents.deleteTasks")!.run({ ctx: {}, arg: ["one", "two"] });
expect(deleteTask).toHaveBeenCalledTimes(2);
expect(showError).toHaveBeenCalledWith("Cannot delete agent tasks", "one: Cannot remove worktree");
});
});
+36 -23
Переглянути файл
@@ -1,13 +1,14 @@
/** Agents tool window: tasks grouped by what they need from the user. */
import { useEffect, useMemo, useState } from "react";
import type { AgentStatus as Status, AgentTask } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { maybeEditorService, type EditorInput } from "@/workbench/contributions";
import { EmptyState, Icon, IconButton, Spinner, T, Tree, showContextMenu } from "@/ui";
import { SESSION_KIND, age, branchLabel, groupTasks, type TaskGroup } from "./model";
import { openHome, openTask, useAgents } from "./store";
import { taskMenu } from "./taskActions";
import { confirmChecked } from "@/workbench/messages";
import { EmptyState, Icon, IconButton, Spinner, T, Tree, showContextMenu, type MenuItem } from "@/ui";
import { SESSION_KIND, age, branchLabel, groupTasks, isBusy, type TaskGroup } from "./model";
import { archiveTask, deleteTask, openHome, openTask, useAgents } from "./store";
import styles from "./Agents.module.css";
import { useTx } from "@/platform/i18n";
import { tx } from "@/platform/i18n";
export function AgentsHeaderActions() {
return (
@@ -43,11 +44,9 @@ export function TaskStatusIcon({ status }: { status: Status }) {
}
export function AgentsView() {
const tx = useTx();
const loaded = useAgents((s) => s.loaded);
const error = useAgents((s) => s.error);
const tasks = useAgents((s) => s.tasks);
const unread = useAgents((s) => s.unread);
const providers = useAgents((s) => s.providers);
const [collapsed, setCollapsed] = useState<Set<string>>(() => new Set(["g:archived"]));
const [selected, setSelected] = useState<Set<string>>(() => {
@@ -60,7 +59,7 @@ export function AgentsView() {
maybeEditorService()?.onActiveInputChange?.((input) => {
const task = sessionTask(input);
if (!task) return;
setSelected((current) => (current.has(task) ? current : new Set([task])));
setSelected(new Set([task]));
const group = groupTasks(useAgents.getState().tasks.values()).find((g) => g.tasks.some((t) => t.id === task));
const key = group && `g:${group.status}`;
if (key) setCollapsed((c) => (c.has(key) ? new Set([...c].filter((k) => k !== key)) : c));
@@ -101,17 +100,10 @@ export function AgentsView() {
selected={selected}
onSelectionChange={(sel, lead) => {
setSelected(sel);
if (sel.size === 1 && lead?.kind === "task" && sel.has(lead.task.id)) openTask(lead.task.id);
if (lead?.kind === "task") openTask(lead.task.id);
}}
onActivate={(n) => n.kind === "task" && openTask(n.task.id)}
onContextMenu={(n, sel, e) => {
if (n?.kind !== "task") return;
const selection = [...sel].flatMap((id) => {
const task = tasks.get(id);
return task ? [task] : [];
});
showContextMenu(e, taskMenu(selection));
}}
onContextMenu={(n, _sel, e) => n?.kind === "task" && showContextMenu(e, taskMenu(n.task))}
renderNode={(n) =>
n.kind === "group" ? (
<span className={styles.row}>
@@ -123,12 +115,7 @@ export function AgentsView() {
) : (
<span className={styles.row} title={n.task.error ?? n.task.title}>
<TaskStatusIcon status={n.task.status} />
<span className={styles.title} data-unread={unread.has(n.task.id) || undefined}>
{n.task.title}
</span>
{unread.has(n.task.id) && (
<span className={styles.unreadDot} role="img" aria-label={tx("Unread")} title={tx("Unread")} />
)}
<span className={styles.title}>{n.task.title}</span>
<span className={styles.detail}>
{providerName(n.task.provider)}
{n.task.isolation === "worktree" ? ` · ${branchLabel(n.task.branch)}` : ""}
@@ -149,3 +136,29 @@ export function AgentsView() {
</div>
);
}
function taskMenu(task: AgentTask): MenuItem[] {
const busy = isBusy(task.status);
return [
{ label: "Open", run: () => openTask(task.id) },
{ label: "Open in Terminal", icon: "terminal", run: () => void executeAction("terminal.openAt", task.cwd) },
{ kind: "separator" },
{ label: "Archive", disabled: busy || task.status === "archived", run: () => void archiveTask(task.id) },
{ label: "Delete…", run: () => void confirmDelete(task) },
];
}
async function confirmDelete(task: AgentTask) {
const worktree = task.isolation === "worktree";
const r = await confirmChecked({
title: "Delete Agent Task",
message: worktree
? tx`Delete “${task.title}”? Its branch ${task.branch ?? ""} is kept.`
: tx`Delete “${task.title}”? Files it changed are kept.`,
ok: "Delete",
icon: "warning",
checkbox: worktree ? "Also remove its worktree folder" : undefined,
checked: worktree,
});
if (r) await deleteTask(task.id, worktree && r.checked);
}
+1 -5
Переглянути файл
@@ -21,7 +21,6 @@ import { HOME_KIND, REGISTRY_PAGE, SESSION_KIND, TOOL_WINDOW } from "./model";
import { sendPaths, sendSelection } from "./references";
import { focusedSession } from "./sessionFocus";
import { connect, disconnect, openHome, useAgents } from "./store";
import { taskActions } from "./taskActions";
/** Settings › Tools › Agents (also used by the Settings window). */
export function activateSettingsPages(): () => void {
@@ -55,9 +54,7 @@ export function activate(): () => void {
component: lazyComponent(() => import("./AgentsView").then((m) => m.AgentsView)),
headerActions: lazyComponent(() => import("./AgentsView").then((m) => m.AgentsHeaderActions)),
useBadge: () => {
const n = useAgents(
(s) => [...s.tasks.values()].filter((t) => t.status === "needsInput" || s.unread.has(t.id)).length,
);
const n = useAgents((s) => [...s.tasks.values()].filter((t) => t.status === "needsInput").length);
return n || null;
},
}),
@@ -90,7 +87,6 @@ export function activate(): () => void {
: [],
}),
registerActions([
...taskActions,
{
id: "agents.findInConversation",
title: "Find in Conversation",
+7 -58
Переглянути файл
@@ -44,8 +44,6 @@ interface AgentsState {
/** Why the tasks could not be loaded. */
error: string | null;
tasks: Map<string, AgentTask>;
/** Tasks with unseen replies or status changes in this project. */
unread: Set<string>;
/** Entries of the tasks (and subagents) opened in this window, by `entriesKey`. */
entries: Map<string, AgentEntry[]>;
changes: Map<string, AgentChange[]>;
@@ -87,7 +85,6 @@ export const useAgents = create<AgentsState>(() => ({
loaded: false,
error: null,
tasks: new Map(),
unread: new Set(),
entries: new Map(),
changes: new Map(),
providers: [],
@@ -113,40 +110,11 @@ export function updateComposer(key: string, patch: Partial<ComposerDraft>) {
}));
}
/** Session tabs on screen; a task can be shown in more than one split. */
const visible = new Map<string, number>();
const windowFocused = () => document.visibilityState !== "hidden" && document.hasFocus();
const viewing = (task: string) => visible.has(task) && windowFocused();
function setUnread(task: string, value: boolean) {
const s = useAgents.getState();
if (s.unread.has(task) === value) return;
const unread = new Set(s.unread);
if (value) unread.add(task);
else unread.delete(task);
useAgents.setState({ unread });
}
function markUnread(task: string) {
const current = useAgents.getState().tasks.get(task);
if (current && current.status !== "archived" && !viewing(task)) setUnread(task, true);
}
/** Session tabs on screen; their tasks do not notify. */
const visible = new Set<string>();
export function markVisible(task: string): () => void {
visible.set(task, (visible.get(task) ?? 0) + 1);
const read = () => {
if (viewing(task)) setUnread(task, false);
};
read();
window.addEventListener("focus", read);
document.addEventListener("visibilitychange", read);
return () => {
const count = (visible.get(task) ?? 1) - 1;
if (count) visible.set(task, count);
else visible.delete(task);
window.removeEventListener("focus", read);
document.removeEventListener("visibilitychange", read);
};
visible.add(task);
return () => visible.delete(task);
}
let generation = 0;
@@ -186,14 +154,7 @@ export async function connect(): Promise<void> {
export function disconnect() {
generation++;
useAgents.setState({
loaded: false,
error: null,
tasks: new Map(),
unread: new Set(),
entries: new Map(),
changes: new Map(),
});
useAgents.setState({ loaded: false, error: null, tasks: new Map(), entries: new Map(), changes: new Map() });
}
function onEvent(e: AgentEvent) {
@@ -202,8 +163,6 @@ function onEvent(e: AgentEvent) {
case "task": {
const prev = s.tasks.get(e.task.id);
useAgents.setState({ tasks: new Map(s.tasks).set(e.task.id, e.task) });
if (e.task.status === "archived") setUnread(e.task.id, false);
else if (attentionChange(prev?.status, e.task.status)) markUnread(e.task.id);
notifyChange(prev, e.task);
if (prev?.status !== e.task.status && !isBusy(e.task.status)) {
void refreshChanges(e.task.id);
@@ -216,9 +175,7 @@ function onEvent(e: AgentEvent) {
tasks.delete(e.id);
const composers = new Map(s.composers);
composers.delete(e.id);
const unread = new Set(s.unread);
unread.delete(e.id);
useAgents.setState({ tasks, composers, unread });
useAgents.setState({ tasks, composers });
editorService().closeInput?.(sessionKey(e.id));
break;
}
@@ -229,14 +186,6 @@ function onEvent(e: AgentEvent) {
break;
}
case "entry": {
if (
!e.subagent &&
((e.entry.type === "agent" && e.entry.text.trim()) ||
e.entry.type === "error" ||
(e.entry.type === "permission" && e.entry.chosen === null))
) {
markUnread(e.task);
}
const key = entriesKey(e.task, e.subagent);
const current = s.entries.get(key);
if (!current) return;
@@ -254,7 +203,7 @@ function onEvent(e: AgentEvent) {
function notifyChange(prev: AgentTask | undefined, task: AgentTask) {
const change = attentionChange(prev?.status, task.status);
if (!change) return;
if (viewing(task.id)) return;
if (visible.has(task.id) && document.hasFocus()) return;
const body =
change === "input"
? "Waiting for your answer"
-115
Переглянути файл
@@ -1,115 +0,0 @@
import type { AgentTask } from "@/bindings";
import type { Action } from "@/platform/actions";
import { tx } from "@/platform/i18n";
import type { MenuItem } from "@/ui";
import { showError, confirmChecked } from "@/workbench/messages";
import { isBusy } from "./model";
import { archiveTask, deleteTask, openTask, useAgents } from "./store";
const canArchive = (task: AgentTask) => !isBusy(task.status) && task.status !== "archived";
function resolveTasks(arg: unknown): AgentTask[] {
if (!Array.isArray(arg)) return [];
return [...new Set(arg)].flatMap((id: unknown) => {
const task = typeof id === "string" ? useAgents.getState().tasks.get(id) : undefined;
return task ? [task] : [];
});
}
async function runTasks(tasks: AgentTask[], run: (task: AgentTask) => Promise<unknown>, title: string) {
const errors: string[] = [];
for (const task of tasks) {
try {
await run(task);
} catch (error) {
errors.push(`${task.title}: ${error instanceof Error ? error.message : String(error)}`);
}
}
if (errors.length) await showError(title, errors.join("\n"));
}
async function confirmDelete(tasks: AgentTask[]) {
if (!tasks.length) return;
const task = tasks[0]!;
const multiple = tasks.length > 1;
const worktree = tasks.some((t) => t.isolation === "worktree");
const r = await confirmChecked({
title: multiple ? "Delete Agent Tasks" : "Delete Agent Task",
message: multiple
? tx`Delete ${tasks.length} agent tasks? Their branches and files outside worktrees are kept.`
: worktree
? tx`Delete “${task.title}”? Its branch ${task.branch ?? ""} is kept.`
: tx`Delete “${task.title}”? Files it changed are kept.`,
ok: "Delete",
icon: "warning",
checkbox: worktree
? multiple
? "Also remove their worktree folders"
: "Also remove its worktree folder"
: undefined,
checked: worktree,
});
if (r)
await runTasks(
tasks,
(t) => deleteTask(t.id, t.isolation === "worktree" && r.checked),
tx("Cannot delete agent tasks"),
);
}
export const taskActions: Action[] = [
{
id: "agents.openTask",
title: "Open Agent Task",
category: "Agents",
hidden: true,
run: ({ arg }) => {
if (typeof arg === "string") openTask(arg);
},
},
{
id: "agents.archiveTasks",
title: "Archive Agent Tasks",
category: "Agents",
hidden: true,
run: ({ arg }) =>
runTasks(resolveTasks(arg).filter(canArchive), (task) => archiveTask(task.id), tx("Cannot archive agent tasks")),
},
{
id: "agents.deleteTasks",
title: "Delete Agent Tasks",
category: "Agents",
hidden: true,
run: ({ arg }) => confirmDelete(resolveTasks(arg)),
},
];
export function taskMenu(tasks: AgentTask[]): MenuItem[] {
if (!tasks.length) return [];
const ids = tasks.map((task) => task.id);
const task = tasks[0]!;
const multiple = tasks.length > 1;
const archivable = tasks.filter(canArchive).length;
return [
...(!multiple
? ([
{ kind: "action", action: "agents.openTask", label: "Open", arg: task.id },
{ kind: "action", action: "terminal.openAt", label: "Open in Terminal", icon: "terminal", arg: task.cwd },
{ kind: "separator" },
] satisfies MenuItem[])
: []),
{
kind: "action",
action: "agents.archiveTasks",
label: multiple ? tx`Archive (${archivable})` : "Archive",
arg: ids,
disabled: !archivable,
},
{
kind: "action",
action: "agents.deleteTasks",
label: multiple ? tx`Delete (${tasks.length})…` : "Delete…",
arg: ids,
},
];
}
-224
Переглянути файл
@@ -1,224 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
import type { AgentEntry, AgentEvent, AgentTask } from "@/bindings";
import { useContributions } from "@/workbench/contributions";
import { AgentsView } from "./AgentsView";
import { AgentsStatus } from "./AgentsStatus";
import { activate } from "./index";
import { connect, disconnect, markVisible, useAgents } from "./store";
const backend = vi.hoisted(() => ({
channel: null as { onmessage: (event: AgentEvent) => void } | null,
tasks: [] as AgentTask[],
notify: vi.fn(),
openInput: vi.fn(),
closeInput: vi.fn(),
}));
vi.mock("@tauri-apps/api/core", async (original) => ({
...(await original<typeof import("@tauri-apps/api/core")>()),
Channel: class {
onmessage = () => {};
},
}));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
isTauri: () => true,
commands: {
agentSubscribe: async (channel: typeof backend.channel) => {
backend.channel = channel;
return { status: "ok", data: backend.tasks };
},
agentProviders: async () => ({ status: "ok", data: [] }),
agentChanges: async () => ({ status: "ok", data: [] }),
},
}));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
editorService: () => ({ openInput: backend.openInput, closeInput: backend.closeInput }),
notifications: () => ({ notify: backend.notify }),
}));
const task = (id: string, status: AgentTask["status"] = "running"): AgentTask => ({
id,
title: id,
status,
provider: "codex",
isolation: "local",
model: null,
cwd: "/project",
branch: null,
base: null,
baseCommit: null,
error: null,
createdMs: 0,
updatedMs: 0,
config: [],
commands: [],
usage: null,
queue: [],
});
const emit = (event: AgentEvent) => act(() => backend.channel!.onmessage(event));
const reply = (id = "one", text = "New reply") =>
emit({ type: "entry", task: id, subagent: null, index: 0, entry: { type: "agent", text } });
const visible: Array<() => void> = [];
const show = (id = "one") => {
let hide!: () => void;
act(() => {
hide = markVisible(id);
});
visible.push(hide);
return () => visible.splice(visible.indexOf(hide), 1)[0]!();
};
beforeEach(async () => {
vi.clearAllMocks();
vi.spyOn(document, "hasFocus").mockReturnValue(true);
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
disconnect();
backend.tasks = [task("one"), task("two", "ready")];
await connect();
});
afterEach(() => {
visible.splice(0).forEach((hide) => hide());
disconnect();
vi.restoreAllMocks();
});
describe("agent unread activity", () => {
it("does not mark historical tasks unread, but tracks replies even without loaded entries", () => {
expect(useAgents.getState().unread.size).toBe(0);
reply();
reply("one", "New reply, streamed further");
reply("two");
expect([...useAgents.getState().unread]).toEqual(["one", "two"]);
expect(useAgents.getState().entries.size).toBe(0);
expect(backend.notify).not.toHaveBeenCalled();
});
it.each(["ready", "needsInput", "failed", "limited"] as const)("marks background %s transitions unread", (status) => {
emit({ type: "task", task: task("one", status) });
expect(useAgents.getState().unread.has("one")).toBe(true);
expect(backend.notify).toHaveBeenCalledTimes(1);
show();
emit({ type: "task", task: task("one", status) });
expect(useAgents.getState().unread.size).toBe(0);
expect(backend.notify).toHaveBeenCalledTimes(1);
});
it("ignores user messages, thoughts, empty replies and subagent streaming", () => {
const entries: AgentEntry[] = [
{ type: "user", text: "Do this", attachments: [] },
{ type: "thought", text: "Thinking" },
{ type: "agent", text: " " },
];
for (const entry of entries) emit({ type: "entry", task: "one", subagent: null, index: 0, entry });
emit({ type: "entry", task: "one", subagent: "child", index: 0, entry: { type: "agent", text: "Working" } });
emit({ type: "task", task: { ...task("one"), title: "Renamed" } });
expect(useAgents.getState().unread.size).toBe(0);
});
it("clears only the viewed task and keeps reading while either split shows it", () => {
reply();
reply("two");
const hide = show();
show();
hide();
reply();
emit({ type: "task", task: task("one", "ready") });
expect([...useAgents.getState().unread]).toEqual(["two"]);
expect(backend.notify).not.toHaveBeenCalled();
});
it("keeps a visible session unread while the window is unfocused, then clears on focus", () => {
vi.mocked(document.hasFocus).mockReturnValue(false);
reply();
show();
expect(useAgents.getState().unread.has("one")).toBe(true);
vi.mocked(document.hasFocus).mockReturnValue(true);
fireEvent(window, new Event("focus"));
expect(useAgents.getState().unread.size).toBe(0);
reply();
expect(useAgents.getState().unread.size).toBe(0);
});
it("does not read hidden windows and removes focus listeners when the session closes", () => {
vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden");
const hide = show();
reply();
fireEvent(window, new Event("focus"));
expect(useAgents.getState().unread.has("one")).toBe(true);
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
fireEvent(document, new Event("visibilitychange"));
expect(useAgents.getState().unread.size).toBe(0);
hide();
reply();
fireEvent(window, new Event("focus"));
expect(useAgents.getState().unread.has("one")).toBe(true);
});
it("cleans up archived and deleted tasks, ignores late replies, and resets on project switch", async () => {
reply();
reply("two");
emit({ type: "task", task: task("one", "archived") });
reply();
expect([...useAgents.getState().unread]).toEqual(["two"]);
emit({ type: "removed", id: "two" });
reply("two");
expect(useAgents.getState().unread.size).toBe(0);
emit({ type: "task", task: task("one") });
reply();
const oldChannel = backend.channel!;
disconnect();
backend.tasks = [task("other")];
await connect();
oldChannel.onmessage({ type: "task", task: task("one", "ready") });
expect(useAgents.getState().unread.size).toBe(0);
expect([...useAgents.getState().tasks.keys()]).toEqual(["other"]);
});
});
describe("agent unread indicators", () => {
it("shows a dot on the task and a clickable status count even when all tasks are idle", () => {
emit({ type: "task", task: task("one", "ready") });
render(
<>
<AgentsView />
<AgentsStatus />
</>,
);
expect(screen.getByRole("img", { name: "Unread" })).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "1 unread" }));
expect(backend.openInput).toHaveBeenCalledWith(expect.objectContaining({ data: { task: "one", title: "one" } }), {
focus: true,
});
show();
expect(screen.queryByRole("img", { name: "Unread" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: /unread/ })).not.toBeInTheDocument();
});
it("counts unread and needs-input tasks once each in the sidebar badge", () => {
const dispose = activate();
try {
const useBadge = useContributions.getState().toolWindows.get("agents")!.useBadge!;
function Badge() {
return <span data-testid="badge">{useBadge()}</span>;
}
act(() =>
useAgents.setState({
tasks: new Map([task("one", "needsInput"), task("two", "ready")].map((t) => [t.id, t])),
unread: new Set(["one", "two"]),
}),
);
render(<Badge />);
expect(screen.getByTestId("badge")).toHaveTextContent("2");
show("two");
expect(screen.getByTestId("badge")).toHaveTextContent("1");
show("one");
expect(screen.getByTestId("badge")).toHaveTextContent("1");
} finally {
act(dispose);
}
});
});
-18
Переглянути файл
@@ -111,24 +111,6 @@ describe("project view context menu", () => {
expect(sub(items, "Git")?.slice(0, 4)).toEqual(["Commit File…", "Add", "-", "Annotate with Git Blame"]);
});
it("offers both ignore destinations for files, directories and multi-selection, separately from IDE exclusion", () => {
const dispose = registerActions(
["vcs.ignoreShared", "vcs.ignoreLocal"].map((id) => ({ id, title: id, run: () => undefined })),
);
try {
for (const nodes of [[node("/p/a")], [node("/p/dir", true)], [node("/p/a"), node("/p/dir", true)]]) {
const git = resolveMenuItems(contextMenuItems(nodes)).find((item) => item.label === "Git")!;
expect(sub(git.submenu!, "Add to .gitignore")).toEqual([".gitignore", ".git/info/exclude"]);
}
const root = resolveMenuItems(contextMenuItems([node("/p", true, true)])).find((item) => item.label === "Git")!;
expect(labels(root.submenu!)).not.toContain("Add to .gitignore");
const folder = contextMenuItems([node("/p/dir", true)]);
expect(sub(folder, "Mark Directory as")).toContain("Excluded");
} finally {
dispose();
}
});
it("shows Mark Directory as for folders, without file-only items", () => {
const l = labels(contextMenuItems([node(`${ROOT}/src`, true)]));
expect(l).toContain("Mark Directory as");
-7
Переглянути файл
@@ -321,13 +321,6 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] {
[
act("vcs.commit", undefined, dirs || nodes.length > 1 ? "Commit…" : "Commit File…"),
act("vcs.addToVcs", arg, "Add"),
nonRoot.length === nodes.length &&
nodes.length > 0 &&
nodes.every((n) => !n.placeholder) &&
submenu("gitIgnore", "Add to .gitignore", [
act("vcs.ignoreShared", arg, ".gitignore"),
act("vcs.ignoreLocal", arg, ".git/info/exclude"),
]),
{ kind: "separator" },
singleFile && act("vcs.annotate", singleFile.path, "Annotate with Git Blame"),
act("vcs.showDiff", arg, "Show Diff"),
+16 -12
Переглянути файл
@@ -179,9 +179,7 @@
}
.noHighlight :global(.cm-changedLine),
.noHighlight :global(.cm-insertedLine),
.noHighlight :global(.cm-changedText),
.noHighlight :global(.cm-diffLine),
.noHighlight :global(.cm-diffChangedGutter) {
.noHighlight :global(.cm-changedText) {
background: none !important;
}
/* Side-by-side without alignment (IDEA's default): each pane scrolls itself. */
@@ -218,17 +216,17 @@
position: absolute;
inset: 0;
}
/* The full colours of the change types (cm.ts), so bands and their midlines read as one shape. */
/* Opaque mixes of the line backgrounds (cm.ts), so bands and their midlines read as one shape. */
.host :global(.cm-diffBand-inserted) {
--band: var(--diff-inserted);
--band: color-mix(in srgb, var(--success) 26%, var(--bg-app));
}
.host :global(.cm-diffBand-deleted) {
--band: var(--diff-deleted);
--band: color-mix(in srgb, var(--danger) 26%, var(--bg-app));
}
.host :global(.cm-diffBand-modified) {
--band: var(--diff-modified);
--band: color-mix(in srgb, var(--gutter-added) 20%, var(--bg-app));
}
.host :global(.cm-diffBand) {
.host :global(.cm-diffBand:not(.cm-diffBand-modified)) {
fill: var(--band);
}
.host :global(.cm-diffBandLine) {
@@ -236,6 +234,12 @@
stroke: var(--band);
stroke-width: 1px;
}
.host :global(.cm-diffBandStopA) {
stop-color: color-mix(in srgb, var(--gutter-deleted) 20%, var(--bg-app));
}
.host :global(.cm-diffBandStopB) {
stop-color: color-mix(in srgb, var(--gutter-added) 20%, var(--bg-app));
}
.host :global(.cm-diffDivider button.cm-diffArrow) {
position: absolute;
display: flex;
@@ -262,16 +266,16 @@
}
/* Where the other pane has lines this one lacks. */
.host :global(.cm-diffGap-inserted) {
box-shadow: inset 0 1px 0 var(--gutter-added);
box-shadow: inset 0 1px 0 var(--success);
}
.host :global(.cm-diffGap-deleted) {
box-shadow: inset 0 1px 0 var(--gutter-deleted);
box-shadow: inset 0 1px 0 var(--danger);
}
.host :global(.cm-diffGap-inserted.cm-diffGapEnd) {
box-shadow: inset 0 -1px 0 var(--gutter-added);
box-shadow: inset 0 -1px 0 var(--success);
}
.host :global(.cm-diffGap-deleted.cm-diffGapEnd) {
box-shadow: inset 0 -1px 0 var(--gutter-deleted);
box-shadow: inset 0 -1px 0 var(--danger);
}
/* Review comments under diff lines (pull requests). */
+20 -19
Переглянути файл
@@ -5,7 +5,15 @@ import clsx from "clsx";
import { EditorView, keymap } from "@codemirror/view";
import { Prec, Text, type Extension } from "@codemirror/state";
import { history, historyKeymap } from "@codemirror/commands";
import { MergeView, getChunks, goToNextChunk, goToPreviousChunk, unifiedMergeView, Chunk } from "@codemirror/merge";
import {
MergeView,
getChunks,
goToNextChunk,
goToPreviousChunk,
rejectChunk,
unifiedMergeView,
Chunk,
} from "@codemirror/merge";
import { attachDocument, embeddedEditorExtensions, type DocumentAttachment } from "@/editor/api";
import { setFindOpen } from "@/editor/core/cm/find";
import { FindPanel, searchAgain, seedFind, type FindTarget } from "@/editor/core/view/FindBar";
@@ -15,14 +23,14 @@ import { bindingsFor, normalizeBinding, shortcutLabel, strokeOf } from "@/platfo
import { tx } from "@/platform/i18n";
import { IconButton, Select, Spinner, T, showContextMenu } from "@/ui";
import { editorService, type EditorInput } from "@/workbench/contributions";
import { changedLineGutters, diffWords, languageFor, viewerBase } from "./cm";
import { applyChunk, arrowControls, chunkAt, hoverRevert, revertUnifiedChunk } from "./diffControls";
import { languageFor, viewerBase } from "./cm";
import { applyChunk, arrowControls, chunkAt, hoverRevert } from "./diffControls";
import {
HIGHLIGHT_OPTIONS,
IGNORE_OPTIONS,
ideaDiffConfig,
loadDiffOptions,
saveDiffOptions,
whitespaceDiff,
type DiffViewOptions,
type HighlightPolicy,
type IgnorePolicy,
@@ -251,7 +259,8 @@ export function DiffEditor({ input }: { input: EditorInput }) {
},
});
const collapseUnchanged = opts.collapse ? { margin: 3, minSize: 6 } : undefined;
const diffConfig = ideaDiffConfig(opts.ignore, opts.highlight);
const override = whitespaceDiff(opts.ignore);
const diffConfig = { override };
const highlightChanges = opts.highlight === "words";
const inclusion = includable ? inclusionGutter(path, textA) : [];
const side = (att: DocumentAttachment | null, editable: boolean, notes?: "left" | "right"): Extension[] => [
@@ -280,14 +289,11 @@ export function DiffEditor({ input }: { input: EditorInput }) {
? { toA: editableA, toB: editableB, apply: (i, source) => merge && applyChunk(merge, i, source) }
: undefined,
});
// IDEA's colouring: lines by chunk type, carried into the gutters, and typed word highlights.
const colours = [changedLineGutters, highlightChanges ? diffWords : []];
const mv = new MergeView({
a: {
doc: textA,
extensions: [
side(attached.a, editableA, "left"),
colours,
panes?.extension ?? [],
focusTracker("a"),
findWatch("a"),
@@ -298,7 +304,6 @@ export function DiffEditor({ input }: { input: EditorInput }) {
doc: textB,
extensions: [
side(attached.b, editableB, "right"),
colours,
panes?.extension ?? [],
listener,
focusTracker("b"),
@@ -314,9 +319,9 @@ export function DiffEditor({ input }: { input: EditorInput }) {
!panes && (editableA || editableB)
? arrowControls(() => merge, { toA: editableA, toB: editableB })
: undefined,
// Words are highlighted by type (`diffWords`), and gutters tinted instead of a change bar.
highlightChanges: false,
gutter: false,
highlightChanges,
// Unpadded panes tint the gutters of changed lines instead of a change bar.
gutter: !panes,
collapseUnchanged,
diffConfig,
});
@@ -348,14 +353,13 @@ export function DiffEditor({ input }: { input: EditorInput }) {
focusTracker("b"),
findWatch("b"),
inclusion,
highlightChanges ? diffWords : [],
unifiedMergeView({
original: textA,
highlightChanges,
gutter: true,
syntaxHighlightDeletions: true,
mergeControls: editableB
? (type) => {
? (type, action) => {
const btn = document.createElement("button");
if (type === "accept") {
btn.hidden = true;
@@ -363,10 +367,7 @@ export function DiffEditor({ input }: { input: EditorInput }) {
}
btn.textContent = "Revert";
btn.title = "Revert this change";
btn.onmousedown = (event) => {
event.preventDefault();
revertUnifiedChunk(view, view.posAtDOM(btn));
};
btn.onmousedown = action;
return btn;
}
: false,
@@ -535,7 +536,7 @@ export function DiffEditor({ input }: { input: EditorInput }) {
const cur = currentChunk();
if (!views || !cur) return;
if (views.merge) applyChunk(views.merge, cur.index, "a");
else revertUnifiedChunk(views.b, cur.chunk.fromB);
else rejectChunk(views.b, cur.chunk.fromB);
};
const stageChunk = async () => {
+49 -181
Переглянути файл
@@ -1,24 +1,23 @@
import { describe, expect, it } from "vitest";
import { Chunk, MergeView } from "@codemirror/merge";
import { ChangeSet, Text } from "@codemirror/state";
import type { EditorView } from "@codemirror/view";
import { Text } from "@codemirror/state";
import { applyChunk, arrowControls } from "../diffControls";
import {
DEFAULT_DIFF_OPTIONS,
parseDiffOptions,
ideaChunks,
ideaDiffConfig,
transferChunk,
whitespaceDiff,
type IgnorePolicy,
} from "../diffOptions";
import { clipboardDiffData, compareFilesData, parseTextsArg } from "../compare";
import { diffInput, diffTitle, sideFile, sideKey } from "../diffInput";
import { changedLineGutters, chunkKind, diffWords, viewerBase } from "../cm";
import { changedLineGutters, viewerBase } from "../cm";
const doc = (s: string) => Text.of(s.split("\n"));
function chunks(a: string, b: string, ignore: IgnorePolicy) {
return ideaChunks(doc(a), doc(b), ignore, "words");
const override = whitespaceDiff(ignore);
return Chunk.build(doc(a), doc(b), { override });
}
describe("diff options", () => {
@@ -125,121 +124,47 @@ describe("diff options", () => {
}
});
it("colours lines by their chunk's type, as IDEA does", () => {
it("decorates consecutive inserted and deleted lines as whole lines", () => {
const parent = document.createElement("div");
document.body.appendChild(parent);
const extensions = [viewerBase({ readOnly: true }), diffWords];
const mv = new MergeView({
a: { doc: "keep\nremoved one\nremoved two\nmid\nvalue = old\nend\n", extensions },
b: { doc: "keep\nmid\nvalue = new\nadded\nend\n", extensions },
a: { doc: "before\nremoved one\nremoved two\nafter\n", extensions: viewerBase({ readOnly: true }) },
b: { doc: "before\nafter\n", extensions: viewerBase({ readOnly: true }) },
parent,
highlightChanges: false,
diffConfig: ideaDiffConfig("none", "words"),
diffConfig: { override: whitespaceDiff("none") },
});
const lines = (v: EditorView, kind: string) =>
[...v.dom.querySelectorAll(`.cm-diffLine-${kind}`)].map((e) => e.textContent);
expect(lines(mv.a, "deleted")).toEqual(["removed one", "removed two"]);
// A block with lines on both sides is modified as a whole, on both sides.
expect(lines(mv.a, "modified")).toEqual(["value = old"]);
expect(lines(mv.b, "modified")).toEqual(["value = new", "added"]);
expect(lines(mv.b, "inserted")).toEqual([]);
expect(chunkKind(mv.chunks[1]!)).toBe("modified");
expect(mv.a.dom.querySelectorAll(".cm-diffWholeLine")).toHaveLength(2);
expect(mv.b.dom.querySelectorAll(".cm-diffWholeLine")).toHaveLength(0);
mv.destroy();
parent.remove();
});
it("highlights the words of a modified block by their own type", async () => {
it("keeps word highlighting on paired lines of a multi-line replacement", () => {
const parent = document.createElement("div");
document.body.appendChild(parent);
const extensions = [viewerBase({ readOnly: true }), diffWords];
const mv = new MergeView({
a: { doc: "x\n syncScroll: boolean;\ny\n", extensions },
b: { doc: "x\n /** Docs. */\n syncScrolling: boolean;\ny\n", extensions },
a: {
doc: "before\nfrom old.first import X\nfrom old.second import Y\nafter\n",
extensions: viewerBase({ readOnly: true }),
},
b: {
doc: "before\nfrom new.first import A\nfrom new.second import B\nadded line\nafter\n",
extensions: viewerBase({ readOnly: true }),
},
parent,
highlightChanges: false,
diffConfig: ideaDiffConfig("none", "words"),
diffConfig: { override: whitespaceDiff("none") },
});
// The left pane highlights its words once the right one exists.
await Promise.resolve();
const words = (v: EditorView, kind: string) =>
[...v.dom.querySelectorAll(`.cm-diffWord.cm-diffWord-${kind}`)].map((e) => e.textContent);
// The edited identifier is highlighted whole, joined by the comment added before it.
expect(words(mv.a, "modified")).toEqual(["syncScroll"]);
expect(words(mv.b, "modified").join("")).toBe("/** Docs. */ syncScrolling");
expect(mv.a.dom.classList.contains("cm-diffWords")).toBe(true);
mv.destroy();
parent.remove();
});
it("marks inserted and deleted words inside a modified line", async () => {
const parent = document.createElement("div");
document.body.appendChild(parent);
const extensions = [viewerBase({ readOnly: true }), diffWords];
const mv = new MergeView({
a: { doc: "call(first, extra, last)\n", extensions },
b: { doc: "call(first, last, more)\n", extensions },
parent,
highlightChanges: false,
diffConfig: ideaDiffConfig("none", "words"),
});
// The left pane highlights its words once the right one exists.
await Promise.resolve();
const words = (v: EditorView, kind: string) =>
[...v.dom.querySelectorAll(`.cm-diffWord.cm-diffWord-${kind}`)].map((e) => e.textContent);
expect(words(mv.a, "deleted").join("")).toContain("extra");
expect(words(mv.b, "inserted").join("")).toContain("more");
expect(words(mv.a, "inserted")).toEqual([]);
expect(words(mv.b, "deleted")).toEqual([]);
mv.destroy();
parent.remove();
});
it("diffs changed blocks by words (ByWord)", () => {
const pairs = (a: string, b: string) =>
chunks(a, b, "none").flatMap((ch) =>
ch.changes.map((c) => [
a.slice(ch.fromA + c.fromA, ch.fromA + c.toA),
b.slice(ch.fromB + c.fromB, ch.fromB + c.toB),
]),
);
// An edited identifier is changed whole.
expect(pairs(" syncScroll: boolean;", " syncScrolling: boolean;")).toEqual([["syncScroll", "syncScrolling"]]);
// Punctuation is matched between matched words only: two changed words around ":" are one fragment.
expect(pairs(" syncScroll: true,", " syncScrolling: false,")).toEqual([
["syncScroll: true", "syncScrolling: false"],
expect(mv.a.dom.querySelectorAll(".cm-changedLine")).toHaveLength(2);
expect(mv.a.dom.querySelector(".cm-diffWholeLine")).toBeNull();
expect([...mv.a.dom.querySelectorAll(".cm-changedText")].map((e) => e.textContent)).toEqual([
"old",
"X",
"old",
"Y",
]);
expect(pairs("f(a, b)", "f(a, x, b)")).toEqual([["", " x,"]]);
// Each character of a script written without spaces is a word.
expect(pairs("你好世界", "你们世界")).toEqual([["好", "们"]]);
expect(pairs("a b", "a b")).toEqual([[" ", ""]]);
// A 10,000-line block edited on every line still pairs up its words.
const big = (kw: string) =>
Array.from({ length: 10_000 }, (_, i) => `export ${kw} value${i} = compute(${i});\n`).join("");
const changes = pairs(big("const"), big("let"));
expect(changes).toHaveLength(10_000);
expect(changes.every(([a, b]) => a === "const" && b === "let")).toBe(true);
});
it("keeps a line with only words added modified on both sides", async () => {
const parent = document.createElement("div");
document.body.appendChild(parent);
const extensions = [viewerBase({ readOnly: true }), diffWords];
const mv = new MergeView({
a: { doc: "f() {\n return a;\n}\n", extensions },
b: { doc: "f() {\n return a + b;\n}\n", extensions },
parent,
highlightChanges: false,
diffConfig: ideaDiffConfig("none", "words"),
});
await Promise.resolve();
expect([...mv.a.dom.querySelectorAll(".cm-diffLine-modified")].map((e) => e.textContent)).toEqual([" return a;"]);
expect([...mv.b.dom.querySelectorAll(".cm-diffLine-modified")].map((e) => e.textContent)).toEqual([
" return a + b;",
]);
// IDEA keeps the space before an inserted word in the fragment.
expect([...mv.b.dom.querySelectorAll(".cm-diffWord-inserted")].map((e) => e.textContent).join("")).toBe(" + b");
// and marks where it would be on the other side
expect(mv.a.dom.querySelectorAll(".cm-diffWordEmpty.cm-diffWord-inserted")).toHaveLength(1);
expect(mv.b.dom.querySelectorAll(".cm-changedLine")).toHaveLength(3);
expect([...mv.b.dom.querySelectorAll(".cm-diffWholeLine")].map((e) => e.textContent)).toEqual(["added line"]);
expect(mv.b.dom.querySelectorAll(".cm-changedLine:not(.cm-diffWholeLine) .cm-changedText")).toHaveLength(4);
mv.destroy();
parent.remove();
});
@@ -250,76 +175,47 @@ describe("diff options", () => {
const extensions = [viewerBase({ readOnly: true }), changedLineGutters];
const mv = new MergeView({
a: { doc: "keep\nlet x = 1;\nend\n", extensions },
b: { doc: "keep\nlet x = 2;\nadded\nend\nnew\n", extensions },
b: { doc: "keep\nlet x = 2;\nadded\nend\n", extensions },
parent,
gutter: false,
diffConfig: ideaDiffConfig("none", "words"),
diffConfig: { override: whitespaceDiff("none") },
});
const numbers = (v: typeof mv.a, cls: string) =>
[...v.dom.querySelectorAll(`.cm-lineNumbers .${cls}`)].map((e) => e.textContent);
expect(numbers(mv.a, "cm-diffGutter-modified")).toEqual(["2"]);
expect(numbers(mv.b, "cm-diffGutter-modified")).toEqual(["2", "3"]);
expect(numbers(mv.b, "cm-diffGutter-inserted")).toEqual(["5"]);
expect(numbers(mv.a, "cm-diffChangedGutter")).toEqual(["2"]);
expect(numbers(mv.b, "cm-diffChangedGutter")).toEqual(["2", "3"]);
expect(numbers(mv.b, "cm-diffWholeGutter")).toEqual(["3"]);
mv.destroy();
parent.remove();
});
it("shows a final line break added as an inserted empty line, gutter included", () => {
it("marks a deleted last line as a whole line", () => {
const parent = document.createElement("div");
document.body.appendChild(parent);
const extensions = [viewerBase({ readOnly: true }), changedLineGutters];
const mv = new MergeView({
a: { doc: "alpha\nbeta", extensions },
b: { doc: "alpha\nbeta\n", extensions },
a: { doc: "keep\ngone", extensions: viewerBase({ readOnly: true }) },
b: { doc: "keep", extensions: viewerBase({ readOnly: true }) },
parent,
gutter: false,
diffConfig: ideaDiffConfig("none", "words"),
diffConfig: { override: whitespaceDiff("none") },
});
const lines = [...mv.b.contentDOM.querySelectorAll(".cm-line")].map((l) => l.classList.contains("cm-diffLine"));
const gutters = [...mv.b.dom.querySelectorAll(".cm-lineNumbers .cm-gutterElement:not([style*='hidden'])")]
.filter((e) => e.textContent)
.map((e) => e.classList.contains("cm-diffChangedGutter"));
// IDEA compares lines without their breaks: "beta" is unchanged, the empty last line inserted.
expect(lines).toEqual([false, false, true]);
expect(gutters).toEqual(lines);
expect(mv.b.contentDOM.querySelectorAll(".cm-diffLine-inserted")).toHaveLength(1);
expect([...mv.a.dom.querySelectorAll(".cm-diffWholeLine")].map((e) => e.textContent)).toEqual(["gone"]);
mv.destroy();
parent.remove();
});
it("shows a last line removed as a deleted line only", async () => {
const parent = document.createElement("div");
document.body.appendChild(parent);
const extensions = [viewerBase({ readOnly: true }), diffWords];
const mv = new MergeView({
a: { doc: "keep\ngone", extensions },
b: { doc: "keep", extensions },
parent,
highlightChanges: false,
diffConfig: ideaDiffConfig("none", "words"),
});
await Promise.resolve();
// "keep" loses its line break, which IDEA does not count as a change.
expect([...mv.a.dom.querySelectorAll(".cm-diffLine")].map((e) => e.textContent)).toEqual(["gone"]);
expect(mv.a.dom.querySelectorAll(".cm-diffLine-deleted")).toHaveLength(1);
mv.destroy();
parent.remove();
});
it("keeps word highlighting for a single-line replacement", async () => {
it("keeps word highlighting for a single-line replacement", () => {
const parent = document.createElement("div");
document.body.appendChild(parent);
const mv = new MergeView({
a: { doc: "before\nvalue = old\nafter\n", extensions: [viewerBase({ readOnly: true }), diffWords] },
b: { doc: "before\nvalue = new\nafter\n", extensions: [viewerBase({ readOnly: true }), diffWords] },
a: { doc: "before\nvalue = old\nafter\n", extensions: viewerBase({ readOnly: true }) },
b: { doc: "before\nvalue = new\nafter\n", extensions: viewerBase({ readOnly: true }) },
parent,
highlightChanges: false,
diffConfig: ideaDiffConfig("none", "words"),
diffConfig: { override: whitespaceDiff("none") },
});
// The left pane highlights its words once the right one exists.
await Promise.resolve();
expect([...mv.a.dom.querySelectorAll(".cm-diffWord-modified")].map((e) => e.textContent)).toEqual(["old"]);
expect([...mv.b.dom.querySelectorAll(".cm-diffWord-modified")].map((e) => e.textContent)).toEqual(["new"]);
expect(mv.a.dom.querySelector(".cm-diffWholeLine")).toBeNull();
expect(mv.b.dom.querySelector(".cm-diffWholeLine")).toBeNull();
expect(mv.a.dom.querySelector(".cm-changedText")).not.toBeNull();
expect(mv.b.dom.querySelector(".cm-changedText")).not.toBeNull();
mv.destroy();
parent.remove();
});
@@ -409,31 +305,3 @@ describe("compare entry points", () => {
expect(diffInput(compareFilesData("/p/a", "/p/b")).key).toContain("file:/p/a");
});
});
describe("oversized line comparison", () => {
it("falls back to transferable chunks on initial comparison and either-side edits", () => {
const a = doc("alpha\n".repeat(12000) + "beta\n".repeat(12000));
const b = doc("beta\n".repeat(12000) + "alpha\n".repeat(12000));
const config = ideaDiffConfig("none", "words");
const built = Chunk.build(a, b, config);
const editB = ChangeSet.of({ from: 0, insert: "header\n" }, b.length);
const nextB = editB.apply(b);
const updatedB = Chunk.updateB(built, a, nextB, editB, config);
const editA = ChangeSet.of({ from: 0, insert: "other\n" }, a.length);
const nextA = editA.apply(a);
const updatedA = Chunk.updateA(built, nextA, b, editA, config);
for (const [chunks, source, target] of [
[built, a, b],
[updatedB, a, nextB],
[updatedA, nextA, b],
] as const) {
expect(chunks.length).toBeGreaterThan(0);
let restored = target;
for (const chunk of [...chunks].reverse()) {
const edit = transferChunk(chunk, "a", source, restored);
restored = restored.replace(edit.from, edit.to, doc(edit.insert));
}
expect(restored.toString()).toBe(source.toString());
}
}, 20000);
});
+4 -62
Переглянути файл
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { render, screen, waitFor, within } from "@testing-library/react";
import type { EditorInput } from "@/workbench/contributions";
import { Chunk } from "@codemirror/merge";
import { Text } from "@codemirror/state";
@@ -29,19 +29,6 @@ vi.mock("@/workbench/contributions", async (importOriginal) => ({
editorService: () => ({ openFile }),
}));
vi.mock("@/editor/api", async (importOriginal) => ({
...(await importOriginal<typeof import("@/editor/api")>()),
attachDocument: (path: string) =>
Promise.resolve({
path,
text: () => working,
readOnly: false,
extension: [],
save: () => Promise.resolve(),
release: () => {},
}),
}));
import { DiffEditor, mapLine } from "../DiffEditor";
/** Git Log opens a commit's file: both sides are revisions. */
@@ -107,7 +94,7 @@ describe("Diff toolbar", () => {
// Unpadded panes joined by the divider.
await waitFor(() => expect(document.querySelector(".cm-diffDivider")).not.toBeNull());
expect(document.querySelector(".cm-changeGutter")).toBeNull();
expect(document.querySelector(".cm-merge-b .cm-lineNumbers .cm-diffGutter-inserted")?.textContent).toBe("2");
expect(document.querySelector(".cm-merge-b .cm-lineNumbers .cm-diffWholeGutter")?.textContent).toBe("2");
// The lock turns scrolling together off without rebuilding the panes.
const divider = document.querySelector(".cm-diffDivider");
(await screen.findByRole("button", { name: "Synchronize Scrolling" })).click();
@@ -117,9 +104,9 @@ describe("Diff toolbar", () => {
const item = await screen.findByRole("menuitemcheckbox", { name: "Align Changes" });
expect(item.getAttribute("aria-checked")).toBe("false");
item.click();
// Padded panes, the changed lines' gutters still tinted as in IDEA.
// Padded panes with a change bar.
await waitFor(() => expect(document.querySelector(".cm-diffDivider")).toBeNull());
expect(document.querySelector(".cm-merge-b .cm-lineNumbers .cm-diffGutter-inserted")?.textContent).toBe("2");
expect(document.querySelector(".cm-changeGutter")).not.toBeNull();
expect(JSON.parse(localStorage.getItem("openidea.vcs.diffOptions")!)).toMatchObject({
alignChanges: true,
syncScroll: false,
@@ -191,48 +178,3 @@ describe("Jump to Source of a revision diff", () => {
expect(await jumpFrom(0, 2)).toEqual(["/p/a.ts", { selection: { line: 5, col: 1 }, focus: true }]);
});
});
describe("Unified Revert", () => {
for (const control of ["toolbar", "chunk"] as const) {
it.each([
["a\nb", "a"],
["same", "same\n"],
["same\n", "same"],
["", "added"],
["deleted", ""],
])(`${control} restores %j from %j`, async (original, changed) => {
localStorage.setItem("openidea.vcs.diffOptions", JSON.stringify({ mode: "unified", collapse: false }));
texts.HEAD = original;
working = changed;
const mounted = render(
<DiffEditor
input={
{
...input,
data: {
path: "/p/a.ts",
left: { type: "rev", rev: "HEAD" },
right: { type: "worktree" },
},
} as EditorInput
}
/>,
);
try {
await waitFor(() => expect(document.querySelectorAll(".cm-editor")).toHaveLength(1));
const view = EditorView.findFromDOM(document.querySelector<HTMLElement>(".cm-editor")!)!;
if (control === "toolbar") {
const button = await screen.findByRole("button", { name: "Revert Change" });
await waitFor(() => expect(button).not.toBeDisabled());
fireEvent.click(button);
} else {
fireEvent.mouseDown(await screen.findByRole("button", { name: /^Revert$/ }));
}
await waitFor(() => expect(view.state.doc.toString()).toBe(original));
} finally {
mounted.unmount();
localStorage.clear();
}
});
}
});
-51
Переглянути файл
@@ -1,51 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
write: vi.fn(),
reload: vi.fn(),
refresh: vi.fn(),
failure: vi.fn(),
}));
vi.mock("@/platform/ipc", () => ({
commands: { vcsAddToIgnore: mocks.write },
call: async (result: Promise<unknown>) => result,
}));
vi.mock("@/features/project-tree/store", () => ({ reloadAll: mocks.reload }));
vi.mock("../store", () => ({ refreshNow: mocks.refresh }));
vi.mock("../ops", () => ({
runOp: async (_title: string, run: () => Promise<unknown>) => {
try {
return await run();
} catch (error) {
mocks.failure(error);
return undefined;
}
},
}));
import { addToIgnore } from "../ignore";
describe("ignore action", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.write.mockResolvedValue(null);
});
it.each(["gitignore", "localExclude"] as const)(
"routes all paths to %s then refreshes status and tree",
async (destination) => {
await addToIgnore(["/p/file", "/p/directory"], destination);
expect(mocks.write).toHaveBeenCalledWith(["/p/file", "/p/directory"], destination);
expect(mocks.refresh).toHaveBeenCalledOnce();
expect(mocks.reload).toHaveBeenCalledOnce();
},
);
it("refreshes after a failed or partially completed multi-repository write", async () => {
mocks.write.mockRejectedValue(new Error("locked; retry"));
await addToIgnore(["/p/file"], "gitignore");
expect(mocks.failure).toHaveBeenCalledOnce();
expect(mocks.refresh).toHaveBeenCalledOnce();
expect(mocks.reload).toHaveBeenCalledOnce();
});
it("ignores an empty selection", async () => {
await addToIgnore([], "gitignore");
expect(mocks.write).not.toHaveBeenCalled();
});
});
-36
Переглянути файл
@@ -1,36 +0,0 @@
import { afterEach, describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { useProject } from "@/platform/project";
import type { Settings } from "@/platform/ipc";
import { viewerBase } from "../cm";
const previous = useProject.getState().settings;
const views: EditorView[] = [];
afterEach(() => {
views.splice(0).forEach((v) => v.destroy());
useProject.setState({ settings: previous });
});
const setEditor = (editor: object) => useProject.setState({ settings: { editor } as unknown as Settings });
describe("viewer font", () => {
it("follows the editor's font settings, also when they change", () => {
setEditor({ fontFamily: "Fira Code", fontSize: 16, lineHeight: 22 });
const view = new EditorView({
state: EditorState.create({ doc: "a", extensions: viewerBase({ readOnly: true }) }),
});
views.push(view);
const style = () => view.dom.style;
expect(style().getPropertyValue("--openidea-editor-font")).toContain("Fira Code");
expect(style().getPropertyValue("--openidea-editor-font-size")).toBe("16px");
expect(style().getPropertyValue("--openidea-editor-line-height")).toBe("22px");
expect(view.dom.classList.contains("cm-openidea-ligatures")).toBe(false);
setEditor({ fontSize: 11, ligatures: true });
expect(style().getPropertyValue("--openidea-editor-font")).toBe("");
expect(style().getPropertyValue("--openidea-editor-font-size")).toBe("11px");
expect(view.dom.classList.contains("cm-openidea-ligatures")).toBe(true);
});
});
-10
Переглянути файл
@@ -41,8 +41,6 @@ import {
import { refreshNow, repoName } from "./store";
import { tx } from "@/platform/i18n";
import { addToIgnore } from "./ignore";
const VCS = "vcsAvailable";
const IN_COMMIT_WINDOW = "vcsAvailable && activeToolWindow == commit";
@@ -458,14 +456,6 @@ export function registerVcsActions(): () => void {
void revealCommit(id, commit ? commitRepo(commit) : undefined);
},
},
...(["gitignore", "localExclude"] as const).map((destination): Action => ({
id: destination === "gitignore" ? "vcs.ignoreShared" : "vcs.ignoreLocal",
title: destination === "gitignore" ? "Add to .gitignore" : "Add to .git/info/exclude",
category: "Git",
when: VCS,
keywords: ["ignore", "unversioned", "exclude"],
run: ({ arg }) => addToIgnore(contextPaths(arg), destination),
})),
{
id: "vcs.addToVcs",
title: "Add to VCS",
+84 -189
Переглянути файл
@@ -8,7 +8,6 @@ import {
EditorState,
RangeSet,
RangeSetBuilder,
StateEffect,
StateField,
type Extension,
type Line,
@@ -22,72 +21,28 @@ import {
highlightActiveLine,
keymap,
lineNumbers,
WidgetType,
type DecorationSet,
type ViewUpdate,
} from "@codemirror/view";
import { getChunks, mergeViewSiblings, type Chunk } from "@codemirror/merge";
import { getChunks } from "@codemirror/merge";
import { defaultKeymap } from "@codemirror/commands";
import { search, searchKeymap } from "@codemirror/search";
import { tags as t } from "@lezer/highlight";
import { findExtension } from "@/editor/core/cm/find";
import { caretExtension } from "@/editor/core/cm/prefs";
import { fontExtension } from "@/editor/core/cm/setup";
import { caretStyles, findLocals, findStyles } from "@/editor/core/cm/theme";
import { editorPrefs } from "@/platform/editorSettings";
import { useProject } from "@/platform/project";
import { hasInnerFragments } from "./diffOptions";
/** IDEA's change types (TextDiffType): both sides have text, only the new side, only the old side. */
export type DiffKind = "modified" | "inserted" | "deleted";
const kindOf = (hasA: boolean, hasB: boolean): DiffKind => (hasA && hasB ? "modified" : hasA ? "deleted" : "inserted");
/** A chunk's type (DiffUtil.getLineDiffType), by the sides it has lines on. */
export const chunkKind = (chunk: Chunk): DiffKind => kindOf(chunk.fromA !== chunk.toA, chunk.fromB !== chunk.toB);
const KINDS: readonly DiffKind[] = ["modified", "inserted", "deleted"];
const byKind = <T>(make: (kind: DiffKind) => T) =>
Object.fromEntries(KINDS.map((k) => [k, make(k)])) as Record<DiffKind, T>;
/** Line backgrounds by type; `fine` ones (words compared) are lighter. */
const lineDecos = byKind((kind) => ({
coarse: Decoration.line({ class: `cm-diffLine cm-diffLine-${kind}` }),
fine: Decoration.line({ class: `cm-diffLine cm-diffLine-${kind} cm-diffLine-fine` }),
}));
const wordDecos = byKind((kind) => Decoration.mark({ class: `cm-diffWord cm-diffWord-${kind}` }));
/** A word on the other side only: a thin bar where it would be (DiffEmptyHighlighterRenderer). */
class EmptyWordMarker extends WidgetType {
constructor(readonly kind: DiffKind) {
super();
}
eq(other: EmptyWordMarker) {
return other.kind === this.kind;
}
toDOM() {
const span = document.createElement("span");
span.className = `cm-diffWordEmpty cm-diffWord-${this.kind}`;
span.setAttribute("aria-hidden", "true");
return span;
}
}
const emptyWordDecos = byKind((kind) => Decoration.widget({ widget: new EmptyWordMarker(kind), side: 1 }));
const wholeLine = Decoration.line({ class: "cm-diffWholeLine" });
/**
* Calls `f` for the changed lines of a side-by-side pane between `vpFrom` and
* `vpTo`, with the type of their chunk (DiffUtil.getLineDiffType): a chunk
* with lines on both sides is modified as a whole, however its words changed.
* `vpTo`, with whether the line has no counterpart on the other side (inserted
* or deleted as a whole). Lines paired with a line on the other side keep the
* line tint plus word-level highlights.
*/
function forChangedLines(
state: EditorState,
vpFrom: number,
vpTo: number,
f: (line: Line, kind: DiffKind, fine: boolean) => void,
) {
function forChangedLines(state: EditorState, vpFrom: number, vpTo: number, f: (line: Line, whole: boolean) => void) {
const info = getChunks(state);
if (!info || !info.side) return;
const isA = info.side === "a";
@@ -95,70 +50,38 @@ function forChangedLines(
for (const chunk of info.chunks) {
const from = isA ? chunk.fromA : chunk.fromB;
const to = isA ? chunk.toA : chunk.toB;
if (from > vpTo) break;
if (from >= vpTo) break;
if (from === to || to < vpFrom) continue;
const kind = chunkKind(chunk);
const fine = hasInnerFragments(chunk);
// A line starting at `vpTo` is still in view (the empty last line).
for (let line = doc.lineAt(Math.max(from, vpFrom)); line.from < to && line.from <= vpTo;) {
f(line, kind, fine);
const otherEmpty = isA ? chunk.fromB === chunk.toB : chunk.fromA === chunk.toA;
const ranges = chunk.changes.map((c) => (isA ? [c.fromA, c.toA] : [c.fromB, c.toB]).map((p) => p + from));
// Covered including the line break after it, or the one before it (a deleted last line).
const covered = (line: Line) =>
ranges.some(([f = 0, t = 0]) => (f <= line.from && t > line.to) || (f < line.from && t >= line.to));
for (let line = doc.lineAt(Math.max(from, vpFrom)); line.from < Math.min(to, vpTo);) {
f(line, otherEmpty || covered(line));
if (line.number === doc.lines) break;
line = doc.line(line.number + 1);
}
}
}
/**
* Line backgrounds in the colour of their chunk's type
* (DiffDrawUtil.LineHighlighterBuilder). The unified view shows every new
* line as inserted, below the old ones as deleted (createUnifiedChunkHighlighters).
*/
function lineDeco(view: EditorView): DecorationSet {
const unified = !mergeViewSiblings(view);
/** Solid background for the lines changed as a whole. */
function wholeLineDeco(view: EditorView): DecorationSet {
const builder = new RangeSetBuilder<Decoration>();
forChangedLines(view.state, view.viewport.from, view.viewport.to, (line, kind, fine) => {
const decos = lineDecos[unified ? "inserted" : kind];
builder.add(line.from, line.from, fine ? decos.fine : decos.coarse);
forChangedLines(view.state, view.viewport.from, view.viewport.to, (line, whole) => {
if (whole) builder.add(line.from, line.from, wholeLine);
});
return builder.finish();
}
/**
* The inner fragments of chunks whose words were compared, each in the colour
* of its own type (SimpleDiffChangeUi.createInlineHighlighter); a fragment
* empty on this side is a thin bar.
*/
function wordDeco(view: EditorView): DecorationSet {
const info = getChunks(view.state);
// The unified view highlights words itself (`highlightChanges`).
if (!info || !info.side || !mergeViewSiblings(view)) return Decoration.none;
const isA = info.side === "a";
const { from: vpFrom, to: vpTo } = view.viewport;
const builder = new RangeSetBuilder<Decoration>();
for (const chunk of info.chunks) {
const base = isA ? chunk.fromA : chunk.fromB;
if (base > vpTo) break;
if ((isA ? chunk.toA : chunk.toB) < vpFrom || !hasInnerFragments(chunk)) continue;
for (const c of chunk.changes) {
const [from, to] = isA ? [c.fromA, c.toA] : [c.fromB, c.toB];
const kind = kindOf(c.fromA !== c.toA, c.fromB !== c.toB);
if (from < to) builder.add(base + from, base + to, wordDecos[kind]);
else builder.add(base + from, base + from, emptyWordDecos[kind]);
}
}
return builder.finish();
}
class LineClassMarker extends GutterMarker {
constructor(readonly elementClass: string) {
super();
}
}
const gutterMarkers = byKind((kind) => ({
coarse: new LineClassMarker(`cm-diffChangedGutter cm-diffGutter-${kind}`),
fine: new LineClassMarker(`cm-diffChangedGutter cm-diffGutter-${kind} cm-diffGutter-fine`),
}));
const changedGutter = new LineClassMarker("cm-diffChangedGutter");
const wholeGutter = new LineClassMarker("cm-diffChangedGutter cm-diffWholeGutter");
/** The line background of changed lines carried into the gutters (line numbers, inclusion boxes), as in IDEA. */
export const changedLineGutters = StateField.define<RangeSet<GutterMarker>>({
@@ -172,42 +95,29 @@ export const changedLineGutters = StateField.define<RangeSet<GutterMarker>>({
function changedGutterMarkers(state: EditorState): RangeSet<GutterMarker> {
const builder = new RangeSetBuilder<GutterMarker>();
forChangedLines(state, 0, state.doc.length, (line, kind, fine) =>
builder.add(line.from, line.from, fine ? gutterMarkers[kind].fine : gutterMarkers[kind].coarse),
forChangedLines(state, 0, state.doc.length + 1, (line, whole) =>
builder.add(line.from, line.from, whole ? wholeGutter : changedGutter),
);
return builder.finish();
}
/** Recomputes `build` when the document, viewport or chunks change. */
const chunkDecorations = (build: (view: EditorView) => DecorationSet) =>
ViewPlugin.fromClass(
class {
decorations: DecorationSet;
constructor(view: EditorView) {
this.decorations = build(view);
}
update(update: ViewUpdate) {
if (
update.docChanged ||
update.viewportChanged ||
getChunks(update.startState)?.chunks !== getChunks(update.state)?.chunks
)
this.decorations = build(update.view);
}
},
{ decorations: (value) => value.decorations },
);
const changedLines = chunkDecorations(lineDeco);
/**
* IDEA's "Highlight words" for a side-by-side pane: the inner fragments of
* chunks whose words were compared, over their lighter line background.
*/
export const diffWords: Extension = [
chunkDecorations(wordDeco),
EditorView.editorAttributes.of({ class: "cm-diffWords" }),
];
const wholeChangedLines = ViewPlugin.fromClass(
class {
decorations: DecorationSet;
constructor(view: EditorView) {
this.decorations = wholeLineDeco(view);
}
update(update: ViewUpdate) {
if (
update.docChanged ||
update.viewportChanged ||
getChunks(update.startState)?.chunks !== getChunks(update.state)?.chunks
)
this.decorations = wholeLineDeco(update.view);
}
},
{ decorations: (value) => value.decorations },
);
export const viewerHighlight = HighlightStyle.define([
{
@@ -235,16 +145,10 @@ export const viewerTheme = EditorView.theme(
height: "100%",
backgroundColor: "var(--bg-app)",
color: "var(--fg)",
fontSize: "var(--openidea-editor-font-size, var(--fs-code))",
fontSize: "var(--fs-code)",
...findLocals,
},
".cm-scroller": {
fontFamily: "var(--openidea-editor-font, var(--font-mono))",
fontWeight: "var(--fw-code, 400)",
lineHeight: "var(--openidea-editor-line-height, var(--lh-code))",
fontVariantLigatures: "none",
},
"&.cm-openidea-ligatures .cm-scroller": { fontVariantLigatures: "normal" },
".cm-scroller": { fontFamily: "var(--font-mono)", fontWeight: "var(--fw-code, 400)", lineHeight: "var(--lh-code)" },
".cm-content": { caretColor: "var(--caret, var(--fg-strong))", WebkitUserSelect: "text", userSelect: "text" },
...caretStyles,
"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, ::selection": {
@@ -258,38 +162,44 @@ export const viewerTheme = EditorView.theme(
},
".cm-lineNumbers .cm-gutterElement": { padding: "0 8px 0 12px", minWidth: "32px" },
".cm-activeLineGutter": { backgroundColor: "transparent", color: "var(--fg-secondary)" },
// Side-by-side panes colour lines by their chunk's type (changedLines) instead of the library's tint.
"&.cm-merge-a .cm-changedLine, &.cm-merge-b .cm-changedLine": { backgroundColor: "transparent" },
".cm-line.cm-diffLine-modified, .cm-diffGutter-modified": { backgroundColor: "var(--diff-modified)" },
".cm-line.cm-diffLine-inserted, .cm-diffGutter-inserted": { backgroundColor: "var(--diff-inserted)" },
".cm-line.cm-diffLine-deleted, .cm-diffGutter-deleted": { backgroundColor: "var(--diff-deleted)" },
// Chunks whose words were compared take the lighter colour (TextDiffType.getIgnoredColor), their fragments the full one.
...Object.fromEntries(
KINDS.map((k) => [
`.cm-line.cm-diffLine-fine.cm-diffLine-${k}, .cm-diffGutter-fine.cm-diffGutter-${k}`,
{ backgroundColor: `color-mix(in srgb, var(--diff-${k}) 40%, var(--bg-app))` },
]),
),
// Full line height, as IDEA paints them: an inline background only covers the font's height,
// leaving stripes between the lines of a multi-line fragment.
".cm-diffWord": { display: "inline-block" },
".cm-diffWord-modified": { backgroundColor: "var(--diff-modified)" },
".cm-diffWord-inserted": { backgroundColor: "var(--diff-inserted)" },
".cm-diffWord-deleted": { backgroundColor: "var(--diff-deleted)" },
".cm-diffWordEmpty": {
display: "inline-block",
width: "2px",
height: "1lh",
margin: "0 -1px",
verticalAlign: "top",
// @codemirror/merge
"&.cm-merge-a .cm-changedLine, .cm-deletedChunk": {
backgroundColor: "color-mix(in srgb, var(--gutter-deleted) 12%, transparent)",
},
// The unified view: old lines deleted, new lines inserted.
".cm-deletedChunk": { backgroundColor: "var(--diff-deleted)" },
"&.cm-diffWords .cm-deletedChunk": {
backgroundColor: "color-mix(in srgb, var(--diff-deleted) 40%, var(--bg-app))",
"&.cm-merge-b .cm-changedLine, .cm-inlineChangedLine": {
backgroundColor: "color-mix(in srgb, var(--gutter-added) 12%, transparent)",
},
"&.cm-merge-a .cm-changedLine.cm-diffWholeLine": {
backgroundColor: "color-mix(in srgb, var(--danger) 26%, transparent)",
},
"&.cm-merge-b .cm-changedLine.cm-diffWholeLine": {
backgroundColor: "color-mix(in srgb, var(--success) 26%, transparent)",
},
"&.cm-merge-a .cm-diffWholeLine .cm-changedText, &.cm-merge-b .cm-diffWholeLine .cm-changedText": {
background: "transparent",
},
"&.cm-merge-a .cm-changedText, .cm-deletedChunk .cm-deletedText": {
background: "color-mix(in srgb, var(--danger) 26%, transparent)",
},
"&.cm-merge-b .cm-changedText": {
background: "color-mix(in srgb, var(--success) 26%, transparent)",
},
"&.cm-merge-b .cm-changedText, .cm-insertedLine .cm-changedText": {
background: "color-mix(in srgb, var(--success) 26%, transparent)",
},
// Gutters of changed lines take the line background (changedLineGutters).
"&.cm-merge-a .cm-diffChangedGutter": {
backgroundColor: "color-mix(in srgb, var(--gutter-deleted) 12%, transparent)",
},
"&.cm-merge-b .cm-diffChangedGutter": {
backgroundColor: "color-mix(in srgb, var(--gutter-added) 12%, transparent)",
},
"&.cm-merge-a .cm-diffWholeGutter": {
backgroundColor: "color-mix(in srgb, var(--danger) 26%, transparent)",
},
"&.cm-merge-b .cm-diffWholeGutter": {
backgroundColor: "color-mix(in srgb, var(--success) 26%, transparent)",
},
".cm-deletedChunk .cm-deletedText": { background: "var(--diff-deleted)" },
"&.cm-merge-b .cm-changedText": { background: "var(--diff-inserted)" },
".cm-changeGutter": { width: "3px", paddingLeft: "0" },
"&.cm-merge-a .cm-changedLineGutter, .cm-deletedLineGutter": { background: "var(--gutter-deleted)" },
"&.cm-merge-b .cm-changedLineGutter": { background: "var(--gutter-modified)" },
@@ -321,33 +231,18 @@ export const viewerTheme = EditorView.theme(
);
const caretSlot = new Compartment();
const fontSlot = new Compartment();
const editorSettings = () => useProject.getState().settings?.editor;
/**
* The editor's caret (Settings › Editor › General › Appearance) and font
* (Settings › Editor › Font), kept in step with the settings.
*/
function viewerEditorLook(): Extension {
/** The editor's caret (Settings › Editor › General › Appearance), kept in step with the settings. */
function viewerCaret(): Extension {
return [
caretSlot.of(caretExtension(editorPrefs())),
fontSlot.of(fontExtension(editorSettings())),
ViewPlugin.define((view) => {
let appearance = editorPrefs().appearance;
let editor = editorSettings();
const unsubscribe = useProject.subscribe(() => {
const effects: StateEffect<unknown>[] = [];
const next = editorPrefs();
if (JSON.stringify(next.appearance) !== JSON.stringify(appearance)) {
appearance = next.appearance;
effects.push(caretSlot.reconfigure(caretExtension(next)));
}
if (editorSettings() !== editor) {
editor = editorSettings();
effects.push(fontSlot.reconfigure(fontExtension(editor)));
}
if (effects.length) view.dispatch({ effects });
if (JSON.stringify(next.appearance) === JSON.stringify(appearance)) return;
appearance = next.appearance;
view.dispatch({ effects: caretSlot.reconfigure(caretExtension(next)) });
});
return { destroy: unsubscribe };
}),
@@ -361,14 +256,14 @@ function viewerEditorLook(): Extension {
export function viewerBase(opts: { readOnly: boolean; lineNumbers?: boolean; findBar?: boolean }): Extension[] {
return [
opts.lineNumbers === false ? [] : lineNumbers(),
viewerEditorLook(),
viewerCaret(),
highlightActiveLine(),
opts.findBar
? [findExtension(), keymap.of(defaultKeymap)]
: [search({ top: true }), keymap.of([...searchKeymap, ...defaultKeymap])],
syntaxHighlighting(viewerHighlight),
viewerTheme,
changedLines,
wholeChangedLines,
EditorState.readOnly.of(opts.readOnly),
EditorView.editable.of(!opts.readOnly),
// Non-editable revision panes still need keyboard selection and copy.
-133
Переглянути файл
@@ -1,133 +0,0 @@
/**
* IntelliJ's own comparison tests (LineComparisonUtilTest,
* WordComparisonUtilTest, SplitComparisonUtilTest; Apache-2.0, Copyright
* JetBrains s.r.o. and contributors), converted from their Kotlin DSL into
* `ideaCases.json`, run against the port.
*/
import { describe, expect, it } from "vitest";
import {
compareLineFragments,
compareLinesInner,
compareWords,
processBlocks,
type ComparisonPolicy,
type LineFragment,
type Range,
} from "..";
import cases from "./ideaCases.json";
type Policy = "default" | "trim" | "ignore";
type Change = [number, number, number, number];
interface Case {
source: string;
test: string;
type: "lines" | "lines_inner" | "words" | "splitter";
squash: boolean;
trim: boolean;
before: string;
after: string;
changes: Partial<Record<Policy, Change[]>>;
matchings: Partial<Record<Policy, [string, string]>>;
policies: Policy[];
}
/** PolicyData.get: "ignore" falls back to "trim", then "default". */
const forPolicy = <T>(data: Partial<Record<Policy, T>>, policy: Policy): T | undefined =>
policy === "ignore"
? (data.ignore ?? data.trim ?? data.default)
: policy === "trim"
? (data.trim ?? data.default)
: data.default;
const POLICY: Record<Policy, ComparisonPolicy> = { default: "default", trim: "trim", ignore: "ignore" };
/** Changed character offsets marked by non-space characters, '.' skipped (DiffTestCase.parseMatching). */
function parseMatching(matching: string): number[] {
return [...matching.replace(/\./g, "")].flatMap((c, i) => (c !== " " ? [i] : []));
}
/** Changed lines: lines (split at '_' / '*') with a character other than ' ' and '_' (parseLineMatching). */
function parseLineMatching(matching: string): number[] {
const out: number[] = [];
let line = 0;
let index = 0;
while (index < matching.length) {
let end = matching.slice(index).search(/[_*]/) + 1;
end = end === 0 ? matching.length : index + end;
if (/[^ _]/.test(matching.slice(index, end))) out.push(line);
line++;
index = end;
}
return out;
}
const charSets = (fragments: readonly Range[]) => {
const s1 = new Set<number>();
const s2 = new Set<number>();
for (const f of fragments) {
for (let i = f.start1; i < f.end1; i++) s1.add(i);
for (let i = f.start2; i < f.end2; i++) s2.add(i);
}
return [[...s1].sort((a, b) => a - b), [...s2].sort((a, b) => a - b)];
};
const lineSets = (fragments: readonly LineFragment[]) =>
charSets(fragments.map((f) => ({ start1: f.startLine1, end1: f.endLine1, start2: f.startLine2, end2: f.endLine2 })));
const lineChanges = (fragments: readonly LineFragment[]): Change[] =>
fragments.map((f) => [f.startLine1, f.endLine1, f.startLine2, f.endLine2]);
const rangeChanges = (fragments: readonly Range[]): Change[] =>
fragments.map((f) => [f.start1, f.end1, f.start2, f.end2]);
function checkWords(fragments: readonly Range[], changes?: Change[], matching?: [string, string]) {
if (changes) expect(rangeChanges(fragments)).toEqual(changes);
if (matching) expect(charSets(fragments)).toEqual([parseMatching(matching[0]), parseMatching(matching[1])]);
}
function run(c: Case, policy: Policy) {
const p = POLICY[policy];
const changes = forPolicy(c.changes, policy);
const matching = forPolicy(c.matchings, policy);
expect(changes ?? matching, "the case has expectations").toBeDefined();
switch (c.type) {
case "lines": {
const fragments = compareLineFragments(c.before, c.after, p);
if (changes) expect(lineChanges(fragments)).toEqual(changes);
if (matching)
expect(lineSets(fragments)).toEqual([parseLineMatching(matching[0]), parseLineMatching(matching[1])]);
break;
}
case "lines_inner": {
const fragments = processBlocks(compareLinesInner(c.before, c.after, p), c.before, c.after, p, true, false);
expect(fragments).toHaveLength(1);
const [f] = fragments;
expect([f!.startOffset1, f!.endOffset1, f!.startOffset2, f!.endOffset2]).toEqual([
0,
c.before.length,
0,
c.after.length,
]);
checkWords(f!.inner!, changes, matching);
checkWords(compareWords(c.before, c.after, p), changes, matching);
break;
}
case "words":
checkWords(compareWords(c.before, c.after, p), changes, matching);
break;
case "splitter": {
const inner = compareLinesInner(c.before, c.after, p);
expect(lineChanges(processBlocks(inner, c.before, c.after, p, c.squash, c.trim))).toEqual(changes);
break;
}
}
}
describe("IntelliJ comparison tests", () => {
(cases as Case[]).forEach((c, i) => {
for (const policy of new Set(c.policies))
it(`${c.source}.${c.test} #${i} ${c.type} ${JSON.stringify(c.before)} - ${JSON.stringify(c.after)} (${policy})`, () =>
run(c, policy));
});
});
File diff suppressed because it is too large. Load diff
-30
Переглянути файл
@@ -1,30 +0,0 @@
/**
* Character-level comparison of punctuation (IntelliJ's ByCharRt
* .comparePunctuation, ported; Apache-2.0, Copyright JetBrains s.r.o. and
* contributors): only punctuation is matched, everything else stays changed.
*/
import { ChangeBuilder, type DiffIterable, unchanged, diffSequences } from "./iterables";
import { isPunctuation } from "./text";
export function comparePunctuation(text1: string, text2: string): DiffIterable {
const chars = (text: string) => {
const codes: number[] = [];
const offsets: number[] = [];
for (let i = 0; i < text.length; i++) {
const c = text.charCodeAt(i);
if (isPunctuation(c)) {
codes.push(c);
offsets.push(i);
}
}
return { codes, offsets };
};
const chars1 = chars(text1);
const chars2 = chars(text2);
const changes = diffSequences(chars1.codes, chars2.codes);
const builder = new ChangeBuilder(text1.length, text2.length);
for (const r of unchanged(changes))
for (let i = 0; i < r.end1 - r.start1; i++)
builder.markEqual(chars1.offsets[r.start1 + i]!, chars2.offsets[r.start2 + i]!);
return builder.finish();
}
-205
Переглянути файл
@@ -1,205 +0,0 @@
/**
* Line-level comparison (IntelliJ's ByLineRt with SmartLineChangeCorrector,
* ported; Apache-2.0, Copyright JetBrains s.r.o. and contributors): lines are
* first matched ignoring whitespace and "unimportant" lines (blank, `}`), the
* gaps are filled, boundaries optimized, then whitespace-only matches that
* the policy doesn't allow are corrected.
*/
import { optimizeLineChunks, UNIMPORTANT_LINE_CHAR_COUNT, type LineInfo } from "./chunkOptimizer";
import {
ChangeBuilder,
create,
type DiffIterable,
diffSequences,
expandEqual,
ExpandChangeBuilder,
unchanged,
} from "./iterables";
import { isEmptyRange, type Range } from "./lcs";
import { type ComparisonPolicy, isSpace, lineKey } from "./text";
interface Line extends LineInfo {
readonly content: string;
/** The key ignoring whitespace. */
readonly iwKey: string;
}
function toLine(content: string, policy: ComparisonPolicy): Line {
let nonSpaceChars = 0;
for (let i = 0; i < content.length; i++) if (!isSpace(content[i])) nonSpaceChars++;
const iwKey = lineKey(content, "ignore");
return { content, key: policy === "ignore" ? iwKey : lineKey(content, policy), iwKey, nonSpaceChars };
}
/** Line changes between two lists of line texts (without line breaks). */
export function compareLines(
lines1: readonly string[],
lines2: readonly string[],
policy: ComparisonPolicy,
): DiffIterable {
const l1 = lines1.map((l) => toLine(l, policy));
const l2 = lines2.map((l) => toLine(l, policy));
const iw1 = l1.map((l) => l.iwKey);
const iw2 = l2.map((l) => l.iwKey);
if (policy === "ignore") {
const changes = optimizeLineChunks(l1, l2, compareSmart(l1, l2, iw1, iw2));
const keys1 = l1.map((l) => l.key);
const keys2 = l2.map((l) => l.key);
const expanded: Range[] = [];
for (const c of changes.changes) {
const r = expandEqual(keys1, keys2, c.start1, c.start2, c.end1, c.end2);
if (!isEmptyRange(r)) expanded.push(r);
}
return create(expanded, l1.length, l2.length);
}
const iwChanges = optimizeLineChunks(l1, l2, compareSmart(l1, l2, iw1, iw2));
return correctChangesSecondStep(l1, l2, iwChanges);
}
/**
* Matches lines ignoring the unimportant ones, then compares the gaps between
* the matches with all lines (compareSmart + SmartLineChangeCorrector).
*/
function compareSmart(
lines1: readonly Line[],
lines2: readonly Line[],
keys1: string[],
keys2: string[],
): DiffIterable {
const big = (lines: readonly Line[]) => {
const indexes: number[] = [];
lines.forEach((l, i) => l.nonSpaceChars > UNIMPORTANT_LINE_CHAR_COUNT && indexes.push(i));
return indexes;
};
const indexes1 = big(lines1);
const indexes2 = big(lines2);
const changes = diffSequences(
indexes1.map((i) => keys1[i]!),
indexes2.map((i) => keys2[i]!),
);
const builder = new ChangeBuilder(lines1.length, lines2.length);
const matchGap = (start1: number, end1: number, start2: number, end2: number) => {
const expand = expandEqual(keys1, keys2, start1, start2, end1, end2);
const inner = diffSequences(keys1.slice(expand.start1, expand.end1), keys2.slice(expand.start2, expand.end2));
builder.markEqual(start1, start2, expand.start1, expand.start2);
for (const r of unchanged(inner))
builder.markEqualCount(expand.start1 + r.start1, expand.start2 + r.start2, r.end1 - r.start1);
builder.markEqual(expand.end1, expand.end2, end1, end2);
};
let last1 = 0;
let last2 = 0;
for (const r of unchanged(changes)) {
for (let i = 0; i < r.end1 - r.start1; i++) {
const start1 = indexes1[r.start1 + i]!;
const start2 = indexes2[r.start2 + i]!;
matchGap(last1, start1, last2, start2);
builder.markEqual(start1, start2, start1 + 1, start2 + 1);
last1 = start1 + 1;
last2 = start2 + 1;
}
}
matchGap(last1, lines1.length, last2, lines2.length);
return builder.finish();
}
/**
* Fixes lines matched ignoring whitespace but not equal under the policy
* (ByLineRt.correctChangesSecondStep). Equal lines stay matched, unmatched
* stay unmatched; for whitespace-equal runs the alignment with the most equal
* pairs wins, so ".{ ..{ ...{" vs "..{ ...{" matches the last two.
*/
function correctChangesSecondStep(
lines1: readonly Line[],
lines2: readonly Line[],
changes: DiffIterable,
): DiffIterable {
const builder = new ExpandChangeBuilder(
lines1.map((l) => l.key),
lines2.map((l) => l.key),
);
const equal = (i1: number, i2: number) => lines1[i1]!.key === lines2[i2]!.key;
let sample: string | null = null;
let last1 = 0;
let last2 = 0;
const alignExactMatching = (sub1: number[], sub2: number[]) => {
const n = Math.max(sub1.length, sub2.length);
// brute force over the combinations: limit the search space
if (n > 10 || sub1.length === sub2.length) {
for (let i = 0; i < Math.min(sub1.length, sub2.length); i++)
if (equal(sub1[i]!, sub2[i]!)) builder.markEqual(sub1[i]!, sub2[i]!);
return;
}
if (sub1.length < sub2.length) {
const matching = bestMatchingAlignment(sub1, sub2, equal);
for (let i = 0; i < sub1.length; i++) {
const index2 = sub2[matching[i]!]!;
if (equal(sub1[i]!, index2)) builder.markEqual(sub1[i]!, index2);
}
} else {
const matching = bestMatchingAlignment(sub2, sub1, (i2, i1) => equal(i1, i2));
for (let i = 0; i < sub2.length; i++) {
const index1 = sub1[matching[i]!]!;
if (equal(index1, sub2[i]!)) builder.markEqual(index1, sub2[i]!);
}
}
};
const flush = (line1: number, line2: number) => {
if (sample === null) return;
const start1 = Math.max(last1, builder.index1);
const start2 = Math.max(last2, builder.index2);
const sub1: number[] = [];
const sub2: number[] = [];
for (let i = start1; i < line1; i++)
if (lines1[i]!.iwKey === sample) {
sub1.push(i);
last1 = i + 1;
}
for (let i = start2; i < line2; i++)
if (lines2[i]!.iwKey === sample) {
sub2.push(i);
last2 = i + 1;
}
alignExactMatching(sub1, sub2);
sample = null;
};
for (const r of unchanged(changes)) {
for (let i = 0; i < r.end1 - r.start1; i++) {
const index1 = r.start1 + i;
const index2 = r.start2 + i;
if (sample === lines1[index1]!.iwKey) continue;
flush(index1, index2);
if (equal(index1, index2)) builder.markEqual(index1, index2);
else sample = lines1[index1]!.iwKey;
}
}
flush(changes.length1, changes.length2);
return builder.finish();
}
/** The combination of `sub2` positions for `sub1` with the most equal pairs (getBestMatchingAlignment). */
function bestMatchingAlignment(sub1: number[], sub2: number[], equal: (i1: number, i2: number) => boolean): number[] {
const size = sub1.length;
const comb = new Array<number>(size).fill(0);
let best = Array.from({ length: size }, (_, i) => i);
let bestWeight = 0;
const combinations = (start: number, n: number, k: number) => {
if (k === size) {
let weight = 0;
for (let i = 0; i < size; i++) if (equal(sub1[i]!, sub2[comb[i]!]!)) weight++;
if (weight > bestWeight) {
bestWeight = weight;
best = [...comb];
}
return;
}
for (let i = start; i <= n; i++) {
comb[k] = i;
combinations(i + 1, n, k + 1);
}
};
combinations(0, sub2.length - 1, 0);
return best;
}
-428
Переглянути файл
@@ -1,428 +0,0 @@
/**
* Word-level comparison of a changed block (IntelliJ's ByWordRt
* .compareAndSplit with LineFragmentSplitter, ported; Apache-2.0, Copyright
* JetBrains s.r.o. and contributors): words and line breaks are diffed, the
* block is split into "logically different" line blocks, punctuation between
* matched words is matched by character, and whitespace by the policy.
*/
import { comparePunctuation } from "./byChar";
import { optimizeWordChunks, type WordChunk } from "./chunkOptimizer";
import { ChangeBuilder, create, type DiffIterable, diffSequences, subIterable, unchanged } from "./iterables";
import { isEmptyRange, range, type Range } from "./lcs";
import {
type ComparisonPolicy,
charCount,
expandWhitespaces,
expandWhitespacesBackward,
expandWhitespacesForward,
isAlpha,
isContinuousScript,
isEqualsIgnoreWhitespacesRange,
isEqualsRange,
isSpace,
trimEnd,
trimRange,
trimStart,
} from "./text";
export interface InlineChunk extends WordChunk {
/** Equal keys are equal chunks: the word itself, or "\n". */
readonly key: string;
}
/**
* The words of a text (ByWordRt.getInlineChunks): runs of letters and digits
* (anything but ASCII whitespace and punctuation), single characters of
* scripts written without spaces, and line breaks. Punctuation is matched
* separately.
*/
export function getInlineChunks(text: string): InlineChunk[] {
const chunks: InlineChunk[] = [];
const word = (from: number, to: number): InlineChunk => ({
offset1: from,
offset2: to,
newline: false,
key: text.slice(from, to),
});
let wordStart = -1;
for (let offset = 0; offset < text.length;) {
const ch = text.codePointAt(offset)!;
const n = charCount(ch);
const alpha = isAlpha(ch);
if (alpha && !isContinuousScript(ch)) {
if (wordStart === -1) wordStart = offset;
} else {
if (wordStart !== -1) {
chunks.push(word(wordStart, offset));
wordStart = -1;
}
if (alpha) chunks.push(word(offset, offset + n));
else if (ch === 10) chunks.push({ offset1: offset, offset2: offset + 1, newline: true, key: "\n" });
}
offset += n;
}
if (wordStart !== -1) chunks.push(word(wordStart, text.length));
return chunks;
}
/** Word changes of two texts (ByWordRt.compare). */
export function compareWords(text1: string, text2: string, policy: ComparisonPolicy): readonly Range[] {
const words1 = getInlineChunks(text1);
const words2 = getInlineChunks(text2);
const keys1 = words1.map((w) => w.key);
const keys2 = words2.map((w) => w.key);
let wordChanges = diffSequences(keys1, keys2);
wordChanges = optimizeWordChunks(keys1, keys2, words1, words2, text1, text2, wordChanges);
const delimiters = matchPunctuation(text1, text2, words1, words2, 0, 0, wordChanges);
return matchWhitespaces(text1, text2, delimiters, policy).changes;
}
export interface LineBlock {
/** Changed ranges of the block's texts, relative to `offsets`. */
readonly fragments: readonly Range[];
readonly offsets: Range;
readonly newlines1: number;
readonly newlines2: number;
}
/** Word changes of a changed line block, split into line blocks (ByWordRt.compareAndSplit). */
export function compareAndSplit(text1: string, text2: string, policy: ComparisonPolicy): LineBlock[] {
const words1 = getInlineChunks(text1);
const words2 = getInlineChunks(text2);
const keys1 = words1.map((w) => w.key);
const keys2 = words2.map((w) => w.key);
let wordChanges = diffSequences(keys1, keys2);
wordChanges = optimizeWordChunks(keys1, keys2, words1, words2, text1, text2, wordChanges);
const wordBlocks = splitLineFragments(text1, text2, words1, words2, wordChanges);
const changed = wordChanges.changes;
let index = 0;
return wordBlocks.map((block) => {
const { offsets, words } = block;
while (index < changed.length) {
const r = changed[index]!;
if (r.end1 < words.start1 || r.end2 < words.start2) index++;
else break;
}
const sub = subIterable(changed, words.start1, words.end1, words.start2, words.end2, index);
const subtext1 = text1.slice(offsets.start1, offsets.end1);
const subtext2 = text2.slice(offsets.start2, offsets.end2);
const subwords1 = words1.slice(words.start1, words.end1);
const subwords2 = words2.slice(words.start2, words.end2);
const delimiters = matchPunctuation(subtext1, subtext2, subwords1, subwords2, offsets.start1, offsets.start2, sub);
const iterable = matchWhitespaces(subtext1, subtext2, delimiters, policy);
return {
fragments: iterable.changes,
offsets,
newlines1: subwords1.filter((w) => w.newline).length,
newlines2: subwords2.filter((w) => w.newline).length,
};
});
}
interface WordBlock {
readonly words: Range;
readonly offsets: Range;
}
interface PendingChunk {
readonly block: WordBlock;
readonly hasEqualWords: boolean;
readonly hasWordsInside: boolean;
readonly isEqualIgnoreWhitespaces: boolean;
}
/**
* Splits a changed block at matched line breaks and at matched first words of
* lines (LineFragmentSplitter). Word indexes: -1 is the start of the text,
* `words.length` its end.
*/
function splitLineFragments(
text1: string,
text2: string,
words1: readonly InlineChunk[],
words2: readonly InlineChunk[],
iterable: DiffIterable,
): WordBlock[] {
const result: WordBlock[] = [];
let last1 = -1;
let last2 = -1;
let pending: PendingChunk | null = null;
const offset = (words: readonly InlineChunk[], text: string, index: number) =>
index === -1 ? 0 : index === words.length ? text.length : words[index]!.offset2;
const createChunk = (start1: number, start2: number, end1: number, end2: number, hasEqualWords: boolean) => {
const offsets = range(
offset(words1, text1, start1),
offset(words1, text1, end1),
offset(words2, text2, start2),
offset(words2, text2, end2),
);
const words = range(
Math.max(0, start1 + 1),
Math.min(end1 + 1, words1.length),
Math.max(0, start2 + 1),
Math.min(end2 + 1, words2.length),
);
const block = { words, offsets };
let hasWordsInside = false;
for (let i = words.start1; i < words.end1 && !hasWordsInside; i++) hasWordsInside = !words1[i]!.newline;
for (let i = words.start2; i < words.end2 && !hasWordsInside; i++) hasWordsInside = !words2[i]!.newline;
return {
block,
hasEqualWords,
hasWordsInside,
isEqualIgnoreWhitespaces: isEqualsIgnoreWhitespacesRange(text1, text2, offsets),
};
};
const shouldMerge = (c1: PendingChunk, c2: PendingChunk) =>
// lines matched only by '\n'
(!c1.hasEqualWords && !c2.hasEqualWords) ||
// whitespace-only changed lines
(c1.isEqualIgnoreWhitespaces && c2.isEqualIgnoreWhitespaces) ||
// a block without words in it
!c1.hasWordsInside ||
!c2.hasWordsInside;
const merge = (c1: PendingChunk, c2: PendingChunk): PendingChunk => ({
block: {
words: range(c1.block.words.start1, c2.block.words.end1, c1.block.words.start2, c2.block.words.end2),
offsets: range(c1.block.offsets.start1, c2.block.offsets.end1, c1.block.offsets.start2, c2.block.offsets.end2),
},
hasEqualWords: c1.hasEqualWords || c2.hasEqualWords,
hasWordsInside: c1.hasWordsInside || c2.hasWordsInside,
isEqualIgnoreWhitespaces: c1.isEqualIgnoreWhitespaces && c2.isEqualIgnoreWhitespaces,
});
const addLineChunk = (end1: number, end2: number, hasEqualWords: boolean) => {
if (last1 > end1 || last2 > end2) return;
const chunk = createChunk(last1, last2, end1, end2, hasEqualWords);
if (isEmptyRange(chunk.block.offsets)) return;
if (pending && shouldMerge(pending, chunk)) pending = merge(pending, chunk);
else {
if (pending) result.push(pending.block);
pending = chunk;
}
last1 = end1;
last2 = end2;
};
const firstInLine = (words: readonly InlineChunk[], index: number) => index === 0 || words[index - 1]!.newline;
let hasEqualWords = false;
for (const r of unchanged(iterable)) {
for (let i = 0; i < r.end1 - r.start1; i++) {
const index1 = r.start1 + i;
const index2 = r.start2 + i;
if (words1[index1]!.newline && words2[index2]!.newline) {
// split by matched newlines
addLineChunk(index1, index2, hasEqualWords);
hasEqualWords = false;
} else {
if (firstInLine(words1, index1) && firstInLine(words2, index2)) {
// split by matched first word in line
addLineChunk(index1 - 1, index2 - 1, hasEqualWords);
hasEqualWords = false;
}
hasEqualWords = true;
}
}
}
addLineChunk(words1.length, words2.length, hasEqualWords);
if (pending) result.push((pending as PendingChunk).block);
return result;
}
/**
* Matches punctuation between words (AdjustmentPunctuationMatcher): the
* separators around each pair of matched words are compared by character, so
* "[ X { A ! B } Y ]" vs "( X ... Y )" compares "[" with "(", "{" + "}" with
* "..." and "]" with ")".
*/
function matchPunctuation(
text1: string,
text2: string,
words1: readonly InlineChunk[],
words2: readonly InlineChunk[],
startShift1: number,
startShift2: number,
changes: DiffIterable,
): DiffIterable {
const len1 = text1.length;
const len2 = text2.length;
const builder = new ChangeBuilder(len1, len2);
const startOffset1 = (i: number) => words1[i]!.offset1 - startShift1;
const startOffset2 = (i: number) => words2[i]!.offset1 - startShift2;
const endOffset1 = (i: number) => words1[i]!.offset2 - startShift1;
const endOffset2 = (i: number) => words2[i]!.offset2 - startShift2;
let lastStart1 = -1;
let lastStart2 = -1;
let lastEnd1 = -1;
let lastEnd2 = -1;
const matchRange = (start1: number, start2: number, end1: number, end2: number) => {
if (start1 === end1 && start2 === end2) return;
const inner = comparePunctuation(text1.slice(start1, end1), text2.slice(start2, end2));
for (const r of unchanged(inner))
builder.markEqual(start1 + r.start1, start2 + r.start2, start1 + r.end1, start2 + r.end2);
};
// One sequence compared with two others as if they were one (comparePunctuation2Side).
const compare2Side = (text: string, text21: string, text22: string): [Range[], Range[]] => {
const changes = comparePunctuation(text, text21 + text22);
const ranges1: Range[] = [];
const ranges2: Range[] = [];
const split = text21.length;
for (const r of unchanged(changes)) {
if (r.end2 <= split) ranges1.push(r);
else if (r.start2 >= split) ranges2.push(range(r.start1, r.end1, r.start2 - split, r.end2 - split));
else {
const len = split - r.start2;
ranges1.push(range(r.start1, r.start1 + len, r.start2, split));
ranges2.push(range(r.start1 + len, r.end1, 0, r.end2 - split));
}
}
return [ranges1, ranges2];
};
const matchComplexRange = (
start11: number,
start12: number,
end11: number,
end12: number,
start21: number,
start22: number,
end21: number,
end22: number,
) => {
if (start11 === start21 && end11 === end21) {
const [first, second] = compare2Side(
text1.slice(start11, end11),
text2.slice(start12, end12),
text2.slice(start22, end22),
);
for (const r of first)
builder.markEqual(start11 + r.start1, start12 + r.start2, start11 + r.end1, start12 + r.end2);
for (const r of second)
builder.markEqual(start11 + r.start1, start22 + r.start2, start11 + r.end1, start22 + r.end2);
} else if (start12 === start22 && end12 === end22) {
// mirrored: two left sides against one right side
const [first, second] = compare2Side(
text2.slice(start12, end12),
text1.slice(start11, end11),
text1.slice(start21, end21),
);
for (const r of first)
builder.markEqual(start11 + r.start2, start12 + r.start1, start11 + r.end2, start12 + r.end1);
for (const r of second)
builder.markEqual(start21 + r.start2, start12 + r.start1, start21 + r.end2, start12 + r.end1);
} else {
throw new Error("unexpected punctuation ranges");
}
};
const matchForward = (index1: number, index2: number) => {
lastStart1 = index1 === -1 ? 0 : endOffset1(index1);
lastStart2 = index2 === -1 ? 0 : endOffset2(index2);
lastEnd1 = index1 + 1 === words1.length ? len1 : startOffset1(index1 + 1);
lastEnd2 = index2 + 1 === words2.length ? len2 : startOffset2(index2 + 1);
};
const matchBackward = (index1: number, index2: number) => {
const start1 = index1 === 0 ? 0 : endOffset1(index1 - 1);
const start2 = index2 === 0 ? 0 : endOffset2(index2 - 1);
const end1 = index1 === words1.length ? len1 : startOffset1(index1);
const end2 = index2 === words2.length ? len2 : startOffset2(index2);
if (lastStart1 === start1 && lastStart2 === start2) {
// adjacent matched words, match the gap between ("A B" - "A B")
matchRange(start1, start2, end1, end2);
} else if (lastStart1 < start1 && lastStart2 < start2) {
// matched words with unmatched ones between ("A X B" - "A Y B")
matchRange(lastStart1, lastStart2, lastEnd1, lastEnd2);
matchRange(start1, start2, end1, end2);
} else {
// one side adjacent, the other with unmatched words between ("A B" - "A Y B")
matchComplexRange(lastStart1, lastStart2, lastEnd1, lastEnd2, start1, start2, end1, end2);
}
lastStart1 = lastStart2 = lastEnd1 = lastEnd2 = -1;
};
matchForward(-1, -1);
for (const r of unchanged(changes)) {
for (let i = 0; i < r.end1 - r.start1; i++) {
const index1 = r.start1 + i;
const index2 = r.start2 + i;
matchBackward(index1, index2);
builder.markEqual(startOffset1(index1), startOffset2(index2), endOffset1(index1), endOffset2(index2));
matchForward(index1, index2);
}
}
matchBackward(words1.length, words2.length);
return builder.finish();
}
/** Whitespace handling of the changes by policy (ByWordRt.matchAdjustmentWhitespaces). */
export function matchWhitespaces(text1: string, text2: string, iterable: DiffIterable, policy: ComparisonPolicy) {
if (policy === "ignore") return ignoreSpaces(iterable, text1, text2);
const corrected = defaultSpaces(iterable, text1, text2);
return policy === "trim" ? trimSpaces(corrected, text1, text2) : corrected;
}
/** Equal whitespace at the edges of a change is unchanged (DefaultCorrector). */
function defaultSpaces(iterable: DiffIterable, text1: string, text2: string): DiffIterable {
const changes: Range[] = [];
for (const r of iterable.changes) {
const endCut = expandWhitespacesBackward(text1, text2, r.start1, r.start2, r.end1, r.end2);
const startCut = expandWhitespacesForward(text1, text2, r.start1, r.start2, r.end1 - endCut, r.end2 - endCut);
const expanded = range(r.start1 + startCut, r.end1 - endCut, r.start2 + startCut, r.end2 - endCut);
if (!isEmptyRange(expanded)) changes.push(expanded);
}
return create(changes, text1.length, text2.length);
}
/** Whitespace is matched where possible and ignored where not (IgnoreSpacesCorrector). */
function ignoreSpaces(iterable: DiffIterable, text1: string, text2: string): DiffIterable {
const changes: Range[] = [];
for (const r of iterable.changes) {
const trimmed = trimRange(text1, text2, expandWhitespaces(text1, text2, r));
if (!isEmptyRange(trimmed) && !isEqualsIgnoreWhitespacesRange(text1, text2, trimmed)) changes.push(trimmed);
}
return create(changes, text1.length, text2.length);
}
function isLeadingSpace(text: string, start: number): boolean {
if (start < 0 || start === text.length || !isSpace(text[start])) return false;
for (let i = start - 1; i >= 0; i--) {
if (text[i] === "\n") return true;
if (!isSpace(text[i])) return false;
}
return true;
}
function isTrailingSpace(text: string, end: number): boolean {
if (end < 0 || end === text.length || !isSpace(text[end])) return false;
for (let i = end; i < text.length; i++) {
if (text[i] === "\n") return true;
if (!isSpace(text[i])) return false;
}
return true;
}
const isLeadingTrailingSpace = (text: string, i: number) => isLeadingSpace(text, i) || isTrailingSpace(text, i);
/** Leading and trailing whitespace of lines is not a change (TrimSpacesCorrector). */
function trimSpaces(iterable: DiffIterable, text1: string, text2: string): DiffIterable {
const changes: Range[] = [];
for (const r of iterable.changes) {
let { start1, start2, end1, end2 } = r;
if (isLeadingTrailingSpace(text1, start1)) start1 = trimStart(text1, start1, end1);
if (isLeadingTrailingSpace(text1, end1 - 1)) end1 = trimEnd(text1, start1, end1);
if (isLeadingTrailingSpace(text2, start2)) start2 = trimStart(text2, start2, end2);
if (isLeadingTrailingSpace(text2, end2 - 1)) end2 = trimEnd(text2, start2, end2);
const trimmed = range(start1, end1, start2, end2);
if (!isEmptyRange(trimmed) && !isEqualsRange(text1, text2, trimmed)) changes.push(trimmed);
}
return create(changes, text1.length, text2.length);
}
-183
Переглянути файл
@@ -1,183 +0,0 @@
/**
* Shifts ambiguous changes to where people expect them (IntelliJ's
* ChunkOptimizer, ported; Apache-2.0, Copyright JetBrains s.r.o. and
* contributors): touching changes are merged, and an insertion or deletion
* that could sit at several places moves to a word boundary (words) or next to
* an empty line (lines).
*/
import { createUnchanged, expandBackward, expandForward, type DiffIterable, unchanged } from "./iterables";
import { range, type Range } from "./lcs";
import { isSpace } from "./text";
/** `touchLeft`: the changes touch on the left side; returns the shift (> 0 forward, < 0 backward). */
type GetShift = (
touchLeft: boolean,
equalForward: number,
equalBackward: number,
range1: Range,
range2: Range,
) => number;
function optimize<T>(data1: readonly T[], data2: readonly T[], iterable: DiffIterable, getShift: GetShift) {
const ranges: Range[] = [];
const processLastRanges = (): void => {
if (ranges.length < 2) return;
const range1 = ranges[ranges.length - 2]!;
const range2 = ranges[ranges.length - 1]!;
// Changes that don't touch can't be optimized (the input would not be an LCS).
if (range1.end1 !== range2.start1 && range1.end2 !== range2.start2) return;
const count1 = range1.end1 - range1.start1;
const count2 = range2.end1 - range2.start1;
const equalForward = expandForward(
data1,
data2,
range1.end1,
range1.end2,
Math.min(range1.end1 + count2, data1.length),
Math.min(range1.end2 + count2, data2.length),
);
const equalBackward = expandBackward(
data1,
data2,
Math.max(range2.start1 - count1, 0),
Math.max(range2.start2 - count1, 0),
range2.start1,
range2.start2,
);
if (equalForward === 0 && equalBackward === 0) return;
// merge chunks left [A]B[B] -> [AB]B
if (equalForward === count2) {
ranges.splice(-2, 2, range(range1.start1, range1.end1 + count2, range1.start2, range1.end2 + count2));
return processLastRanges();
}
// merge chunks right [A]A[B] -> A[AB]
if (equalBackward === count1) {
ranges.splice(-2, 2, range(range2.start1 - count1, range2.end1, range2.start2 - count1, range2.end2));
return processLastRanges();
}
const shift = getShift(range1.end1 === range2.start1, equalForward, equalBackward, range1, range2);
if (shift !== 0)
ranges.splice(
-2,
2,
range(range1.start1, range1.end1 + shift, range1.start2, range1.end2 + shift),
range(range2.start1 + shift, range2.end1, range2.start2 + shift, range2.end2),
);
};
for (const r of unchanged(iterable)) {
ranges.push(r);
processLastRanges();
}
return createUnchanged(ranges, data1.length, data2.length);
}
export interface WordChunk {
readonly offset1: number;
readonly offset2: number;
readonly newline: boolean;
}
/**
* Words: fewer chunks, and fewer changed "sentences" (runs of words not
* separated by whitespace): "[AX] [AZ]" - "[AX] AY [AZ]", not "[AX A][Z]".
*/
export function optimizeWordChunks(
keys1: readonly string[],
keys2: readonly string[],
words1: readonly WordChunk[],
words2: readonly WordChunk[],
text1: string,
text2: string,
iterable: DiffIterable,
): DiffIterable {
const separated = (text: string, word1: WordChunk, word2: WordChunk) => {
if (word1.newline || word2.newline) return true;
for (let i = word1.offset2; i < word2.offset1; i++) if (isSpace(text[i])) return true;
return false;
};
const edgeShift = (text: string, words: readonly WordChunk[], offset: number, count: number, ltr: boolean) => {
for (let i = 0; i < count; i++) {
const [w1, w2] = ltr
? [words[offset + i]!, words[offset + i + 1]!]
: [words[offset - i - 1]!, words[offset - i]!];
if (separated(text, w1, w2)) return i + 1;
}
return -1;
};
return optimize(keys1, keys2, iterable, (touchLeft, equalForward, equalBackward, _range1, range2) => {
const words = touchLeft ? words1 : words2;
const text = touchLeft ? text1 : text2;
const touchStart = touchLeft ? range2.start1 : range2.start2;
// already separated by whitespace
if (separated(text, words[touchStart - 1]!, words[touchStart]!)) return 0;
// shift chunks left [X]A Y[A ZA] -> [XA] YA [ZA]
const left = edgeShift(text, words, touchStart, equalForward, true);
if (left > 0) return left;
// shift chunks right [AX A]Y A[Z] -> [AX] AY [AZ]
const right = edgeShift(text, words, touchStart - 1, equalBackward, false);
if (right > 0) return -right;
return 0;
});
}
/** Lines with at most this many non-space characters are "unimportant" (`}`, blank). */
export const UNIMPORTANT_LINE_CHAR_COUNT = 3;
export interface LineInfo {
readonly key: string;
readonly nonSpaceChars: number;
}
/**
* Lines: fewer chunks, and insertions / deletions bounded by an empty (or
* unimportant) line: "ABooYZ [ABuuYZ ]ABzzYZ", not "ABooYZ AB[uuYZ AB]zzYZ".
*/
export function optimizeLineChunks(
lines1: readonly LineInfo[],
lines2: readonly LineInfo[],
iterable: DiffIterable,
): DiffIterable {
const nextUnimportant = (lines: readonly LineInfo[], offset: number, count: number, threshold: number) => {
for (let i = 0; i < count; i++) if (lines[offset + i]!.nonSpaceChars <= threshold) return i;
return -1;
};
const prevUnimportant = (lines: readonly LineInfo[], offset: number, count: number, threshold: number) => {
for (let i = 0; i < count; i++) if (lines[offset - i]!.nonSpaceChars <= threshold) return i;
return -1;
};
const toShift = (forward: number, backward: number): number | null => {
if (forward === -1 && backward === -1) return null;
if (forward === 0 || backward === 0) return 0;
return forward !== -1 ? forward : -backward;
};
const keys1 = lines1.map((l) => l.key);
const keys2 = lines2.map((l) => l.key);
return optimize(keys1, keys2, iterable, (touchLeft, equalForward, equalBackward, range1, range2) => {
// an empty line boundary in unchanged lines: the insertion / deletion goes right before / after it
const unchangedBoundary = (threshold: number) => {
const lines = touchLeft ? lines1 : lines2;
const touchStart = touchLeft ? range2.start1 : range2.start2;
return toShift(
nextUnimportant(lines, touchStart, equalForward + 1, threshold),
prevUnimportant(lines, touchStart - 1, equalBackward + 1, threshold),
);
};
// an empty line boundary in changed lines: the insertion / deletion starts / ends with it
const changedBoundary = (threshold: number) => {
const lines = touchLeft ? lines2 : lines1;
const changeStart = touchLeft ? range1.end2 : range1.end1;
const changeEnd = touchLeft ? range2.start2 : range2.start1;
return toShift(
nextUnimportant(lines, changeStart, equalForward + 1, threshold),
prevUnimportant(lines, changeEnd - 1, equalBackward + 1, threshold),
);
};
return (
unchangedBoundary(0) ??
changedBoundary(0) ??
unchangedBoundary(UNIMPORTANT_LINE_CHAR_COUNT) ??
changedBoundary(UNIMPORTANT_LINE_CHAR_COUNT) ??
0
);
});
}
-255
Переглянути файл
@@ -1,255 +0,0 @@
/**
* IntelliJ's text comparison (ComparisonManagerImpl.compareLinesInner and
* processBlocks, ported; Apache-2.0, Copyright JetBrains s.r.o. and
* contributors): lines are compared, each changed block is compared by words
* and split into line blocks, then adjoining blocks are squashed back and,
* when ignoring whitespace and empty lines, whitespace-only blocks trimmed.
*/
import { compareLines } from "./byLine";
import { compareAndSplit } from "./byWord";
import { DiffTooBigError, type Range } from "./lcs";
import { type ComparisonPolicy, isEqualTexts, stripSpaces } from "./text";
export type { ComparisonPolicy } from "./text";
export type { Range } from "./lcs";
export { compareWords } from "./byWord";
export interface LineFragment {
readonly startLine1: number;
readonly endLine1: number;
readonly startLine2: number;
readonly endLine2: number;
/** Text offsets; the end includes the last line's line break, when it has one. */
readonly startOffset1: number;
readonly endOffset1: number;
readonly startOffset2: number;
readonly endOffset2: number;
/**
* Changed ranges inside the fragment, relative to its start offsets; null
* when not computed (by-line highlighting, or a block too big to compare).
*/
readonly inner: readonly Range[] | null;
}
export interface CompareOptions {
policy: ComparisonPolicy;
/** Compare changed blocks by words ("Highlight words"). */
words: boolean;
/** Drop leading / trailing whitespace-only blocks ("Ignore whitespaces and empty lines"). */
trimChunks?: boolean;
/** Keep the line blocks words split a change into ("Highlight split changes"). */
split?: boolean;
}
/** Do not compare by words after that many blocks were too big (DiffConfig.MAX_BAD_LINES). */
const MAX_BAD_LINES = 3;
class LineOffsets {
private readonly starts: number[] = [0];
constructor(readonly text: string) {
for (let i = text.indexOf("\n"); i >= 0; i = text.indexOf("\n", i + 1)) this.starts.push(i + 1);
}
get lineCount() {
return this.starts.length;
}
lineStart(line: number) {
return this.starts[line]!;
}
lineEnd(line: number, includeNewline = false) {
if (line === this.starts.length - 1) return this.text.length;
return this.starts[line + 1]! - (includeNewline ? 0 : 1);
}
lines(): string[] {
return this.starts.map((_, i) => this.text.slice(this.lineStart(i), this.lineEnd(i)));
}
/** Offsets of lines `[start, end)` (ComparisonManagerImpl.getOffsets). */
offsets(start: number, end: number): [number, number] {
if (start === end) {
const offset = start < this.lineCount ? this.lineStart(start) : this.lineEnd(this.lineCount - 1, true);
return [offset, offset];
}
return [this.lineStart(start), this.lineEnd(end - 1, true)];
}
}
/** Line fragments of two texts with their inner word changes, as IDEA's diff viewer computes them. */
export function compareTexts(text1: string, text2: string, options: CompareOptions): LineFragment[] {
const { policy } = options;
const fragments = options.words
? compareLinesInner(text1, text2, policy)
: compareLineFragments(text1, text2, policy);
return processBlocks(fragments, text1, text2, policy, !options.split, !!options.trimChunks);
}
/** Changed lines (ComparisonManagerImpl.compareLines). */
export function compareLineFragments(text1: string, text2: string, policy: ComparisonPolicy): LineFragment[] {
const offsets1 = new LineOffsets(text1);
const offsets2 = new LineOffsets(text2);
return compareLines(offsets1.lines(), offsets2.lines(), policy).changes.map((r) => {
const [startOffset1, endOffset1] = offsets1.offsets(r.start1, r.end1);
const [startOffset2, endOffset2] = offsets2.offsets(r.start2, r.end2);
return {
startLine1: r.start1,
endLine1: r.end1,
startLine2: r.start2,
endLine2: r.end2,
startOffset1,
endOffset1,
startOffset2,
endOffset2,
inner: null,
};
});
}
/** Changed lines split into line blocks with their word changes (ComparisonManagerImpl.compareLinesInner). */
export function compareLinesInner(text1: string, text2: string, policy: ComparisonPolicy): LineFragment[] {
return innerFragments(compareLineFragments(text1, text2, policy), text1, text2, policy);
}
function innerFragments(
fragments: readonly LineFragment[],
text1: string,
text2: string,
policy: ComparisonPolicy,
): LineFragment[] {
const out: LineFragment[] = [];
let tooBig = 0;
for (const f of fragments) {
const sub1 = text1.slice(f.startOffset1, f.endOffset1);
const sub2 = text2.slice(f.startOffset2, f.endOffset2);
if (f.startLine1 === f.endLine1 || f.startLine2 === f.endLine2) {
// insertion / deletion
out.push(isEqualTexts(sub1, sub2, policy) ? { ...f, inner: [] } : f);
continue;
}
if (tooBig >= MAX_BAD_LINES) {
out.push(f);
continue;
}
try {
const blocks = compareAndSplit(sub1, sub2, policy);
let line1 = f.startLine1;
let line2 = f.startLine2;
blocks.forEach((block, i) => {
// the last block ends with the fragment, whatever its last line
const last = i === blocks.length - 1;
const endLine1 = last ? f.endLine1 : line1 + block.newlines1;
const endLine2 = last ? f.endLine2 : line2 + block.newlines2;
out.push({
startLine1: line1,
endLine1,
startLine2: line2,
endLine2,
startOffset1: f.startOffset1 + block.offsets.start1,
endOffset1: f.startOffset1 + block.offsets.end1,
startOffset2: f.startOffset2 + block.offsets.start2,
endOffset2: f.startOffset2 + block.offsets.end2,
inner: block.fragments,
});
line1 = endLine1;
line2 = endLine2;
});
} catch (e) {
if (!(e instanceof DiffTooBigError)) throw e;
out.push(f);
tooBig++;
}
}
return out;
}
const adjoining = (before: LineFragment, after: LineFragment) =>
before.endLine1 === after.startLine1 &&
before.endLine2 === after.startLine2 &&
before.endOffset1 === after.startOffset1 &&
before.endOffset2 === after.startOffset2;
/** Squashes adjoining fragments and trims whitespace-only ones at their edges (processBlocks). */
export function processBlocks(
fragments: LineFragment[],
text1: string,
text2: string,
policy: ComparisonPolicy,
squash: boolean,
trim: boolean,
): LineFragment[] {
if ((!squash && !trim) || !fragments.length) return fragments;
const out: LineFragment[] = [];
let start = 0;
for (let i = 1; i <= fragments.length; i++) {
if (i < fragments.length && adjoining(fragments[i - 1]!, fragments[i]!)) continue;
out.push(...processAdjoining(fragments.slice(start, i), text1, text2, policy, squash, trim));
start = i;
}
return out;
}
function processAdjoining(
fragments: LineFragment[],
text1: string,
text2: string,
policy: ComparisonPolicy,
squash: boolean,
trim: boolean,
): LineFragment[] {
let start = 0;
let end = fragments.length;
if (trim && policy === "ignore") {
const ignorable = (f: LineFragment) =>
(f.inner !== null && f.inner.length === 0) ||
stripSpaces(text1.slice(f.startOffset1, f.endOffset1)) === stripSpaces(text2.slice(f.startOffset2, f.endOffset2));
while (start < end && ignorable(fragments[start]!)) start++;
while (start < end && ignorable(fragments[end - 1]!)) end--;
}
if (start === end) return [];
return squash ? [doSquash(fragments.slice(start, end))] : fragments.slice(start, end);
}
function doSquash(fragments: LineFragment[]): LineFragment {
if (fragments.length === 1) return fragments[0]!;
const first = fragments[0]!;
const last = fragments[fragments.length - 1]!;
const inner: Range[] = [];
for (const f of fragments) {
const shift1 = f.startOffset1 - first.startOffset1;
const shift2 = f.startOffset2 - first.startOffset2;
const own = f.inner ?? [
{ start1: 0, end1: f.endOffset1 - f.startOffset1, start2: 0, end2: f.endOffset2 - f.startOffset2 },
];
for (const r of own) {
const prev = inner[inner.length - 1];
if (prev && prev.end1 === r.start1 + shift1 && prev.end2 === r.start2 + shift2)
inner[inner.length - 1] = {
start1: prev.start1,
end1: r.end1 + shift1,
start2: prev.start2,
end2: r.end2 + shift2,
};
else
inner.push({
start1: r.start1 + shift1,
end1: r.end1 + shift1,
start2: r.start2 + shift2,
end2: r.end2 + shift2,
});
}
}
return {
startLine1: first.startLine1,
endLine1: last.endLine1,
startLine2: first.startLine2,
endLine2: last.endLine2,
startOffset1: first.startOffset1,
endOffset1: last.endOffset1,
startOffset2: first.startOffset2,
endOffset2: last.endOffset2,
inner,
};
}
-191
Переглянути файл
@@ -1,191 +0,0 @@
/**
* Changed / unchanged ranges between two sequences (IntelliJ's DiffIterable
* and DiffIterableUtil, ported; Apache-2.0, Copyright JetBrains s.r.o. and
* contributors). Changes are kept as a sorted list; "fair" iterables, whose
* unchanged ranges have equal lengths on both sides, use the same shape.
*/
import { diffKeys, isEmptyRange, range, type Range } from "./lcs";
export interface DiffIterable {
readonly length1: number;
readonly length2: number;
readonly changes: readonly Range[];
}
export const create = (changes: readonly Range[], length1: number, length2: number): DiffIterable => ({
length1,
length2,
changes,
});
/** The ranges between the changes (ChangeDiffIterableBase.UnchangedIterator). */
export function unchanged(it: DiffIterable): Range[] {
const out: Range[] = [];
let last1 = 0;
let last2 = 0;
let i = 0;
const { changes } = it;
if (changes.length && changes[0]!.start1 === 0 && changes[0]!.start2 === 0) {
last1 = changes[0]!.end1;
last2 = changes[0]!.end2;
i = 1;
}
for (; i < changes.length; i++) {
const c = changes[i]!;
out.push(range(last1, c.start1, last2, c.start2));
last1 = c.end1;
last2 = c.end2;
}
if (last1 !== it.length1 || last2 !== it.length2) out.push(range(last1, it.length1, last2, it.length2));
return out;
}
export const invert = (it: DiffIterable): DiffIterable => create(unchanged(it), it.length1, it.length2);
export const createUnchanged = (ranges: readonly Range[], length1: number, length2: number) =>
invert(create(ranges, length1, length2));
/** Both changed and unchanged ranges in order, without empty ones (DiffIterableUtil.iterateAll). */
export function iterateAll(it: DiffIterable): [Range, boolean][] {
const out: [Range, boolean][] = [];
let last1 = 0;
let last2 = 0;
for (const c of it.changes) {
const gap = range(last1, c.start1, last2, c.start2);
if (!isEmptyRange(gap)) out.push([gap, true]);
out.push([c, false]);
last1 = c.end1;
last2 = c.end2;
}
const tail = range(last1, it.length1, last2, it.length2);
if (!isEmptyRange(tail)) out.push([tail, true]);
return out;
}
/** Changes of sequences of keys compared by equality (DiffIterableUtil.diff). */
export const diffSequences = <T>(a: readonly T[], b: readonly T[]): DiffIterable =>
create(diffKeys(a, b), a.length, b.length);
/** The part of `changed` inside the given ranges, relative to their starts (SubiterableDiffIterable). */
export function subIterable(
changed: readonly Range[],
start1: number,
end1: number,
start2: number,
end2: number,
firstIndex: number,
): DiffIterable {
const out: Range[] = [];
for (let i = firstIndex; i < changed.length; i++) {
const r = changed[i]!;
if (r.end1 < start1 || r.end2 < start2) continue;
if (r.start1 > end1 || r.start2 > end2) break;
const sub = range(
Math.max(start1, r.start1) - start1,
Math.min(end1, r.end1) - start1,
Math.max(start2, r.start2) - start2,
Math.min(end2, r.end2) - start2,
);
if (!isEmptyRange(sub)) out.push(sub);
}
return create(out, end1 - start1, end2 - start2);
}
/** Collects changes from the equal ranges marked in order (DiffIterableUtil.ChangeBuilder). */
export class ChangeBuilder {
index1 = 0;
index2 = 0;
protected readonly changes: Range[] = [];
constructor(
readonly length1: number,
readonly length2: number,
) {}
markEqual(index1: number, index2: number, end1 = index1 + 1, end2 = index2 + 1) {
if (index1 === end1 && index2 === end2) return;
if (this.index1 !== index1 || this.index2 !== index2) this.addChange(this.index1, this.index2, index1, index2);
this.index1 = end1;
this.index2 = end2;
}
markEqualCount(index1: number, index2: number, count: number) {
this.markEqual(index1, index2, index1 + count, index2 + count);
}
finish(): DiffIterable {
if (this.length1 !== this.index1 || this.length2 !== this.index2) {
this.addChange(this.index1, this.index2, this.length1, this.length2);
this.index1 = this.length1;
this.index2 = this.length2;
}
return create(this.changes, this.length1, this.length2);
}
protected addChange(start1: number, start2: number, end1: number, end2: number) {
this.changes.push(range(start1, end1, start2, end2));
}
}
/** A ChangeBuilder that shrinks each change by its equal ends (ExpandChangeBuilder). */
export class ExpandChangeBuilder<T> extends ChangeBuilder {
constructor(
private readonly objects1: readonly T[],
private readonly objects2: readonly T[],
) {
super(objects1.length, objects2.length);
}
protected override addChange(start1: number, start2: number, end1: number, end2: number) {
const r = expandEqual(this.objects1, this.objects2, start1, start2, end1, end2);
if (!isEmptyRange(r)) super.addChange(r.start1, r.start2, r.end1, r.end2);
}
}
/** Shrinks `[start, end)` by the equal elements at both ends (TrimUtil.expand). */
export function expandEqual<T>(
a: ArrayLike<T>,
b: ArrayLike<T>,
start1: number,
start2: number,
end1: number,
end2: number,
): Range {
const forward = expandForward(a, b, start1, start2, end1, end2);
start1 += forward;
start2 += forward;
const backward = expandBackward(a, b, start1, start2, end1, end2);
return range(start1, end1 - backward, start2, end2 - backward);
}
export function expandForward<T>(
a: ArrayLike<T>,
b: ArrayLike<T>,
start1: number,
start2: number,
end1: number,
end2: number,
): number {
const old = start1;
while (start1 < end1 && start2 < end2 && a[start1] === b[start2]) {
start1++;
start2++;
}
return start1 - old;
}
export function expandBackward<T>(
a: ArrayLike<T>,
b: ArrayLike<T>,
start1: number,
start2: number,
end1: number,
end2: number,
): number {
const old = end1;
while (start1 < end1 && start2 < end2 && a[end1 - 1] === b[end2 - 1]) {
end1--;
end2--;
}
return old - end1;
}
-512
Переглянути файл
@@ -1,512 +0,0 @@
/**
* Longest common subsequence of two sequences, ported from the IntelliJ
* Platform (`com.intellij.util.diff`: Diff, Reindexer, MyersLCS,
* PatienceIntLCS, UniqueLCS; Apache-2.0, Copyright JetBrains s.r.o. and
* contributors): common prefix / suffix trimmed, elements unique to one side
* discarded, then Myers' O(ND) diff bounded by a threshold, falling back to
* patience diff when the sequences differ too much.
*/
/** Half-open index ranges `[start1, end1)` and `[start2, end2)`. */
export interface Range {
readonly start1: number;
readonly end1: number;
readonly start2: number;
readonly end2: number;
}
export const range = (start1: number, end1: number, start2: number, end2: number): Range => ({
start1,
end1,
start2,
end2,
});
export const isEmptyRange = (r: Range) => r.start1 === r.end1 && r.start2 === r.end2;
/** The sequences differ too much to be compared (DiffTooBigException). */
export class DiffTooBigError extends Error {
constructor() {
super("Diff is too big");
}
}
/** Thrown inside the LCS when a bounded search gives up (FilesTooBigForDiffException). */
class FilesTooBig extends Error {}
/** Changed ranges between two int sequences (Diff.buildChanges). */
export function diffInts(a: ArrayLike<number>, b: ArrayLike<number>): Range[] {
const n1 = a.length;
const n2 = b.length;
let startShift = 0;
while (startShift < Math.min(n1, n2) && a[startShift] === b[startShift]) startShift++;
let endCut = 0;
while (endCut < Math.min(n1, n2) - startShift && a[n1 - endCut - 1] === b[n2 - endCut - 1]) endCut++;
const len1 = n1 - startShift - endCut;
const len2 = n2 - startShift - endCut;
if (len1 === 0 || len2 === 0)
return len1 || len2 ? [range(startShift, startShift + len1, startShift, startShift + len2)] : [];
const ints1 = Int32Array.from({ length: len1 }, (_, i) => a[startShift + i]!);
const ints2 = Int32Array.from({ length: len2 }, (_, i) => b[startShift + i]!);
try {
return buildChanges(ints1, ints2, startShift);
} catch (e) {
if (e instanceof FilesTooBig) throw new DiffTooBigError();
throw e;
}
}
/** Changed ranges between two sequences of keys, equal keys being equal elements. */
export function diffKeys<T>(a: readonly T[], b: readonly T[]): Range[] {
const numbers = new Map<T, number>();
const enumerate = (xs: readonly T[]) =>
Int32Array.from(xs, (x) => {
let n = numbers.get(x);
if (n === undefined) numbers.set(x, (n = numbers.size + 1));
return n;
});
return diffInts(enumerate(a), enumerate(b));
}
function buildChanges(ints1: Int32Array, ints2: Int32Array, startShift: number): Range[] {
const out: Range[] = [];
let index1 = startShift;
let index2 = startShift;
const builder: LCSBuilder = {
addEqual(length) {
index1 += length;
index2 += length;
},
addChange(first, second) {
out.push(range(index1, index1 + first, index2, index2 + second));
index1 += first;
index2 += second;
},
};
const reindexer = new Reindexer();
const [discarded1, discarded2] = reindexer.discardUnique(ints1, ints2);
if (discarded1.length === 0 && discarded2.length === 0) {
builder.addChange(ints1.length, ints2.length);
return out;
}
let changes: [Uint8Array, Uint8Array];
try {
const lcs = new MyersLCS(discarded1, discarded2);
lcs.executeWithThreshold();
changes = lcs.changes;
} catch (e) {
if (!(e instanceof FilesTooBig)) throw e;
const lcs = new PatienceLCS(discarded1, discarded2);
lcs.execute(true);
changes = lcs.changes;
}
reindexer.reindex(changes, builder);
return out;
}
interface LCSBuilder {
addEqual(length: number): void;
addChange(first: number, second: number): void;
}
const fill = (bits: Uint8Array, from: number, to: number, value = 1) => {
if (to > from) bits.fill(value, from, to);
};
/** Myers' O(ND) diff with linear space (MyersLCS); `changes` marks the unmatched elements. */
class MyersLCS {
private readonly vForward: Int32Array;
private readonly vBackward: Int32Array;
constructor(
private readonly first: Int32Array,
private readonly second: Int32Array,
private readonly start1 = 0,
private readonly count1 = first.length,
private readonly start2 = 0,
private readonly count2 = second.length,
private readonly changes1: Uint8Array = new Uint8Array(first.length),
private readonly changes2: Uint8Array = new Uint8Array(second.length),
) {
fill(changes1, start1, start1 + count1);
fill(changes2, start2, start2 + count2);
this.vForward = new Int32Array(count1 + count2 + 1);
this.vBackward = new Int32Array(count1 + count2 + 1);
}
get changes(): [Uint8Array, Uint8Array] {
return [this.changes1, this.changes2];
}
/** Bounds D by A + B·√N: expected O(N) under common assumptions. */
executeLinear() {
this.run(20000 + 10 * Math.floor(Math.sqrt(this.count1 + this.count2)), false);
}
executeWithThreshold() {
this.run(Math.max(20000 + 10 * Math.floor(Math.sqrt(this.count1 + this.count2)), DELTA_THRESHOLD_SIZE), true);
}
private run(threshold: number, throwException: boolean) {
if (this.count1 === 0 || this.count2 === 0) return;
this.execute(0, this.count1, 0, this.count2, Math.min(threshold, this.count1 + this.count2), throwException);
}
// LCS(old[oldStart, oldEnd), new[newStart, newEnd))
private execute(
oldStart: number,
oldEnd: number,
newStart: number,
newEnd: number,
differenceEstimate: number,
throwException: boolean,
) {
if (!(oldStart < oldEnd && newStart < newEnd)) return;
const { vForward: VF, vBackward: VB } = this;
const oldLength = oldEnd - oldStart;
const newLength = newEnd - newStart;
VF[newLength + 1] = 0;
VB[newLength + 1] = 0;
const halfD = (differenceEstimate + 1) >> 1;
let xx = -1;
let kk = -1;
let td = -1;
loop: for (let d = 0; d <= halfD; d++) {
const L = newLength + Math.max(-d, -newLength + ((d ^ newLength) & 1));
const R = newLength + Math.min(d, oldLength - ((d ^ oldLength) & 1));
for (let k = L; k <= R; k += 2) {
let x = k === L || (k !== R && VF[k - 1]! < VF[k + 1]!) ? VF[k + 1]! : VF[k - 1]! + 1;
const y = x - k + newLength;
x += this.commonForward(oldStart + x, newStart + y, Math.min(oldEnd - oldStart - x, newEnd - newStart - y));
VF[k] = x;
}
if ((oldLength - newLength) % 2 !== 0) {
for (let k = L; k <= R; k += 2) {
if (oldLength - (d - 1) <= k && k <= oldLength + (d - 1)) {
if (VF[k]! + VB[newLength + oldLength - k]! >= oldLength) {
xx = VF[k]!;
kk = k;
td = 2 * d - 1;
break loop;
}
}
}
}
for (let k = L; k <= R; k += 2) {
let x = k === L || (k !== R && VB[k - 1]! < VB[k + 1]!) ? VB[k + 1]! : VB[k - 1]! + 1;
const y = x - k + newLength;
x += this.commonBackward(
oldEnd - 1 - x,
newEnd - 1 - y,
Math.min(oldEnd - oldStart - x, newEnd - newStart - y),
);
VB[k] = x;
}
if ((oldLength - newLength) % 2 === 0) {
for (let k = L; k <= R; k += 2) {
if (oldLength - d <= k && k <= oldLength + d) {
if (VF[oldLength + newLength - k]! + VB[k]! >= oldLength) {
xx = oldLength - VB[k]!;
kk = oldLength + newLength - k;
td = 2 * d;
break loop;
}
}
}
}
}
if (td > 1) {
const yy = xx - kk + newLength;
const oldDiff = (td + 1) >> 1;
if (0 < xx && 0 < yy) this.execute(oldStart, oldStart + xx, newStart, newStart + yy, oldDiff, throwException);
if (oldStart + xx < oldEnd && newStart + yy < newEnd)
this.execute(oldStart + xx, oldEnd, newStart + yy, newEnd, td - oldDiff, throwException);
} else if (td >= 0) {
let x = oldStart;
let y = newStart;
while (x < oldEnd && y < newEnd) {
const common = this.commonForward(x, y, Math.min(oldEnd - x, newEnd - y));
if (common > 0) {
fill(this.changes1, this.start1 + x, this.start1 + x + common, 0);
fill(this.changes2, this.start2 + y, this.start2 + y + common, 0);
x += common;
y += common;
} else if (oldEnd - oldStart > newEnd - newStart) x++;
else y++;
}
} else if (throwException) {
// The difference is more than the given estimate.
throw new FilesTooBig();
}
}
private commonForward(oldIndex: number, newIndex: number, maxLength: number): number {
let x = oldIndex;
let y = newIndex;
maxLength = Math.min(maxLength, this.count1 - oldIndex, this.count2 - newIndex);
while (x - oldIndex < maxLength && this.first[this.start1 + x] === this.second[this.start2 + y]) {
x++;
y++;
}
return x - oldIndex;
}
private commonBackward(oldIndex: number, newIndex: number, maxLength: number): number {
let x = oldIndex;
let y = newIndex;
maxLength = Math.min(maxLength, Math.min(oldIndex, newIndex) + 1);
while (oldIndex - x < maxLength && this.first[this.start1 + x] === this.second[this.start2 + y]) {
x--;
y--;
}
return oldIndex - x;
}
}
const DELTA_THRESHOLD_SIZE = 20000;
/** Patience diff (PatienceIntLCS): unique common elements anchor the match, Myers fills the gaps. */
class PatienceLCS {
private readonly changes1: Uint8Array;
private readonly changes2: Uint8Array;
constructor(
private readonly first: Int32Array,
private readonly second: Int32Array,
) {
this.changes1 = new Uint8Array(first.length);
this.changes2 = new Uint8Array(second.length);
}
get changes(): [Uint8Array, Uint8Array] {
return [this.changes1, this.changes2];
}
execute(failOnSmallReduction = false) {
this.run(0, this.first.length, 0, this.second.length, failOnSmallReduction ? 2 : -1);
}
private run(start1: number, count1: number, start2: number, count2: number, thresholdCheckCounter: number) {
if (count1 === 0 && count2 === 0) return;
if (count1 === 0 || count2 === 0) return this.addChange(start1, count1, start2, count2);
let startOffset = 0;
while (
startOffset < Math.min(count1, count2) &&
this.first[start1 + startOffset] === this.second[start2 + startOffset]
)
startOffset++;
start1 += startOffset;
start2 += startOffset;
count1 -= startOffset;
count2 -= startOffset;
let endOffset = 0;
while (
endOffset < Math.min(count1, count2) &&
this.first[start1 + count1 - endOffset - 1] === this.second[start2 + count2 - endOffset - 1]
)
endOffset++;
count1 -= endOffset;
count2 -= endOffset;
if (count1 === 0 || count2 === 0) return this.addChange(start1, count1, start2, count2);
if (thresholdCheckCounter === 0) this.checkReduction(count1, count2);
thresholdCheckCounter = Math.max(-1, thresholdCheckCounter - 1);
const matching = uniqueLCS(this.first, this.second, start1, count1, start2, count2);
if (!matching) {
if (thresholdCheckCounter >= 0) this.checkReduction(count1, count2);
new MyersLCS(
this.first,
this.second,
start1,
count1,
start2,
count2,
this.changes1,
this.changes2,
).executeLinear();
return;
}
const [m1, m2] = matching;
const matched = m1.length;
this.run(start1, m1[0]!, start2, m2[0]!, thresholdCheckCounter);
for (let i = 1; i < matched; i++) {
const s1 = m1[i - 1]! + 1;
const s2 = m2[i - 1]! + 1;
const c1 = m1[i]! - s1;
const c2 = m2[i]! - s2;
if (c1 > 0 || c2 > 0) this.run(start1 + s1, c1, start2 + s2, c2, thresholdCheckCounter);
}
let s1: number, c1: number, s2: number, c2: number;
if (m1[matched - 1] === count1 - 1) [s1, c1] = [count1 - 1, 0];
else [s1, c1] = [m1[matched - 1]! + 1, count1 - m1[matched - 1]! - 1];
if (m2[matched - 1] === count2 - 1) [s2, c2] = [count2 - 1, 0];
else [s2, c2] = [m2[matched - 1]! + 1, count2 - m2[matched - 1]! - 1];
this.run(start1 + s1, c1, start2 + s2, c2, thresholdCheckCounter);
}
private addChange(start1: number, count1: number, start2: number, count2: number) {
fill(this.changes1, start1, start1 + count1);
fill(this.changes2, start2, start2 + count2);
}
private checkReduction(count1: number, count2: number) {
if (count1 * 2 < this.first.length) return;
if (count2 * 2 < this.second.length) return;
throw new FilesTooBig();
}
}
/** Longest increasing run of the elements unique on both sides (UniqueLCS), as relative indexes; null if none. */
function uniqueLCS(
first: Int32Array,
second: Int32Array,
start1: number,
count1: number,
start2: number,
count2: number,
): [Int32Array, Int32Array] | null {
// key -> (offset1 + 1), or -1 when repeated; match: offset1 -> (offset2 + 1)
const map = new Map<number, number>();
const match = new Int32Array(count1);
for (let i = 0; i < count1; i++) {
const key = first[start1 + i]!;
const value = map.get(key) ?? 0;
if (value === -1) continue;
map.set(key, value === 0 ? i + 1 : -1);
}
let count = 0;
for (let i = 0; i < count2; i++) {
const key = second[start2 + i]!;
const value = map.get(key) ?? 0;
if (value === 0 || value === -1) continue;
if (match[value - 1] === 0) {
match[value - 1] = i + 1;
count++;
} else {
match[value - 1] = 0;
map.set(key, -1);
count--;
}
}
if (count === 0) return null;
const sequence = new Int32Array(count);
const lastElement = new Int32Array(count);
const predecessor = new Int32Array(count1);
let length = 0;
for (let i = 0; i < count1; i++) {
const m = match[i]!;
if (m === 0) continue;
// first j with sequence[j] > m (elements are distinct)
let lo = 0;
let hi = length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (sequence[mid]! < m) lo = mid + 1;
else hi = mid;
}
sequence[lo] = m;
lastElement[lo] = i;
predecessor[i] = lo > 0 ? lastElement[lo - 1]! : -1;
if (lo === length) length++;
}
const ret: [Int32Array, Int32Array] = [new Int32Array(length), new Int32Array(length)];
for (let i = length - 1, curr = lastElement[length - 1]!; curr !== -1; i--, curr = predecessor[curr]!) {
ret[0][i] = curr;
ret[1][i] = match[curr]! - 1;
}
return ret;
}
/** Drops elements that can't be matched and maps the result back (Reindexer). */
class Reindexer {
private readonly oldIndices: [Int32Array, Int32Array] = [new Int32Array(0), new Int32Array(0)];
private readonly originalLengths = [-1, -1];
private readonly discardedLengths = [-1, -1];
discardUnique(ints1: Int32Array, ints2: Int32Array): [Int32Array, Int32Array] {
const discarded1 = this.discard(ints2, ints1, 0);
return [discarded1, this.discard(discarded1, ints2, 1)];
}
private discard(needed: Int32Array, toDiscard: Int32Array, arrayIndex: 0 | 1): Int32Array {
this.originalLengths[arrayIndex] = toDiscard.length;
const present = new Set(needed);
const discarded: number[] = [];
const oldIndices: number[] = [];
for (let i = 0; i < toDiscard.length; i++) {
if (present.has(toDiscard[i]!)) {
discarded.push(toDiscard[i]!);
oldIndices.push(i);
}
}
this.oldIndices[arrayIndex] = Int32Array.from(oldIndices);
this.discardedLengths[arrayIndex] = discarded.length;
return Int32Array.from(discarded);
}
reindex(discardedChanges: [Uint8Array, Uint8Array], builder: LCSBuilder) {
const [orig1, orig2] = this.originalLengths as [number, number];
const [disc1, disc2] = this.discardedLengths as [number, number];
const [old1, old2] = this.oldIndices;
let changes1: Uint8Array;
let changes2: Uint8Array;
if (disc1 === orig1 && disc2 === orig2) {
[changes1, changes2] = discardedChanges;
} else {
changes1 = new Uint8Array(orig1);
changes2 = new Uint8Array(orig2);
const increment = (indexes: Int32Array, i: number, set: Uint8Array, length: number) => {
fill(set, indexes[i]! + 1, i + 1 < indexes.length ? indexes[i + 1]! : length);
return i + 1;
};
let x = 0;
let y = 0;
while (x < disc1 || y < disc2) {
if (x < disc1 && y < disc2 && !discardedChanges[0][x] && !discardedChanges[1][y]) {
x = increment(old1, x, changes1, orig1);
y = increment(old2, y, changes2, orig2);
} else if (discardedChanges[0][x]) {
changes1[old1[x]!] = 1;
x = increment(old1, x, changes1, orig1);
} else if (discardedChanges[1][y]) {
changes2[old2[y]!] = 1;
y = increment(old2, y, changes2, orig2);
}
}
fill(changes1, 0, disc1 === 0 ? orig1 : old1[0]!);
fill(changes2, 0, disc2 === 0 ? orig2 : old2[0]!);
}
let x = 0;
let y = 0;
while (x < orig1 && y < orig2) {
const startX = x;
while (x < orig1 && y < orig2 && !changes1[x] && !changes2[y]) {
x++;
y++;
}
if (x > startX) builder.addEqual(x - startX);
let dx = 0;
let dy = 0;
while (x < orig1 && changes1[x]) {
dx++;
x++;
}
while (y < orig2 && changes2[y]) {
dy++;
y++;
}
if (dx !== 0 || dy !== 0) builder.addChange(dx, dy);
}
if (x !== orig1 || y !== orig2) builder.addChange(orig1 - x, orig2 - y);
}
}
-128
Переглянути файл
@@ -1,128 +0,0 @@
/**
* Character classes, whitespace trimming and text equality under a
* comparison policy (IntelliJ's TrimUtil, ComparisonUtil and CharacterUtils,
* ported; Apache-2.0, Copyright JetBrains s.r.o. and contributors).
*/
import { range, type Range } from "./lcs";
export type ComparisonPolicy = "default" | "trim" | "ignore";
/** Whitespace for comparison purposes: space, tab and line break only (Strings.isWhiteSpace). */
export const isSpace = (c: string | undefined) => c === " " || c === "\t" || c === "\n";
const isSpaceCode = (c: number) => c === 32 || c === 9 || c === 10;
/** ASCII punctuation, except `_`. */
export function isPunctuation(c: number): boolean {
if (c === 95) return false;
return (c >= 33 && c <= 47) || (c >= 58 && c <= 64) || (c >= 91 && c <= 96) || (c >= 123 && c <= 126);
}
export const isWhiteSpaceCodePoint = (c: number) => c < 128 && isSpaceCode(c);
export const isAlpha = (c: number) => !isWhiteSpaceCodePoint(c) && !isPunctuation(c);
const DECIMAL_DIGIT = /\p{Nd}/u;
const IDEOGRAPHIC = /\p{Ideographic}/u;
const ALPHABETIC = /\p{Alphabetic}/u;
const SPACELESS_SCRIPT = /[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Javanese}]/u;
/** Characters that are words on their own: CJK, Thai, symbols, anything outside the BMP. */
export function isContinuousScript(c: number): boolean {
if (c < 128) return false;
const s = String.fromCodePoint(c);
if (DECIMAL_DIGIT.test(s)) return false;
if (c > 0xffff) return true;
if (IDEOGRAPHIC.test(s)) return true;
if (!ALPHABETIC.test(s)) return true;
return SPACELESS_SCRIPT.test(s);
}
export const charCount = (codePoint: number) => (codePoint >= 0x10000 ? 2 : 1);
export function trimStart(text: string, start: number, end: number): number {
while (start < end && isSpace(text[start])) start++;
return start;
}
export function trimEnd(text: string, start: number, end: number): number {
while (start < end && isSpace(text[end - 1])) end--;
return end;
}
/** Both sides of a range without their surrounding whitespace. */
export function trimRange(text1: string, text2: string, r: Range): Range {
const start1 = trimStart(text1, r.start1, r.end1);
const start2 = trimStart(text2, r.start2, r.end2);
return range(start1, trimEnd(text1, start1, r.end1), start2, trimEnd(text2, start2, r.end2));
}
/** Shrinks a range by the equal whitespace at both ends (TrimUtil.expandWhitespaces). */
export function expandWhitespaces(text1: string, text2: string, r: Range): Range {
const forward = expandWhitespacesForward(text1, text2, r.start1, r.start2, r.end1, r.end2);
const start1 = r.start1 + forward;
const start2 = r.start2 + forward;
const backward = expandWhitespacesBackward(text1, text2, start1, start2, r.end1, r.end2);
return range(start1, r.end1 - backward, start2, r.end2 - backward);
}
export function expandWhitespacesForward(
text1: string,
text2: string,
start1: number,
start2: number,
end1: number,
end2: number,
): number {
const old = start1;
while (start1 < end1 && start2 < end2 && text1[start1] === text2[start2] && isSpace(text1[start1])) {
start1++;
start2++;
}
return start1 - old;
}
export function expandWhitespacesBackward(
text1: string,
text2: string,
start1: number,
start2: number,
end1: number,
end2: number,
): number {
const old = end1;
while (start1 < end1 && start2 < end2 && text1[end1 - 1] === text2[end2 - 1] && isSpace(text1[end1 - 1])) {
end1--;
end2--;
}
return old - end1;
}
/** The text without whitespace (StringsKmp.equalsIgnoreWhitespaces compares these). */
export const stripSpaces = (s: string) => s.replace(/[ \t\n]+/g, "");
/** The text without surrounding whitespace. */
export function trimSpaces(s: string): string {
const start = trimStart(s, 0, s.length);
return s.slice(start, trimEnd(s, start, s.length));
}
/** A line's identity under a policy: equal keys are equal lines (ComparisonUtil.isEquals). */
export function lineKey(s: string, policy: ComparisonPolicy): string {
return policy === "default" ? s : policy === "trim" ? trimSpaces(s) : stripSpaces(s);
}
/** Texts equal under a policy, trimming every line for "trim" (ComparisonUtil.isEqualTexts). */
export function isEqualTexts(text1: string, text2: string, policy: ComparisonPolicy): boolean {
if (policy === "default") return text1 === text2;
if (policy === "ignore") return stripSpaces(text1) === stripSpaces(text2);
const lines1 = text1.split("\n");
const lines2 = text2.split("\n");
return lines1.length === lines2.length && lines1.every((l, i) => trimSpaces(l) === trimSpaces(lines2[i]!));
}
export const isEqualsRange = (text1: string, text2: string, r: Range) =>
text1.slice(r.start1, r.end1) === text2.slice(r.start2, r.end2);
export const isEqualsIgnoreWhitespacesRange = (text1: string, text2: string, r: Range) =>
stripSpaces(text1.slice(r.start1, r.end1)) === stripSpaces(text2.slice(r.start2, r.end2));
+1 -11
Переглянути файл
@@ -5,7 +5,7 @@
*/
import { StateEffect, StateField, type Extension, type Range } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet } from "@codemirror/view";
import { getChunks, getOriginalDoc, type Chunk, type MergeView } from "@codemirror/merge";
import { getChunks, type Chunk, type MergeView } from "@codemirror/merge";
import { iconMarkup } from "@/ui";
import { transferChunk } from "./diffOptions";
@@ -17,16 +17,6 @@ export function applyChunk(mv: MergeView, index: number, source: "a" | "b") {
dst.dispatch({ changes: transferChunk(chunk, source, src.state.doc, dst.state.doc), userEvent: "revert" });
}
/** Reverts a unified change with the same line-boundary handling as the split viewer. */
export function revertUnifiedChunk(view: EditorView, pos: number) {
const chunk = getChunks(view.state)?.chunks.find((c) => c.fromB <= pos && c.endB >= pos);
if (!chunk) return;
view.dispatch({
changes: transferChunk(chunk, "a", getOriginalDoc(view.state), view.state.doc),
userEvent: "revert",
});
}
/** A ">>" / "<<" button; the chunk index comes from the nearest `data-chunk` (itself included). */
export function arrowButton(dir: "a-to-b" | "b-to-a", run: (chunkIndex: number) => void): HTMLButtonElement {
const btn = document.createElement("button");
+135 -111
Переглянути файл
@@ -1,12 +1,10 @@
/**
* Diff viewer settings (IDEA's diff toolbar): viewer kind, whitespace policy,
* highlighting, collapsed unchanged fragments and synchronized scrolling, plus
* chunks computed by IDEA's comparison and per-chunk transfer helpers.
* the whitespace-ignoring diff algorithm and per-chunk transfer helpers.
*/
import { Change, Chunk, type DiffConfig } from "@codemirror/merge";
import type { ChangeDesc, Text } from "@codemirror/state";
import { compareTexts, type ComparisonPolicy, type LineFragment } from "./comparison";
import { DiffTooBigError } from "./comparison/lcs";
import { Change, diff, type Chunk } from "@codemirror/merge";
import type { Text } from "@codemirror/state";
export type DiffMode = "split" | "unified";
export type IgnorePolicy = "none" | "trim" | "whitespace" | "whitespaceAndLines";
@@ -84,125 +82,151 @@ export function saveDiffOptions(o: DiffViewOptions) {
}
}
const IDEA = Symbol("ideaDiff");
interface IdeaDiff {
policy: ComparisonPolicy;
words: boolean;
trimChunks: boolean;
interface Line {
/** Start offset. */
from: number;
/** End offset including the line break. */
to: number;
key: string;
}
const COMPARISON_POLICY: Record<IgnorePolicy, ComparisonPolicy> = {
none: "default",
trim: "trim",
whitespace: "ignore",
whitespaceAndLines: "ignore",
};
/**
* A MergeView `diffConfig` whose chunks come from IDEA's comparison
* (`./comparison`) instead of `@codemirror/merge`'s own diff: lines matched as
* IDEA does, word fragments by IDEA's rules, no merging of nearby changes.
*/
export function ideaDiffConfig(ignore: IgnorePolicy, highlight: HighlightPolicy): DiffConfig {
const idea: IdeaDiff = {
policy: COMPARISON_POLICY[ignore],
words: highlight === "words",
trimChunks: ignore === "whitespaceAndLines",
};
const config: DiffConfig = {};
(config as Record<symbol, IdeaDiff>)[IDEA] = idea;
return config;
function lineKey(text: string, policy: IgnorePolicy): string {
if (policy === "trim") return text.trim();
if (policy === "none") return text;
return text.replace(/\s+/g, "");
}
/** The line fragment a chunk was built from. */
const fragments = new WeakMap<Chunk, LineFragment>();
/**
* Whether the chunk has IDEA's inner fragments (its words were compared):
* such a chunk gets the lighter line background (TextDiffType "ignored"
* colour) with its `changes` in full colour.
*/
export const hasInnerFragments = (chunk: Chunk) => !!fragments.get(chunk)?.inner;
/** IDEA's line fragments as chunks; `changes` hold the inner fragments, or the whole block. */
export function ideaChunks(a: Text, b: Text, ignore: IgnorePolicy, highlight: HighlightPolicy): readonly Chunk[] {
return toChunks(a, b, ideaOf(ideaDiffConfig(ignore, highlight))!);
}
function toChunks(a: Text, b: Text, idea: IdeaDiff): readonly Chunk[] {
let compared: LineFragment[];
try {
compared = compareTexts(a.toString(), b.toString(), idea);
} catch (error) {
if (!(error instanceof DiffTooBigError)) throw error;
// Repeated lines can exhaust IDEA's search. Keep the viewer usable with a bounded, coarser diff.
return build.call(Chunk, a, b, { scanLimit: 500 });
function splitLines(s: string, policy: IgnorePolicy): Line[] {
const out: Line[] = [];
let from = 0;
for (;;) {
const nl = s.indexOf("\n", from);
const end = nl < 0 ? s.length : nl;
const key = lineKey(s.slice(from, end), policy) + (policy === "none" && nl >= 0 ? "\n" : "");
if (!(policy === "whitespaceAndLines" && key === "")) out.push({ from, to: nl < 0 ? s.length : nl + 1, key });
if (nl < 0) return out;
from = nl + 1;
}
return compared.map((f) => {
// `to` is one past the last line's end, past the document for its last line.
const toA = f.startLine1 === f.endLine1 ? f.startOffset1 : f.endLine1 === a.lines ? a.length + 1 : f.endOffset1;
const toB = f.startLine2 === f.endLine2 ? f.startOffset2 : f.endLine2 === b.lines ? b.length + 1 : f.endOffset2;
const changes = f.inner
? f.inner.map((r) => new Change(r.start1, r.end1, r.start2, r.end2))
: [new Change(0, f.endOffset1 - f.startOffset1, 0, f.endOffset2 - f.startOffset2)];
const chunk = new Chunk(changes, f.startOffset1, toA, f.startOffset2, toB);
fragments.set(chunk, f);
return chunk;
});
}
// Every chunk computation of MergeView and unifiedMergeView goes through these.
const ideaOf = (conf?: DiffConfig) => (conf as Record<symbol, IdeaDiff | undefined> | undefined)?.[IDEA];
const { build, updateA, updateB } = Chunk;
Chunk.build = (a: Text, b: Text, conf?: DiffConfig) => {
const idea = ideaOf(conf);
return idea ? toChunks(a, b, idea) : build.call(Chunk, a, b, conf);
};
Chunk.updateA = (chunks: readonly Chunk[], a: Text, b: Text, changes: ChangeDesc, conf?: DiffConfig) => {
const idea = ideaOf(conf);
return idea ? toChunks(a, b, idea) : updateA.call(Chunk, chunks, a, b, changes, conf);
};
Chunk.updateB = (chunks: readonly Chunk[], a: Text, b: Text, changes: ChangeDesc, conf?: DiffConfig) => {
const idea = ideaOf(conf);
return idea ? toChunks(a, b, idea) : updateB.call(Chunk, chunks, a, b, changes, conf);
};
/** First char code used to encode lines (skips control chars), and the surrogate gap. */
const BASE = 0x21;
/** Text of lines `[from, to)` (0-based), without the last line break. */
const linesContent = (doc: Text, from: number, to: number) => doc.sliceString(doc.line(from + 1).from, doc.line(to).to);
function encoder() {
const codes = new Map<string, string>();
let next = BASE;
return (key: string): string | null => {
let c = codes.get(key);
if (c === undefined) {
if (next === 0xd800) next = 0xe000;
if (next > 0xffff) return null;
c = String.fromCharCode(next++);
codes.set(key, c);
}
return c;
};
}
/** Bounds the expensive diff search; larger inputs fall back to a cheaper, coarser match. */
const DIFF_CONFIG = { scanLimit: 500 };
/**
* Diff of encoded lines (one char per line). Lines that occur exactly once on
* each side anchor the match (patience diff), and only the gaps between the
* anchors get a regular diff, so distant edits in long files stay separate
* without a quadratic search.
*/
function diffLines(a: string, b: string): Change[] {
const seen = new Map<string, { inA: number; inB: number; at: number }>();
for (let i = 0; i < a.length; i++) {
const e = seen.get(a[i]!);
if (e) e.inA++;
else seen.set(a[i]!, { inA: 1, inB: 0, at: i });
}
for (const c of b) {
const e = seen.get(c);
if (e) e.inB++;
}
// Unique common lines as [indexA, indexB] in A order, then their longest increasing run in B.
const pairs: [number, number][] = [];
for (let j = 0; j < b.length; j++) {
const e = seen.get(b[j]!);
if (e && e.inA === 1 && e.inB === 1) pairs.push([e.at, j]);
}
pairs.sort((x, y) => x[0] - y[0]);
const tails: number[] = [];
const prev = new Array<number>(pairs.length);
for (let i = 0; i < pairs.length; i++) {
let lo = 0;
let hi = tails.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (pairs[tails[mid]!]![1] < pairs[i]![1]) lo = mid + 1;
else hi = mid;
}
prev[i] = lo > 0 ? tails[lo - 1]! : -1;
tails[lo] = i;
}
const anchors: [number, number][] = [];
for (let i = tails.length ? tails[tails.length - 1]! : -1; i >= 0; i = prev[i]!) anchors.push(pairs[i]!);
anchors.reverse().push([a.length, b.length]);
const out: Change[] = [];
let fromA = 0;
let fromB = 0;
for (const [toA, toB] of anchors) {
if (toA > fromA || toB > fromB)
for (const c of diff(a.slice(fromA, toA), b.slice(fromB, toB), DIFF_CONFIG))
out.push(new Change(c.fromA + fromA, c.toA + fromA, c.fromB + fromB, c.toB + fromB));
fromA = toA + 1;
fromB = toB + 1;
}
return out;
}
/**
* Match lines first, then compare the contents of changed blocks for word
* highlighting. The line keys also implement the whitespace policy.
*/
export function whitespaceDiff(policy: IgnorePolicy): (a: string, b: string) => readonly Change[] {
return (a, b) => {
const la = splitLines(a, policy);
const lb = splitLines(b, policy);
const enc = encoder();
const ea: string[] = [];
const eb: string[] = [];
for (const l of la) {
const c = enc(l.key);
if (c === null) return diff(a, b, DIFF_CONFIG);
ea.push(c);
}
for (const l of lb) {
const c = enc(l.key);
if (c === null) return diff(a, b, DIFF_CONFIG);
eb.push(c);
}
const out: Change[] = [];
const at = (lines: Line[], i: number) => (i > 0 ? lines[i - 1]!.to : 0);
for (const c of diffLines(ea.join(""), eb.join(""))) {
const fromA = c.toA > c.fromA ? la[c.fromA]!.from : at(la, c.fromA);
const toA = c.toA > c.fromA ? la[c.toA - 1]!.to : fromA;
const fromB = c.toB > c.fromB ? lb[c.fromB]!.from : at(lb, c.fromB);
const toB = c.toB > c.fromB ? lb[c.toB - 1]!.to : fromB;
if (fromA === toA || fromB === toB) {
out.push(new Change(fromA, toA, fromB, toB));
continue;
}
for (const inner of diff(a.slice(fromA, toA), b.slice(fromB, toB), DIFF_CONFIG))
out.push(new Change(inner.fromA + fromA, inner.toA + fromA, inner.fromB + fromB, inner.toB + fromB));
}
return out;
};
}
/**
* The change that copies a chunk's content from one side to the other
* (IDEA's ">>" / "<<" and Revert), in the destination's coordinates. Lines are
* replaced as DiffUtil.applyModification does, so a missing final line break
* stays missing.
* (IDEA's ">>" / "<<" and Revert), in the destination's coordinates.
*/
export function transferChunk(chunk: Chunk, source: "a" | "b", src: Text, dst: Text) {
const f = fragments.get(chunk);
if (!f) return transferByOffsets(chunk, source, src, dst);
const [srcFrom, srcTo, dstFrom, dstTo] =
source === "a"
? [f.startLine1, f.endLine1, f.startLine2, f.endLine2]
: [f.startLine2, f.endLine2, f.startLine1, f.endLine1];
if (dstFrom === dstTo) {
const text = linesContent(src, srcFrom, srcTo);
return dstFrom === dst.lines
? { from: dst.length, to: dst.length, insert: "\n" + text }
: { from: dst.line(dstFrom + 1).from, to: dst.line(dstFrom + 1).from, insert: text + "\n" };
}
let from = dst.line(dstFrom + 1).from;
let to = dst.line(dstTo).to;
if (srcFrom === srcTo) {
// Lines removed with a line break: the one before them, or else the one after.
if (from > 0) from--;
else if (to < dst.length) to++;
return { from, to, insert: "" };
}
return { from, to, insert: linesContent(src, srcFrom, srcTo) };
}
/** `transferChunk` for chunks not built from line fragments. */
function transferByOffsets(chunk: Chunk, source: "a" | "b", src: Text, dst: Text) {
const [srcFrom, srcTo, dstFrom, dstTo] =
source === "a"
? [chunk.fromA, chunk.toA, chunk.fromB, chunk.toB]
+15 -5
Переглянути файл
@@ -8,7 +8,7 @@
import { RangeSetBuilder, type Extension } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
import { getChunks, type Chunk, type MergeView } from "@codemirror/merge";
import { changedLineGutters, chunkKind, type DiffKind } from "./cm";
import { changedLineGutters } from "./cm";
import { arrowButton } from "./diffControls";
type Side = "a" | "b";
@@ -91,6 +91,9 @@ export function transferY(bands: readonly Band[], y: number, from: Side): number
return m1 > m0 ? s0 + ((y - m0) * (s1 - s0)) / (m1 - m0) : s0;
}
type ChangeKind = "inserted" | "deleted" | "modified";
const kindOf = (c: Chunk): ChangeKind => (c.fromA === c.toA ? "inserted" : c.fromB === c.toB ? "deleted" : "modified");
/** The divider band between [a0, a1] on the left and [b0, b1] on the right (DiffDrawUtil.makeCurve). */
export function bandPath(w: number, a0: number, a1: number, b0: number, b1: number): string {
// An empty side is a 2px sliver on its boundary.
@@ -101,7 +104,7 @@ export function bandPath(w: number, a0: number, a1: number, b0: number, b1: numb
return `M0 ${a0}C${c1} ${a0} ${c2} ${b0} ${w} ${b0}L${w} ${b1}C${c2} ${b1} ${c1} ${a1} 0 ${a1}Z`;
}
const gapMark = (kind: DiffKind, end: boolean) =>
const gapMark = (kind: ChangeKind, end: boolean) =>
Decoration.line({ class: `cm-diffGap cm-diffGap-${kind}${end ? " cm-diffGapEnd" : ""}` });
/** A line where the other side has lines this one lacks, as in IDEA's empty-side marker. */
@@ -119,7 +122,7 @@ function gapDeco(view: EditorView): DecorationSet {
if (from < vpFrom) continue;
// Past the end of a document without a final line break: below its last line.
const line = doc.lineAt(Math.min(from, doc.length));
builder.add(line.from, line.from, gapMark(chunkKind(c), from > doc.length));
builder.add(line.from, line.from, gapMark(kindOf(c), from > doc.length));
}
return builder.finish();
}
@@ -140,6 +143,7 @@ const gapMarks = ViewPlugin.fromClass(
const SVG = "http://www.w3.org/2000/svg";
const ARROW_HEIGHT = 16;
let gradients = 0;
export interface UnalignedPanesOptions {
/** Scrolling one pane carries the other along. */
@@ -158,6 +162,7 @@ export class UnalignedPanes {
private readonly divider = document.createElement("div");
private readonly svg = document.createElementNS(SVG, "svg");
private readonly bandLayer = document.createElementNS(SVG, "g");
private readonly gradient = `cm-diffBandGradient-${++gradients}`;
private readonly arrowEls = new Map<string, HTMLButtonElement>();
/** Scroll position each pane was last moved to by the other one, to tell its echo from the user. */
private readonly moved: Record<Side, { top: number | null; left: number | null }> = {
@@ -174,6 +179,10 @@ export class UnalignedPanes {
this.extension = [gapMarks, changedLineGutters, EditorView.updateListener.of(() => this.schedule())];
this.divider.className = "cm-diffDivider";
this.svg.setAttribute("aria-hidden", "true");
this.svg.innerHTML =
`<defs><linearGradient id="${this.gradient}" x1="0" x2="1">` +
`<stop offset="0" class="cm-diffBandStopA"/><stop offset="1" class="cm-diffBandStopB"/>` +
`</linearGradient></defs>`;
this.svg.appendChild(this.bandLayer);
this.divider.appendChild(this.svg);
}
@@ -312,11 +321,12 @@ export class UnalignedPanes {
const [b0, b1] = extent(mv.b, c.fromB, c.toB).map((y) => y + offB) as [number, number];
if (a0 > h + 1 && b0 > h + 1) break;
if (a1 < -1 && b1 < -1) continue;
const kind = chunkKind(c);
const kind = kindOf(c);
const fill = kind === "modified" ? ` fill="url(#${this.gradient})"` : "";
const mid = (a0 + a1) / 2;
const midB = (b0 + b1) / 2;
paths +=
`<path class="cm-diffBand cm-diffBand-${kind}" d="${bandPath(w, a0, a1, b0, b1)}"/>` +
`<path class="cm-diffBand cm-diffBand-${kind}"${fill} d="${bandPath(w, a0, a1, b0, b1)}"/>` +
`<path class="cm-diffBandLine cm-diffBand-${kind}" d="M0 ${mid}C${w * 0.3} ${mid} ${w * 0.7} ${midB} ${w} ${midB}"/>`;
if (arrows?.toB) this.placeArrow(shown, i, "a-to-b", arrowTop(a0, a1), h);
if (arrows?.toA) this.placeArrow(shown, i, "b-to-a", arrowTop(b0, b1), h);
-19
Переглянути файл
@@ -1,19 +0,0 @@
/** Project-host ignore writes; shared by the project menu and Find Action. */
import type { IgnoreDestination } from "@/bindings";
import { call, commands } from "@/platform/ipc";
import { reloadAll } from "@/features/project-tree/store";
import { runOp } from "./ops";
import { refreshNow } from "./store";
export async function addToIgnore(paths: string[], destination: IgnoreDestination) {
if (!paths.length) return;
await runOp(
destination === "gitignore" ? "Add to .gitignore" : "Add to .git/info/exclude",
async () => {
await call(commands.vcsAddToIgnore(paths, destination));
},
{ refresh: false },
);
// Also refresh after a partial failure in a multi-repository selection.
await Promise.all([refreshNow(), reloadAll()]);
}
+1 -15
Переглянути файл
@@ -1033,7 +1033,6 @@
"Log filters": "日志筛选器",
"Long tasks": "长任务",
"Looking for references…": "正在查找引用…",
"Finding navigation target…": "正在查找跳转目标…",
"Looks for TODO and FIXME in added lines.": "在新增的行中查找 TODO 和 FIXME。",
"Macros": "宏",
"Main Menu": "主菜单",
@@ -2153,7 +2152,6 @@
"Underscored": "下划线",
"Underwaved": "波浪线",
"Undo": "撤消",
"Unread": "未读",
"Undo Commit": "撤消提交",
"Undo Commit…": "撤消提交…",
"Undo Move / Rename": "撤消移动/重命名",
@@ -3246,7 +3244,6 @@
"Also remove its worktree folder": "同时删除它的 worktree 目录",
"needs input": "等待输入",
"running": "正在运行",
"unread": "未读",
"This agent task no longer exists": "这个 Agent 任务已不存在",
"Local checkout": "当前工作区",
"Needs input": "等待输入",
@@ -4737,16 +4734,5 @@
"Add New Interpreter…": "添加新的解释器…",
"Interpreter Settings…": "解释器设置…",
"Cannot select Python interpreter": "无法选择 Python 解释器",
"Python Interpreter: {label}": "Python 解释器:{label}",
"Add to .gitignore": "添加到 .gitignore",
"Add to .git/info/exclude": "添加到 .git/info/exclude",
"Delete Agent Tasks": "删除 Agent 任务",
"Open Agent Task": "打开 Agent 任务",
"Archive Agent Tasks": "归档 Agent 任务",
"Delete {count} agent tasks? Their branches and files outside worktrees are kept.": "是否删除这 {count} 个 Agent 任务?它们的分支及 worktree 以外的文件将保留。",
"Also remove their worktree folders": "同时删除它们的 worktree 目录",
"Cannot delete agent tasks": "无法删除 Agent 任务",
"Cannot archive agent tasks": "无法归档 Agent 任务",
"Archive ({count})": "归档({count})",
"Delete ({count})…": "删除({count})…"
"Python Interpreter: {label}": "Python 解释器:{label}"
}
+1 -4
Переглянути файл
@@ -18,10 +18,7 @@ describe("remote invoke", () => {
});
it("routes served commands, keeps opening / closing local and sets global settings on both sides", () => {
const served = new Set(["vcs_add_to_ignore", "fs_read_dir", "open_project", "close_project", "settings_set"]);
expect(remoteRouting("vcs_add_to_ignore", { paths: ["/remote/file"], destination: "localExclude" }, served)).toBe(
"remote",
);
const served = new Set(["fs_read_dir", "open_project", "close_project", "settings_set"]);
expect(remoteRouting("fs_read_dir", { path: "/a" }, served)).toBe("remote");
expect(remoteRouting("window_open_settings", {}, served)).toBe("local");
expect(remoteRouting("open_project", { path: "/a" }, served)).toBe("local");
-13
Переглянути файл
@@ -73,10 +73,6 @@ html {
--gutter-modified: #375fad;
--gutter-added: #549159;
--gutter-deleted: #868a91;
/* diff viewer change types (IDEA DIFF_MODIFIED / INSERTED / DELETED) */
--diff-modified: #385570;
--diff-inserted: #294436;
--diff-deleted: #484a4a;
/* coverage (IDEA LINE_FULL / PARTIAL / NONE_COVERAGE), following the theme's status colours */
--coverage-covered: var(--gutter-added);
@@ -452,9 +448,6 @@ html {
--gutter-modified: #88adf7;
--gutter-added: #7fc784;
--gutter-deleted: #767a8a;
--diff-modified: #c2d8f2;
--diff-inserted: #bee6be;
--diff-deleted: #d6d6d6;
/* syntax (Light scheme + Default / Python defaults) */
--syn-keyword: #0033b3;
@@ -706,9 +699,6 @@ html {
--gutter-modified: #6e95e8;
--gutter-added: #6fb875;
--gutter-deleted: #a5a8ae;
--diff-modified: #000099;
--diff-inserted: #00400f;
--diff-deleted: #4d2e08;
--syn-keyword: #e8a885;
--syn-string: #8ccc94;
@@ -986,9 +976,6 @@ html {
--info: var(--palette-blue);
--vcs-modified: var(--palette-blue);
--gutter-modified: var(--palette-blue);
--diff-modified: color-mix(in srgb, var(--palette-blue) 30%, var(--palette-bg));
--diff-inserted: color-mix(in srgb, var(--palette-green) 30%, var(--palette-bg));
--diff-deleted: color-mix(in srgb, var(--palette-fg) 18%, var(--palette-bg));
--syn-link: var(--palette-blue);
--link-hover: var(--palette-cyan);
--danger: var(--palette-red);
-1
Переглянути файл
@@ -267,7 +267,6 @@ export function Tree<T>(props: TreeProps<T>) {
commitSelection(next, row.key);
} else {
const a = anchor != null ? (indexOfKey.get(anchor) ?? i) : leadIndex >= 0 ? leadIndex : i;
setAnchor(rows[a]!.key);
const [s, e] = a < i ? [a, i] : [i, a];
const next = new Set<string>();
for (let j = s; j <= e; j++) if (!rows[j]!.loading) next.add(rows[j]!.key);
-3
Переглянути файл
@@ -63,9 +63,6 @@
"--gutter-modified": "#469e98",
"--gutter-added": "#549159",
"--gutter-deleted": "#75869d",
"--diff-modified": "#2f4f63",
"--diff-inserted": "#294436",
"--diff-deleted": "#43494f",
// Shadows and window controls
"--shadow-popup": "0 6px 20px rgba(0, 0, 0, 0.45)",