Compare commits

..
Author SHA1 Message Date
l0ng-ai 59b71295b2 fix(vcs): title git HTTPS credential prompts Username / Password instead of SSH 2026-11-23 22:27:04 +08:00
Bert Verhelstandbertyhell 5eff75cab5 fix(remote): keep scratches and generated requests on the host that writes them (#5439)
In a remote (SSH/WSL) window, Generate Request in HTTP Client failed with Permission denied: the scratches folder was resolved on the desktop and its path sent to the remote host. Scratches and generated HTTP requests now live in the data directory of the host that writes them (created on demand, rechecked on later calls), and remote IPC routing is installed before session listeners run.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 22:24:23 +08:00
l0ng-ai aec1382e79 fix(agents): keep the prompt box free of scrollbars until it reaches its height limit (#5472)
After one exchange, a new session's empty prompt box showed a horizontal scrollbar and a vertical thumb (visible with always-on scrollbars): the CodeMirror scroller kept a fixed height slightly taller than its content and allowed horizontal overflow. The scroller now sizes to its wrapped text, never scrolls horizontally, and scrolls vertically only past its 280 px limit.
2026-11-23 22:02:22 +08:00
l0ng-ai 999d84b189 fix(run): resolve Java launches in attached projects (#5471)
Running or debugging a Java main class of a project attached to the window failed to compile (its Maven dependencies were missing): launch preparation used the primary project's root, build model, settings and cache. Run/Debug/test launches now resolve the owning attached project (innermost root containing the module) and use its build model, Maven reactor, settings, classpath and launch-snapshot cache; older saved configurations resolve the same way.
2026-11-23 22:01:15 +08:00
jiejie1133 9fda9b92c2 fix(editor): edit a repeated template variable from one caret (#5443)
After expanding Java `fori`, the three occurrences of `i` were all editing selections, so arrow keys moved three carets. The shared snippet engine now selects only the first occurrence of each variable and mirrors edits to the others, for every live template and language and for LSP snippets with repeated placeholders; the Java-specific handling is gone.

Co-authored-by: jiejie1133 <[email protected]>
2026-11-23 21:41:18 +08:00
fun90andfun90 261eb03009 fix(markdown): open preview links to another file at the linked heading (#5422)
Clicking a link to a heading in another file (e.g. [§5.2](b.md#52-状态机)) in the Markdown preview opened the file at the top. The destination now opens at the heading, in Preview Only and split mode, also when the file wasn't open yet (the preview scrolls once it has rendered). Markdown file-type aliases are honoured and a later link click wins over a slower earlier one.

Co-authored-by: fun90 <[email protected]>
2026-11-23 21:21:17 +08:00
l0ng-ai db8b553364 fix(editor): merge inheritance gutter markers by line and kind (#5470)
Lombok-generated members (@SuperBuilder, @Data) put one override/implemented marker per generated method on the annotation line, filling the gutter. Markers of the same kind on a line now collapse into one icon with a combined tooltip; clicking it opens the target chooser (a single target still opens directly). Applies to all four inheritance marker kinds.
2026-11-23 21:19:14 +08:00
langxpandkradme 2494b2efdf fix(libraries): reveal classes from unlisted classifier jars (#5414)
Select Opened File could not reveal a class opened from a dependency JAR that used a Maven classifier and was absent from External Libraries. The document knew its exact archive, but the Project view only searches registered archive roots.
External Libraries now adds the exact archive referenced by the active library document, labels it with its Maven coordinate when available, and removes the temporary entry once the build model lists the same archive.

Co-authored-by: kradme <[email protected]>
2026-11-23 21:13:35 +08:00
Muuandmuutot d78ce7ec66 fix(editor): offer contributed Copy Path links in the tab and library menus (#5400)
Copy Path/Reference… built a different submenu per entry point: the project view and the editor caret chooser list the contributed copy items (features/vcs: Path From Repository Root, GitHub Link), while the editor tab menu and the External Libraries menu hand-wrote theirs and silently dropped every contribution. Both hand-written submenus now append the same `copyPath` menu group, so all four entry points agree — and future contributions appear everywhere at once.

Co-authored-by: muutot <[email protected]>
2026-11-23 21:10:34 +08:00
Bert Verhelstandbertyhell 9df9499bf5 fix(project-view): open files on single click when preview tabs are enabled (#5419)
With **Settings › Editor › General › Editor Tabs › Enable preview tab** on, a single click on a file in the Project view now opens it in the preview tab, and the next single click reuses that tab. Before, the click did nothing. The cause was two switches that weren't connected. The Project view checked its own "Enable Preview Tab" view option, which was off by default and only reachable from the view's ⋮ menu. The Settings checkbox was a separate setting, `editor.tabs.previewTab`, which was only read when a preview tab was created.
IntelliJ IDEA documents these as two ways into one setting, so this PR makes them one. The Project view reads `editor.tabs.previewTab` for single click and for Autoscroll to Source. Its ⋮ › Behavior › Enable Preview Tab item and the `project.option.previewTab` action (the id is unchanged) now write that setting. The old view option is removed from the saved Project view options when they load.
What existing users will see:
- Defaults (Settings on, view option off): single click now opens a preview tab. This is the fix. The editor setting already defaulted to on, so users who never changed anything get single-click preview after this change.
- Both on: no change.
- Both off: no change.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 21:10:08 +08:00
aconeshanaandaconeshana d4b5581441 fix(ui): paste into a tree's speed search, not the view's Paste (#5401)
In the Project view, copy a keyword, press ⌘F, then ⌘V: the app reported "No files on the clipboard" and the search box stayed empty, instead of pasting the keyword the user had copied to search with.
A tree's speed search is not a text field — its query is built from printable keydowns. So `⌘V` never reached the query: the keymap dispatcher ran `project.paste` on the selected folder, and the paste event that followed bubbled to the Project view's clipboard fallback, which runs the same action again.
The shared `Tree` now claims `⌘V` while a search is active (as it already claims `⌫` since #3226) and takes the clipboard text into its query: pasted text is flattened onto one line and the search jumps to the nearest match. With the search closed, or with a clipboard that holds no text, the view's Paste runs exactly as before.
Every tree with a speed search gets this — the Project view, the Database view, the Services tree and the GitHub changes tree all render `src/ui/Tree.tsx`.

Co-authored-by: aconeshana <[email protected]>
2026-11-23 21:00:08 +08:00
Bert Verhelstandbertyhell d96060f08b fix(ui): scroll text fields while drag-selecting past their edges (#5429)
Drag-selecting in a long Find in Files query (or any text field) and moving the pointer past the field's left or right edge didn't scroll the text, so you couldn't select past what's visible. IntelliJ IDEA does scroll. WebKitGTK extends the selection in this case but never scrolls the field to follow it. Arrow keys do scroll. Now, while a drag that started in the field is past one of its edges, the field moves the selection end and the scroll position itself, faster the further out the pointer is. Once the pointer is back inside, WebKit's own selection takes over again. Both `Input` and `SearchField` get this.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:59:53 +08:00
Bert Verhelstandbertyhell 507258daec fix(editor): stop clipping Code Vision hints that are taller than 16px (#5418)
The Code Vision row above a declaration (usage count, author) cut off the top or bottom of its text, most visibly for Chinese labels like "10 个用法" / "无用法". The row was a fixed `height: 16px` with `overflow: hidden`, while its text is the editor font size minus 1px. At larger editor fonts, or with CJK fallback fonts that ink below the Latin metrics (Microsoft YaHei, Noto Sans CJK), the glyphs didn't fit.
The row now has `min-height: 16px`, and its items use `line-height: normal`, so the row grows to the ascent and descent of the fonts actually used. At the default font a Latin-only row is still exactly 16px. The line-end hint (Code Vision kinds set to "right") has the same 1em box with `overflow: hidden`. It keeps its size and position but now clips only horizontally.

Co-authored-by: bertyhell <[email protected]>
2026-11-23 20:59:37 +08:00
72 changed files with 2171 additions and 520 deletions

No files matched your search

+2 -1
View File
@@ -488,7 +488,7 @@ async fn find_java_module(call: &Call, main: &str) -> IdeResult<Option<String>>
/// (compile errors are added to `errors`). Other configurations are returned as they are.
async fn resolve_jvm_application(
call: &Call,
config: RunConfig,
mut config: RunConfig,
errors: &mut BuildErrors,
) -> IdeResult<Result<RunConfig, String>> {
if !JVM_APPLICATION_KINDS.contains(&config.kind.as_str()) {
@@ -544,6 +544,7 @@ async fn resolve_jvm_application(
(Some(exec), "java") => exec.clone(),
_ => config.command.clone(),
};
config.extras.module = Some(module);
Ok(Ok(RunConfig { command, args, ..config }))
}
+10 -5
View File
@@ -1,6 +1,6 @@
//! Maven / Gradle tool windows (the build model and its background sync) and
//! Build › Build Project (compiling with the project's build system).
mod workspace;
pub(super) mod workspace;
use super::dependencies::{MavenCentralArtifacts, MavenCentralGroups, MavenCentralVersions};
use crate::ops::Channel;
@@ -181,7 +181,7 @@ fn prepare_plan(mut plan: compile::BuildPlan, root: &Path, settings: &Settings)
/// `model` building with the Maven profiles of the last sync (`-P`), as Maven runs from
/// the tool window do.
fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
pub(super) fn with_profiles(mut model: BuildModel, cache: &Path) -> BuildModel {
let profiles = ide_build::maven_profiles(cache);
if let (Some(m), false) = (&mut model.maven, profiles.is_empty()) {
for p in &mut m.projects {
@@ -952,16 +952,18 @@ pub async fn build_run(
items: Vec::new(),
});
}
let mut launch_caches = Vec::new();
let plan = if let Some(id) = cmake {
launch_caches.push(cache.clone());
let configs = super::run::project_configs(&root, &settings, &config_dir)?;
cmake_plan(&root, kind, &configs, &id)?
} else if let Some(workspace) = ide_workspace::workspace::Workspace::load(&root)? {
let mut combined: Option<compile::BuildPlan> = None;
for member in workspace.projects.iter().filter(|p| file.as_ref().is_none_or(|f| f.starts_with(p))) {
let settings = ide_workspace::SettingsStore::load(&config_dir, Some(member)).effective();
let member_cache =
if member == &root { cache.clone() } else { cache.join(crate::project::project_key(member)) };
let member_cache = workspace::cache_at(&root, &cache, member);
let model = with_profiles(load(member, &member_cache, &settings), &member_cache);
launch_caches.push(member_cache);
let plan = prepare_plan(
compile::plan(
member,
@@ -985,6 +987,7 @@ pub async fn build_run(
plan
} else {
let model = with_profiles(load(&root, &cache, &settings), &cache);
launch_caches.push(cache.clone());
match compile::plan(
&root,
&model,
@@ -1007,7 +1010,9 @@ pub async fn build_run(
});
if kind == BuildKind::Rebuild {
// The clean removed outputs that earlier launch snapshots still hold.
launch_project.java_launch_snapshots.lock().forget_reusable_snapshots();
for cache in launch_caches {
launch_project.java_launches.for_cache(&cache).snapshots.lock().forget_reusable_snapshots();
}
}
let result = result?;
if result.success && single && kind == BuildKind::Build {
+23 -6
View File
@@ -1,12 +1,33 @@
use super::*;
use std::path::PathBuf;
pub(super) struct Scope {
pub(in crate::ops) struct Scope {
pub root: PathBuf,
pub cache: PathBuf,
pub settings: Settings,
}
pub(in crate::ops) fn scope_for(project: &Project, path: &Path) -> IdeResult<Scope> {
let workspace = ide_workspace::workspace::Workspace::load(&project.root)?;
let root = workspace
.as_ref()
.and_then(|w| w.projects.iter().filter(|p| path.starts_with(p)).max_by_key(|p| p.components().count()))
.unwrap_or(&project.root);
Ok(Scope {
cache: cache_at(&project.root, &project.build_cache_dir(), root),
settings: if root == &project.root {
project.settings.effective()
} else {
project.settings.for_project(root).effective()
},
root: root.clone(),
})
}
pub(super) fn cache_at(window_root: &Path, cache: &Path, root: &Path) -> PathBuf {
if root == window_root { cache.to_owned() } else { cache.join(crate::project::project_key(root)) }
}
pub(super) fn scopes(project: &Project, config: &Path) -> IdeResult<Vec<Scope>> {
scopes_at(&project.root, &project.build_cache_dir(), config, project.settings.effective())
}
@@ -19,11 +40,7 @@ fn scopes_at(root: &Path, cache: &Path, config: &Path, settings: Settings) -> Id
.into_iter()
.filter(|p| p.is_dir())
.map(|root| Scope {
cache: if root == window_root {
cache.to_owned()
} else {
cache.join(crate::project::project_key(&root))
},
cache: cache_at(window_root, cache, &root),
settings: ide_workspace::SettingsStore::load(config, Some(&root)).effective(),
root,
})
+10
View File
@@ -228,6 +228,15 @@ pub fn fs_create_dir(path: PathBuf) -> IdeResult<()> {
ide_vfs::create_dir(&path)
}
/// The scratch files' folder of this host (`<data dir>/scratches`), created. A remote window
/// keeps its scratches on the server, where its file commands run.
#[command(trust = always)]
pub fn fs_scratches_dir(host: &Host) -> IdeResult<ide_core::IpcPath> {
let dir = host.data_dir.join("scratches");
std::fs::create_dir_all(&dir)?;
Ok(dir.into())
}
/// Toggle Read-only Attribute: sets the writable bit (and the open document's
/// state). Returns whether the file is read-only now.
#[command(trust = always)]
@@ -383,6 +392,7 @@ ide_command::domain!(
fs_read_dir,
fs_read_text,
fs_rename,
fs_scratches_dir,
fs_set_writable,
fs_synchronize_directories,
fs_undo_delete,
+57 -62
View File
@@ -4,7 +4,7 @@ pub(crate) mod cache;
use crate::Host;
use ide_command::command;
use super::build::load;
use super::build::{load, with_profiles, workspace};
use ide_build::BuildModel;
use ide_build::compile;
use ide_core::error::ErrorKind;
@@ -46,37 +46,44 @@ pub(crate) async fn resolve_launch(
) -> IdeResult<JavaLaunchInfo> {
let started = std::time::Instant::now();
let project = host.project(window)?;
let module = project.root.join(module);
let module = ide_core::project_roots::resolve(&project.root, &module);
let scope = {
let (project, module) = (project.clone(), module.clone());
tokio::task::spawn_blocking(move || workspace::scope_for(&project, &module))
.await
.map_err(|e| IdeError::internal(e.to_string()))??
};
if !project.lsp.java_served_by_jdtls(&module) {
return resolve_launch_without_jdtls(host, &project, module, test, policy, cancel).await;
return resolve_launch_without_jdtls(host, &project, module, scope, test, policy, cancel).await;
}
let waiting = project.java_launches_waiting.add(module.clone(), test, policy);
let settings = project.settings.effective();
let scope = std::sync::Arc::new(scope);
let launches = project.java_launches.for_cache(&scope.cache);
let waiting = launches.waiting.add(module.clone(), test, policy);
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
let build = policy != BuildPolicy::NoBuild;
let full = policy == BuildPolicy::Rebuild;
let build_kind = if full { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, external, mut delegated, prefer_maven, is_maven) = {
let project = project.clone();
let settings = settings.clone();
let (model, external, mut delegated, is_maven) = {
let scope = scope.clone();
let launches = launches.clone();
let module = module.clone();
tokio::task::spawn_blocking(move || {
project.java_launch_snapshots.lock().initialize();
let model = load(&project.root, &project.build_cache_dir(), &settings);
let non_java = build && compile::launch_has_non_java_sources(&project.root, &model, &module, test);
let is_maven =
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module));
let prefer_maven = settings.languages.java.maven.delegate_build;
launches.snapshots.lock().initialize();
let root = &scope.root;
let model = load_launch_model(&scope);
let non_java = build && compile::launch_has_non_java_sources(root, &model, &module, test);
let is_maven = is_maven_module(root, &model, &module);
let delegated = build
&& delegates_to_external_build(
is_maven,
policy,
non_java,
cache::has_record(&project.root, &project.build_cache_dir(), &module),
cache::has_record(root, &scope.cache, &module),
prefer_maven,
);
let external = non_java || delegated;
(model, external, delegated, prefer_maven, is_maven)
(model, external, delegated, is_maven)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
@@ -101,7 +108,7 @@ pub(crate) async fn resolve_launch(
}
let model = std::sync::Arc::new(model);
let members = if delegated {
build_members(&project, &model, &module, test, prefer_maven, &waiting, cancel).await?
build_members(&project, &scope, &model, &module, test, &waiting, cancel).await?
} else {
Vec::new()
};
@@ -110,7 +117,8 @@ pub(crate) async fn resolve_launch(
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || {
let _external_build = external_build;
let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings);
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
// Module outputs the launch runs from a snapshot of: the originals must not come back.
let mut snapshotted = Vec::new();
// The modules of the launches sharing this build also share its classpath probe.
@@ -118,8 +126,8 @@ pub(crate) async fn resolve_launch(
std::iter::once(module.clone()).chain(members.iter().map(|m| m.module.clone())).collect();
let built = if delegated {
let rebuild_on_jdt_errors = rebuild_on_jdt_errors(policy, prefer_maven, info.error_count);
let outputs = project.java_launch_snapshots.lock().build(
&project.root,
let outputs = launches.snapshots.lock().build(
root,
&model,
&module,
cache::BuildOptions { test, policy, rebuild_on_jdt_errors, members },
@@ -132,7 +140,7 @@ pub(crate) async fn resolve_launch(
snapshotted = outputs.originals;
copies
} else if external {
let built = compile::build_for_launch(&project.root, &model, &module, test, build_kind, &cancel)?;
let built = compile::build_for_launch(root, &model, &module, test, build_kind, &cancel)?;
if let Some(failure) = built.failure {
if policy != BuildPolicy::MakeAndContinueOnErrors {
return Err(IdeError::internal(failure));
@@ -149,24 +157,15 @@ pub(crate) async fn resolve_launch(
// m2e runs inside jdtls on the server JDK and can resolve a different
// Maven profile/classifier than the module build. Ask the same Maven
// process that built the module for its runtime/test dependencies.
let maven_cp = compile::module_classpaths(
&project.root,
&model,
&probed,
test,
local_repo,
&project.build_cache_dir(),
&cancel,
);
let maven_cp = compile::module_classpaths(root, &model, &probed, test, local_repo, cache, &cancel);
merge_maven_launch_classpath(&mut class_paths, &mut info, maven_cp, &snapshotted)?;
} else {
append_unique_class_paths(&mut class_paths, std::mem::take(&mut info.class_paths));
}
info.class_paths = class_paths;
apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test);
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
if build && !delegated {
let cache_dir = project.build_cache_dir();
match compile::process_launch_resources(&project.root, &model, &cache_dir, &info.class_paths, &cancel) {
match compile::process_launch_resources(root, &model, cache, &info.class_paths, &cancel) {
Ok(tasks) if !tasks.is_empty() => tracing::info!(?tasks, "Processed launch resources with Gradle"),
Ok(_) => {}
Err(e) if e.kind == ErrorKind::Cancelled => return Err(e),
@@ -177,7 +176,7 @@ pub(crate) async fn resolve_launch(
}
}
let compile_ms = started.elapsed().as_millis() - lsp_ms;
finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir);
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
@@ -194,28 +193,36 @@ pub(crate) async fn resolve_launch(
.map_err(|e| IdeError::internal(e.to_string()))?
}
fn load_launch_model(scope: &workspace::Scope) -> BuildModel {
with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache)
}
fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module))
}
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
/// build tool compiles it, and the classpath comes from that server, else from Maven.
async fn resolve_launch_without_jdtls(
host: &Host,
project: &std::sync::Arc<crate::Project>,
module: PathBuf,
scope: workspace::Scope,
test: bool,
policy: BuildPolicy,
cancel: &CancellationToken,
) -> IdeResult<JavaLaunchInfo> {
let started = std::time::Instant::now();
let settings = project.settings.effective();
let scope = std::sync::Arc::new(scope);
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
let (model, built) = {
let (root, cache, settings, module, cancel) =
(project.root.clone(), project.build_cache_dir(), settings.clone(), module.clone(), cancel.clone());
let (scope, module, cancel) = (scope.clone(), module.clone(), cancel.clone());
tokio::task::spawn_blocking(move || {
let model = load(&root, &cache, &settings);
let model = load_launch_model(&scope);
let built = if policy == BuildPolicy::NoBuild {
None
} else {
Some(compile::build_for_launch(&root, &model, &module, test, kind, &cancel))
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel))
};
(model, built)
})
@@ -249,9 +256,9 @@ async fn resolve_launch_without_jdtls(
let build_ms = started.elapsed().as_millis();
let from_server = project.lsp.java_server_classpath(&module, test, cancel).await?;
let data_dir = host.local_data_dir.clone();
let project = project.clone();
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || {
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
match from_server {
Some(server) => {
info.project_root = server.classpath.project_root;
@@ -260,26 +267,14 @@ async fn resolve_launch_without_jdtls(
append_unique_class_paths(&mut class_paths, server.classpath.class_paths);
}
None => {
let is_maven = model
.maven
.as_ref()
.is_some_and(|m| m.projects.iter().any(|p| project.root.join(&p.dir) == module));
if !is_maven {
if !is_maven_module(root, &model, &module) {
return Err(IdeError::unavailable(
"Cannot resolve the classpath: the Java language server does not report it \
(java-analyzer/projectClasspath), and the module is not a Maven project",
));
}
let local_repo = ide_sdk::apply::maven_local_repository(&project.root, &settings);
let classpath = compile::module_classpath(
&project.root,
&model,
&module,
test,
local_repo,
&project.build_cache_dir(),
&cancel,
)?;
let local_repo = ide_sdk::apply::maven_local_repository(root, settings);
let classpath = compile::module_classpath(root, &model, &module, test, local_repo, cache, &cancel)?;
append_unique_class_paths(
&mut class_paths,
std::env::split_paths(&classpath).map(|p| p.to_string_lossy().into_owned()),
@@ -287,8 +282,8 @@ async fn resolve_launch_without_jdtls(
}
}
info.class_paths = class_paths;
apply_library_classpath(&mut info, &project.root, &settings.project_structure.libraries, test);
finish_launch(&mut info, &project.root, &module, &settings, &model, &data_dir);
apply_library_classpath(&mut info, root, &settings.project_structure.libraries, test);
finish_launch(&mut info, root, &module, settings, &model, &data_dir);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
@@ -445,10 +440,10 @@ fn apply_library_classpath(
/// whether its JDT errors call for a clean rebuild (as its own launch would decide).
async fn build_members(
project: &std::sync::Arc<crate::Project>,
scope: &std::sync::Arc<workspace::Scope>,
model: &std::sync::Arc<BuildModel>,
module: &Path,
test: bool,
prefer_maven: bool,
waiting: &cache::WaitingGuard,
cancel: &CancellationToken,
) -> IdeResult<Vec<cache::Member>> {
@@ -456,10 +451,11 @@ async fn build_members(
if others.is_empty() {
return Ok(Vec::new());
}
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
let joining = {
let (project, model, module) = (project.clone(), model.clone(), module.to_path_buf());
let (scope, model, module) = (scope.clone(), model.clone(), module.to_path_buf());
tokio::task::spawn_blocking(move || {
joining_launches(&project.root, &project.build_cache_dir(), &model, &module, test, others, prefer_maven)
joining_launches(&scope.root, &scope.cache, &model, &module, test, others, prefer_maven)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
@@ -500,8 +496,7 @@ fn joining_launches(
others
.into_iter()
.filter(|o| {
let is_maven =
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == o.module));
let is_maven = is_maven_module(root, model, &o.module);
o.test == test
&& matches!(o.policy, BuildPolicy::Automatic | BuildPolicy::Make)
&& compile::launch_reactor(root, model, &o.module).as_ref() == Some(&reactor)
+24
View File
@@ -64,6 +64,30 @@ pub(super) struct Member {
pub rebuild_on_jdt_errors: bool,
}
/// Launches share a build only within the same workspace project's cache.
#[derive(Default)]
pub(crate) struct Sessions(Mutex<HashMap<PathBuf, Arc<Launches>>>);
pub(in crate::ops) struct Launches {
pub waiting: Waiting,
pub snapshots: Mutex<Session>,
}
impl Sessions {
pub(in crate::ops) fn for_cache(&self, cache: &Path) -> Arc<Launches> {
self.0
.lock()
.entry(cache.to_owned())
.or_insert_with(|| {
Arc::new(Launches {
waiting: Waiting::default(),
snapshots: Mutex::new(Session::new(cache.to_owned())),
})
})
.clone()
}
}
/// Java launches from their start until their build: one launch's Maven run also builds
/// the modules of launches still waiting (configurations started together, #3971).
#[derive(Default)]
+4 -1
View File
@@ -242,7 +242,10 @@ fn settings_only(
.cloned()
});
if workspace.as_ref().is_some_and(|w| w.is_container(&project.root)) || member.is_some() {
if config.extras.module.is_none() && !matches!(config.kind.as_str(), "application" | "spring-boot") {
let jvm = matches!(config.kind.as_str(), "application" | "spring-boot");
if jvm && member.is_some() && config.cwd.is_none() {
config.cwd = Some(owner.into());
} else if config.extras.module.is_none() && !jvm {
config.extras.module = config.cwd.as_deref().map(ide_core::ipc_path::to_ipc);
}
ide_run::scope::rebase(config, &project.root, None);
+4 -12
View File
@@ -51,10 +51,8 @@ pub struct Project {
pub(crate) member_excludes: MemberExcludes,
/// Per-project cache directory (build tool sync results…).
pub cache_dir: PathBuf,
/// Superseded launch snapshots retained until this project session ends.
pub(crate) java_launch_snapshots: Mutex<crate::ops::java::cache::Session>,
/// Java launches waiting for their build, which can share one Maven run.
pub(crate) java_launches_waiting: crate::ops::java::cache::Waiting,
/// Pending launches and retained snapshots, scoped to each workspace project.
pub(crate) java_launches: crate::ops::java::cache::Sessions,
/// Reasons this window was already told why Kotlin is debugged with kotlin-debug-adapter.
pub(crate) kotlin_debug_notices: Mutex<HashSet<&'static str>>,
/// Database tool window: data sources and their connections.
@@ -641,10 +639,7 @@ impl Host {
detected_roots,
member_excludes,
cache_dir: self.local_data_dir.join("cache").join(&project_key),
java_launch_snapshots: Mutex::new(crate::ops::java::cache::Session::new(
self.local_data_dir.join("cache").join(&project_key).join("build"),
)),
java_launches_waiting: Default::default(),
java_launches: Default::default(),
kotlin_debug_notices: Mutex::default(),
db,
http_history,
@@ -891,10 +886,7 @@ impl Host {
detected_roots: Arc::default(),
member_excludes: Arc::default(),
cache_dir: self.local_data_dir.join("cache").join(&project_key),
java_launch_snapshots: Mutex::new(crate::ops::java::cache::Session::new(
self.local_data_dir.join("cache").join(&project_key).join("build"),
)),
java_launches_waiting: Default::default(),
java_launches: Default::default(),
kotlin_debug_notices: Mutex::default(),
db,
http_history,
+7
View File
@@ -74,6 +74,13 @@ async fn serves_projects_files_documents_search_and_runs() {
let info: ServerInfo = peer.request("initialize", json!({ "version": rpc::PROTOCOL_VERSION }), None).await.unwrap();
assert_eq!(info.protocol, rpc::PROTOCOL_VERSION);
let scratch_path = base.join("data/scratches");
assert!(!scratch_path.exists());
let expected = serde_json::to_value(ide_core::IpcPath::from(scratch_path.clone())).unwrap();
assert_eq!(invoke(&peer, "fs_scratches_dir", json!({})).await.unwrap(), expected);
assert!(scratch_path.is_dir());
assert_eq!(invoke(&peer, "fs_scratches_dir", json!({})).await.unwrap(), expected);
let opened = invoke(&peer, "open_project", json!({ "path": project })).await.unwrap();
assert_eq!(opened["name"], "demo");
assert_eq!(opened["trusted"], false);
+101
View File
@@ -6,6 +6,107 @@ use std::{
time::Duration,
};
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn java_launch_builds_the_owning_workspace_reactor() {
use ide_run::BuildPolicy;
use ide_workspace::{SettingsStore, settings::SettingsScope};
use std::{fs, os::unix::fs::PermissionsExt};
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let config_dir = base.join("config");
let primary = base.join("primary");
let sibling = base.join("spring");
let nested = primary.join("nested");
let roots = [&primary, &sibling, &nested];
for (i, root) in roots.into_iter().enumerate() {
fs::create_dir_all(root.join("app")).unwrap();
fs::write(
root.join("pom.xml"),
format!("<project><groupId>demo</groupId><artifactId>reactor-{i}</artifactId><version>1</version><packaging>pom</packaging><modules><module>app</module></modules></project>"),
)
.unwrap();
fs::write(
root.join("app/pom.xml"),
format!("<project><parent><groupId>demo</groupId><artifactId>reactor-{i}</artifactId><version>1</version></parent><artifactId>app</artifactId></project>"),
)
.unwrap();
let wrapper = root.join("mvnw");
fs::write(
&wrapper,
r#"#!/bin/sh
set -eu
printf '%s\n' "$*" >> calls
mkdir -p app/target/classes
case " $* " in *" test-compile "*) mkdir -p app/target/test-classes;; esac
scope=runtime
for arg in "$@"; do
case "$arg" in
-Dmdep.includeScope=*) scope="${arg#*=}";;
esac
done
for arg in "$@"; do
case "$arg" in
-Dmdep.outputFile=*)
touch "app/$scope.jar"
printf '%s\n' "$PWD/app/$scope.jar" > "app/${arg#*=}";;
esac
done
"#,
)
.unwrap();
fs::set_permissions(wrapper, fs::Permissions::from_mode(0o755)).unwrap();
SettingsStore::load(&config_dir, Some(root))
.set(
SettingsScope::Project,
"languages.java.maven.activeProfiles",
serde_json::json!(format!("member-{i}")),
)
.unwrap();
}
// Exercise the build-tool classpath fallback without starting an installed server.
let global = SettingsStore::load(&config_dir, None);
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
global
.set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false))
.unwrap();
}
let host = Host::new(HostConfig {
config_dir,
data_dir: base.join("data"),
local_data_dir: base.join("data"),
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
syntax: Arc::default(),
sink_for: Box::new(|_| Arc::new(NullSink)),
owner: |w| w,
runtime: tokio::runtime::Handle::current(),
project_environment: false,
});
for root in roots {
host.trust.decide(root, true, false).unwrap();
}
host.open_project("main", &primary).unwrap();
for root in [&sibling, &nested] {
ops::project::attach_workspace(&host, "main", root).unwrap();
}
for (index, root) in roots.into_iter().enumerate() {
let module = if root == &sibling { root.join("app") } else { root.strip_prefix(&primary).unwrap().join("app") };
let test = index != 0;
let info = ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next())
.await
.unwrap();
let out = root.join("app/target").join(if test { "test-classes" } else { "classes" });
let jar = root.join("app").join(if test { "test.jar" } else { "runtime.jar" });
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == out));
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == jar));
let calls = fs::read_to_string(root.join("calls")).unwrap();
assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}");
assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}");
assert!(calls.contains("dependency:build-classpath"), "{calls}");
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn linked_projects_share_navigation_but_keep_files_repositories_and_run_directories() {
let temp = tempfile::tempdir().unwrap();
+57
View File
@@ -131,3 +131,60 @@ for (const home of [false, true]) {
}
}
}
test("short prompts fit before and after a completed agent exchange", async ({ workbench: page }) => {
await prepare(page, true, false);
const box = page.getByRole("textbox", { name: "Message", exact: true }).filter({ visible: true });
const scroller = page.locator(".cm-scroller").filter({ has: box });
const overflow = () =>
scroller.evaluate((el) => ({
x: el.scrollWidth - el.clientWidth,
y: el.scrollHeight - el.clientHeight,
}));
await expect(box.locator(".cm-placeholder")).toBeVisible();
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await box.fill("Reply with OK.");
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await page.getByRole("button", { name: "Start", exact: true }).click();
await expect(page.locator("html")).toHaveAttribute("data-submitted-prompt", /Reply with OK/);
await page.evaluate(() => document.dispatchEvent(new Event("test:agent-ack")));
await expect(page.getByRole("tab", { name: task.title })).toBeVisible();
await page.evaluate(async (id) => {
const storePath = "/src/features/agents/store.ts";
const { useAgents } = await import(storePath);
useAgents.setState({
entries: new Map([
[
id,
[
{ type: "user", text: "Reply with OK.", attachments: [] },
{ type: "agent", text: "OK" },
],
],
]),
});
}, task.id);
await expect(page.getByText("OK", { exact: true })).toBeVisible();
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await page.getByRole("button", { name: "Agents", exact: true }).click();
await page.getByRole("button", { name: "New Agent Task", exact: true }).click();
await expect(box.locator(".cm-placeholder")).toBeVisible();
await expect(scroller).toHaveCSS("overflow-x", "hidden");
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await box.fill("Short draft");
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
await box.fill("word".repeat(2000));
await expect(scroller).toHaveCSS("overflow-y", "auto");
await expect
.poll(async () => {
const { x, y } = await overflow();
return x === 0 && y > 0;
})
.toBe(true);
await box.fill("");
await expect(box.locator(".cm-placeholder")).toBeVisible();
await expect.poll(overflow).toEqual({ x: 0, y: 0 });
});
+52
View File
@@ -0,0 +1,52 @@
import type { Locator, Page } from "@playwright/test";
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
/** Opens the sample with the server's lenses `titles` above its first line, at editor font `fontSize`. */
async function lensRow(page: Page, fontSize: number, titles: string[]): Promise<{ editor: Locator; row: Locator }> {
const editor = await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate(
async ({ fontSize, titles }) => {
const projectPath = "/src/platform/project.ts";
const { useProject } = await import(/* @vite-ignore */ projectPath);
const settings = useProject.getState().settings;
useProject.setState({ settings: { ...settings, editor: { ...settings?.editor, fontSize } } });
const at = { line: 0, col: 0 };
window.__ipc.handlers.lsp_code_lens = () =>
titles.map((title) => ({ range: { start: at, end: at }, command: { title, command: "noop", arguments: [] } }));
},
{ fontSize, titles },
);
// An edit asks the server for its lenses again.
await editor.locator(".cm-line").first().click();
await page.keyboard.press("End");
await page.keyboard.type(" ");
const row = editor.locator(".cm-openidea-lens");
await expect(row).toContainText(titles[0]!);
return { editor, row };
}
test("a Code Vision row fits CJK hints at a large editor font", async ({ workbench: page }) => {
const { editor, row } = await lensRow(page, 20, ["10 个用法", "无用法"]);
const overflow = await row.evaluate((el) => {
const box = el.getBoundingClientRect();
return [...el.querySelectorAll(".cm-openidea-lensItem")].map((item) => {
const range = document.createRange();
range.selectNodeContents(item);
const text = range.getBoundingClientRect();
return Math.max(box.top - text.top, text.bottom - box.bottom);
});
});
expect(overflow).toHaveLength(2);
for (const px of overflow) expect(px).toBeLessThanOrEqual(0);
// The editor measured the taller row: the lines below it still sit beside their numbers.
const line = editor.locator(".cm-line", { hasText: "class OrderController" });
const number = editor.locator(".cm-lineNumbers .cm-gutterElement", { hasText: /^8$/ });
const [lineTop, numberTop] = [(await line.boundingBox())!.y, (await number.boundingBox())!.y];
expect(Math.abs(lineTop - numberTop)).toBeLessThanOrEqual(1);
});
test("a Code Vision row keeps its height at the default editor font", async ({ workbench: page }) => {
const { row } = await lensRow(page, 13, ["3 usages"]);
expect((await row.boundingBox())!.height).toBe(16);
});
+39
View File
@@ -487,6 +487,45 @@ test("Markdown preview highlights ⌘F matches, selected words and scales diagra
expect(reset.excalidraw).toBeCloseTo(base.excalidraw, 1);
});
for (const mode of ["Preview Only", "Editor and Preview"]) {
test(`Markdown ${mode} reveals a cross-file heading on first open`, async ({ workbench: page }) => {
const path = "/dev/acme-api/linked-heading.md";
const heading = "5.2 状态机";
const spacer = Array.from({ length: 80 }, (_, i) => `Paragraph ${i}.`).join("\n\n");
const target = `# Destination\n\n${spacer}\n\n## ${heading}\n\n${spacer}`;
const editor = await openFromTree(page, "README.md");
await page.evaluate(
async ({ path, target }) => {
const backendModule = "/src/editor/core/backend.ts";
const routeModule = "/src/platform/tauriCore.ts";
const { docBackend } = await import(/* @vite-ignore */ backendModule);
const { setInvokeRoute } = await import(/* @vite-ignore */ routeModule);
docBackend().files.set(path, target);
setInvokeRoute((cmd: string, args?: Record<string, unknown>) =>
cmd === "fs_read_text" && args?.path === path ? Promise.resolve(target) : null,
);
},
{ path, target },
);
await editor.locator(".cm-content").focus();
await page.keyboard.press("Meta+a");
await page.keyboard.insertText("[Linked heading](linked-heading.md#52-%E7%8A%B6%E6%80%81%E6%9C%BA)");
if (mode === "Preview Only") await page.getByRole("button", { name: mode, exact: true }).click();
const destinationTab = page.getByRole("tab", { name: "linked-heading.md", exact: true });
const preview = page.getByRole("document", { name: "Markdown preview" });
await expect(destinationTab).toHaveCount(0);
await preview.getByRole("link", { name: "Linked heading" }).click();
await expect(destinationTab).toHaveAttribute("aria-selected", "true");
await expect(page.getByRole("button", { name: mode, exact: true })).toHaveAttribute("aria-pressed", "true");
await expect(preview.getByRole("heading", { name: heading })).toBeInViewport({ ratio: 1 });
if (mode === "Editor and Preview") {
await expect(editor.locator(".cm-line", { hasText: heading })).toBeInViewport({ ratio: 1 });
}
});
}
test("Markdown preview keeps following find and edits after scrolling the source", async ({ workbench: page }) => {
const editor = await openFromTree(page, "README.md");
const content = editor.locator(".cm-content");
+9
View File
@@ -37,6 +37,15 @@ test("type-ahead jumps to a matching node", async ({ workbench: page }) => {
await expect(tree.locator('[role="treeitem"][aria-selected="true"]')).toHaveText("README.md");
});
test("a single click shows the file in the preview tab, which the next one reuses", async ({ workbench: page }) => {
const tabs = page.getByRole("tablist", { name: "Editor tabs" });
await page.getByRole("treeitem", { name: "README.md", exact: true }).click();
await expect(tabs.getByRole("tab", { name: "README.md" })).toBeVisible();
await page.getByRole("treeitem", { name: "settings.gradle.kts", exact: true }).click();
await expect(tabs.getByRole("tab", { name: "settings.gradle.kts" })).toBeVisible();
await expect(tabs.getByRole("tab", { name: "README.md" })).toHaveCount(0);
});
test("Rename targets a file or folder directly from its context menu", async ({ workbench: page }) => {
await page.setViewportSize({ width: 720, height: 480 });
const menu = page.getByRole("menu", { name: "Context menu" });
+1 -2
View File
@@ -12,9 +12,8 @@ test("the scratch language chooser fits short windows and keeps recents separate
const { setScratchBackend } = await import(/* @vite-ignore */ scratch);
const { rememberLanguage } = await import(/* @vite-ignore */ store);
setScratchBackend({
dataDir: async () => "/test-app-data",
scratchesDir: async () => "/test-app-data/scratches",
listNames: async () => [],
createDir: async () => {},
createFile: async () => {},
languages: async () => [
...Array.from({ length: 24 }, (_, i) => {
+1
View File
@@ -286,6 +286,7 @@ fs_read_range always project_host bin
fs_read_text always project_host bindings async
fs_rename always project_host bindings async
fs_resolve_reference always project_host bindings async
fs_scratches_dir always project_host bindings sync
fs_set_writable always project_host bindings sync
fs_synchronize_directories always project_host bindings async
fs_undo_delete always project_host bindings async
+5
View File
@@ -707,6 +707,11 @@ export const commands = {
fsRename: (from: string, to: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_rename", { from, to })),
/** The existing file or directory a path written in `from` names (`href`, `url()`, a string literal). */
fsResolveReference: (from: IpcPath, value: string) => typedError<string | null, IdeError>(__TAURI_INVOKE("fs_resolve_reference", { from, value })),
/**
* The scratch files' folder of this host (`<data dir>/scratches`), created. A remote window
* keeps its scratches on the server, where its file commands run.
*/
fsScratchesDir: () => typedError<IpcPath, IdeError>(__TAURI_INVOKE("fs_scratches_dir")),
/**
* Toggle Read-only Attribute: sets the writable bit (and the open document's
* state). Returns whether the file is read-only now.
+10 -2
View File
@@ -238,11 +238,13 @@ function buildDecorations(state: EditorState): DecorationSet {
const lensTheme = EditorView.theme({
// IDEA paints code vision with the colour scheme's Inline hints attribute.
// At least 16px, and taller when the hint font needs it: the row grows with its items, so a
// large editor font or a fallback font that inks below the baseline (CJK) is never cut off.
".cm-openidea-lens": {
display: "flex",
alignItems: "center",
gap: "12px",
height: "16px",
minHeight: "16px",
color: "var(--fg-inlay, var(--fg-muted))",
WebkitUserSelect: "none",
userSelect: "none",
@@ -276,7 +278,10 @@ const lensTheme = EditorView.theme({
// Pinned to the line, the hint may run past the editor's edge (IDEA clips it there); cap it so a
// long one cannot stretch across the whole window first.
maxWidth: "min(60ch, 50vw)",
overflow: "hidden",
// The box is 1em tall (the anchor's `lineHeight: 1`): clip only past the side, so a glyph that
// inks above or below its em box (CJK fallback fonts) still shows whole.
overflowX: "clip",
overflowY: "visible",
pointerEvents: "auto",
},
".cm-openidea-lensItem": {
@@ -293,6 +298,9 @@ const lensTheme = EditorView.theme({
fontFamily: "var(--font-ui)",
fontSize: "calc(1em - 1px)",
},
// The row's items size to the fonts their text is drawn with (fallback fonts included), not to the
// editor's line height, which `font: inherit` brings along.
".cm-openidea-lens > .cm-openidea-lensItem": { lineHeight: "normal" },
".cm-openidea-lensAction": { cursor: "pointer" },
".cm-openidea-lensAction:hover": { color: "var(--accent)", textDecoration: "underline" },
".cm-openidea-lensIcon-run": { color: "var(--success)" },
+82
View File
@@ -0,0 +1,82 @@
import { afterEach, describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView, runScopeHandlers } from "@codemirror/view";
import { applySnippet, hasLinkedSnippetField } from "./linkedSnippet";
let view: EditorView;
afterEach(() => view.destroy());
function expand(snippet: string) {
view = new EditorView({
state: EditorState.create({ extensions: [EditorState.allowMultipleSelections.of(true)] }),
parent: document.body,
});
applySnippet(view, [{ from: 0, to: 0, snippet }]);
}
const selected = () => view.state.selection.ranges.map(({ from, to }) => view.state.sliceDoc(from, to));
const doc = () => view.state.doc.toString();
const type = (text: string) => view.dispatch(view.state.replaceSelection(text));
const press = (key: string) => runScopeHandlers(view, new KeyboardEvent("keydown", { key }), "editor");
describe("linked snippets", () => {
it("selects the first occurrence of each variable and mirrors edits within its group", () => {
expand("${1:x}/${1:x} ${2:y}/${2:y}${0}");
expect(selected()).toEqual(["x"]);
expect(view.state.selection.main.from).toBe(0);
type("name");
expect(doc()).toBe("name/name y/y");
expect(press("Tab")).toBe(true);
expect(selected()).toEqual(["y"]);
expect(view.state.selection.main.from).toBe("name/name ".length);
type("label");
expect(doc()).toBe("name/name label/label");
});
it("tracks adjacent empty occurrences and the next variable independently", () => {
expand("${1}${1}${2:end}${0}");
expect(selected()).toEqual([""]);
type("x");
type("y");
expect(doc()).toBe("xyxyend");
expect(press("Tab")).toBe(true);
expect(selected()).toEqual(["end"]);
type("!");
expect(doc()).toBe("xyxy!");
});
it.each(["Escape", "Tab"])("ends mirroring on %s", (key) => {
expand("${1:x}/${1:x}${0}");
if (key === "Escape") {
expect(press(key)).toBe(true);
expect(hasLinkedSnippetField(view.state, 1)).toBe(true);
}
expect(press(key)).toBe(true);
expect(hasLinkedSnippetField(view.state, 1)).toBe(false);
const { head } = view.state.selection.main;
expect(head).toBe(key === "Escape" ? 1 : doc().length);
view.dispatch({ changes: { from: 0, to: 1, insert: "changed" } });
expect(doc()).toBe("changed/x");
});
it("keeps a repeated last placeholder active until the end of the snippet", () => {
expand("${1:one} ${2:two}/${2:two}");
expect(press("Tab")).toBe(true);
expect(selected()).toEqual(["two"]);
type("new");
expect(doc()).toBe("one new/new");
expect(press("Tab")).toBe(true);
expect(view.state.selection.main.head).toBe(doc().length);
});
it("keeps fields linked after a separate edit before the snippet", () => {
expand("call(${1:arg}, ${1:arg})${0}");
const prefix = "import call;\n";
view.dispatch({ changes: { from: 0, insert: prefix }, userEvent: "input.complete" });
expect(selected()).toEqual(["arg"]);
type("value");
expect(doc()).toBe(prefix + "call(value, value)");
expect(press("Tab")).toBe(true);
expect(view.state.selection.main.head).toBe(doc().length);
});
});
+346
View File
@@ -0,0 +1,346 @@
import {
clearSnippet,
closeCompletion,
completionStatus,
pickedCompletion,
snippet,
type Completion,
} from "@codemirror/autocomplete";
import { isolateHistory } from "@codemirror/commands";
import { indentUnit } from "@codemirror/language";
import {
ChangeSet,
EditorSelection,
EditorState,
MapMode,
Prec,
StateEffect,
StateField,
Text,
type ChangeSpec,
type Transaction,
} from "@codemirror/state";
import { Decoration, EditorView, keymap, WidgetType, type Command } from "@codemirror/view";
import { isExternalChange } from "@/editor/api";
interface SnippetSite {
from: number;
to: number;
snippet: string;
}
interface SnippetRange {
from: number;
to: number;
field: number;
}
interface Segment extends SnippetRange {
site: number;
primary: boolean;
}
interface ActiveSnippet {
segments: readonly Segment[];
active: number;
last: number;
mainSite: number;
completion: boolean;
}
const setSnippet = StateEffect.define<ActiveSnippet | null>();
const fieldMark = Decoration.mark({ class: "cm-snippetField" });
const fieldCursor = Decoration.widget({
widget: new (class extends WidgetType {
toDOM() {
const span = document.createElement("span");
span.className = "cm-snippetFieldPosition";
return span;
}
ignoreEvent() {
return false;
}
})(),
});
function primarySegments(value: ActiveSnippet, field = value.active) {
return value.segments.filter((segment) => segment.field === field && segment.primary);
}
function contains(range: SnippetRange, from: number, to: number): boolean {
return range.from <= from && to <= range.to;
}
function selectionInField(value: ActiveSnippet, selection: EditorSelection): boolean {
const primaries = primarySegments(value);
return selection.ranges.every(({ from, to }) => primaries.some((segment) => contains(segment, from, to)));
}
const fields = StateField.define<ActiveSnippet | null>({
create: () => null,
update(value, tr) {
const next = tr.effects.find((effect) => effect.is(setSnippet));
if (next) return next.value;
if (!value) return null;
if (tr.docChanged) {
const segments: Segment[] = [];
for (const segment of value.segments) {
const from = tr.changes.mapPos(segment.from, -1, MapMode.TrackDel);
const to = tr.changes.mapPos(segment.to, 1, MapMode.TrackDel);
if (from === null || to === null || from < (segments.at(-1)?.to ?? 0)) return null;
segments.push({ ...segment, from, to });
}
value = { ...value, segments };
}
return tr.selection && !selectionInField(value, tr.selection) ? null : value;
},
provide: (field) =>
EditorView.decorations.from(field, (value) =>
value
? Decoration.set(
value.segments.map(({ from, to }) => (from === to ? fieldCursor : fieldMark).range(from, to)),
true,
)
: Decoration.none,
),
});
// Keep the edit and its mirrors in one history entry.
const mirrorEdits = EditorState.transactionFilter.of((tr) => {
const value = tr.startState.field(fields, false);
if (
!value ||
!tr.docChanged ||
isExternalChange(tr) ||
tr.isUserEvent("undo") ||
tr.isUserEvent("redo") ||
tr.effects.some((effect) => effect.is(setSnippet))
)
return tr;
const primaries = primarySegments(value);
const edited = new Map<Segment, number>();
let outside = false;
let touchesOtherSegment = false;
tr.changes.iterChangedRanges((from, to, newFrom, newTo) => {
const segment = primaries.find((range) => contains(range, from, to));
if (segment) edited.set(segment, (edited.get(segment) ?? 0) + (newTo - newFrom) - (to - from));
else {
outside = true;
touchesOtherSegment ||= value.segments.some((range) => from <= range.to && to >= range.from);
}
}, true);
if (outside) return edited.size || touchesOtherSegment ? [tr, { effects: setSnippet.of(null) }] : tr;
const changes: ChangeSpec[] = [];
const replacements = new Map<number, Text>();
let typedOffset = 0;
let mirrorOffset = 0;
// Map in source order so neighboring stops keep their own boundaries even when they touch.
const segments = value.segments.map((segment) => {
const start = segment.from + typedOffset;
const from = start + mirrorOffset;
let length = segment.to - segment.from;
const delta = edited.get(segment);
if (delta !== undefined) {
length += delta;
replacements.set(segment.site, tr.newDoc.slice(start, start + length));
typedOffset += delta;
} else if (segment.field === value.active && !segment.primary) {
const insert = replacements.get(segment.site);
if (insert && !insert.eq(tr.newDoc.slice(start, start + length))) {
changes.push({ from: start, to: start + length, insert });
mirrorOffset += insert.length - length;
length = insert.length;
}
}
return { ...segment, from, to: from + length };
});
const mirrors = ChangeSet.of(changes, tr.newDoc.length);
const next = { ...value, segments };
const staysInField = selectionInField(next, tr.newSelection.map(mirrors));
return [tr, { changes: mirrors, effects: setSnippet.of(staysInField ? next : null), sequential: true }];
});
function clearLinkedSnippet(view: EditorView): boolean {
if (!view.state.field(fields, false)) return false;
view.dispatch({ effects: setSnippet.of(null) });
return true;
}
export const escapeSnippet: Command = (view) => {
const sel = view.state.selection;
if (sel.ranges.some((r) => !r.empty)) {
closeCompletion(view);
view.dispatch({
selection: EditorSelection.create(
sel.ranges.map((r) => EditorSelection.cursor(r.head)),
sel.mainIndex,
),
});
return true;
}
if (completionStatus(view.state) === "active") return closeCompletion(view);
return clearLinkedSnippet(view) || clearSnippet(view);
};
function fieldSelection(value: ActiveSnippet, field: number): EditorSelection {
return EditorSelection.create(
primarySegments(value, field).map(({ from, to }) => EditorSelection.range(from, to)),
value.mainSite,
);
}
function selectField(view: EditorView, value: ActiveSnippet, active: number): boolean {
if (active < 0 || active > value.last) return false;
view.dispatch({
selection: fieldSelection(value, active),
effects: setSnippet.of(active === value.last ? null : { ...value, active }),
scrollIntoView: true,
});
return true;
}
export function hasLinkedSnippetField(state: EditorState, direction: 1 | -1): boolean {
const value = state.field(fields, false);
return !!value && (direction === 1 ? value.active < value.last : value.active > 0);
}
export const nextLiveSnippetField: Command = (view) => {
const value = view.state.field(fields, false);
return !!value && !value.completion && selectField(view, value, value.active + 1);
};
const linkedSnippetExtension = [
fields,
mirrorEdits,
Prec.highest(
keymap.of([
{
key: "Tab",
run: (view) => {
const value = view.state.field(fields);
return (
!!value &&
!view.state.readOnly &&
completionStatus(view.state) !== "active" &&
selectField(view, value, value.active + 1)
);
},
shift: (view) => {
const value = view.state.field(fields);
return !!value && selectField(view, value, value.active - 1);
},
},
{ key: "Escape", run: (view) => !!view.state.field(fields) && escapeSnippet(view) },
]),
),
EditorView.domEventHandlers({
mousedown(event, view) {
const value = view.state.field(fields);
if (!value || event.button !== 0) return false;
const pos = view.posAtCoords({ x: event.clientX, y: event.clientY });
if (pos === null) return false;
const segment = value.segments.find((range) => contains(range, pos, pos));
return !!segment && segment.field !== value.active && selectField(view, value, segment.field);
},
}),
];
function codeMirrorSnippet(tr: Transaction): { active: number; ranges: SnippetRange[] } | undefined {
// CodeMirror exposes the native snippet's unmerged ranges through its state effect.
return tr.effects
.map(({ value }) => value)
.find((value) => {
return value && typeof value.active === "number" && Array.isArray(value.ranges);
});
}
export function snippetFieldMoved(tr: Transaction): number | undefined {
const linked = tr.effects.find((effect) => effect.is(setSnippet));
if (linked) return linked.value?.completion ? undefined : linked.value?.active;
return codeMirrorSnippet(tr)?.active;
}
/** Render with CodeMirror to keep its snippet syntax and indentation. */
function instantiate(source: EditorState, site: SnippetSite) {
const line = source.doc.lineAt(site.from);
const from = site.from - line.from;
const to = site.to - line.from;
const state = EditorState.create({
doc: source.doc.slice(line.from, source.doc.lineAt(site.to).to),
selection: EditorSelection.cursor(to),
extensions: [indentUnit.of(source.facet(indentUnit))],
});
let insert = Text.empty;
let ranges: SnippetRange[] = [];
// An extra anonymous stop exposes the range effect even when a snippet has only one field.
snippet(site.snippet + "#{}")(
{
state,
dispatch(tr) {
tr.changes.iterChanges((_from, _to, _start, _end, text) => {
insert = text;
});
ranges = codeMirrorSnippet(tr)?.ranges ?? [];
},
},
null,
from,
to,
);
const end = ranges.at(-1);
const seen = new Set<number>();
const segments = ranges.slice(0, -1).map((range) => {
const primary = !seen.has(range.field);
seen.add(range.field);
return { ...range, primary };
});
return { ...site, offset: from, insert, segments, end };
}
export function applySnippet(view: EditorView, sites: readonly SnippetSite[], completion: Completion | null = null) {
const { state } = view;
const { main } = state.selection;
const entries = sites.map((site) =>
instantiate(state, { ...site, to: sites.length === 1 && site.to === main.from ? main.to : site.to }),
);
if (entries.length === 1 && entries[0]!.segments.every((segment) => segment.primary)) {
const { snippet: source, from, to } = sites[0]!;
clearLinkedSnippet(view);
snippet(source)(view, completion, from, to);
return;
}
const changes = state.changes(entries.map(({ from, to, insert }) => ({ from, to, insert })));
let last = Math.max(...entries[0]!.segments.map(({ field }) => field));
const needsEnd = entries.some(({ segments }) =>
segments.some((segment) => segment.field === last && !segment.primary),
);
if (needsEnd) last++;
const segments = entries.flatMap((entry, site) => {
const offset = changes.mapPos(entry.from, -1) - entry.offset;
const ranges = [...entry.segments];
if (needsEnd && entry.end) ranges.push({ ...entry.end, primary: true });
return ranges.map((segment) => ({ ...segment, site, from: segment.from + offset, to: segment.to + offset }));
});
const value = {
segments,
active: 0,
last,
mainSite: sites.length === 1 ? 0 : state.selection.mainIndex,
completion: !!completion,
};
clearSnippet(view);
view.dispatch({
changes,
selection: fieldSelection(value, 0),
effects: [
setSnippet.of(last > 0 ? value : null),
...(state.field(fields, false) === undefined ? [StateEffect.appendConfig.of(linkedSnippetExtension)] : []),
],
annotations: completion ? pickedCompletion.of(completion) : isolateHistory.of("full"),
userEvent: completion ? "input.complete" : undefined,
scrollIntoView: true,
});
}
+41
View File
@@ -8,6 +8,7 @@ import { resetDistractionFree, setDistractionFree } from "@/workbench/distractio
import * as contributions from "@/workbench/contributions";
import {
registerEditorKind,
registerMenuGroup,
registerTextEditorWrapper,
setProjectViewLead,
useProjectViewLead,
@@ -579,6 +580,46 @@ describe("EditorController", () => {
useProject.setState({ project: null, settings: null });
});
it("offers contributed Copy Path links in the tab menu like the other copy menus", async () => {
useProject.setState({
project: { name: "p", root: "/p", trusted: true, isGit: true, settings: {} } as never,
settings: {} as never,
});
const dispose = registerActions(
["project.copyAbsolutePath", "project.copyFileName", "project.copyRelativePath"].map((id) => ({
id,
title: id,
run: () => undefined,
})),
);
const links = registerMenuGroup({
id: "test.link",
menus: ["copyPath"],
items: () => [{ id: "test.copyLink", label: "GitHub Link", verbatim: true, run: () => undefined }],
});
try {
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "" }));
ctrl.start();
await ctrl.openFile("/p/a.ts", { focus: false });
const s = useTabs.getState();
const pane = s.panes[s.activePane]!;
const submenu = resolveMenuItems(ctrl.tabMenu(pane.id, pane.tabs[0]!)).find(
(i) => i.label === "Copy Path/Reference…",
)!.submenu!;
expect(resolveMenuItems(submenu).map((i) => (i.kind === "separator" ? "-" : i.label))).toEqual([
"Absolute Path",
"File Name",
"Path From Content Root",
"-",
"GitHub Link",
]);
} finally {
dispose();
links();
useProject.setState({ project: null, settings: null });
}
});
it.each(["editor", "tab"])(
"offers grouped Git actions in the %s menu and preserves action enablement",
async (menu) => {
+3
View File
@@ -2324,6 +2324,9 @@ export class EditorController implements SlotHost {
},
] as MenuItem[])
: []),
// The links the project view and the editor chooser offer (features/vcs: GitHub Link).
{ kind: "separator" },
...menuGroupItems("copyPath", { paths: [path] }),
],
},
{ kind: "separator" },
+17
View File
@@ -297,6 +297,23 @@ describe("applying completions", () => {
await vi.waitFor(() => expect(view.state.selection.main.head).toBe(17));
});
it("edits repeated LSP placeholders from one selection", () => {
const { view, req } = setup("lo|", "", [EditorState.allowMultipleSelections.of(true)]);
const completion = makeCompletion(
item({ kind: "snippet", insertText: "log(${1:value}, $1, ${2:label})$0", isSnippet: true }),
req,
);
apply(view, completion, 0);
expect(view.state.selection.ranges).toHaveLength(1);
expect(view.state.doc.toString()).toBe("log(value, value, label)");
view.dispatch(view.state.replaceSelection("name"));
expect(view.state.doc.toString()).toBe("log(name, name, label)");
expect(runScopeHandlers(view, new KeyboardEvent("keydown", { key: "Enter" }), "editor")).toBe(false);
expect(runScopeHandlers(view, new KeyboardEvent("keydown", { key: "Tab" }), "editor")).toBe(true);
const { from, to } = view.state.selection.main;
expect(view.state.sliceDoc(from, to)).toBe("label");
});
it("leaves an item its server inserts to the server, and puts the caret after what it inserted", async () => {
const executed: string[] = [];
setInvokeRoute((cmd) => {
+3 -2
View File
@@ -16,7 +16,6 @@ import {
moveCompletionSelection,
pickedCompletion,
selectedCompletion,
snippet,
startCompletion,
type Completion,
type CompletionContext,
@@ -53,6 +52,7 @@ import {
typeColumnText,
withoutDuplicates,
} from "./completionItems";
import { applySnippet } from "@/editor/core/cm/linkedSnippet";
import { lspSnippetToCm, lspSnippetToPlainWithCaret, snippetVariables } from "./snippet";
import { docOf, isUnavailable, lspDoc, lspRequest, reportLspError } from "./lsp";
import { offsetToPos, posToOffset, textEditsToChanges } from "./positions";
@@ -296,7 +296,8 @@ export function applyLspCompletion(
start = tr.changes.mapPos(start, 1);
end = tr.changes.mapPos(end, 1);
}
snippet(lspSnippetToCm(item.insertText, snippetVariables(req.path)))(view, completion, start, end);
const source = lspSnippetToCm(item.insertText, snippetVariables(req.path));
applySnippet(view, [{ from: start, to: end, snippet: source }], completion);
// A call snippet without a stop (`ArrayList<>()`): the caret goes inside until
// signature help says there is nothing to pass.
const head = view.state.selection.main.head;
+3 -1
View File
@@ -4,6 +4,7 @@
* it follows the caret and closes when the server reports no signature;
* ⇥ / ⇧⇥ move to the next / previous argument.
*/
import { hasLinkedSnippetField } from "@/editor/core/cm/linkedSnippet";
import { EditorSelection, Prec, StateEffect, StateField, type Extension } from "@codemirror/state";
import { completionStatus, hasNextSnippetField, hasPrevSnippetField } from "@codemirror/autocomplete";
import {
@@ -289,7 +290,8 @@ function moveToArgument(view: EditorView, dir: 1 | -1): boolean {
if (!state.field(signatureField, false) || state.readOnly) return false;
if (state.selection.ranges.length > 1 || completionStatus(state) === "active") return false;
// Snippet / template fields and the in-place rename own ⇥.
if (dir > 0 ? hasNextSnippetField(state) : hasPrevSnippetField(state)) return false;
if (hasLinkedSnippetField(state, dir) || (dir > 0 ? hasNextSnippetField(state) : hasPrevSnippetField(state)))
return false;
if (inplaceRenameActive(state)) return false;
const head = state.selection.main.head;
const to = argumentStop(state.doc.toString(), head, dir);
+8 -2
View File
@@ -193,11 +193,17 @@ export function lspSnippetToCm(snippet: string, vars: SnippetVariables = {}): st
const hasField = nodes.some(
(n) => n.t === "tab" || n.t === "choice" || (n.t === "var" && vars[n.name] === undefined && !n.children),
);
const defaults = new Map<number, string>();
for (const node of nodes) {
if (node.t === "text" || node.t === "var" || node.n === 0 || defaults.has(node.n)) continue;
if (node.t === "choice") defaults.set(node.n, node.options[0] ?? "");
else if (node.children) defaults.set(node.n, flatten(node.children, vars));
}
let out = "";
for (const n of nodes) {
if (n.t === "text") out += escapeText(n.v);
else if (n.t === "tab") out += field(n.n, n.children ? flatten(n.children, vars) : "");
else if (n.t === "choice") out += field(n.n, n.options[0] ?? "");
else if (n.t === "tab") out += field(n.n, defaults.get(n.n) ?? (n.children ? flatten(n.children, vars) : ""));
else if (n.t === "choice") out += field(n.n, defaults.get(n.n) ?? n.options[0] ?? "");
else {
const v = vars[n.name];
if (v !== undefined) out += escapeText(v);
+2
View File
@@ -36,7 +36,9 @@
outline: none;
}
.field :global(.cm-scroller) {
height: auto;
max-height: 280px;
overflow-x: hidden;
overflow-y: auto;
font-family: inherit;
line-height: 1.5;
+1 -1
View File
@@ -140,7 +140,6 @@ export async function javaLaunchConfig(
root: string,
preparation?: JavaPreparation,
): Promise<LaunchConfig> {
const cwd = rc.cwd ? join(root, rc.cwd) : root;
rc = await withEnvFiles(rc, root);
const parsed = parseJavaArgs(rc.args);
if (!parsed.mainClass) throw new Error(`No main class in '${rc.name}'`);
@@ -155,6 +154,7 @@ export async function javaLaunchConfig(
},
},
);
const cwd = resolved.cwd ? join(root, resolved.cwd) : root;
if (info.errorCount > 0 && !preparation?.report)
notifications().notify({
group: "run",
@@ -2,22 +2,17 @@ import { EditorView } from "@codemirror/view";
import { activeEditor, editorsFor, useEditorRegistry, type TextEditorHandle } from "@/editor/api";
import { tx } from "@/platform/i18n";
import { call, commands, emitLocalIdeEvent, IpcError } from "@/platform/ipc";
import { appDataDir } from "@/platform/platformInfo";
import { scratchesDir } from "@/platform/scratchesDir";
import { editorService } from "@/workbench/contributions";
import { appendRequests } from "./spring/request";
export const GENERATED_REQUESTS = "generated-requests.http";
async function scratchFile(): Promise<{ path: string; created: boolean }> {
const dir = `${await appDataDir()}/scratches`;
const ignoreExisting = (e: unknown) => {
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
};
await call(commands.fsCreateDir(dir)).catch(ignoreExisting);
const path = `${dir}/${GENERATED_REQUESTS}`;
const path = `${await scratchesDir()}/${GENERATED_REQUESTS}`;
let created = true;
await call(commands.fsCreateFile(path)).catch((e) => {
ignoreExisting(e);
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
created = false;
});
return { path, created };
+8 -6
View File
@@ -8,8 +8,8 @@
import { activeEditor, registerEditorContribution, registerLanguageMode } from "@/editor/api";
import { executeAction, getAction, registerActions } from "@/platform/actions";
import { call, commands, emitLocalIdeEvent, IpcError, isTauri } from "@/platform/ipc";
import { appDataDir } from "@/platform/platformInfo";
import { useProject } from "@/platform/project";
import { scratchesDir } from "@/platform/scratchesDir";
import {
editorService,
notifications,
@@ -116,11 +116,13 @@ function directoryArg(arg: unknown): string | null {
/** New HTTP Request: `requests[_n].http` in `directory`, else a scratch, with an example request. */
async function newRequest(directory?: string) {
try {
const dir = directory ?? `${await appDataDir()}/scratches`;
try {
await call(commands.fsCreateDir(dir));
} catch (e) {
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
const dir = directory ?? (await scratchesDir());
if (directory) {
try {
await call(commands.fsCreateDir(dir));
} catch (e) {
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
}
}
const names = new Set((await call(commands.fsReadDir(dir))).map((e) => e.name.toLowerCase()));
let name = "requests.http";
@@ -4,12 +4,6 @@ import { provideEditorService, provideNotificationService } from "@/workbench/co
import { springControllers } from "./endpoints";
import { generateRequests } from "./editor";
// The backend reports the user data directory `/`-separated on every OS.
vi.mock("@/platform/platformInfo", async (importOriginal) => ({
...(await importOriginal<typeof import("@/platform/platformInfo")>()),
appDataDir: async () => "C:/Users/me/AppData/Roaming/ai.l0ng.openidea",
}));
// No backend here: the file commands answer like a project without Spring
// configuration files (empty configs, the files the body lookup probes missing).
vi.mock("@/platform/ipc", async (importOriginal) => {
@@ -19,7 +13,8 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
call: async (p: Promise<unknown>) => await p,
commands: {
...m.commands,
fsCreateDir: async () => null,
// The backend reports the scratches folder `/`-separated on every OS.
fsScratchesDir: async () => "C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches",
fsCreateFile: async () => null,
fsReadText: async () => "",
},
+72 -20
View File
@@ -17,14 +17,40 @@ import {
isLibraryPath,
registerEditorContribution,
setLibraryRoots,
useEditorRegistry,
} from "@/editor/api";
import { call, isCancelled, isTauri, nextRequestId, onIdeEvent } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { libraryArchiveRoot } from "@/platform/virtualDocs";
import { registerProjectViewRoot, type ProjectViewRootContribution } from "@/workbench/contributions";
import { goModNavigationExtension } from "./goModNavigation";
export const EXTERNAL_LIBRARIES_LABEL = "External Libraries";
/** A jdtls URI's `maven.*` attributes, as the group label used by build dependencies. */
function archiveGroupName(uri: string, fallback: string): string {
let query = uri.split("?")[1] ?? "";
try {
query = decodeURIComponent(query);
} catch {
return fallback;
}
const field = (name: string) => new RegExp(`maven\\.${name}=/([^=]+)=`).exec(query)?.[1];
const [group, artifact, version] = [field("groupId"), field("artifactId"), field("version")];
if (!group || !artifact || !version) return fallback;
const classifier = field("classifier");
return `Maven: ${group}:${artifact}:${version}${classifier ? `:${classifier}` : ""}`;
}
/** A class opened from a jar the build model has not listed yet; show its exact archive. */
export function openedLibraryGroup(uri: string, groups: readonly LibraryGroup[]): LibraryGroup | null {
const archive = libraryArchiveRoot(uri);
if (!archive || groups.some((group) => group.roots.some((root) => root.path === archive))) return null;
const separator = Math.max(archive.lastIndexOf("/"), archive.lastIndexOf("\\"));
const name = archive.slice(separator + 1, -1) || archive;
return { name: archiveGroupName(uri, name), kind: "classpath", roots: [{ name, path: archive }] };
}
const GROUP_ICONS: Record<string, string> = {
python: "file-python",
jdk: "file-java",
@@ -174,6 +200,10 @@ export function activate(): () => void {
let shown = "";
/** The last complete result: what a refresh shows for ecosystems that haven't reported yet. */
let settled: LibraryGroup[] = [];
/** The last build/SDK result, before archives opened from the editor are added. */
let backendGroups: LibraryGroup[] = [];
/** One group per opened archive, so the build model can replace each archive independently. */
let openedGroups: LibraryGroup[] = [];
let request: RequestId | undefined;
/** The project whose libraries are shown (and `settled`). */
let shownFor: string | null = null;
@@ -184,8 +214,36 @@ export function activate(): () => void {
shown = "";
shownGroups = [];
settled = [];
backendGroups = [];
openedGroups = [];
shownFor = null;
};
const render = (groups: LibraryGroup[]) => {
backendGroups = groups;
const covered = new Set(groups.flatMap((g) => g.roots.map((r) => r.path)));
openedGroups = openedGroups.filter((g) => !g.roots.some((r) => covered.has(r.path)));
const all = mergeLibraryGroups([...groups, ...openedGroups]);
const key = JSON.stringify(all);
if (key === shown) return;
// The new node replaces the old one in place: removing it first would drop it from the tree
// until the new one renders, and collapse it.
const [oldRoot, oldReadOnly] = [disposeRoot, disposeReadOnly];
disposeRoot = disposeReadOnly = () => {};
shown = key;
// ⌘-hover may have probed a go.mod entry before its module was listed.
if (goModules(all) !== goModules(shownGroups)) invalidateNavigationProviders();
shownGroups = all;
const root = librariesRoot(all);
if (root) {
disposeReadOnly = setLibraryRoots(
"externalLibraries",
all.flatMap((g) => g.roots.map((r) => r.path)),
);
disposeRoot = registerProjectViewRoot(root);
}
oldRoot();
oldReadOnly();
};
const refresh = () => {
const id = ++seq;
if (request !== undefined) void commands.cancelRequest(request).catch(() => {});
@@ -200,26 +258,7 @@ export function activate(): () => void {
let collected: LibraryGroup[] = [];
const show = (groups: LibraryGroup[]) => {
if (id !== seq) return;
const key = JSON.stringify(groups);
if (key === shown) return;
// The new node replaces the old one in place: removing it first would drop it from the tree
// until the new one renders, and collapse it.
const [oldRoot, oldReadOnly] = [disposeRoot, disposeReadOnly];
disposeRoot = disposeReadOnly = () => {};
shown = key;
// ⌘-hover may have probed a go.mod entry before its module was listed.
if (goModules(groups) !== goModules(shownGroups)) invalidateNavigationProviders();
shownGroups = groups;
const root = librariesRoot(groups);
if (root) {
disposeReadOnly = setLibraryRoots(
"externalLibraries",
groups.flatMap((g) => g.roots.map((r) => r.path)),
);
disposeRoot = registerProjectViewRoot(root);
}
oldRoot();
oldReadOnly();
render(groups);
};
const channel = new Channel<LibraryGroup[]>();
channel.onmessage = (groups) => {
@@ -242,6 +281,13 @@ export function activate(): () => void {
});
};
refresh();
const showOpenedLibrary = (path: string | null) => {
if (!path || !shownFor) return;
const group = openedLibraryGroup(path, shownGroups);
if (!group) return;
openedGroups.push(group);
render(backendGroups);
};
const disposeGoMod = registerEditorContribution({
id: "libraries.goModNavigation",
extensions: goModNavigationExtension((path, version) => goModuleRoot(shownGroups, path, version), isLibraryPath),
@@ -252,6 +298,11 @@ export function activate(): () => void {
const unsub = useProject.subscribe((s, prev) => {
if (sdkKey(s) !== sdkKey(prev)) refresh();
});
const unsubEditor = useEditorRegistry.subscribe((s, prev) => {
const path = s.active?.ctx.path ?? null;
if (path !== (prev.active?.ctx.path ?? null)) showOpenedLibrary(path);
});
showOpenedLibrary(useEditorRegistry.getState().active?.ctx.path ?? null);
let timer: ReturnType<typeof setTimeout> | undefined;
const unsubFs = onIdeEvent("fsChanged", (e) => {
if (!touchesManifest([...e.created, ...e.modified, ...e.removed])) return;
@@ -268,6 +319,7 @@ export function activate(): () => void {
if (request !== undefined) void commands.cancelRequest(request).catch(() => {});
clearTimeout(timer);
unsub();
unsubEditor();
unsubFs();
unsubRoots();
disposeActions();
+22 -1
View File
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it } from "vitest";
import { isLibraryPath, setLibraryRoots } from "@/editor/api";
import { librariesRoot, touchesManifest } from "./index";
import { librariesRoot, openedLibraryGroup, touchesManifest } from "./index";
import { mergeLibraryGroups } from "@/platform/libraries";
describe("External Libraries", () => {
@@ -116,6 +116,27 @@ describe("External Libraries", () => {
expect(isLibraryPath("/jdk/lib/src.zip!/java.base/java/lang/String.java")).toBe(true);
});
it("adds the classifier jar opened from a library class when the build model omits it", () => {
const uri =
"jdt://contents/demo-lib-1.0-jdk21.jar/com.example.lib/Helper.class?=demo/%5C/m2%5C/com%5C/example%5C/demo-lib%5C/1.0%5C/demo-lib-1.0-jdk21.jar=/maven.groupId=/com.example=/=/maven.artifactId=/demo-lib=/=/maven.version=/1.0=/=/maven.classifier=/jdk21=/=%3Ccom.example.lib(Helper.class";
expect(openedLibraryGroup(uri, [])).toEqual({
name: "Maven: com.example:demo-lib:1.0:jdk21",
kind: "classpath",
roots: [
{
name: "demo-lib-1.0-jdk21.jar",
path: "/m2/com/example/demo-lib/1.0/demo-lib-1.0-jdk21.jar!",
},
],
});
});
it("does not duplicate an archive the build model already lists", () => {
const uri = "jdt://contents/a.jar/p/C.class?=demo/%5C/m2%5C/a.jar%3Cp%28C.class";
const group = { name: "a.jar", kind: "maven", roots: [{ name: "a.jar", path: "/m2/a.jar!" }] };
expect(openedLibraryGroup(uri, [group])).toBeNull();
});
it("refreshes on manifest changes outside node_modules", () => {
expect(touchesManifest(["/p/src/main.rs", "/p/Cargo.toml"])).toBe(true);
expect(touchesManifest(["C:\\p\\go.mod"])).toBe(true);
+59 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { LibraryGroup } from "@/bindings";
const results: LibraryGroup[][] = [];
@@ -31,6 +31,7 @@ vi.mock("@/platform/ipc", () => ({
}));
const { activate } = await import("./index");
const { useEditorRegistry } = await import("@/editor/api");
const { useProject } = await import("@/platform/project");
const { useProjectViewRoots } = await import("@/workbench/contributions");
const { executeAction } = await import("@/platform/actions");
@@ -42,6 +43,13 @@ const rust = (version: string): LibraryGroup => ({
});
describe("External Libraries refresh", () => {
afterEach(() => {
results.length = 0;
streamed.length = 0;
hang = false;
useEditorRegistry.setState({ active: null });
});
it("replaces the node in place when the libraries change", async () => {
useProject.setState({
project: { root: "/p", trusted: true } as ReturnType<typeof useProject.getState>["project"],
@@ -86,4 +94,54 @@ describe("External Libraries refresh", () => {
dispose();
}
});
it("keeps other opened archives with the same name when the build lists one of them", async () => {
const first = "/first/library.jar!";
const second = "/second/library.jar!";
useProject.setState({
project: { root: "/p", trusted: true } as ReturnType<typeof useProject.getState>["project"],
});
const dispose = activate();
const paths = () =>
useProjectViewRoots
.getState()
.roots.get("externalLibraries")
?.children?.flatMap((group) => group.children?.map((root) => root.path) ?? [])
.sort();
try {
for (const archive of [first, second]) {
useEditorRegistry.setState({ active: { ctx: { path: `jar:file://${archive}/p/Example.class` } } as never });
}
await vi.waitFor(() => expect(paths()).toEqual([first, second]));
results.push([{ name: "Build dependency", kind: "gradle", roots: [{ name: "library.jar", path: first }] }]);
await executeAction("libraries.reload");
await vi.waitFor(() =>
expect(useProjectViewRoots.getState().roots.get("externalLibraries")?.children?.[0]?.label).toBe(
"Build dependency",
),
);
expect(paths()).toEqual([first, second]);
} finally {
dispose();
}
});
it("shows the exact classifier jar of the library class opened in the editor", async () => {
const uri =
"jdt://contents/demo-lib-1.0-jdk21.jar/com.example.lib/Helper.class?=demo/%5C/m2%5C/com%5C/example%5C/demo-lib%5C/1.0%5C/demo-lib-1.0-jdk21.jar=/maven.classifier=/jdk21=/=%3Ccom.example.lib(Helper.class";
useProject.setState({
project: { root: "/p", trusted: true } as ReturnType<typeof useProject.getState>["project"],
});
useEditorRegistry.setState({ active: { ctx: { path: uri } } as never });
results.push([]);
const dispose = activate();
const labels = () =>
useProjectViewRoots
.getState()
.roots.get("externalLibraries")
?.children?.[0]?.children?.map((g) => g.label);
await vi.waitFor(() => expect(labels()).toContain("demo-lib-1.0-jdk21.jar"));
dispose();
});
});
+36 -13
View File
@@ -2,7 +2,17 @@ import { shortcutLabel } from "@/platform/keymap";
import { IconButton, type MenuItem } from "@/ui";
import { useProject } from "@/platform/project";
import { userScopes } from "@/platform/scopes";
import { VIEW_MODES, setScopeView, setViewMode, setViewOption, useProjectTree, type ViewOptions } from "./store";
import { useEditorPrefs } from "@/platform/editorSettings";
import {
VIEW_MODES,
previewTabEnabled,
setPreviewTabEnabled,
setScopeView,
setViewMode,
setViewOption,
useProjectTree,
type ViewOptions,
} from "./store";
import type { SortKey } from "./model";
/** The title's "Project ▾" pane switcher (IDEA: Project / Project Files / Open Files / …). */
@@ -35,9 +45,22 @@ export function useProjectTitleMenu(): { label: string; items: MenuItem[] } {
}
/** The on / off view options. */
export type ToggleOption = {
type ViewToggle = {
[K in keyof ViewOptions]-?: ViewOptions[K] extends boolean ? K : never;
}[keyof ViewOptions];
/** The view's switches, plus the editor's preview tab setting it shares (as in IDEA). */
export type ToggleOption = ViewToggle | "previewTab";
const toggleState = (key: ToggleOption, options: ViewOptions, preview: boolean) =>
key === "previewTab" ? preview : options[key];
export const isToggled = (key: ToggleOption) =>
toggleState(key, useProjectTree.getState().options, previewTabEnabled());
export function flipToggle(key: ToggleOption) {
if (key === "previewTab") void setPreviewTabEnabled(!previewTabEnabled());
else setViewOption(key, !useProjectTree.getState().options[key]);
}
const APPEARANCE_OPTIONS: Array<[ToggleOption, string]> = [
["showHidden", "Show Hidden Files"],
@@ -90,22 +113,26 @@ export const SORT_LABELS: Array<[key: SortKey, actionLabel: string, menuLabel: s
/** Project view options in the header's "⋮" menu. */
export function useProjectHeaderMenu(): MenuItem[] {
const options = useProjectTree((s) => s.options);
const preview = useEditorPrefs().tabs.previewTab;
const option = (key: ToggleOption, label: string): MenuItem => ({
id: key,
label,
checked: toggleState(key, options, preview),
run: () => flipToggle(key),
});
const unity = useProjectTree((s) => s.mode === "unity");
return [
{
label: "Behavior",
submenu: BEHAVIOR_OPTIONS.map(([key, label]) => option(key, label, options)),
submenu: BEHAVIOR_OPTIONS.map(([key, label]) => option(key, label)),
},
{
label: "Appearance",
submenu: [
...(unity
? [
option("showUnityMeta", "Show Meta Files", options),
option("showUnityGenerated", "Show Generated Files", options),
]
? [option("showUnityMeta", "Show Meta Files"), option("showUnityGenerated", "Show Generated Files")]
: []),
...APPEARANCE_OPTIONS.map(([key, label]) => option(key, label, options)),
...APPEARANCE_OPTIONS.map(([key, label]) => option(key, label)),
],
},
{
@@ -118,12 +145,8 @@ export function useProjectHeaderMenu(): MenuItem[] {
run: () => setViewOption("sortBy", sortBy),
})),
{ kind: "separator" },
option(...FOLDERS_FIRST, options),
option(...FOLDERS_FIRST),
],
},
];
}
function option(key: ToggleOption, label: string, options: ViewOptions): MenuItem {
return { id: key, label, checked: options[key], run: () => setViewOption(key, !options[key]) };
}
+87 -14
View File
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { act, fireEvent, render, renderHook, screen, waitFor, within } from "@testing-library/react";
import { emitLocalIdeEvent } from "@/platform/ipc";
import { installRepeatedDoubleClick } from "@/platform/doubleClick";
import { getContext, setContext } from "@/platform/context";
@@ -22,13 +22,17 @@ import { beginNew, canPaste } from "./operations";
import { initProjectTree, selectModel, setSelection, setViewOption, useProjectTree } from "./store";
import type { OutlineItem } from "@/bindings";
import { _emitEditorEvent, useEditorRegistry } from "@/editor/api";
import { ProjectHeaderActions } from "./HeaderActions";
import { ProjectHeaderActions, useProjectHeaderMenu } from "./HeaderActions";
import { executeAction, getAction } from "@/platform/actions";
import { useProject } from "@/platform/project";
import type { MenuItem } from "@/ui";
import { loadOutline } from "./store";
const ipc = vi.hoisted(() => ({
docOpen: vi.fn(),
docClose: vi.fn(),
docOutline: vi.fn(),
settingsSet: vi.fn(),
}));
vi.mock("@/bindings", async (orig) => {
const real = await orig<typeof import("@/bindings")>();
@@ -58,6 +62,11 @@ const deferred = <T,>() => {
};
const ROOT = "/w/acme";
const initialSettings = useProject.getState().settings;
/** Settings › Editor › General › Editor Tabs › Enable preview tab. */
const previewTabSettings = (on: boolean) => ({ editor: { tabs: { previewTab: on } } });
const setPreviewTabSetting = (on: boolean) => act(() => useProject.setState({ settings: previewTabSettings(on) }));
let fs: MemoryFs;
let openFile: ReturnType<typeof vi.fn>;
let dispose: () => void;
@@ -98,6 +107,7 @@ beforeEach(() => {
afterEach(() => {
dispose();
useProject.setState({ settings: initialSettings });
setProjectFsForTests(null);
uninstallDispatcher?.();
uninstallDispatcher = null;
@@ -222,6 +232,42 @@ describe("ProjectView", () => {
}
});
it("pastes a copied keyword into the tree's speed search instead of pasting files", async () => {
dispatchViaKeymap();
// Explorer holds a file, and the user wants to paste a word they copied from somewhere else
// into the search they just opened with ⌘F.
fs.nodes.set("/elsewhere/Photo.png", { kind: "file", size: 3 });
setOsClipboardForTests({
files: async () => ["/elsewhere/Photo.png"],
hasFiles: async () => true,
setFiles: async () => false,
});
try {
const { tree, row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("src"));
tree.focus();
fireEvent.keyDown(tree, { key: "f", code: "KeyF", metaKey: true });
fireEvent.paste(tree, {
clipboardData: { getData: () => "Read" },
} as unknown as ClipboardEventInit);
expect(within(tree.parentElement!).getByRole("status")).toHaveTextContent("Read");
// The file Paste never ran: give a wrong one the time to land, then check the project.
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 50));
});
expect([...fs.nodes.keys()].filter((p) => p.startsWith("/w/acme/") && p.endsWith("Photo.png"))).toEqual([]);
// Closed, ⌘V is the view's file Paste again.
fireEvent.keyDown(tree, { key: "Escape", code: "Escape" });
fireEvent.keyDown(tree, { key: "v", code: "KeyV", metaKey: true });
await waitFor(() =>
expect([...fs.nodes.keys()].some((p) => p.startsWith("/w/acme/") && p.endsWith("Photo.png"))).toBe(true),
);
} finally {
setOsClipboardForTests(null);
}
});
it("clears cut dimming and disables Paste on focus after the OS clipboard becomes text", async () => {
dispatchViaKeymap();
let files: string[] = [];
@@ -257,21 +303,48 @@ describe("ProjectView", () => {
}
});
it("opens files on double click and previews on single click only when enabled", async () => {
it("opens files on double click and previews on single click while the editor's preview tab is on", async () => {
const { row, rows } = setup();
await waitFor(() => expect(rows()).toContain("README.md"));
const content = row("README.md").querySelector("[data-project-path]")!;
fireEvent.click(content, { detail: 1 });
expect(openFile).not.toHaveBeenCalled();
fireEvent.doubleClick(row("README.md"));
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: undefined, focus: true });
act(() => setViewOption("previewTab", true));
// Settings › Editor › General › Editor Tabs › Enable preview tab is on by default.
fireEvent.click(content, { detail: 1 });
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: true, focus: false });
openFile.mockClear();
fireEvent.click(content, { detail: 3 });
expect(openFile).not.toHaveBeenCalled();
act(() => setViewOption("previewTab", false));
setPreviewTabSetting(false);
fireEvent.click(content, { detail: 1 });
expect(openFile).not.toHaveBeenCalled();
fireEvent.doubleClick(row("README.md"));
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview: undefined, focus: true });
});
it("toggles the editor's preview tab setting from the Behavior menu and its action", async () => {
ipc.settingsSet.mockImplementation(async (_scope: string, _key: string, value: string) =>
ok(previewTabSettings(JSON.parse(value) as boolean)),
);
const { result } = renderHook(() => useProjectHeaderMenu());
type Item = Extract<MenuItem, { id?: string }>;
const behavior = () => (result.current[0] as Item).submenu as Item[];
const item = () => behavior().find((i) => i.id === "previewTab")!;
expect(item().checked).toBe(true);
act(() => item().run!());
await waitFor(() => expect(item().checked).toBe(false));
expect(ipc.settingsSet).toHaveBeenLastCalledWith("global", "editor.tabs.previewTab", "false");
const action = getAction("project.option.previewTab")!;
expect(action.toggled!()).toBe(false);
act(() => void executeAction(action.id));
await waitFor(() => expect(item().checked).toBe(true));
});
it("drops the former view-only preview tab option from saved view options", () => {
localStorage.setItem("openidea.projectTree.options", JSON.stringify({ previewTab: true, singleClickOpen: true }));
vi.resetModules();
return import("./store").then(({ useProjectTree: fresh }) => {
expect(fresh.getState().options).not.toHaveProperty("previewTab");
expect(fresh.getState().options.singleClickOpen).toBe(true);
});
});
it("follows tab switches with Always Select Opened File, hiding Select Opened File", async () => {
@@ -701,17 +774,17 @@ describe("Show Members", () => {
},
);
it("autoscrolls to source without handing files to another application", async () => {
it.each([true, false])("autoscrolls to source with preview tabs set to %s", async (preview) => {
const { rows, row } = setup();
setPreviewTabSetting(preview);
act(() => {
setViewOption("autoscrollToSource", true);
setViewOption("singleClickOpen", false);
setViewOption("previewTab", false);
});
await waitFor(() => expect(rows()).toContain("README.md"));
fireEvent.mouseDown(row("README.md"));
await waitFor(() =>
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", expect.objectContaining({ external: false })),
expect(openFile).toHaveBeenLastCalledWith("/w/acme/README.md", { preview, focus: false, external: false }),
);
});
@@ -724,14 +797,14 @@ describe("Show Members", () => {
setViewOption("showMembers", true);
setViewOption("autoscrollToSource", false);
setViewOption("singleClickOpen", false);
setViewOption("previewTab", false);
useProject.setState({ settings: previewTabSettings(false) });
useProjectTree.setState({ expanded: new Set([ROOT, "/w/acme/src", APP]) });
});
await waitFor(() => expect(rows()).toContain("main"));
const content = () => row("main").querySelector("[data-project-key]")!;
fireEvent.click(content(), { detail: 1 });
expect(openFile).not.toHaveBeenCalled();
act(() => setViewOption("previewTab", true));
setPreviewTabSetting(true);
fireEvent.click(content(), { detail: 1 });
expect(openFile).toHaveBeenLastCalledWith(
APP,
+5 -7
View File
@@ -91,6 +91,7 @@ import {
explainHiddenPath,
loadDir,
loadOutline,
previewTabEnabled,
revealPath,
selectModel,
setDropTarget,
@@ -584,13 +585,10 @@ export function ProjectView() {
setSelection(next, lead?.key ?? null);
const { options: o } = useProjectTree.getState();
if (revealing.current || !o.autoscrollToSource || !lead || lead.dir || lead.placeholder || next.size !== 1) return;
const opts = { preview: previewTabEnabled(), focus: false, external: false };
if (lead.member) {
void revealRange(
lead.path,
{ start: lead.member.selection_range.start },
{ preview: o.previewTab, focus: false, external: false },
);
} else void openFile(lead.path, { preview: o.previewTab, focus: false, external: false });
void revealRange(lead.path, { start: lead.member.selection_range.start }, opts);
} else void openFile(lead.path, opts);
}, []);
const onActivate = useCallback((node: ProjectNode) => {
@@ -633,7 +631,7 @@ export function ProjectView() {
if (o.singleClickExpand) toggleExpanded(node);
return;
}
if (!o.singleClickOpen && !o.previewTab) return;
if (!o.singleClickOpen && !previewTabEnabled()) return;
const opts = { preview: o.singleClickOpen ? undefined : true, focus: false };
if (node.member) void revealRange(node.path, { start: node.member.selection_range.start }, opts);
else void openFile(node.path, opts);
+3 -3
View File
@@ -6,7 +6,7 @@ import { canRevealInFileManager, revealInFileManagerLabel } from "@/platform/fil
import { dirname, useProject } from "@/platform/project";
import { showContextMenu, type MenuItem } from "@/ui";
import { maybeEditorService, menuGroupItems, toolWindowService } from "@/workbench/contributions";
import { OPTION_LABELS, SORT_LABELS } from "./HeaderActions";
import { OPTION_LABELS, SORT_LABELS, flipToggle, isToggled } from "./HeaderActions";
import { compareTarget, newMenuItems, revealLabel } from "./contextMenu";
import { openNewPopup } from "./newPopupModel";
import type { ProjectNode } from "./model";
@@ -191,8 +191,8 @@ export function registerProjectActions(): () => void {
category: "View",
// IDEA's former name of Always Select Opened File.
keywords: ["project", "tree", "toggle", ...(key === "autoscrollFromSource" ? ["autoscroll from source"] : [])],
toggled: () => useProjectTree.getState().options[key],
run: () => setViewOption(key, !useProjectTree.getState().options[key]),
toggled: () => isToggled(key),
run: () => flipToggle(key),
}));
const modes: Action[] = VIEW_MODES.map(([mode, label]) => ({
@@ -145,6 +145,22 @@ describe("project view context menu", () => {
]);
});
it("lists contributed links in Copy Path/Reference… of library files too", () => {
disposers.push(
registerMenuGroup({
id: "test.link",
menus: ["copyPath"],
items: (_menu, ctx) => [{ label: `Link ${ctx.paths.join()}`, verbatim: true, run: () => undefined }],
}),
);
expect(sub(contextMenuItems([{ ...node("/root/.m2/lib.jar"), readOnly: true }]), "Copy Path/Reference…")).toEqual([
"Absolute Path",
"File Name",
"-",
"Link /root/.m2/lib.jar",
]);
});
it("groups clipboard, search, file changes, formatting and history actions for a file", () => {
const items = contextMenuItems([node(`${ROOT}/src/a.py`)]);
expect(labels(items)).toEqual([
+2
View File
@@ -512,6 +512,8 @@ function libraryMenuItems(nodes: ProjectNode[]): MenuItem[] {
run: () => void copyPaths("absolute", nodes),
},
{ id: "name", label: "File Name", run: () => void copyPaths("name", nodes) },
{ kind: "separator" },
...menuGroupItems("copyPath", menuGroupContext(nodes)),
],
},
{ kind: "separator" },
+20 -4
View File
@@ -13,6 +13,8 @@ import { libraryEntryPaths } from "@/platform/virtualDocs";
import { isIgnoredName } from "@/platform/ignoredNames";
import { tx, txPart } from "@/platform/i18n";
import { notifications } from "@/workbench/contributions";
import { editorPrefs } from "@/platform/editorSettings";
import { useProject } from "@/platform/project";
import { ipcPath } from "@/platform/paths";
import {
DEFAULT_TREE_OPTIONS,
@@ -57,8 +59,6 @@ export interface ViewOptions extends TreeOptions {
singleClickOpen: boolean;
/** Single click on a folder row expands / collapses it. */
singleClickExpand: boolean;
/** Single click shows files in the preview tab (IDEA's "Enable Preview Tab"). */
previewTab: boolean;
/** Show a file's declarations as expandable rows below it. */
showMembers: boolean;
/** Show the location of each project root beside its name. */
@@ -73,8 +73,6 @@ export const DEFAULT_VIEW_OPTIONS: ViewOptions = {
autoscrollToSource: false,
singleClickOpen: false,
singleClickExpand: false,
// IDEA's "Enable Preview Tab" is off by default.
previewTab: false,
showMembers: false,
showRootPaths: true,
horizontalScroll: true,
@@ -82,6 +80,8 @@ export const DEFAULT_VIEW_OPTIONS: ViewOptions = {
function storedOptions(): ViewOptions {
const options = { ...DEFAULT_VIEW_OPTIONS, ...readJson<Partial<ViewOptions>>(OPTIONS_KEY) };
// Former view-only switch, now the editor's preview tab setting (`previewTabEnabled`).
delete (options as { previewTab?: unknown }).previewTab;
if (!["name", "type", "modified"].includes(options.sortBy)) options.sortBy = "name";
return options;
}
@@ -502,6 +502,22 @@ export function setViewOption<K extends keyof ViewOptions>(key: K, value: ViewOp
writeJson(OPTIONS_KEY, options);
}
/** Single click shows files in the preview tab: IDEA's "Enable Preview Tab" is the editor's own setting. */
export const previewTabEnabled = () => editorPrefs().tabs.previewTab;
export async function setPreviewTabEnabled(on: boolean): Promise<void> {
try {
const settings = await call(commands.settingsSet("global", "editor.tabs.previewTab", JSON.stringify(on)));
useProject.setState({ settings });
} catch (e) {
notifications().notify({
level: "error",
title: "Cannot change the setting",
body: e instanceof Error ? e.message : String(e),
});
}
}
// ---------------------------------------------------------------------------
// Loading
+49 -2
View File
@@ -3,8 +3,8 @@ import type { RunConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { menuGroupItems, registerMenuGroup } from "@/workbench/contributions";
import type { MenuItem } from "@/ui";
import { canDebugProduced, choiceItems, compiledDebugPlan, contextMenuItems } from "./contextRun";
import { OPTIMISTIC, produceContextChoices, type ToolEnv } from "./producers";
import { canDebugProduced, choiceItems, compiledDebugPlan, contextMenuItems, projectContext } from "./contextRun";
import { OPTIMISTIC, produceContext, produceContextChoices, type ToolEnv } from "./producers";
import { gutterTestState, markerIcon, targetMenuItems } from "./runGutter";
import { useRun } from "./store";
import type { RunTarget } from "./targets";
@@ -115,6 +115,53 @@ describe("run context menu group", () => {
expect(contextMenuItems("projectView", { paths: [`${ROOT}/src/components`], dirs: [true] })).toEqual([]);
});
it("routes an attached Spring Boot main and its tests through the member's Maven build", () => {
const member = "/work/spring";
const project = useProject.getState().project!;
useProject.setState({ project: { ...project, workspace: { version: 1, name: "app", projects: [ROOT, member] } } });
const maven: RunConfig = { ...npmTest, kind: "maven", command: "mvn", args: ["test"], debugAdapter: null };
useRun.setState({
configs: [
{ ...maven, id: "maven:test" },
{ ...maven, id: "member:test", cwd: member },
],
});
const content = [
"package demo;",
"import org.springframework.boot.SpringApplication;",
"import org.springframework.boot.autoconfigure.SpringBootApplication;",
"@SpringBootApplication",
"public class App {",
" public static void main(String[] args) { SpringApplication.run(App.class, args); }",
"}",
].join("\n");
const main = { ...projectContext(), path: `${member}/src/main/java/demo/App.java`, content, line: 5 };
expect(produceContext(main, OPTIMISTIC)?.config).toMatchObject({
kind: "spring-boot",
module: member,
args: ["-cp", "${classpath}", "demo.App"],
});
expect(
produceContext(
{
...main,
path: `${member}/src/test/java/demo/AppTest.java`,
content: "package demo;\nclass AppTest {\n @Test\n void starts() {}\n}",
line: 3,
},
OPTIMISTIC,
)?.config,
).toMatchObject({
kind: "maven",
cwd: member,
args: ["test", "-Dtest=demo.AppTest#starts", "-Dsurefire.failIfNoSpecifiedTests=false"],
});
expect(produceContext({ ...main, path: `${ROOT}/src/main/java/demo/App.java` }, OPTIMISTIC)?.config).toMatchObject({
kind: "spring-boot",
module: "",
});
});
it("shows nothing when no producer matches or for several paths", () => {
expect(contextMenuItems("editor", { paths: [`${ROOT}/README.md`], text: "# hi", line: 0 })).toEqual([]);
expect(contextMenuItems("projectView", { paths: [`${ROOT}/a.js`, `${ROOT}/b.js`], dirs: [false, false] })).toEqual(
+4 -3
View File
@@ -50,15 +50,16 @@ async function ensureConfigs() {
}
/** The focused editor's file, text and caret line. */
/** Project folders outside its root: Project Structure content roots and Gradle modules (as of the last sync). */
/** Attached projects, Project Structure content roots and external Gradle modules. */
export function projectContentRoots(): string[] {
const own = effectiveContentRoots(validateProjectStructure(useProject.getState().settings?.projectStructure));
const { project, settings } = useProject.getState();
const own = effectiveContentRoots(validateProjectStructure(settings?.projectStructure));
// The build model keeps the folders of modules outside the project absolute.
const gradle = (useBuildModel.getState().model?.gradle ?? [])
.flatMap((g) => g.projects)
.map((p) => p.dir)
.filter((d) => isAbsolute(d));
return [...new Set([...own, ...gradle])];
return [...new Set([...(project?.workspace?.projects ?? []), ...own, ...gradle])];
}
const isAbsolute = (p: string) => p.startsWith("/") || /^[A-Za-z]:[\\/]/.test(p);
+22
View File
@@ -68,6 +68,7 @@ beforeEach(() => {
afterEach(() => {
resetRuns();
_resetI18nForTests();
useProject.setState({ project: null });
});
it.each(["sibling", "/outside/modules"])("runs from %s using the stored module's classpath", async (cwd) => {
@@ -142,6 +143,27 @@ it("finds the source module for an old saved configuration without a module", as
);
});
it.each([null, "/elsewhere"])("recovers an attached module from its indexed path with cwd %s", async (cwd) => {
const root = "/p";
const member = "/other/spring";
const module = `${member}/web`;
useProject.setState({
project: { root, workspace: { version: 1, name: "demo", projects: [root, member] } } as never,
});
ipc.findFiles.mockResolvedValueOnce({
status: "ok",
data: [{ path: `${module}/src/main/java/a/Main.java`, relPath: "spring/web/src/main/java/a/Main.java" }],
});
const session = await startRun({ ...config, cwd });
expect(session?.status).toBe("running");
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(module, false, "automatic", expect.any(Number));
expect(ipc.runStart).toHaveBeenCalledWith(
expect.objectContaining({ cwd: cwd ?? module, module }),
expect.anything(),
expect.any(Number),
);
});
it.each([["-cp", "lib/*"], []])("colours Spring Boot runs without classpath resolution (%j)", async (...classpath) => {
const args = ["-Xmx256m", ...classpath, "a.Main", "--spring.profiles.active=dev"];
const boot = { ...config, kind: "spring-boot", args };
@@ -3,6 +3,7 @@ import { act, fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { getAction } from "@/platform/actions";
import { onIdeEvent } from "@/platform/ipc";
import { useRemote } from "@/platform/remote";
import { useProjectViewRoots } from "@/workbench/contributions";
import {
chooserRows,
@@ -102,9 +103,8 @@ describe("creating scratch files", () => {
opened = [];
carets = [];
backend = {
dataDir: async () => "/data/",
scratchesDir: async () => "/data/scratches/",
listNames: async (dir) => [...files].filter((f) => f.startsWith(dir + "/")).map((f) => f.slice(dir.length + 1)),
createDir: async () => {},
createFile: async (p, text) => {
files.add(p);
contents.set(p, text);
@@ -177,14 +177,43 @@ describe("creating scratch files", () => {
});
});
describe("scratches of a remote window", () => {
afterEach(() => {
useRemote.setState({ session: null });
setScratchBackend(tauriScratchBackend);
});
it("moves the Scratches root to the server's folder when the window attaches to it in place", async () => {
const remote = () => useRemote.getState().session !== null;
setScratchBackend({
scratchesDir: async () => (remote() ? "/home/me/.openidea/data/scratches" : "C:/Users/me/AppData/scratches"),
listNames: async () => [],
createFile: async () => {},
languages: async () => [],
open: async () => {},
});
const root = () => useProjectViewRoots.getState().roots.get("scratches")?.path;
const dispose = activate();
try {
await vi.waitFor(() => expect(root()).toBe("C:/Users/me/AppData/scratches"));
useRemote.setState({ session: { root: "/home/me/project" } as never });
await vi.waitFor(() => expect(root()).toBe("/home/me/.openidea/data/scratches"));
useRemote.setState({ session: null });
await vi.waitFor(() => expect(root()).toBe("C:/Users/me/AppData/scratches"));
} finally {
dispose();
}
expect(root()).toBeUndefined();
});
});
describe("deleting scratch files", () => {
afterEach(() => setScratchBackend(tauriScratchBackend));
it("reports deletions inside the scratches folder as file system changes", async () => {
setScratchBackend({
dataDir: async () => "/data",
scratchesDir: async () => "/data/scratches",
listNames: async () => [],
createDir: async () => {},
createFile: async () => {},
languages: async () => [],
open: async () => {},
+14 -2
View File
@@ -5,6 +5,7 @@
import { registerActions } from "@/platform/actions";
import { onFileOperation } from "@/platform/fileOps";
import { emitLocalIdeEvent } from "@/platform/ipc";
import { useRemote } from "@/platform/remote";
import { registerMenuGroup, registerOverlay, registerProjectViewRoot } from "@/workbench/contributions";
import { ScratchChooserHost } from "./ScratchChooser";
import { openChooser } from "./store";
@@ -20,10 +21,15 @@ export function activate(): () => void {
let disposed = false;
let unregisterRoot = () => {};
let dir: string | null = null;
if (scratchesAvailable())
let generation = 0;
const registerRoot = () => {
const current = ++generation;
unregisterRoot();
unregisterRoot = () => {};
dir = null;
void scratchesDir()
.then((path) => {
if (disposed) return;
if (disposed || current !== generation) return;
dir = path;
unregisterRoot = registerProjectViewRoot({
id: "scratches",
@@ -35,7 +41,13 @@ export function activate(): () => void {
});
})
.catch((e: unknown) => console.warn("scratch files: no scratches folder", e));
};
if (scratchesAvailable()) registerRoot();
const disposers = [
// Attaching to (or leaving) a remote server moves the scratches to that host.
useRemote.subscribe((state, previous) => {
if (state.session !== previous.session && scratchesAvailable()) registerRoot();
}),
// The file watcher covers the project only: deleted scratches close their editors like watched files.
onFileOperation((op) => {
const removed = dir && op.kind === "deleted" ? op.paths.filter((p) => p === dir || p.startsWith(`${dir}/`)) : [];
+12 -30
View File
@@ -1,27 +1,26 @@
/**
* Scratch files live in the app data dir (`<appData>/scratches`), not in the
* project, like IDEA's config-dir scratches. Creating one picks the next free
* `scratch[_n].<ext>` name and opens it as a normal document.
* Scratch files live in the user data dir (`<data>/scratches`) of the host that runs the
* window's file commands (the server in a remote window), not in the project, like IDEA's
* config-dir scratches. Creating one picks the next free `scratch[_n].<ext>` name and opens
* it as a normal document.
*/
import { IpcError, call, commands, emitLocalIdeEvent, isTauri } from "@/platform/ipc";
import { appDataDir } from "@/platform/platformInfo";
import { call, commands, emitLocalIdeEvent, isTauri } from "@/platform/ipc";
import { scratchesDir as hostScratchesDir } from "@/platform/scratchesDir";
import { editorService, notifications } from "@/workbench/contributions";
import { scratchContent, scratchFileName, scratchLanguages, type ScratchLanguage } from "./model";
export interface ScratchBackend {
/** Absolute app data dir. */
dataDir(): Promise<string>;
/** Absolute scratches folder, created. */
scratchesDir(): Promise<string>;
listNames(dir: string): Promise<string[]>;
createDir(dir: string): Promise<void>;
createFile(path: string, text: string): Promise<void>;
languages(): Promise<ScratchLanguage[]>;
open(path: string, caret: { line: number; col: number } | null): Promise<void>;
}
export const tauriScratchBackend: ScratchBackend = {
dataDir: appDataDir,
scratchesDir: hostScratchesDir,
listNames: async (dir) => (await call(commands.fsReadDir(dir))).map((e) => e.name),
createDir: async (dir) => void (await call(commands.fsCreateDir(dir))),
createFile: async (path, text) =>
void (await call(
text ? commands.fsCreateFileBytes(path, [...new TextEncoder().encode(text)]) : commands.fsCreateFile(path),
@@ -35,30 +34,13 @@ let backend: ScratchBackend = tauriScratchBackend;
/** Tests swap the backend. */
export function setScratchBackend(b: ScratchBackend) {
backend = b;
dirPromise = null;
}
export const scratchBackend = () => backend;
let dirPromise: Promise<string> | null = null;
/** `<appData>/scratches`, created on first use. */
export function scratchesDir(): Promise<string> {
if (!dirPromise) {
dirPromise = (async () => {
const dir = `${(await backend.dataDir()).replace(/\/+$/, "")}/scratches`;
try {
await backend.createDir(dir);
} catch (e) {
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
}
return dir;
})();
dirPromise.catch(() => {
dirPromise = null;
});
}
return dirPromise;
/** The scratches folder, created if needed. */
export async function scratchesDir(): Promise<string> {
return (await backend.scratchesDir()).replace(/\/+$/, "");
}
export const scratchesAvailable = () => isTauri() || backend !== tauriScratchBackend;
+2 -2
View File
@@ -2,7 +2,7 @@
import { useState } from "react";
import { useTx } from "@/platform/i18n";
import { Checkbox, Dialog, Input } from "@/ui";
import { answerAskpass, askpassAnswer, useAskpass, type AskpassPrompt } from "./askpass";
import { answerAskpass, askpassAnswer, askpassTitle, useAskpass, type AskpassPrompt } from "./askpass";
import styles from "./Ssh.module.css";
export function AskpassHost() {
@@ -39,7 +39,7 @@ function AskpassDialog({ prompt: p }: { prompt: AskpassPrompt }) {
return (
<Dialog
open
title={tx(p.kind === "secret" ? "SSH Password" : "SSH")}
title={tx(askpassTitle(p))}
onClose={cancel}
width={440}
buttons={[
+9
View File
@@ -45,3 +45,12 @@ export function answerAskpass(
// on success and drops it again when authentication fails.
void send(p.id, answer, remember).catch(() => {});
}
/** The dialog title: git asks for HTTPS credentials (any host, e.g. a token as the password) as well as ssh. */
export function askpassTitle(
p: Pick<AskpassPrompt, "kind" | "prompt">,
): "Password" | "Username" | "SSH Password" | "SSH" {
const https = /\bhttps?:\/\//i.test(p.prompt);
if (p.kind === "secret") return https ? "Password" : "SSH Password";
return https ? "Username" : "SSH";
}
+13 -1
View File
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { DEFAULT_SSH_CONFIG, type SshConfigValid } from "@/platform/remoteSettings";
import { answerAskpass, askpassAnswer, dropAskpass, enqueueAskpass, useAskpass } from "./askpass";
import { answerAskpass, askpassAnswer, askpassTitle, dropAskpass, enqueueAskpass, useAskpass } from "./askpass";
import { type ConnectDeps, openSshTerminal, sessionItems, sshRemedy } from "./session";
describe("askpass queue", () => {
@@ -40,6 +40,18 @@ describe("askpass queue", () => {
});
});
describe("askpass title", () => {
it("names git HTTPS credentials without calling them SSH", () => {
expect(askpassTitle({ kind: "secret", prompt: "Password for 'https://[email protected]': " })).toBe("Password");
expect(askpassTitle({ kind: "text", prompt: "Username for 'https://cnb.cool': " })).toBe("Username");
});
it("keeps the SSH titles for ssh prompts", () => {
expect(askpassTitle({ kind: "secret", prompt: "dev@host's password: " })).toBe("SSH Password");
expect(askpassTitle({ kind: "text", prompt: "Enter passphrase for key '/home/u/.ssh/id_ed25519': " })).toBe("SSH");
});
});
describe("Start SSH Session chooser", () => {
const config = (patch: Partial<SshConfigValid>): SshConfigValid => ({ ...DEFAULT_SSH_CONFIG, ...patch });
@@ -1,9 +1,10 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { registerAction } from "@/platform/actions";
import { EditorSelection, EditorState, type Extension } from "@codemirror/state";
import { EditorView, runScopeHandlers } from "@codemirror/view";
import { cursorCharRight, history, undo } from "@codemirror/commands";
import { EditorView, keymap, runScopeHandlers } from "@codemirror/view";
import { cursorCharRight, history, redo, standardKeymap, undo } from "@codemirror/commands";
import { nextOccurrence, occurrenceSearch } from "@/editor/core/cm/editing";
import { hasLinkedSnippetField } from "@/editor/core/cm/linkedSnippet";
import { completedSyntaxState } from "@/test/syntax";
import { languages } from "@codemirror/language-data";
import {
@@ -284,14 +285,55 @@ describe("surround with", () => {
describe("template fields", () => {
const selected = (v: EditorView) => v.state.sliceDoc(v.state.selection.main.from, v.state.selection.main.to);
it("edits the Java fori index from a single caret and lets the initializer be edited separately", async () => {
const doc = "class Main {\n void f() {\n fori\n }\n}";
const v = await editor("java", doc, doc.indexOf("fori") + 4, [history(), keymap.of(standardKeymap)]);
expect(tab(v)).toBe(true);
expect(v.state.selection.ranges).toHaveLength(1);
expect(selected(v)).toBe("i");
expect(v.state.selection.main.from).toBe(v.state.doc.toString().indexOf("int i") + "int ".length);
const expanded = v.state.doc.toString();
v.dispatch(v.state.replaceSelection("index"));
const renamed = expanded.replace(/\bi\b/g, "index");
expect(v.state.doc.toString()).toBe(renamed);
expect(undo(v)).toBe(true);
expect(v.state.doc.toString()).toBe(expanded);
expect(redo(v)).toBe(true);
expect(v.state.doc.toString()).toBe(renamed);
const afterZero = renamed.indexOf(" = 0") + " = 0".length;
while (v.state.selection.main.head < afterZero) expect(press(v, "ArrowRight")).toBe(true);
expect(v.state.selection.main.head).toBe(afterZero);
expect(v.state.selection.ranges).toHaveLength(1);
expect(press(v, "Backspace")).toBe(true);
v.dispatch(v.state.replaceSelection("1"));
expect(v.state.doc.toString()).toBe(renamed.replace(" = 0", " = 1"));
});
it("keeps one index caret per Java fori expansion", async () => {
const doc = "class Main {\n void f() {\n fori\n fori\n }\n}";
const v = await editor("java", doc);
carets(v, doc.indexOf("fori") + 4, doc.lastIndexOf("fori") + 4);
expect(tab(v)).toBe(true);
expect(v.state.selection.ranges).toHaveLength(2);
expect(v.state.selection.mainIndex).toBe(1);
v.dispatch(v.state.replaceSelection("index"));
expect(v.state.doc.toString().match(/\bindex\b/g)).toHaveLength(6);
expect(press(v, "Enter")).toBe(true);
expect(v.state.selection.ranges.every((range) => range.empty)).toBe(true);
expect(runScopeHandlers(v, new KeyboardEvent("keydown", { key: "Tab", shiftKey: true }), "editor")).toBe(true);
expect(v.state.selection.ranges.map((r) => v.state.sliceDoc(r.from, r.to))).toEqual(["index", "index"]);
});
it("links fields and advances all carets through separately indented expansions", async () => {
const doc = "function first() {\n fori\n}\nfunction second() {\n fori\n}";
const v = await editor("typescript", doc, undefined, [history()]);
carets(v, doc.indexOf("fori") + 4, doc.lastIndexOf("fori") + 4);
const before = v.state.selection;
expect(tab(v)).toBe(true);
expect(v.state.selection.ranges.map((r) => v.state.sliceDoc(r.from, r.to))).toEqual(Array(6).fill("i"));
expect(v.state.selection.mainIndex).toBe(3);
expect(v.state.selection.ranges.map((r) => v.state.sliceDoc(r.from, r.to))).toEqual(["i", "i"]);
expect(v.state.selection.mainIndex).toBe(1);
expect(v.state.doc.line(3).text).toBe(" ");
expect(v.state.doc.line(8).text).toBe(" ");
@@ -301,7 +343,7 @@ describe("template fields", () => {
expect(v.state.selection.ranges).toHaveLength(2);
expect(v.state.selection.ranges.every((r) => v.state.sliceDoc(r.head, r.head + 7) === ".length")).toBe(true);
expect(runScopeHandlers(v, new KeyboardEvent("keydown", { key: "Tab", shiftKey: true }), "editor")).toBe(true);
expect(v.state.selection.ranges).toHaveLength(6);
expect(v.state.selection.ranges).toHaveLength(2);
expect(tab(v)).toBe(true);
expect(tab(v)).toBe(true);
expect(v.state.selection.ranges.map((r) => r.head)).toEqual([v.state.doc.line(3).to, v.state.doc.line(8).to]);
@@ -365,15 +407,36 @@ describe("template fields", () => {
await tick();
expect(press(v, "Escape")).toBe(true);
expect(v.state.selection.main.empty).toBe(true);
expect(hasNextSnippetField(v.state)).toBe(true);
expect(hasLinkedSnippetField(v.state, 1)).toBe(true);
expect(press(v, "Escape")).toBe(true);
expect(hasNextSnippetField(v.state)).toBe(false);
expect(hasLinkedSnippetField(v.state, 1)).toBe(false);
// Outside a template Enter and Esc are left to the editor.
expect(press(v, "Escape")).toBe(false);
});
});
describe("⌘J Insert Live Template", () => {
it.each([
{ label: "sout", insert: "System.out.println();" },
{ label: "fori", insert: "for (int i = 0; i < ; i++) {" },
])("replaces a backward selection when picking $label", async ({ label, insert }) => {
const text = "class Main {\n void f() {\n payload\n leftover\n return;\n }\n}";
const from = text.indexOf("payload");
const to = text.indexOf("leftover") + "leftover".length;
const v = await editor("java", text, from, [autocompletion()]);
v.dispatch({ selection: { anchor: to, head: from } });
insertLiveTemplate(v);
const result = await templateCompletionSource(new CompletionContext(v.state, from, true));
const option = result?.options.find((candidate) => candidate.label === label);
if (typeof option?.apply !== "function") throw new Error("Expected a live template completion");
option.apply(v, option, result!.from, from);
expect(v.state.doc.line(3).text.trim()).toBe(insert);
expect(v.state.doc.toString()).not.toMatch(/payload|leftover/);
expect(v.state.doc.toString()).toContain("return;");
expect(v.state.selection.ranges).toHaveLength(1);
});
it("opens a lookup restricted to live templates and ends with it", async () => {
const v = await editor("typescript", "function f() {\n ", undefined, [autocompletion()]);
const exclusive = () =>
+11 -71
View File
@@ -4,13 +4,11 @@
* application / field navigation.
*/
import {
clearSnippet,
closeCompletion,
completionStatus,
nextSnippetField,
pickedCompletion,
prevSnippetField,
snippet,
snippetKeymap,
startCompletion,
type Completion,
@@ -18,16 +16,7 @@ import {
type CompletionResult,
type CompletionSource,
} from "@codemirror/autocomplete";
import {
EditorSelection,
EditorState,
Facet,
Prec,
StateEffect,
StateField,
type Extension,
type Transaction,
} from "@codemirror/state";
import { EditorSelection, EditorState, Facet, Prec, StateEffect, StateField, type Extension } from "@codemirror/state";
import { EditorView, keymap, type Command } from "@codemirror/view";
import { executeAction, getAction } from "@/platform/actions";
import { useProject } from "@/platform/project";
@@ -50,14 +39,7 @@ import { showChooser, type ChooserItem } from "./popup/store";
import { expandEmmetAtCaret } from "./emmet/editor";
import { hasEmmet, loadEmmet } from "./emmet/model";
import { readClipboardPlainText } from "@/platform/clipboard";
import {
applyMulticaretSnippet,
clearMulticaretSnippet,
hasMulticaretSnippet,
moveMulticaretField,
multicaretFieldMoved,
multicaretSnippetExtension,
} from "./multicaretSnippet";
import { applySnippet, escapeSnippet, nextLiveSnippetField, snippetFieldMoved } from "@/editor/core/cm/linkedSnippet";
export interface TemplateDocInfo {
path: string;
@@ -149,23 +131,19 @@ async function expandAtSites(
const clipboard = needsClipboard(t) ? await readClipboard() : "";
if (view.state.doc !== state.doc || !view.state.selection.eq(state.selection) || view.state.readOnly) return;
let expansions = sites.map(({ from }) => expansionAt(state, t, from, clipboard, opts));
if (sites.length === 1) {
const { from, to } = sites[0]!;
clearMulticaretSnippet(view);
snippet(expansions[0]!.snippet)(view, null, from, to);
} else {
if (sites.length > 1) {
// A variable stays editable everywhere if any caret needs it as a tab stop.
const editable = new Set(expansions.flatMap((e) => e.fields));
if (expansions.some((e) => e.fields.length !== editable.size)) {
const variables = t.variables?.map((v) => (editable.has(v.name) ? { ...v, skipIfDefined: false } : v));
expansions = sites.map(({ from }) => expansionAt(state, { ...t, variables }, from, clipboard, opts));
}
applyMulticaretSnippet(
view,
sites.map((site, i) => ({ ...site, snippet: expansions[i]!.snippet })),
);
}
const exp = expansions[0]!;
applySnippet(
view,
sites.map((site, i) => ({ ...site, snippet: expansions[i]!.snippet })),
);
if (view.state.field(fieldCompletion, false) !== undefined)
view.dispatch({ effects: setFieldCompletion.of(exp.completing) });
if (exp.completeFirst) setTimeout(() => startCompletion(view), 0);
@@ -189,63 +167,29 @@ const fieldCompletion = StateField.define<readonly boolean[]>({
update: (value, tr) => tr.effects.find((e) => e.is(setFieldCompletion))?.value ?? value,
});
/**
* The snippet field a transaction moves to. CodeMirror doesn't expose it; its
* snippet-state effect carries the active snippet (`{ ranges, active }`).
*/
function movedToField(tr: Transaction): number | null {
for (const e of tr.effects) {
const v = e.value as { active?: unknown; ranges?: unknown } | null;
if (v && typeof v === "object" && typeof v.active === "number" && Array.isArray(v.ranges)) return v.active;
}
return null;
}
/** Moving to a field that asks for completion opens it, as IDEA does. */
const completeOnFieldMove = EditorView.updateListener.of((u) => {
if (u.docChanged) return;
const flags = u.state.field(fieldCompletion);
const field = u.transactions.map((tr) => multicaretFieldMoved(tr) ?? movedToField(tr)).findLast((i) => i !== null);
const field = u.transactions.map((tr) => snippetFieldMoved(tr)).findLast((i) => i !== undefined);
if (field == null || !flags[field]) return;
setTimeout(() => {
if (u.view.state.selection === u.state.selection) startCompletion(u.view);
}, 0);
});
/**
* Esc in a template, as in IDEA: first drops the selection (closing the lookup)
* or closes the lookup; only with neither does it leave the template.
*/
export const escapeTemplate: Command = (view) => {
const sel = view.state.selection;
if (sel.ranges.some((r) => !r.empty)) {
closeCompletion(view);
view.dispatch({
selection: EditorSelection.create(
sel.ranges.map((r) => EditorSelection.cursor(r.head)),
sel.mainIndex,
),
});
return true;
}
if (completionStatus(view.state) === "active") return closeCompletion(view);
return clearMulticaretSnippet(view) || clearSnippet(view);
};
const unlessLookup =
(cmd: Command): Command =>
(view) =>
completionStatus(view.state) === "active" ? false : cmd(view);
const nextMulticaretField = moveMulticaretField(1);
/**
* Whether the active snippet came from a live template or Emmet, where Enter moves to the
* next field. A completion's snippet (an LSP `<tag>$1</tag>$0`) keeps Enter for new lines.
*/
const templateSnippet = StateField.define<boolean>({
create: () => false,
update: (value, tr) => (movedToField(tr) === 0 && tr.docChanged ? !tr.annotation(pickedCompletion) : value),
update: (value, tr) => (snippetFieldMoved(tr) === 0 && tr.docChanged ? !tr.annotation(pickedCompletion) : value),
});
/** Tab moves to the next field; Enter too in templates (the lookup's while it is open). */
@@ -255,7 +199,7 @@ const templateFieldKeys = snippetKeymap.of([
key: "Enter",
run: unlessLookup((view) => view.state.field(templateSnippet, false) === true && nextSnippetField(view)),
},
{ key: "Escape", run: escapeTemplate },
{ key: "Escape", run: escapeSnippet },
]);
// ---------------------------------------------------------------------------
@@ -672,7 +616,6 @@ export function templateEditorExtension(ctx: EditorDocContext): Extension {
fieldCompletion,
templateSnippet,
completeOnFieldMove,
multicaretSnippetExtension,
templateFieldKeys,
templateLookup,
endTemplateLookup,
@@ -685,14 +628,11 @@ export function templateEditorExtension(ctx: EditorDocContext): Extension {
]),
Prec.high(
keymap.of([
{ key: "Enter", run: unlessLookup(nextMulticaretField) },
{ key: "Escape", run: (view) => hasMulticaretSnippet(view.state) && escapeTemplate(view) },
{ key: "Enter", run: unlessLookup(nextLiveSnippetField) },
{
key: "Tab",
shift: moveMulticaretField(-1),
run: (view) => {
if (view.state.readOnly || completionStatus(view.state) === "active") return false;
if (nextMulticaretField(view)) return true;
if (expandPostfixAtCaret(view)) return true;
if (useLiveTemplateOptions.getState().expandWithTab && expandLiveTemplateAtCaret(view)) return true;
return expandEmmetAtCaret(view, ctx.language);
-180
View File
@@ -1,180 +0,0 @@
import { clearSnippet, nextSnippetField, snippet } from "@codemirror/autocomplete";
import { isolateHistory } from "@codemirror/commands";
import { indentUnit } from "@codemirror/language";
import {
EditorSelection,
EditorState,
MapMode,
StateEffect,
StateField,
Text,
type Transaction,
} from "@codemirror/state";
import { Decoration, EditorView, WidgetType, type Command } from "@codemirror/view";
export interface SnippetSite {
from: number;
to: number;
snippet: string;
}
interface ActiveFields {
groups: readonly EditorSelection[];
active: number;
}
const setFields = StateEffect.define<ActiveFields | null>();
const fieldMark = Decoration.mark({ class: "cm-snippetField" });
const fieldCursor = Decoration.widget({
widget: new (class extends WidgetType {
toDOM() {
const span = document.createElement("span");
span.className = "cm-snippetFieldPosition";
return span;
}
ignoreEvent() {
return false;
}
})(),
});
const fields = StateField.define<ActiveFields | null>({
create: () => null,
update(value, tr) {
const next = tr.effects.find((e) => e.is(setFields));
if (next) return next.value;
if (!value) return null;
const { active } = value;
let { groups } = value;
if (tr.docChanged) {
const mapped: EditorSelection[] = [];
for (const group of groups) {
const ranges = [];
for (const range of group.ranges) {
const from = tr.changes.mapPos(range.from, -1, MapMode.TrackDel);
const to = tr.changes.mapPos(range.to, 1, MapMode.TrackDel);
if (from === null || to === null) return null;
ranges.push(EditorSelection.range(from, to));
}
mapped.push(EditorSelection.create(ranges, group.mainIndex));
}
groups = mapped;
}
const current = groups[active]!.ranges;
if (tr.selection && !tr.selection.ranges.every((r) => current.some((f) => f.from <= r.from && r.to <= f.to)))
return null;
return groups === value.groups ? value : { groups, active };
},
provide: (field) =>
EditorView.decorations.from(field, (v) =>
v
? Decoration.set(
v.groups.flatMap((g) => g.ranges.map((r) => (r.empty ? fieldCursor : fieldMark).range(r.from, r.to))),
true,
)
: Decoration.none,
),
});
export const hasMulticaretSnippet = (state: EditorState) => !!state.field(fields, false);
export function multicaretFieldMoved(tr: Transaction): number | undefined {
return tr.effects.find((e) => e.is(setFields))?.value?.active;
}
export const clearMulticaretSnippet: Command = (view) => {
if (!hasMulticaretSnippet(view.state)) return false;
view.dispatch({ effects: setFields.of(null) });
return true;
};
function selectField(view: EditorView, value: ActiveFields, active: number): boolean {
const selection = value.groups[active];
if (!selection) return false;
view.dispatch({
selection,
effects: setFields.of(active === value.groups.length - 1 ? null : { ...value, active }),
scrollIntoView: true,
});
return true;
}
export const moveMulticaretField =
(direction: 1 | -1): Command =>
(view) => {
const value = view.state.field(fields, false);
return value ? selectField(view, value, value.active + direction) : false;
};
export const multicaretSnippetExtension = [
fields,
EditorView.domEventHandlers({
mousedown(event, view) {
const value = view.state.field(fields);
if (!value || event.button !== 0) return false;
const pos = view.posAtCoords({ x: event.clientX, y: event.clientY });
if (pos === null) return false;
const index = value.groups.findIndex((g) => g.ranges.some((r) => r.from <= pos && pos <= r.to));
return index !== value.active && selectField(view, value, index);
},
}),
];
/** Ask CodeMirror to render each snippet in its line's indentation and expose its tab stops. */
function instantiate(source: EditorState, site: SnippetSite) {
const line = source.doc.lineAt(site.from);
const from = site.from - line.from;
const to = site.to - line.from;
let state = EditorState.create({
doc: line.text,
selection: EditorSelection.cursor(to),
extensions: [EditorState.allowMultipleSelections.of(true), indentUnit.of(source.facet(indentUnit))],
});
const dispatch = (tr: Transaction) => {
state = tr.state;
};
let insert = Text.empty;
snippet(site.snippet)(
{
state,
dispatch: (tr) => {
tr.changes.iterChanges((_from, _to, _start, _end, text) => {
insert = text;
});
dispatch(tr);
},
},
null,
from,
to,
);
const groups = [];
do {
groups.push(state.selection);
} while (nextSnippetField({ state, dispatch }));
return { from: site.from, to: site.to, offset: from, insert, groups };
}
export function applyMulticaretSnippet(view: EditorView, sites: readonly SnippetSite[]) {
const { state } = view;
const entries = sites.map((site) => instantiate(state, site));
const changes = state.changes(entries.map(({ from, to, insert }) => ({ from, to, insert })));
const groups = entries[0]!.groups.map((_, field) => {
let main = 0;
const ranges = entries.flatMap((entry, i) => {
const group = entry.groups[field]!;
const offset = changes.mapPos(entry.from, -1) - entry.offset;
if (i < state.selection.mainIndex) main += group.ranges.length;
return group.ranges.map((r) => EditorSelection.range(r.from + offset, r.to + offset));
});
return EditorSelection.create(ranges, main);
});
clearSnippet(view);
view.dispatch({
changes,
selection: groups[0]!,
effects: setFields.of(groups.length > 1 ? { groups, active: 0 } : null),
annotations: isolateHistory.of("full"),
scrollIntoView: true,
});
}
+6 -4
View File
@@ -10,6 +10,7 @@ export const BINARY_KIND = "binary";
const IMAGE_EXTENSIONS = new Set(["png", "jpg", "jpeg", "gif", "webp", "svg", "ico", "bmp", "avif"]);
const MARKDOWN_EXTENSIONS = new Set(["md", "markdown", "mdown", "mkd", "mkdn", "mdwn"]);
const MARKDOWN_SOURCE_EXTENSIONS = new Set([...MARKDOWN_EXTENSIONS, "mdx", "ronn", "workbook"]);
function extension(path: string): string {
const name = path.slice(path.lastIndexOf("/") + 1);
@@ -21,12 +22,13 @@ export const isImagePath = (path: string) => IMAGE_EXTENSIONS.has(extension(path
export const isSvgPath = (path: string) => extension(path) === "svg";
/**
* Whether `path` gets the Markdown preview, decided synchronously so a tab never opens
* without it first: Markdown by Settings › File Types.
* Whether `path` gets the Markdown preview under Settings › File Types.
* The source check also includes Markdown extensions that open in the editor alone.
*/
export function isMarkdownPath(path: string): boolean {
export function isMarkdownPath(path: string, mode: "preview" | "source" = "preview"): boolean {
const { settings, project } = useProject.getState();
return hasFileType(path, ["markdown"], MARKDOWN_EXTENSIONS, settings?.files, project?.root ?? null);
const extensions = mode === "source" ? MARKDOWN_SOURCE_EXTENSIONS : MARKDOWN_EXTENSIONS;
return hasFileType(path, ["markdown"], extensions, settings?.files, project?.root ?? null);
}
/** Whether the file's name matches one of `patterns` (`*.xlsx`); Windows/macOS match case-insensitively. */
@@ -50,6 +50,7 @@ import { MarkdownLayoutActions } from "./MarkdownLayoutActions";
import {
ANCHOR_PREFIX,
createMarkdownRenderer,
headingLine,
previewLineAtOffset,
previewOffsetForLine,
resolveLink,
@@ -59,6 +60,7 @@ import { applyImageZoomWidth, svgDataUrlSize } from "@/ui/svgSize";
import styles from "./Markdown.module.css";
import { tx } from "@/platform/i18n";
import { wheelZoomStep } from "@/platform/wheelZoom";
import { isMarkdownPath } from "../fileKinds";
import { attachPanZoom } from "../panZoom";
/** Loaded local images by absolute path (data URLs), shared by all previews. */
@@ -76,6 +78,18 @@ function imageUrl(path: string): Promise<string> {
return p;
}
/**
* Line of the heading `anchor` in the Markdown file `path`, from an open editor's text (unsaved
* edits included) or else the file on disk; undefined when the file is not Markdown, cannot be
* read or has no such heading.
*/
async function anchorLine(path: string, anchor: string): Promise<number | undefined> {
if (!isMarkdownPath(path, "source")) return undefined;
const open = editorsFor(path)[0];
const text = open ? open.view.state.doc.toString() : await call(commands.fsReadText(path)).catch(() => null);
return (text === null ? null : headingLine(text, anchor)) ?? undefined;
}
function openExternal(url: string) {
if (isTauri()) void import("@tauri-apps/plugin-opener").then((m) => m.openUrl(url)).catch(() => {});
else window.open(url, "_blank", "noopener");
@@ -209,6 +223,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
const html = useMemo(() => render(deferred), [render, deferred]);
const renderSvg = html.includes(' data-math="') ? use(loadSvgRenderer()) : null;
const ref = useRef<HTMLDivElement>(null);
const linkRequest = useRef(0);
const blocks = useRef<ReturnType<typeof blocksOf>>([]);
const theme = useSyncExternalStore(subscribeTheme, themeKey, () => "");
const diagrams = useRef<Node[]>([]);
@@ -223,7 +238,12 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
/** `<details>` the reader opened or closed, by position: each edit re-renders them as written. */
const toggled = useRef(new Map<number, boolean>());
useLayoutEffect(() => toggled.current.clear(), [path]);
useLayoutEffect(() => {
toggled.current.clear();
return () => {
linkRequest.current++;
};
}, [path]);
useLayoutEffect(() => {
ref.current?.querySelectorAll("details").forEach((d, i) => {
const open = toggled.current.get(i);
@@ -382,6 +402,8 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
useLayoutEffect(() => {
const root = ref.current;
if (!root || caretSeq === seenCaret.current) return;
// First-open navigation can arrive before the destination's deferred Markdown is rendered.
if (!sync && deferred !== text) return;
seenCaret.current = caretSeq;
if (sync) return;
if (find && find.currentMatchIndex >= 0) {
@@ -403,7 +425,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
restoreRetry.current = null;
}
setShownLine(path, caretLine);
}, [caretSeq, caretLine, sync, path, find]);
}, [caretSeq, caretLine, sync, path, find, deferred, text]);
// Search (⌘F) and selection occurrence highlights in the preview.
useLayoutEffect(() => {
@@ -542,6 +564,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
e.preventDefault();
const target = resolveLink(path, a.getAttribute("href") ?? "");
if (!target) return;
const request = ++linkRequest.current;
const scrollTo = (id: string) => {
const root = ref.current;
if (!root) return;
@@ -555,10 +578,14 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
else if (target.kind === "anchor") scrollTo(target.id);
else if (target.path === path && target.anchor) scrollTo(target.anchor);
else
void maybeEditorService()?.openFile(target.path, {
focus: true,
...(target.line !== undefined ? { selection: { line: target.line, col: 0 } } : {}),
});
void (async () => {
const line = target.line ?? (target.anchor ? await anchorLine(target.path, target.anchor) : undefined);
if (request !== linkRequest.current) return;
await maybeEditorService()?.openFile(target.path, {
focus: true,
...(line !== undefined ? { selection: { line, col: 0 } } : {}),
});
})();
};
return (
@@ -0,0 +1,140 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { _addEditor, _removeEditor, editorContributions, type EditorDocContext } from "@/editor/api";
import { fontZoom } from "@/editor/core/cm/prefs";
import { useContextKeys } from "@/platform/context";
import { useProject } from "@/platform/project";
import type { Settings } from "@/platform/ipc";
import { registerMarkdownLiveSource, useLiveMarkdown } from "./live";
import { MarkdownEditor } from "./MarkdownEditor";
import { useMarkdownModes } from "./modes";
const openFile = vi.fn(async () => {});
const targetText = "# 成交对账\n\n正文\n\n## 5.2 状态机\n";
const disk: Record<string, string | Promise<string>> = {
"/p/b.md": targetText,
"/p/c.txt": targetText,
"/p/alias.mkdn": targetText,
"/p/assigned.txt": targetText,
"/p/plain.md": targetText,
"/p/source.mdx": targetText,
};
vi.mock("@/workbench/contributions", async (importOriginal) => ({
...(await importOriginal<typeof import("@/workbench/contributions")>()),
maybeEditorService: () => ({ openFile }),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const ipc = await importOriginal<typeof import("@/platform/ipc")>();
return {
...ipc,
commands: { ...ipc.commands, fsReadText: (path: string) => ({ readText: path }) },
call: (request: unknown) => {
const path = (request as { readText?: string } | null)?.readText;
if (path === undefined) return ipc.call(request as never);
return path in disk ? Promise.resolve(disk[path]) : Promise.reject(new Error("missing"));
},
};
});
const ctx: EditorDocContext = { doc: 1, path: "/p/a.md", language: "markdown", uiMode: null, readOnly: false };
const doc = [
"[disk](b.md#52-%E7%8A%B6%E6%80%81%E6%9C%BA)",
"[open](d.md#52-状态机)",
"[line](b.md#L3)",
"[none](b.md#missing)",
"[text](c.txt#52-状态机)",
"[alias](alias.mkdn#52-状态机)",
"[assigned](assigned.txt#52-状态机)",
"[plain](plain.md#52-状态机)",
"[source](source.mdx#52-状态机)",
"",
].join("\n\n");
describe("preview links to a heading in another file", () => {
const disposers: Array<() => void> = [];
const views: EditorView[] = [];
beforeEach(() => {
openFile.mockClear();
const settings = useProject.getState().settings;
useProject.setState({
settings: {
files: { fileTypeOverrides: { "/p/assigned.txt": "markdown", "/p/plain.md": "plaintext" } },
} as Settings,
});
disposers.push(() => useProject.setState({ settings }));
disposers.push(registerMarkdownLiveSource());
useContextKeys.setState({ projectOpen: true, textEditorActive: true });
const live = editorContributions().find((c) => c.id === "viewers.markdownLive")!;
const view = new EditorView({ state: EditorState.create({ doc, extensions: [fontZoom, live.extensions(ctx)] }) });
// An open editor's unsaved text wins over the file on disk.
const other = new EditorView({ state: EditorState.create({ doc: "# D\n\nnew line\n\n## 5.2 状态机\n" }) });
views.push(view, other);
for (const handle of [
{ view, ctx },
{ view: other, ctx: { ...ctx, doc: 2, path: "/p/d.md" } },
]) {
_addEditor(handle);
disposers.push(() => _removeEditor(handle));
}
act(() => useMarkdownModes.setState((s) => ({ byTab: { ...s.byTab, t: "preview" } })));
});
afterEach(() => {
cleanup();
for (const view of views.splice(0)) view.destroy();
for (const dispose of disposers.splice(0).reverse()) dispose();
useLiveMarkdown.setState({}, true);
useContextKeys.setState({}, true);
});
const renderPreview = async () => {
render(
<MarkdownEditor path={ctx.path} tabId="t">
<div />
</MarkdownEditor>,
);
const preview = screen.getByRole("document", { name: "Markdown preview" });
await waitFor(() => expect(preview.querySelectorAll("a")).toHaveLength(9));
};
it("opens the file at the heading line", async () => {
await renderPreview();
const click = async (name: string) => {
openFile.mockClear();
fireEvent.click(screen.getByText(name));
await waitFor(() => expect(openFile).toHaveBeenCalledTimes(1));
return openFile.mock.calls[0];
};
expect(await click("disk")).toEqual(["/p/b.md", { focus: true, selection: { line: 4, col: 0 } }]);
expect(await click("open")).toEqual(["/p/d.md", { focus: true, selection: { line: 4, col: 0 } }]);
expect(await click("line")).toEqual(["/p/b.md", { focus: true, selection: { line: 2, col: 0 } }]);
expect(await click("none")).toEqual(["/p/b.md", { focus: true }]);
expect(await click("text")).toEqual(["/p/c.txt", { focus: true }]);
expect(await click("alias")).toEqual(["/p/alias.mkdn", { focus: true, selection: { line: 4, col: 0 } }]);
expect(await click("assigned")).toEqual(["/p/assigned.txt", { focus: true, selection: { line: 4, col: 0 } }]);
expect(await click("plain")).toEqual(["/p/plain.md", { focus: true }]);
expect(await click("source")).toEqual(["/p/source.mdx", { focus: true, selection: { line: 4, col: 0 } }]);
});
it("keeps a slow heading lookup from superseding a newer link", async () => {
await renderPreview();
let resolve!: (text: string) => void;
disk["/p/b.md"] = new Promise<string>((done) => {
resolve = done;
});
try {
fireEvent.click(screen.getByText("disk"));
fireEvent.click(screen.getByText("line"));
await waitFor(() =>
expect(openFile).toHaveBeenCalledExactlyOnceWith("/p/b.md", { focus: true, selection: { line: 2, col: 0 } }),
);
await act(async () => resolve(targetText));
expect(openFile).toHaveBeenCalledTimes(1);
} finally {
disk["/p/b.md"] = targetText;
}
});
});
@@ -5,6 +5,7 @@ import { renderMath } from "@/editor/lsp/markdownMath";
import {
createMarkdownRenderer,
frontMatter,
headingLine,
joinPath,
previewLineAtOffset,
previewOffsetForLine,
@@ -286,6 +287,36 @@ describe("markdown preview rendering", () => {
expect(slugify("Hello, World! v2")).toBe("hello-world-v2");
});
it("finds the source line of a heading anchor, as a link from another file opens there", () => {
const text = [
"---",
"title: x",
"---",
"# 成交对账",
"",
"```md",
"## 5.2 状态机",
"```",
"",
"## 5.2 状态机",
"",
"正文",
"",
"## 5.2 状态机",
"",
"### 4.1 Dubbo(`otcs-t0-server` client)",
].join("\n");
expect(headingLine(text, "成交对账")).toBe(3);
expect(headingLine(text, "52-状态机")).toBe(9);
expect(headingLine(text, "52-状态机-1")).toBe(13);
expect(headingLine(text, "user-content-52-状态机")).toBe(9);
expect(headingLine(text, "41-dubbootcs-t0-server-client")).toBe(15);
const link = resolveLink("/repo/a.md", "b.md#52-%E7%8A%B6%E6%80%81%E6%9C%BA");
expect(link).toEqual({ kind: "file", path: "/repo/b.md", anchor: "52-状态机" });
expect(headingLine(text, "missing")).toBeNull();
expect(headingLine(text, "")).toBeNull();
});
it("resolves links against the file", () => {
const file = "/repo/docs/guide.md";
expect(resolveLink(file, "https://x.dev")).toEqual({ kind: "external", url: "https://x.dev" });
+29 -4
View File
@@ -69,6 +69,14 @@ export function slugify(text: string): string {
.replace(/\s/g, "-");
}
/** The id of the next heading titled `text`, counting repeats in `slugs` as GitHub does (`a`, `a-1`, `a-2`…). */
function headingId(slugs: Map<string, number>, text: string): string {
const base = slugify(text);
const n = slugs.get(base) ?? 0;
slugs.set(base, n + 1);
return n ? `${base}-${n}` : base;
}
const countLines = (s: string) => {
let n = 0;
for (let i = s.indexOf("\n"); i >= 0; i = s.indexOf("\n", i + 1)) n++;
@@ -161,10 +169,8 @@ function blocks(text: string): { line: number; html: string }[] {
const list = Object.assign([token], { links: tokens.links }) as TokensList;
let body = marked.parser(list);
if (token.type === "heading") {
const base = slugify((token as Token & { text: string }).text);
const n = slugs.get(base) ?? 0;
slugs.set(base, n + 1);
body = body.replace(/^<h(\d)>/, `<h$1 id="${ANCHOR_PREFIX}${n ? `${base}-${n}` : base}">`);
const id = headingId(slugs, (token as Token & { text: string }).text);
body = body.replace(/^<h(\d)>/, `<h$1 id="${ANCHOR_PREFIX}${id}">`);
}
group ??= { line: start, html: "" };
group.html += body;
@@ -193,6 +199,25 @@ const wrap = (line: number, html: string) => `<div data-line="${line}">${html}</
const sanitizeWhole = (all: readonly { line: number; html: string }[]) =>
purify().sanitize(all.map((b) => wrap(b.line, b.html)).join(""), SANITIZE);
/**
* 0-based source line of the heading the preview gives the anchor `anchor` (with or without
* {@link ANCHOR_PREFIX}), or null when no heading has it. Lets a link to another file open at
* that heading.
*/
export function headingLine(text: string, anchor: string): number | null {
const want = slugify(anchor.startsWith(ANCHOR_PREFIX) ? anchor.slice(ANCHOR_PREFIX.length) : anchor);
if (!want) return null;
const front = frontMatter(text);
const body = front ? text.split("\n").slice(front.lines).join("\n") : text;
const slugs = new Map<string, number>();
let line = front?.lines ?? 0;
for (const token of marked.lexer(body)) {
if (token.type === "heading" && headingId(slugs, (token as Token & { text: string }).text) === want) return line;
line += countLines(token.raw);
}
return null;
}
export function renderMarkdown(text: string): string {
return sanitizeWhole(blocks(text));
}
+11 -2
View File
@@ -14,6 +14,7 @@ import {
type RequestId,
} from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { projectFolder, relativePath, useProject } from "@/platform/project";
import { useBuildPresentation } from "@/platform/projectPresentation";
import { isRemoteWindow } from "@/platform/remote";
@@ -198,6 +199,7 @@ export async function findJavaModule(config: RunConfig): Promise<string | null>
/** Module directories (as {@link jvmModuleDir}) of the project's sources declaring the class `binaryName`. */
export async function classModules(binaryName: string): Promise<string[]> {
const root = useProject.getState().project?.root;
const outer = binaryName.split("$")[0]!;
const simple = outer.slice(outer.lastIndexOf(".") + 1);
const pkg = outer.slice(0, Math.max(0, outer.lastIndexOf(".")));
@@ -210,7 +212,7 @@ export async function classModules(binaryName: string): Promise<string[]> {
for (const file of matches) {
const text = await call(commands.fsReadText(file.path));
const sourcePackage = /^\s*package\s+([\w.]+)\s*[;\r\n]/m.exec(text)?.[1] ?? "";
if (sourcePackage === pkg) modules.add(jvmModuleDir(file.relPath, configs));
if (sourcePackage === pkg) modules.add(jvmModuleDir(root ? relativePath(root, file.path) : file.relPath, configs));
}
return [...modules];
}
@@ -291,5 +293,12 @@ export async function prepareJavaLaunch(config: RunConfig, preparation: JavaPrep
}
if (parsed.classpath && !info.classPaths.length)
throw new Error(tx("The classpath is empty: is the module imported by the Java language server?"));
return { module, info, resolved: resolveJavaCommand(config, info) };
const resolved = resolveJavaCommand({ ...config, module }, info);
const project = useProject.getState().project;
if (resolved.cwd == null && project?.workspace) {
const path = /^(?:[A-Za-z]:)?\//.test(module) ? module : `${project.root}/${module}`;
const owner = projectFolder(project, path);
if (owner && owner.root !== project.root) resolved.cwd = path;
}
return { module, info, resolved };
}
+1 -6
View File
@@ -1,5 +1,5 @@
import { afterEach, expect, it, vi } from "vitest";
import { appDataDir, loadPlatformInfo, usePlatform } from "./platformInfo";
import { loadPlatformInfo, usePlatform } from "./platformInfo";
const appInfo = vi.hoisted(() => vi.fn());
vi.mock("@/platform/ipc", () => ({ isTauri: () => true, commands: { appInfo } }));
@@ -24,11 +24,6 @@ it("keeps platform defaults when the query fails", async () => {
expect(usePlatform.getState()).toEqual(initialPlatform);
});
it("takes the user data directory from the backend, which may have moved it", async () => {
appInfo.mockResolvedValue({ platform: "windows", dataDir: "E:/OpenIDEA/ai.l0ng.openidea/" });
expect(await appDataDir()).toBe("E:/OpenIDEA/ai.l0ng.openidea");
});
it.each([
[
{ left: ["close", "maximize", "minimize"], right: [] },
-8
View File
@@ -41,14 +41,6 @@ export const usePlatform = create<PlatformInfo>(() => {
};
});
let dataDir: Promise<string> | undefined;
/** The user data directory (scratches, plugins, Local History), which `OPENIDEA_DATA_DIR` can move. */
export function appDataDir(): Promise<string> {
dataDir ??= commands.appInfo().then((info) => info.dataDir.replace(/\/+$/, ""));
return dataDir;
}
export async function loadPlatformInfo() {
if (!isTauri()) return;
try {
+28
View File
@@ -4,6 +4,7 @@ import { call, commands, type ChannelFrame, type ExecutionEvent, type ProjectInf
import { useProject } from "./project";
import { disableRemote, enableRemote, useRemote } from "./remote";
import { encodeArgs, remoteRouting } from "./remote";
import { scratchesDir } from "./scratchesDir";
describe("remote invoke", () => {
beforeAll(() => {
@@ -54,6 +55,33 @@ describe("remote invoke", () => {
}
});
it("routes a scratch folder lookup made as soon as the remote session is published", async () => {
const invoke = vi.fn(async (command: string, args: { cmd: string }) => {
expect(command).toBe("remote_invoke");
expect(args.cmd).toBe("fs_scratches_dir");
return JSON.stringify("/home/me/.openidea/data/scratches");
});
vi.stubGlobal("__TAURI_INTERNALS__", { invoke, transformCallback: () => 1 });
const unsubscribe = useRemote.subscribe(({ session }) => {
if (session) void scratchesDir();
});
try {
enableRemote({
target: { kind: "ssh", config: "test" },
root: "/home/me/project",
host: "test",
os: "linux",
commands: ["fs_scratches_dir"],
});
await expect(scratchesDir()).resolves.toBe("/home/me/.openidea/data/scratches");
expect(invoke).toHaveBeenCalledOnce();
} finally {
unsubscribe();
disableRemote();
vi.unstubAllGlobals();
}
});
it("routes served commands, keeps opening / closing local and sets global settings on both sides", () => {
const served = new Set([
"vcs_add_to_ignore",
+1 -1
View File
@@ -153,8 +153,8 @@ const route: InvokeRoute = (cmd, args, options) => {
*/
export function enableRemote(session: RemoteSession) {
routed = new Set(session.commands);
useRemote.setState({ session, lost: null, reconnecting: false });
setInvokeRoute(route);
useRemote.setState({ session, lost: null, reconnecting: false });
}
export function disableRemote() {
+38
View File
@@ -0,0 +1,38 @@
import { afterEach, expect, it, vi } from "vitest";
import { useRemote } from "./remote";
import { scratchesDir } from "./scratchesDir";
// Routed like every file command: the server answers in a remote window.
const fsScratchesDir = vi.hoisted(() => vi.fn());
vi.mock("@/platform/ipc", async (importOriginal) => {
const m = await importOriginal<typeof import("@/platform/ipc")>();
return { ...m, call: async (p: Promise<unknown>) => await p, commands: { ...m.commands, fsScratchesDir } };
});
afterEach(() => useRemote.setState({ session: null }));
it("asks the host again once the window attaches to or leaves a remote server", async () => {
fsScratchesDir.mockResolvedValue("C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches/");
const pending = scratchesDir();
expect(scratchesDir()).toBe(pending);
expect(await pending).toBe("C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches");
expect(await scratchesDir()).toBe("C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches");
expect(fsScratchesDir).toHaveBeenCalledTimes(2);
fsScratchesDir.mockResolvedValue("/home/me/.openidea/data/scratches");
useRemote.setState({ session: { root: "/home/me/project" } as never });
expect(await scratchesDir()).toBe("/home/me/.openidea/data/scratches");
fsScratchesDir.mockResolvedValue("C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches");
useRemote.setState({ session: null });
expect(await scratchesDir()).toBe("C:/Users/me/AppData/Roaming/ai.l0ng.openidea/scratches");
expect(fsScratchesDir).toHaveBeenCalledTimes(4);
});
it("asks again after a failure", async () => {
useRemote.setState({ session: { root: "/p" } as never });
fsScratchesDir.mockRejectedValueOnce(new Error("disconnected"));
await expect(scratchesDir()).rejects.toThrow("disconnected");
fsScratchesDir.mockResolvedValue("/home/me/.openidea/data/scratches");
expect(await scratchesDir()).toBe("/home/me/.openidea/data/scratches");
});
+25
View File
@@ -0,0 +1,25 @@
import { call, commands } from "@/platform/ipc";
import { useRemote } from "@/platform/remote";
let dir: Promise<string> | null = null;
// A window attaches to (or leaves) a remote server in place: the folder is then another host's.
useRemote.subscribe((state, previous) => {
if (state.session !== previous.session) dir = null;
});
/**
* The scratch files' folder (`<user data>/scratches`) of the host that runs this window's file
* commands: the server in a remote window, this machine otherwise. Ensures the folder exists.
*/
export function scratchesDir(): Promise<string> {
if (!dir) {
const pending = call(commands.fsScratchesDir())
.then((path) => path.replace(/\/+$/, ""))
.finally(() => {
if (dir === pending) dir = null;
});
dir = pending;
}
return dir;
}
+6
View File
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
gitRevisionOf,
isVirtualUri,
libraryArchiveRoot,
libraryEntryPaths,
virtualContainer,
virtualName,
@@ -130,6 +131,11 @@ describe("libraryEntryPaths", () => {
]),
).toEqual([`${SOURCES}!/org/x/Y.java`, `${GRADLE}/sourceHash/a-1.0.jar!/org/x/Y.class`]);
});
it("names the archive that contains a library document", () => {
expect(libraryArchiveRoot(JDT)).toBe("/m2/spring-boot-4.1.1.jar!");
expect(libraryArchiveRoot("untitled:Untitled-1")).toBeNull();
});
});
describe("Git revision URIs", () => {
+7
View File
@@ -185,3 +185,10 @@ export function libraryEntryPaths(uri: string, archives: readonly string[] = [])
if (jar.endsWith("/jrt-fs.jar")) return [`${parentDir(jar)}/src.zip!/${module}/${stem}.java`];
return jarCandidates(jar, stem, archives);
}
/** The archive root (`<jar>!`) containing a library document, when it has one. */
export function libraryArchiveRoot(uri: string): string | null {
const entry = libraryEntryPaths(uri)[0];
const separator = entry?.indexOf("!/") ?? -1;
return entry && separator > 0 ? `${entry.slice(0, separator)}!` : null;
}
+18 -2
View File
@@ -5,6 +5,7 @@ import {
type InputHTMLAttributes,
type FocusEvent,
type KeyboardEvent,
type MouseEvent,
type ReactNode,
type Ref,
type TextareaHTMLAttributes,
@@ -12,6 +13,7 @@ import {
import clsx from "clsx";
import { Icon, type IconName } from "./icons";
import { IconButton } from "./Button";
import { startDragAutoscroll } from "./dragAutoscroll";
import styles from "./Input.module.css";
import { setContext } from "@/platform/context";
import { useGivenTx } from "@/platform/i18n";
@@ -37,6 +39,7 @@ export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
autoComplete = "off",
placeholder,
onFocus,
onMouseDown,
"aria-label": ariaLabel,
...rest
},
@@ -62,6 +65,10 @@ export const Input = forwardRef<HTMLInputElement, InputProps>(function Input(
}
onFocus?.(e);
}}
onMouseDown={(e) => {
onMouseDown?.(e);
startDragAutoscroll(e);
}}
className={clsx(styles.input, variant === "bare" ? styles.bare : styles.framed, mono && styles.mono, className)}
{...rest}
/>
@@ -163,7 +170,7 @@ export const SearchField = forwardRef<HTMLInputElement, SearchFieldProps>(functi
commands.current.newLine = multiline ? insertNewLine : undefined;
// oxlint-disable-next-line react/refs
commands.current.history = onHistory;
const { onKeyDown, onFocus, onBlur, ...fieldProps } = rest;
const { onKeyDown, onFocus, onBlur, onMouseDown, ...fieldProps } = rest;
const keyDown = (e: KeyboardEvent<HTMLInputElement>) => {
if (multiline && isNewLineKey(e)) {
e.preventDefault();
@@ -186,7 +193,16 @@ export const SearchField = forwardRef<HTMLInputElement, SearchFieldProps>(functi
}
onBlur?.(e);
};
const handlers = { onKeyDown: keyDown, onFocus: focus, onBlur: blur };
const mouseDown = (e: MouseEvent<HTMLInputElement>) => {
onMouseDown?.(e);
startDragAutoscroll(e);
};
const handlers = {
onKeyDown: keyDown,
onFocus: focus,
onBlur: blur,
onMouseDown: mouseDown,
};
// Removing a focused field fires no blur.
useEffect(() => {
const own = commands.current;
+65
View File
@@ -319,6 +319,71 @@ describe("Tree speed search", () => {
}
});
it.each([
{ os: "macos", preset: "intellij-macos", binding: "Meta+V", key: "v", modifiers: { metaKey: true } },
{ os: "windows", preset: "intellij-windows", binding: "Ctrl+V", key: "v", modifiers: { ctrlKey: true } },
{
os: "windows",
preset: "intellij-windows",
binding: "Shift+Insert",
key: "Insert",
modifiers: { shiftKey: true },
},
])("$binding routes clipboard text to speed search", ({ os, preset, binding, key, modifiers }) => {
const previousOs = usePlatform.getState().os;
usePlatform.setState({ os });
const pasteFiles = vi.fn();
useKeymap.setState({ preset, overrides: { "test.paste": [binding] } });
const find = os === "macos" ? { metaKey: true } : { ctrlKey: true };
const dispose = [
registerAction({ id: "test.paste", title: "Paste", run: pasteFiles }),
installKeyboardDispatcher(),
];
try {
const view = setup({
defaultExpanded: ["src", "main"],
roots: [...data, { id: "notes v1" }, { id: "notes v1" }],
});
const tree = view.tree;
const paste = (text: string) =>
fireEvent.paste(tree, { clipboardData: { getData: () => text } } as unknown as ClipboardEventInit);
view.key("ArrowDown");
// Find arms the search with an empty query; the clipboard text becomes the query.
view.key("f", find);
expect(screen.getByRole("status").textContent).toBe("");
paste("index.t");
expect(screen.getByRole("status")).toHaveTextContent(/^index\.t$/);
expect(view.lead()).toBe("index.ts");
// A line of pasted text joins the query as typing it would; a wrapped name stays one line.
paste("s");
expect(screen.getByRole("status")).toHaveTextContent(/^index\.ts$/);
// Paste is the query's, not the view's file Paste, while the search is active.
view.key(key, modifiers);
expect(pasteFiles).not.toHaveBeenCalled();
// A blank clipboard changes nothing.
paste(" ");
expect(screen.getByRole("status")).toHaveTextContent(/^index\.ts$/);
// Closed, the view's Paste owns the shortcut again.
view.key("Escape");
view.key(key, modifiers);
expect(pasteFiles).toHaveBeenCalledOnce();
expect(view.tree).toHaveFocus();
// A multi-line clipboard is flattened into the one-line query.
view.key("f", find);
paste("App\n.tsx");
expect(screen.getByRole("status")).toHaveTextContent(/^App \.tsx$/);
view.key("Escape");
view.key("f", find);
paste("notes v1");
expect(screen.getByRole("status").textContent).toBe("notes v1");
expect(view.lead()).toBe("notes v1");
} finally {
dispose.forEach((d) => d());
useKeymap.setState({ overrides: {} });
usePlatform.setState({ os: previousOs });
}
});
it("filter mode hides non-matching rows but keeps ancestors", () => {
const { tree, key } = setup({ defaultExpanded: ["src", "main"], speedSearchMode: "filter" });
key("ArrowDown");
+30 -4
View File
@@ -43,6 +43,13 @@ import { useIconRowHeight } from "./iconAppearance";
export type { TreeReorder } from "./treeReorder";
/** The host's native Paste shortcuts. */
const isPasteStroke = (stroke: string) =>
isMacHost() ? stroke === "Meta+V" : stroke === "Ctrl+V" || stroke === "Shift+Insert";
/** Pasted text as one query line: a speed search has no caret and no newlines. */
const queryLine = (text: string) => text.replace(/[\r\n\u2028\u2029]+/g, " ").trim();
export interface TreeRowState {
depth: number;
expanded: boolean;
@@ -398,19 +405,22 @@ export function Tree<T>(props: TreeProps<T>) {
pendingScrollToLead.current = null;
}, [lead, indexOfKey, virtualizer]);
// Speed search owns Escape while active, and ⌫ with any modifier: the query is edited like a
// text field instead of the view's shortcuts running (⌘⌫ is Drop… in the Database view).
// While speed search is active, reserve Backspace and the native Paste shortcuts for the query.
// The view's shortcuts can drop a database object or paste files into the project.
useEffect(() => {
if (!searching) return;
const release = acquirePopup();
const unclaim = registerKeyClaim(
(e) => e.key === "Backspace" && e.target instanceof Node && !!scrollRef.current?.contains(e.target),
(e, stroke) =>
e.target instanceof Node &&
!!scrollRef.current?.contains(e.target) &&
(e.key === "Backspace" || (speedSearch && isPasteStroke(stroke))),
);
return () => {
release();
unclaim();
};
}, [searching]);
}, [searching, speedSearch]);
const setExpanded = (row: Row<T>, open: boolean) => {
if (!row.expandable || row.expanded === open) return;
@@ -545,6 +555,21 @@ export function Tree<T>(props: TreeProps<T>) {
return i;
};
/** The active speed search takes pasted text: its query is edited like a text field. */
const onPaste = (e: React.ClipboardEvent) => {
if (e.defaultPrevented || !speedSearch || !searching) return;
// An inline editor (rename, new value) inside a row keeps the native paste.
if ((e.target as HTMLElement | null)?.closest?.("input, textarea, [contenteditable]")) return;
const text = queryLine(e.clipboardData?.getData("text/plain") ?? "");
if (!text) return;
e.preventDefault();
e.stopPropagation();
const q = query + text;
setQuery(q);
const hit = findMatch(leadIndex, 1, true, q);
if (hit >= 0) selectIndex(hit);
};
const onKeyDown = (e: KeyboardEvent) => {
const row = leadIndex >= 0 ? rows[leadIndex] : undefined;
const pageSize = Math.max(1, Math.floor((scrollRef.current?.clientHeight ?? 300) / rowHeight) - 1);
@@ -728,6 +753,7 @@ export function Tree<T>(props: TreeProps<T>) {
tabIndex={0}
className={styles.tree}
onKeyDown={onKeyDown}
onPaste={onPaste}
onBlur={(e) => {
if (e.currentTarget.contains(e.relatedTarget as Node | null)) return;
endSearch();
+80
View File
@@ -0,0 +1,80 @@
import { cleanup, fireEvent, render } from "@testing-library/react";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { Input, SearchField } from "./Input";
const distancePerCharacter = 20;
const fieldWidth = 100;
const value = "字".repeat(30);
beforeEach(() => {
vi.useFakeTimers();
const canvasContext = {
measureText: (text: string) => ({ width: text.length * distancePerCharacter }),
} as CanvasRenderingContext2D;
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(canvasContext);
});
afterEach(() => {
fireEvent.mouseUp(window);
cleanup();
vi.useRealTimers();
vi.restoreAllMocks();
});
function setFieldGeometry(field: HTMLInputElement | HTMLTextAreaElement) {
Object.defineProperties(field, {
clientWidth: { value: fieldWidth },
scrollWidth: { value: value.length * distancePerCharacter },
});
vi.spyOn(field, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 0, fieldWidth, 20));
}
it.each([
{ edge: "left", pointerX: -1, endpoint: "selectionStart" },
{ edge: "right", pointerX: fieldWidth + 1, endpoint: "selectionEnd" },
] as const)("keeps scrolling past wide characters at the $edge edge", ({ edge, pointerX, endpoint }) => {
const view = render(<SearchField value={value} onChange={() => {}} multiline />);
const field = view.getByRole("textbox") as HTMLTextAreaElement;
setFieldGeometry(field);
field.focus();
field.scrollLeft = 200;
field.setSelectionRange(12, 12);
fireEvent.mouseDown(field, { button: 0, clientX: 42, clientY: 10 });
fireEvent.mouseMove(window, { buttons: 1, clientX: pointerX, clientY: 10 });
for (let i = 0; i < 25; i++) vi.advanceTimersToNextFrame();
if (edge === "left") {
expect(field.scrollLeft).toBeLessThan(200);
expect(field[endpoint]).toBeLessThan(10);
expect(field.selectionEnd).toBe(12);
} else {
expect(field.scrollLeft).toBeGreaterThan(200);
expect(field[endpoint]).toBeGreaterThan(15);
expect(field.selectionStart).toBe(12);
}
fireEvent.mouseUp(window);
const offset = field.scrollLeft;
vi.advanceTimersToNextFrame();
expect(field.scrollLeft).toBe(offset);
});
it.each(["number", "date", "password"])("leaves selection to the browser for %s inputs", (type) => {
const { container } = render(<Input type={type} />);
const field = container.querySelector("input")!;
setFieldGeometry(field);
field.focus();
const selection = vi.spyOn(field, "setSelectionRange").mockImplementation(() => {});
fireEvent.mouseDown(field, { button: 0, clientX: 42, clientY: 10 });
expect(fireEvent.mouseMove(window, { buttons: 1, clientX: 120, clientY: 10 })).toBe(true);
expect(selection).not.toHaveBeenCalled();
});
it("respects a caller that prevents the start of a drag", () => {
const view = render(<Input defaultValue={value} onMouseDown={(e) => e.preventDefault()} />);
const field = view.getByRole("textbox") as HTMLInputElement;
setFieldGeometry(field);
field.focus();
fireEvent.mouseDown(field, { button: 0, clientX: 42, clientY: 10 });
expect(fireEvent.mouseMove(window, { buttons: 1, clientX: 120, clientY: 10 })).toBe(true);
expect(field.scrollLeft).toBe(0);
});
+126
View File
@@ -0,0 +1,126 @@
import type { MouseEvent as ReactMouseEvent } from "react";
type TextField = HTMLInputElement | HTMLTextAreaElement;
let canvas: HTMLCanvasElement | null = null;
function textWidth(field: TextField): ((text: string) => number) | null {
canvas ??= document.createElement("canvas");
const ctx = canvas.getContext("2d");
if (!ctx) return null;
const s = getComputedStyle(field);
ctx.font = `${s.fontStyle} ${s.fontWeight} ${s.fontSize} ${s.fontFamily}`;
return (text) => ctx.measureText(text).width;
}
/** Column of `line` whose left edge is nearest to `x` (px from the line start). */
function columnAt(line: string, x: number, width: (text: string) => number): number {
let lo = 0;
let hi = line.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (width(line.slice(0, mid + 1)) < x) lo = mid + 1;
else hi = mid;
}
if (lo < line.length && width(line.slice(0, lo + 1)) - x < x - width(line.slice(0, lo))) lo++;
return lo;
}
/**
* WebKitGTK extends a text field's selection while the mouse is dragged past
* its left or right edge, but never scrolls the text along. While the pointer
* is outside, move the selection focus and the scroll position ourselves, faster
* the further out the pointer is, like IDEA's text fields.
*/
export function startDragAutoscroll(e: ReactMouseEvent<TextField>) {
const field = e.currentTarget;
if (e.defaultPrevented || e.button !== 0 || e.detail > 1 || field.selectionStart === null) return;
// The canvas measures the real value, while the browser draws masking characters.
if (field instanceof HTMLInputElement && field.type === "password") return;
if (field.scrollWidth <= field.clientWidth || getComputedStyle(field).direction === "rtl") return;
const width = textWidth(field);
if (!width) return;
let pointerX = e.clientX;
let pointerY = e.clientY;
let frame = 0;
let anchor: number | null = null;
let focus = 0;
const edges = () => {
const s = getComputedStyle(field);
const rect = field.getBoundingClientRect();
const left = rect.left + field.clientLeft;
const start = left + parseFloat(s.paddingLeft);
return {
start,
end: left + field.clientWidth - parseFloat(s.paddingRight),
top: rect.top,
bottom: rect.bottom,
};
};
const overshoot = () => {
const { start, end, top, bottom } = edges();
if (field instanceof HTMLTextAreaElement && (pointerY < top || pointerY > bottom)) return 0;
return pointerX < start ? pointerX - start : pointerX > end ? pointerX - end : 0;
};
const tick = () => {
frame = 0;
if (!field.isConnected || field.selectionStart === null) return stop();
const over = overshoot();
if (!over) {
anchor = null;
return;
}
if (anchor === null) {
const backward = field.selectionDirection === "backward";
anchor = (backward ? field.selectionEnd : field.selectionStart) ?? 0;
focus = (backward ? field.selectionStart : field.selectionEnd) ?? 0;
}
const value = field.value;
const lineStart = focus > 0 ? value.lastIndexOf("\n", focus - 1) + 1 : 0;
const newline = value.indexOf("\n", focus);
const line = value.slice(lineStart, newline < 0 ? value.length : newline);
const { start, end } = edges();
const visible = end - start;
const step = Math.sign(over) * Math.min(Math.max(Math.abs(over) / 2, 2), 40);
// Scroll by pixels even when the next caret position is more than one step away.
const previous = field.scrollLeft;
field.scrollLeft = previous + step;
const scrolled = field.scrollLeft;
focus = lineStart + columnAt(line, scrolled + (over < 0 ? 0 : visible), width);
field.setSelectionRange(Math.min(anchor, focus), Math.max(anchor, focus), focus < anchor ? "backward" : "forward");
field.scrollLeft = scrolled;
if (scrolled !== previous) frame = requestAnimationFrame(tick);
};
const move = (ev: MouseEvent) => {
if (!(ev.buttons & 1)) return stop();
if (!field.isConnected) return stop();
pointerX = ev.clientX;
pointerY = ev.clientY;
if (!overshoot()) {
cancelAnimationFrame(frame);
frame = 0;
anchor = null;
return;
}
// Our focus wins over WebKit's, which jumps to the line's start or end.
ev.preventDefault();
if (!frame) tick();
};
const stop = () => {
cancelAnimationFrame(frame);
frame = 0;
window.removeEventListener("mousemove", move, true);
window.removeEventListener("mouseup", stop, true);
window.removeEventListener("blur", stop);
field.removeEventListener("blur", stop);
field.removeEventListener("dragstart", stop);
};
window.addEventListener("mousemove", move, true);
window.addEventListener("mouseup", stop, true);
window.addEventListener("blur", stop);
field.addEventListener("blur", stop);
field.addEventListener("dragstart", stop);
}