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

..
Автор SHA1 Повідомлення Дата
l0ng-ai ec54231f91 fix(i18n): Translate reworded and new UI text, guard the zh catalog
The source-text catalog is keyed by the English text, so rewording a string at
its call site (e.g. the Java "Language server JDK" hint gaining a sentence about
Download JDK…) dropped its translation without any failure.

- Add textCatalog.test.ts: parses src/ with the TypeScript compiler, collects the
  literal text that reaches tx / txTemplate / useTx, <T> and the UI primitives'
  text props and object keys (label, title, hint, description, …), and fails on
  text without a catalog entry and on entries no literal in src/, the Rust crates
  or languages/ spells out any more. Names, code and shortcuts are allowlisted.
- Translate 321 missing texts and update the reworded ones (jdtls JDK hint,
  spelling inspection description, plugin install notification).
- Remove 45 stale entries.
- Spell out "Cannot move" / "Cannot rename" in the file refactoring error so the
  title can be translated.

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 18:03:14 +08:00
l0ng-ai 9d8280104f fix(agents): Run Codex through @agentclientprotocol/codex-acp
@zed-industries/codex-acp is archived; its last release (0.16.0) bundles an
older Codex core that doesn't know newer models, so a config.toml model such as
gpt-6.1-sol fell back to generic metadata with a warning. The maintained adapter,
@agentclientprotocol/codex-acp, runs the Codex App Server from a current
@openai/codex and lists the account's models.
2026-10-27 17:44:04 +08:00
l0ng-ai 8ec35c94ec fix(lsp): Find usages in unopened files outside the language server's scope (#89)
Reference-based features only asked the language server, which analyses its configured scope (e.g. Pyright's `include`) plus open files, so usages in unopened files outside that scope were silently missing.

Find Usages, Show Usages, usage counts, Safe Delete of a symbol, Rename and incoming calls now also search project files that contain the symbol's name (whole word, same language, .gitignore/excludes respected, unsaved edits included, up to 300 files, cancellable). Candidates the first answer didn't cover are opened in the server temporarily, queried and closed again. Files the user has open are never touched, and diagnostics for the temporary files are dropped. An empty result while the server is still indexing is retried once indexing ends. When results may still be incomplete (indexing, file cap), the usages UI says so. `lsp_references` takes a RequestId and is cancelled by newer searches. Not covered yet: the Safe Delete scan when deleting a file or directory.

Fixes #83

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 17:41:20 +08:00
l0ng-ai 482f391fd1 fix(splash): Draw the wordmark as outlines so it can't swap fonts
The splash set its wordmark in Inter, a web font with font-display: swap. When
the font arrived late (on a cold dev start the dev server took up to seconds to
serve it), the splash showed the system font first and switched to Inter just
before fading, so the word grew and shifted. It is now an inline SVG of the same
text in Inter 500, so it renders identically from the first frame. This replaces
the previous attempt, which only moved where the font faces load.
2026-10-27 17:35:37 +08:00
l0ng-ai 866af3d9cb fix(agents): Give child processes the login shell's environment
An app started from Finder or the Dock took only PATH from the login shell, so
variables exported in rc files never reached agents, language servers, run
configurations or debug targets. Claude Code configured for Bedrock through
CLAUDE_CODE_USE_BEDROCK / AWS_REGION in ~/.zshrc fell back to the Anthropic API
and failed with 403.

The shell's environment is read once at startup (in the background when PATH
comes from the cache) and kept in memory only, since it may hold secrets. Spawns
add the variables this process lacks before their own.
2026-10-27 17:16:47 +08:00
l0ng-ai 145f168525 fix(agents): Composer input-method Enter, autocorrect and task header layout
- Enter that commits an input-method candidate no longer sends the message.
- The composer turns off autocorrect, autocapitalisation and spellcheck, which
  popped up correction bubbles over prompts.
- The provider icon in the task header sits inline with the details instead of
  on its own line above them.
2026-10-27 17:16:46 +08:00
l0ng-ai f73c0a6b1d fix(keymap): Don't run the Enter that commits an input-method candidate
WebKit sends the Enter (or Space) that commits a candidate after compositionend,
with isComposing already false and keyCode 229. Handlers that checked isComposing
alone ran it: dialogs confirmed and shortcuts fired while typing Chinese or
Japanese. isImeKey() checks both, and every keydown handler that skipped
composition uses it.
2026-10-27 17:16:46 +08:00
l0ng-ai 2c576418cb fix(splash): Keep the wordmark still until the splash fades
The splash named Inter, but the font faces and antialiasing came with the app CSS,
which the dev server injects only once the bundle runs: the wordmark switched from
the system font to Inter, moving up and changing weight, just before the fade. The
font faces are now linked from index.html and the splash sets its own smoothing.
The splash also stays on one compositing layer, so the fade-out doesn't re-snap
the centred text.
2026-10-27 17:16:46 +08:00
l0ng-ai b70d487a92 fix(ui): Don't draw a second focus box inside framed text fields
The global focus ring listed input and textarea. :is() takes its most specific
argument, so the rule tied with the components' own :focus-visible resets and won
whenever it loaded later: the Settings search field and the agent composer showed
an inner square box inside their focus frame. Text fields show focus with their
frame; the ring stays on checkboxes, radios and other input controls.
2026-10-27 17:16:46 +08:00
胡翀таzzxzz12345 413564efcf feat(editor): Increase / Decrease Font Size, followed by the Markdown preview (#81)
Adds Increase Font Size / Decrease Font Size (⌥⇧. / ⌥⇧, in the IntelliJ keymaps) for the active editor, sharing the ±1px step and limits with ⌘/Ctrl + mouse wheel. The Markdown preview, including code blocks, follows its editor's zoom, and Reset Font Size in All Editors resets it too.

Editor zoom had no effect once a font size was configured in settings: the configured size was applied with higher precedence than the zoom. The zoom now wins.

Co-authored-by: zzxzz12345 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 16:52:25 +08:00
l0ng-ai f675dd2730 feat(vcs): Repository list in the Branches popup for multi-repository projects (#84)
In projects with several repositories the Branches popup began with a wrapping row of repository chips and listed only the selected repository's branches, and the widget always read "repo / branch".

The popup now lists one row per repository (colour, name, current branch) whose submenu holds that repository's branches. When all repositories are on the same branch the widget shows just the branch and the popup offers Common Local / Remote Branches whose actions apply to every repository; otherwise it shows the current repository's Recent / Local / Remote Branches and Tags. The widget and the popup use the same current repository: the one owning the active file, else the selected one. Search covers actions, repositories and branches across repositories. New Branch… creates the branch in all repositories. Single-repository projects are unchanged. `vcs_roots` now returns each repository's branch and HEAD.

Fixes #78

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 16:51:50 +08:00
l0ng-ai 4100ab3341 feat(markdown): Render Mermaid diagrams in the preview (#82)
Fenced ```mermaid blocks in the Markdown preview render as diagrams. mermaid (12.1.0) is loaded lazily, only when a preview contains a diagram, with securityLevel "strict"; colours come from the theme tokens and diagrams re-render on theme changes. Syntax errors show inline under the source. Rendered diagrams are cached by theme + source, so editing elsewhere in the file doesn't redraw them.

Fixes #79

Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 16:23:35 +08:00
胡翀таzzxzz12345 fdd98fbfe4 feat(editor): Navigate inferred type inlay hints (#77)
Some language servers (basedpyright) send inferred type hints as plain text without a label-part location, so ⌘/Ctrl-clicking `: Series` did nothing. For a type hint right after an identifier, ⌘/Ctrl-click now goes to that identifier's type declaration; hints with locations keep direct navigation. Navigable hints show the link underline and pointer only while ⌘/Ctrl is held, including when it is pressed before hovering.

Co-authored-by: zzxzz12345 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VUYsdXA2nkF5v6zsC93dpn
2026-10-27 16:10:19 +08:00
74 змінених файлів з 4862 додано та 320 видалено

No files matched your search

+1 -1
Переглянути файл
@@ -25,7 +25,7 @@ const BUILTIN: &[(&str, &str, &[&str], &str)] = &[
&["npx", "-y", "@agentclientprotocol/[email protected]"],
"Run `claude` in a terminal and sign in.",
),
("codex", "Codex", &["npx", "-y", "@zed-industries/codex-acp@0.16.0"], "Run `codex login` in a terminal."),
("codex", "Codex", &["npx", "-y", "@agentclientprotocol/codex-acp@2.3.0"], "Run `codex login` in a terminal."),
("gemini", "Gemini CLI", &["gemini", "--experimental-acp"], "Run `gemini` in a terminal and sign in."),
("copilot", "GitHub Copilot", &["copilot", "--acp"], "Run `copilot` in a terminal and sign in."),
("cursor", "Cursor", &["cursor-agent", "acp"], "Run `cursor-agent login` in a terminal."),
+33
Переглянути файл
@@ -1,6 +1,8 @@
//! Child-process helpers shared by every crate that spawns tools.
use std::ffi::{OsStr, OsString};
use std::process::Command;
use std::sync::OnceLock;
/// Windows `CREATE_NO_WINDOW` creation flag, for call sites that combine it
/// with other flags. Prefer [`no_window`] otherwise.
@@ -18,3 +20,34 @@ pub fn no_window(cmd: &mut Command) -> &mut Command {
}
cmd
}
static SHELL_ENV: OnceLock<Vec<(OsString, OsString)>> = OnceLock::new();
/// Records the login shell's environment, read once at startup off the main thread.
pub fn set_shell_env(vars: Vec<(OsString, OsString)>) {
let _ = SHELL_ENV.set(vars);
}
/// The login shell's variables this process lacks: an app started from Finder/Dock gets only
/// PATH from the shell, not what rc files export (API keys and provider switches, SDK homes...).
/// Apply before a call site's own variables so those win. Empty until the shell has been read.
pub fn shell_env() -> impl Iterator<Item = (&'static OsStr, &'static OsStr)> {
SHELL_ENV
.get()
.into_iter()
.flatten()
.filter(|(k, _)| std::env::var_os(k).is_none())
.map(|(k, v)| (k.as_os_str(), v.as_os_str()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shell_env_adds_only_what_the_process_lacks() {
set_shell_env(vec![("OPENIDEA_SHELL_ONLY_VAR".into(), "1".into()), ("PATH".into(), "/from/shell".into())]);
let vars: Vec<_> = shell_env().collect();
assert_eq!(vars, [(OsStr::new("OPENIDEA_SHELL_ONLY_VAR"), OsStr::new("1"))]);
}
}
+6 -1
Переглянути файл
@@ -422,7 +422,12 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
};
let mut cmd = tokio::process::Command::new(program);
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(rest).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).kill_on_drop(true);
cmd.args(rest)
.envs(ide_core::process::shell_env())
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
if let Some(cwd) = args.get("cwd").and_then(Value::as_str).filter(|c| !c.is_empty()) {
cmd.current_dir(cwd);
}
+1
Переглянути файл
@@ -312,6 +312,7 @@ impl Peer {
ide_core::process::no_window(cmd.as_std_mut());
cmd.args(args)
.current_dir(cwd)
.envs(ide_core::process::shell_env())
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
+8
Переглянути файл
@@ -75,8 +75,12 @@ impl ClientHandler {
_ => return,
}
};
let ended = matches!(&event, IdeEvent::Task { done: true, .. });
mgr.sink().emit(event);
self.server.refresh_busy_status(mgr.sink());
if ended {
self.server.progress_ended();
}
}
fn publish_diagnostics(&self, mgr: &LspManager, params: Value) {
@@ -88,6 +92,10 @@ impl ClientHandler {
}
};
let Some(path) = uri_to_path(params.uri.as_str()) else { return };
// Files opened only for a request (references search) are not the user's problems.
if self.server.suppresses_diagnostics(&path) {
return;
}
let conv = mgr.conv(self.encoding());
let items = params
.diagnostics
+132 -72
Переглянути файл
@@ -13,6 +13,7 @@ mod handler;
mod inspect;
pub mod jdtls;
mod launch;
mod scope;
mod server;
mod tcp;
mod text;
@@ -23,6 +24,7 @@ mod virtual_doc;
pub use inspect::{FileInspection, InspectHost, InspectOptions};
pub use launch::{LaunchError, Launcher, ProcessLauncher, search_path};
pub use scope::{CandidateFiles, CandidateFn, CandidateQuery, MAX_CANDIDATES};
pub use uri::{is_virtual_uri, path_to_uri_string, uri_target, uri_to_path};
use caps::{ServerCaps, SyncKind};
@@ -143,6 +145,7 @@ pub struct LspManager {
docs: Mutex<HashMap<DocId, DocState>>,
apply_edit_hook: RwLock<Option<ApplyEditHook>>,
config_hook: RwLock<Option<ConfigHook>>,
candidates_hook: RwLock<Option<Arc<CandidateFn>>>,
shutting_down: AtomicBool,
/// `window/showMessage` texts already surfaced; servers repeat them on every restart/reconfigure.
shown_messages: Mutex<HashSet<(String, String)>>,
@@ -183,6 +186,19 @@ fn rpc_err(server: &str, method: &str, e: RpcError) -> IdeError {
}
}
/// Sends the user's `didOpen` for `path`, closing a transient copy of the file
/// first (one a references search opened).
fn user_did_open(server: &Server, run: &Running, path: &Path, uri: &lsp::Uri, params: Value) {
if server.take_transient(path, run.generation)
&& let Err(e) = run.peer.notify("textDocument/didClose", json!({ "textDocument": { "uri": uri } }))
{
tracing::debug!("{}: didClose: {e}", server.name);
}
if let Err(e) = run.peer.notify("textDocument/didOpen", params) {
tracing::debug!("{}: didOpen: {e}", server.name);
}
}
fn unsupported(feature: &str) -> IdeError {
IdeError::unavailable(format!("no running language server supports {feature}"))
}
@@ -235,6 +251,7 @@ impl LspManager {
docs: Mutex::new(HashMap::new()),
apply_edit_hook: RwLock::new(None),
config_hook: RwLock::new(None),
candidates_hook: RwLock::new(None),
shutting_down: AtomicBool::new(false),
shown_messages: Mutex::new(HashSet::new()),
virtual_origins: Mutex::new(HashMap::new()),
@@ -299,10 +316,8 @@ impl LspManager {
}
let mut attached = Attached { server: server.clone(), opened_gen: None };
if let Some(run) = server.running() {
if run.caps.read().open_close
&& let Err(e) = run.peer.notify("textDocument/didOpen", d.did_open_params())
{
tracing::debug!("{}: didOpen: {e}", server.name);
if run.caps.read().open_close {
user_did_open(&server, &run, &d.path, &d.uri, d.did_open_params());
}
attached.opened_gen = Some(run.generation);
}
@@ -481,6 +496,7 @@ impl LspManager {
for (id, title) in server.take_progress() {
self.sink.emit(ide_core::IdeEvent::Task { id, title, message: None, fraction: None, done: true });
}
server.progress_ended();
for path in server.take_diagnostic_paths() {
self.sink.emit(ide_core::IdeEvent::Diagnostics {
path: path.into(),
@@ -596,10 +612,8 @@ impl LspManager {
let params = state.did_open_params();
for a in &mut state.servers {
if let Some(run) = a.server.running() {
if run.caps.read().open_close
&& let Err(e) = run.peer.notify("textDocument/didOpen", params.clone())
{
tracing::debug!("{}: didOpen: {e}", a.server.name);
if run.caps.read().open_close {
user_did_open(&a.server, &run, &state.path, &state.uri, params.clone());
}
a.opened_gen = Some(run.generation);
}
@@ -945,40 +959,61 @@ impl LspManager {
out.finish(Vec::new())
}
pub async fn references(&self, doc: DocId, pos: Pos, include_declaration: bool) -> IdeResult<Vec<Location>> {
/// References of the symbol at `pos`. With `project_wide`, files outside
/// the servers' analysis scope that mention the name are opened for the
/// search (see [`scope`]); without, only what the servers analyse counts
/// (cheap, for bulk scans over many symbols).
pub async fn references(
&self,
doc: DocId,
pos: Pos,
include_declaration: bool,
project_wide: bool,
cancel: CancellationToken,
) -> IdeResult<References> {
let (snap, targets) = self.doc_targets(doc, "find references", |c| c.has("referencesProvider")).await?;
let requests = targets.iter().map(|t| {
let mut params = snap.pos_params(t, pos);
params["context"] = json!({ "includeDeclaration": include_declaration });
let (snap, cancel) = (&snap, &cancel);
async move {
(
t,
self.call::<_, Option<Vec<lsp::Location>>>(
t,
"textDocument/references",
params,
None,
LONG_TIMEOUT,
)
.await,
)
let query = || async move {
let mut params = snap.pos_params(t, pos);
params["context"] = json!({ "includeDeclaration": include_declaration });
let locs: Option<Vec<lsp::Location>> =
self.call(t, "textDocument/references", params, Some(cancel), LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
Ok(locs.unwrap_or_default().iter().filter_map(|l| conv.location(l)).collect::<Vec<Location>>())
};
let files =
|v: &Vec<Location>| v.iter().filter(|l| l.uri.is_none()).map(|l| l.path.to_path_buf()).collect();
let result = if project_wide {
self.widened(snap, t, pos, cancel, query, files).await
} else {
query().await.map(|first| {
let empty = first.is_empty();
scope::Widened::only(first, empty, &t.server)
})
};
(t, result)
}
});
let mut out = Outcome::new();
for (t, r) in join_all(requests).await {
match r {
Ok(locs) => {
let conv = self.conv(t.enc());
let locs: Vec<Location> =
locs.unwrap_or_default().iter().filter_map(|l| conv.location(l)).collect();
Ok(w) => {
let acc = out.value.get_or_insert_with(References::default);
let locs: Vec<Location> = w.first.into_iter().chain(w.second.into_iter().flatten()).collect();
self.note_virtual(&t.server, locs.iter().map(|l| l.uri.as_deref()));
out.value.get_or_insert_with(Vec::new).extend(locs);
acc.locations.extend(locs);
acc.incomplete = acc.incomplete.or(w.incomplete);
}
Err(e) => out.fail(e),
}
}
let mut v = out.finish(Vec::new())?;
convert::dedup_locations(&mut v);
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let mut v = out.finish(References::default())?;
convert::dedup_locations(&mut v.locations);
Ok(v)
}
@@ -1208,13 +1243,29 @@ impl LspManager {
})
}
/// Renames across the project: like [`Self::references`], files outside the
/// server's analysis scope that mention the name are opened for the request.
pub async fn rename(&self, doc: DocId, pos: Pos, new_name: String) -> IdeResult<WorkspaceEdit> {
let (snap, targets) = self.doc_targets(doc, "rename", |c| c.has("renameProvider")).await?;
let t = &targets[0];
let mut params = snap.pos_params(t, pos);
params["newName"] = json!(new_name);
let r: Option<lsp::WorkspaceEdit> = self.call(t, "textDocument/rename", params, None, LONG_TIMEOUT).await?;
Ok(r.map(|e| convert::workspace_edit(&self.conv(t.enc()), e)).unwrap_or_default())
let query = || async {
let mut params = snap.pos_params(t, pos);
params["newName"] = json!(new_name);
let r: Option<lsp::WorkspaceEdit> = self.call(t, "textDocument/rename", params, None, LONG_TIMEOUT).await?;
Ok(r.map(|e| convert::workspace_edit(&self.conv(t.enc()), e)).unwrap_or_default())
};
let files = |e: &WorkspaceEdit| {
e.files
.iter()
.filter_map(|f| match f {
ide_core::FileEdit::Edit { path, .. } => Some(path.to_path_buf()),
_ => None,
})
.collect()
};
let w = self.widened(&snap, t, pos, &CancellationToken::new(), query, files).await?;
// The second edit covers the first: its files stay analysed.
Ok(w.second.unwrap_or(w.first))
}
// ---- file operations (`workspace/willRenameFiles`, `workspace/didRenameFiles`) ----
@@ -1263,16 +1314,17 @@ impl LspManager {
/// Some servers (tsserver) only answer for files of a loaded project: when
/// `t` has no document open, one moved file of its languages is opened for the request.
fn open_for_file_op(&self, t: &Target, moves: &[(PathBuf, PathBuf, bool)]) -> Option<lsp::Uri> {
fn open_for_file_op(&self, t: &Target, moves: &[(PathBuf, PathBuf, bool)]) -> scope::TransientFiles<'_> {
let mut opened = scope::TransientFiles::empty(self, t);
if !t.caps().open_close {
return None;
return opened;
}
let docs = self.docs.lock();
let busy = docs
.values()
.any(|d| d.servers.iter().any(|a| a.server.id == t.server.id && a.opened_gen == Some(t.run.generation)));
let busy =
self.docs.lock().values().any(|d| {
d.servers.iter().any(|a| a.server.id == t.server.id && a.opened_gen == Some(t.run.generation))
});
if busy {
return None;
return opened;
}
let languages = t.server.languages();
let candidate =
@@ -1287,14 +1339,10 @@ impl LspManager {
continue;
}
let Ok(text) = std::fs::read_to_string(&file) else { continue };
let uri = uri::path_to_uri(&file);
let params =
json!({ "textDocument": { "uri": uri, "languageId": language.as_str(), "version": 0, "text": text } });
if t.run.peer.notify("textDocument/didOpen", params).is_ok() {
return Some(uri);
}
opened.hold(&file, &language, &text);
break;
}
None
opened
}
/// Asks the servers for the edits that keep references intact when files or
@@ -1320,9 +1368,7 @@ impl LspManager {
let opened = self.open_for_file_op(&t, &moves);
let r: IdeResult<Option<lsp::WorkspaceEdit>> =
self.call(&t, "workspace/willRenameFiles", params, Some(&cancel), LONG_TIMEOUT).await;
if let Some(uri) = opened {
let _ = t.run.peer.notify("textDocument/didClose", json!({ "textDocument": { "uri": uri } }));
}
drop(opened);
match r {
Ok(Some(edit)) => out.edit.files.extend(convert::workspace_edit(&self.conv(t.enc()), edit).files),
Ok(None) => {}
@@ -1519,32 +1565,46 @@ impl LspManager {
let items: Option<Vec<lsp::CallHierarchyItem>> =
self.call(t, "textDocument/prepareCallHierarchy", snap.pos_params(t, pos), None, DEFAULT_TIMEOUT).await?;
let items = items.filter(|i| !i.is_empty()).ok_or_else(no_hierarchy_target)?;
let mut out = Vec::new();
for item in items {
let params = json!({ "item": item });
match direction {
HierarchyDirection::Incoming => {
let calls: Option<Vec<lsp::CallHierarchyIncomingCall>> =
self.call(t, "callHierarchy/incomingCalls", params, None, LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
for c in calls.unwrap_or_default() {
let (path, _) = uri_target(c.from.uri.as_str());
let ranges = c.from_ranges.iter().map(|r| conv.range(&path, *r)).collect();
out.extend(convert::call_item(&conv, &c.from, ranges));
let query = || async {
let mut out = Vec::new();
for item in &items {
let params = json!({ "item": item });
match direction {
HierarchyDirection::Incoming => {
let calls: Option<Vec<lsp::CallHierarchyIncomingCall>> =
self.call(t, "callHierarchy/incomingCalls", params, None, LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
for c in calls.unwrap_or_default() {
let (path, _) = uri_target(c.from.uri.as_str());
let ranges = c.from_ranges.iter().map(|r| conv.range(&path, *r)).collect();
out.extend(convert::call_item(&conv, &c.from, ranges));
}
}
}
HierarchyDirection::Outgoing => {
let calls: Option<Vec<lsp::CallHierarchyOutgoingCall>> =
self.call(t, "callHierarchy/outgoingCalls", params, None, LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
let (src, _) = uri_target(item.uri.as_str());
for c in calls.unwrap_or_default() {
let ranges = c.from_ranges.iter().map(|r| conv.range(&src, *r)).collect();
out.extend(convert::call_item(&conv, &c.to, ranges));
HierarchyDirection::Outgoing => {
let calls: Option<Vec<lsp::CallHierarchyOutgoingCall>> =
self.call(t, "callHierarchy/outgoingCalls", params, None, LONG_TIMEOUT).await?;
let conv = self.conv(t.enc());
let (src, _) = uri_target(item.uri.as_str());
for c in calls.unwrap_or_default() {
let ranges = c.from_ranges.iter().map(|r| conv.range(&src, *r)).collect();
out.extend(convert::call_item(&conv, &c.to, ranges));
}
}
}
}
}
Ok(out)
};
let out = match direction {
// Callers are references: they may sit in files outside the server's scope.
HierarchyDirection::Incoming => {
let files = |v: &Vec<HierarchyItem>| {
v.iter().filter(|i| i.uri.is_none()).map(|i| i.path.to_path_buf()).collect()
};
let w = self.widened(&snap, t, pos, &CancellationToken::new(), query, files).await?;
w.second.unwrap_or(w.first)
}
HierarchyDirection::Outgoing => query().await?,
};
self.note_virtual(&t.server, out.iter().map(|i| i.uri.as_deref()));
Ok(out)
}
+248
Переглянути файл
@@ -0,0 +1,248 @@
//! Reference searches beyond a server's analysis scope.
//!
//! Servers answer `textDocument/references` (and rename, incoming calls) from
//! the files they analyse: their configured scope (Pyright's `include`, a
//! `tsconfig.json`, a compilation database) plus the open documents. Usages in
//! other project files are silently missing. So, as a word index would, the
//! project files of the server's languages that contain the symbol's name as a
//! whole word (found through the host's [`CandidateFn`]) and that the first
//! answer did not cover are opened on the server for a second request, then
//! closed again. Diagnostics the server publishes for them are dropped.
use crate::server::{Running, Server};
use crate::types::ReferencesIncomplete;
use crate::{DocSnap, LspManager, Target};
use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId, Pos};
use lsp_types as lsp;
use serde_json::json;
use std::collections::HashSet;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
/// Files opened for one search at most.
pub const MAX_CANDIDATES: usize = 300;
/// Larger files (generated code, bundles) are not opened.
const MAX_CANDIDATE_BYTES: u64 = 1 << 20;
/// How long a search that found nothing waits for a server to finish indexing.
const INDEX_WAIT: Duration = Duration::from_secs(10);
/// Project files that may mention a symbol.
#[derive(Clone, Debug)]
pub struct CandidateQuery {
/// Matched as a whole word, case-sensitively.
pub word: String,
/// Only files under this directory (the server's workspace root).
pub root: PathBuf,
/// Only files of these languages.
pub languages: Vec<LanguageId>,
pub limit: usize,
}
#[derive(Clone, Debug, Default)]
pub struct CandidateFiles {
pub files: Vec<PathBuf>,
/// More files matched than `limit`.
pub limit_hit: bool,
}
/// Finds [`CandidateFiles`] (honouring the project's ignore rules); runs on a
/// blocking thread and should stop early when cancelled.
pub type CandidateFn = dyn Fn(&CandidateQuery, &CancellationToken) -> CandidateFiles + Send + Sync;
/// A reference-based answer and, when files were opened for it, the second one.
pub(crate) struct Widened<R> {
pub first: R,
pub second: Option<R>,
pub incomplete: Option<ReferencesIncomplete>,
}
impl<R> Widened<R> {
/// An answer from the server's analysis scope alone; `empty`: it found nothing.
pub fn only(first: R, empty: bool, server: &Server) -> Self {
let incomplete = (empty && server.is_busy()).then_some(ReferencesIncomplete::Indexing);
Self { first, second: None, incomplete }
}
}
/// The name a search is about: the word at `pos` (a PHP `$` sigil dropped).
fn search_word(snap: &DocSnap, pos: Pos) -> Option<String> {
let r = snap.text.word_range_at(pos)?;
let text = snap.text.as_str();
let word = text.get(snap.text.byte_offset(r.start)..snap.text.byte_offset(r.end))?.trim_start_matches('$');
(!word.is_empty() && !word.chars().all(|c| c.is_ascii_digit())).then(|| word.to_owned())
}
impl LspManager {
/// Finds the project files a references search may open (see the module docs).
pub fn set_candidates_hook(&self, hook: Box<CandidateFn>) {
*self.candidates_hook.write() = Some(Arc::from(hook));
}
async fn candidates(&self, t: &Target, word: String, cancel: &CancellationToken) -> Option<CandidateFiles> {
let hook = self.candidates_hook.read().clone()?;
let query = CandidateQuery {
word,
root: t.server.root.clone(),
languages: t.server.languages(),
limit: MAX_CANDIDATES,
};
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || hook(&query, &cancel)).await.ok()
}
/// Runs `query` on `t`; then again with the project files that mention the
/// symbol at `pos` and are not in `covered(first)` opened on the server.
/// A first answer that is empty while the server indexes is retried once
/// indexing ends.
pub(crate) async fn widened<R, F, Fut>(
&self,
snap: &DocSnap,
t: &Target,
pos: Pos,
cancel: &CancellationToken,
query: F,
covered: impl Fn(&R) -> Vec<PathBuf>,
) -> IdeResult<Widened<R>>
where
F: Fn() -> Fut,
Fut: Future<Output = IdeResult<R>>,
{
let busy = t.server.is_busy();
let word = search_word(snap, pos).filter(|_| t.caps().open_close);
let candidates = async {
match word {
Some(w) => self.candidates(t, w, cancel).await,
None => None,
}
};
let (first, candidates) = futures::join!(query(), candidates);
let mut first = first?;
if busy && covered(&first).is_empty() && t.server.wait_idle(INDEX_WAIT, cancel).await {
first = query().await?;
}
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
// Servers report analysis progress often; only "nothing found" while it lasts is suspect.
let mut incomplete =
(t.server.is_busy() && covered(&first).is_empty()).then_some(ReferencesIncomplete::Indexing);
let Some(candidates) = candidates else { return Ok(Widened { first, second: None, incomplete }) };
if candidates.limit_hit {
incomplete = incomplete.or(Some(ReferencesIncomplete::TooManyFiles));
}
let known: HashSet<PathBuf> = covered(&first).into_iter().chain([snap.path.clone()]).collect();
let files: Vec<PathBuf> = candidates.files.into_iter().filter(|f| !known.contains(f)).collect();
if files.is_empty() {
return Ok(Widened { first, second: None, incomplete });
}
let opened = self.open_transient(t, files, cancel).await;
if opened.files.is_empty() {
return Ok(Widened { first, second: None, incomplete });
}
tracing::debug!("{}: opened {} more files for a references search", t.server.name, opened.files.len());
let second = query().await;
drop(opened);
match second {
Ok(second) => {
if !covered(&second).is_empty() && incomplete == Some(ReferencesIncomplete::Indexing) {
incomplete = None;
}
Ok(Widened { first, second: Some(second), incomplete })
}
Err(e) if cancel.is_cancelled() => Err(e),
Err(e) => {
tracing::debug!("{}: widened references search: {}", t.server.name, e.message);
Ok(Widened { first, second: None, incomplete })
}
}
}
/// Opens `files` on `t` (read from disk) unless the user has them open;
/// they are closed when the returned guard drops.
async fn open_transient(&self, t: &Target, files: Vec<PathBuf>, cancel: &CancellationToken) -> TransientFiles<'_> {
let read = {
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || {
files
.into_iter()
.take_while(|_| !cancel.is_cancelled())
.filter(|f| std::fs::metadata(f).is_ok_and(|m| m.is_file() && m.len() <= MAX_CANDIDATE_BYTES))
.filter_map(|f| std::fs::read_to_string(&f).ok().map(|text| (f, text)))
.collect::<Vec<_>>()
})
.await
.unwrap_or_default()
};
let mut guard = TransientFiles { mgr: self, server: t.server.clone(), run: t.run.clone(), files: Vec::new() };
if cancel.is_cancelled() {
return guard;
}
let docs = self.docs.lock();
for (path, text) in read {
if docs.values().any(|d| d.path == path) {
continue;
}
let uri = crate::uri::path_to_uri(&path);
if t.server.hold_transient(&path, t.run.generation) {
let language = self.languages.detect(&path, text.lines().next());
let params = json!({
"textDocument": { "uri": uri, "languageId": language.as_str(), "version": 0, "text": text }
});
if let Err(e) = t.run.peer.notify("textDocument/didOpen", params) {
tracing::debug!("{}: didOpen: {e}", t.server.name);
}
}
guard.files.push((path, uri));
}
guard
}
}
/// Files opened by [`LspManager::open_transient`]; closed on drop.
pub(crate) struct TransientFiles<'a> {
mgr: &'a LspManager,
server: Arc<Server>,
run: Running,
pub files: Vec<(PathBuf, lsp::Uri)>,
}
impl TransientFiles<'_> {
/// Opens one file outside a references search (a file operation needs a loaded project).
pub(crate) fn hold(&mut self, path: &Path, language: &LanguageId, text: &str) {
let _docs = self.mgr.docs.lock();
let uri = crate::uri::path_to_uri(path);
if self.server.hold_transient(path, self.run.generation) {
let params =
json!({ "textDocument": { "uri": uri, "languageId": language.as_str(), "version": 0, "text": text } });
if let Err(e) = self.run.peer.notify("textDocument/didOpen", params) {
tracing::debug!("{}: didOpen: {e}", self.server.name);
}
}
self.files.push((path.to_owned(), uri));
}
}
impl<'a> TransientFiles<'a> {
pub(crate) fn empty(mgr: &'a LspManager, t: &Target) -> Self {
Self { mgr, server: t.server.clone(), run: t.run.clone(), files: Vec::new() }
}
}
impl Drop for TransientFiles<'_> {
fn drop(&mut self) {
if self.files.is_empty() {
return;
}
// Under the documents lock, so a user `didOpen` of the same file can't interleave.
let _docs = self.mgr.docs.lock();
for (path, uri) in self.files.drain(..) {
if self.server.release_transient(&path, self.run.generation)
&& let Err(e) = self.run.peer.notify("textDocument/didClose", json!({ "textDocument": { "uri": uri } }))
{
tracing::debug!("{}: didClose: {e}", self.server.name);
}
}
}
}
+108
Переглянути файл
@@ -17,6 +17,9 @@ use tokio::sync::{Notify, watch};
const STABLE_UPTIME: Duration = Duration::from_secs(180);
const MAX_RESTARTS: usize = 3;
const STDERR_LINES: usize = 50;
/// Diagnostics a server publishes for a transiently opened file shortly after
/// its `didClose` (analysis that was already running) are dropped too.
const TRANSIENT_GRACE: Duration = Duration::from_secs(3);
/// A live, initialized instance.
#[derive(Clone)]
@@ -49,6 +52,17 @@ struct State {
conn: Conn,
}
/// A file opened on the server by the client itself (not by the user) for the
/// duration of a request, e.g. to widen a references search.
struct Transient {
/// Requests holding the file open.
holders: usize,
generation: u64,
/// The user opened the file meanwhile: its `didOpen` replaced ours.
taken: bool,
closed_at: Option<Instant>,
}
pub struct Progress {
pub task: TaskId,
pub title: String,
@@ -80,6 +94,9 @@ pub struct Server {
published: Mutex<HashMap<PathBuf, Instant>>,
/// Woken on every `publishDiagnostics` (Inspect Code waits on it).
pub published_notify: Notify,
/// Woken when the last `$/progress` task ends.
idle_notify: Notify,
transient: Mutex<HashMap<PathBuf, Transient>>,
}
impl Server {
@@ -102,6 +119,8 @@ impl Server {
diagnostics: Mutex::new(HashMap::new()),
published: Mutex::new(HashMap::new()),
published_notify: Notify::new(),
idle_notify: Notify::new(),
transient: Mutex::new(HashMap::new()),
}
}
@@ -305,6 +324,95 @@ impl Server {
self.set_status(sink, if busy { ServerStatus::Busy } else { ServerStatus::Ready }, None);
}
/// Whether the server reports work in progress (indexing, analysis).
pub fn is_busy(&self) -> bool {
!self.progress.lock().is_empty()
}
/// Called after a `$/progress` task ended.
pub fn progress_ended(&self) {
if !self.is_busy() {
self.idle_notify.notify_waiters();
}
}
/// Waits until no `$/progress` task is active; false on timeout or cancellation.
pub async fn wait_idle(&self, timeout: Duration, cancel: &CancellationToken) -> bool {
let deadline = tokio::time::Instant::now() + timeout;
loop {
let notified = self.idle_notify.notified();
if !self.is_busy() || self.running().is_none() {
return !self.is_busy();
}
tokio::select! {
() = notified => {}
() = tokio::time::sleep_until(deadline) => return !self.is_busy(),
() = cancel.cancelled() => return false,
}
}
}
// ---- transiently opened files ----
/// Registers a holder of the transient file `path` on instance `generation`;
/// true when the caller must send `didOpen` (first holder).
pub fn hold_transient(&self, path: &Path, generation: u64) -> bool {
let mut map = self.transient.lock();
map.retain(|_, t| t.holders > 0 || t.closed_at.is_some_and(|c| c.elapsed() < TRANSIENT_GRACE));
let t =
map.entry(path.to_owned()).or_insert(Transient { holders: 0, generation, taken: false, closed_at: None });
if t.holders == 0 || t.generation != generation {
*t = Transient { holders: 1, generation, taken: false, closed_at: None };
return true;
}
t.holders += 1;
false
}
/// Drops a holder of `path`; true when the caller must send `didClose`
/// (last holder, same instance, and the user did not open the file meanwhile).
pub fn release_transient(&self, path: &Path, generation: u64) -> bool {
let mut map = self.transient.lock();
let Some(t) = map.get_mut(path) else { return false };
if t.holders == 0 {
return false;
}
t.holders -= 1;
if t.holders > 0 {
return false;
}
let close = !t.taken && t.generation == generation;
if close {
t.closed_at = Some(Instant::now());
} else {
map.remove(path);
}
close
}
/// The user opens `path` on instance `generation`: true when a transient
/// copy is open there and must be closed before the user's `didOpen`.
pub fn take_transient(&self, path: &Path, generation: u64) -> bool {
let mut map = self.transient.lock();
let Some(t) = map.get_mut(path) else { return false };
let open = t.holders > 0 && !t.taken && t.generation == generation;
if t.holders > 0 {
t.taken = true;
} else {
map.remove(path);
}
open
}
/// Whether diagnostics published for `path` belong to a transient copy
/// and must not reach the Problems view.
pub fn suppresses_diagnostics(&self, path: &Path) -> bool {
self.transient
.lock()
.get(path)
.is_some_and(|t| !t.taken && (t.holders > 0 || t.closed_at.is_some_and(|c| c.elapsed() < TRANSIENT_GRACE)))
}
// ---- bookkeeping ----
pub fn push_stderr(&self, line: String) {
+17
Переглянути файл
@@ -322,3 +322,20 @@ pub struct FileRenameEdits {
/// Servers that failed; their references are not updated.
pub errors: Vec<String>,
}
/// Why a references search may have missed usages.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub enum ReferencesIncomplete {
/// A language server was still indexing.
Indexing,
/// More project files mention the name than were checked.
TooManyFiles,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct References {
pub locations: Vec<Location>,
pub incomplete: Option<ReferencesIncomplete>,
}
+349 -4
Переглянути файл
@@ -27,9 +27,13 @@ struct MockState {
/// uri → text as reconstructed by the mock from didOpen/didChange.
docs: Mutex<HashMap<String, String>>,
responses: Mutex<HashMap<String, Value>>,
/// Computes a response from the request and the open documents (before `responses`).
responder: Mutex<Option<Responder>>,
peer: Mutex<Option<Peer>>,
}
type Responder = Arc<dyn Fn(&MockState, &str, &Value) -> Option<Value> + Send + Sync>;
impl MockState {
fn notified(&self, method: &str) -> Vec<Value> {
self.notifications.lock().iter().filter(|(m, _)| m == method).map(|(_, p)| p.clone()).collect()
@@ -111,11 +115,17 @@ impl Handler for MockHandler {
fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> {
let s = &self.0;
s.requests.lock().push((method.to_owned(), params));
s.requests.lock().push((method.to_owned(), params.clone()));
match method {
"initialize" => Ok(json!({ "capabilities": s.caps.lock().clone(), "serverInfo": { "name": "mock" } })),
"shutdown" => Ok(Value::Null),
_ => Ok(s.responses.lock().get(method).cloned().unwrap_or(Value::Null)),
_ => {
let responder = s.responder.lock().clone();
if let Some(v) = responder.and_then(|f| f(s, method, &params)) {
return Ok(v);
}
Ok(s.responses.lock().get(method).cloned().unwrap_or(Value::Null))
}
}
}
}
@@ -801,7 +811,7 @@ async fn navigation_rename_format_and_decorations() {
assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable);
s.respond("textDocument/references", json!([{ "uri": uri, "range": r(0,3,0,6) }, { "uri": uri, "range": r(1,0,1,3) }, { "uri": uri, "range": r(1,0,1,3) }]));
let refs = h.mgr.references(doc, Pos::new(1, 1), true).await.unwrap();
let refs = h.mgr.references(doc, Pos::new(1, 1), true, true, Default::default()).await.unwrap().locations;
assert_eq!(refs.len(), 2);
assert_eq!(s.requested("textDocument/references")[0]["context"]["includeDeclaration"], true);
@@ -987,7 +997,7 @@ async fn virtual_locations_and_text_document_content() {
"textDocument/references",
json!([{ "uri": uri_of(&path), "range": r(0, 4, 0, 9) }, { "uri": lib, "range": r(2, 4, 2, 9) }]),
);
let refs = h.mgr.references(doc, Pos::new(0, 5), true).await.unwrap();
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap().locations;
assert_eq!(refs.iter().map(|l| l.uri.is_some()).collect::<Vec<_>>(), vec![false, true]);
s.respond(
"textDocument/prepareTypeHierarchy",
@@ -1301,3 +1311,338 @@ async fn css_family_configuration_returns_default_objects() {
assert_eq!(state.requested("initialize")[0]["initializationOptions"]["provideFormatter"], true);
}
}
// ------------------------------------------------------------------ references beyond the analysis scope
const WORD: &str = "target";
/// Locations of [`WORD`] in `text` (ASCII, so UTF-16 columns are byte offsets).
fn occurrences(uri: &str, text: &str) -> Vec<Value> {
let mut out = Vec::new();
for (line, l) in text.lines().enumerate() {
for (col, _) in l.match_indices(WORD) {
let end = col + WORD.len();
out.push(json!({ "uri": uri, "range": {
"start": { "line": line, "character": col }, "end": { "line": line, "character": end } } }));
}
}
out
}
/// A server that only analyses its open documents (minus `blind` URIs), like
/// Pyright for files outside its `include`.
fn open_files_only(blind: Vec<String>) -> Responder {
Arc::new(move |s, method, _| {
let docs: Vec<(String, String)> =
s.docs.lock().iter().filter(|(u, _)| !blind.contains(u)).map(|(u, t)| (u.clone(), t.clone())).collect();
let locs = || docs.iter().flat_map(|(u, t)| occurrences(u, t));
match method {
"textDocument/references" => Some(Value::Array(locs().collect())),
"textDocument/rename" => {
let mut changes = serde_json::Map::new();
for loc in locs() {
let edits = changes.entry(loc["uri"].as_str().unwrap()).or_insert_with(|| json!([]));
edits.as_array_mut().unwrap().push(json!({ "range": loc["range"], "newText": "renamed" }));
}
Some(json!({ "changes": changes }))
}
_ => None,
}
})
}
/// Candidate files: those directly under the root that contain the word; records the queries.
fn grep_candidates(h: &Harness) -> Arc<Mutex<Vec<ide_lsp::CandidateQuery>>> {
let seen = Arc::new(Mutex::new(Vec::new()));
let log = seen.clone();
h.mgr.set_candidates_hook(Box::new(move |q, _| {
log.lock().push(q.clone());
let mut files: Vec<PathBuf> = std::fs::read_dir(&q.root)
.unwrap()
.flatten()
.map(|e| e.path())
.filter(|p| std::fs::read_to_string(p).is_ok_and(|t| t.contains(&q.word)))
.collect();
files.sort();
ide_lsp::CandidateFiles { files, limit_hit: false }
}));
seen
}
fn uris(params: &[Value]) -> Vec<String> {
params.iter().map(|p| p["textDocument"]["uri"].as_str().unwrap().to_owned()).collect()
}
fn diagnostics_for(h: &Harness, path: &Path) -> usize {
h.events.lock().iter().filter(|e| matches!(e, IdeEvent::Diagnostics { path: p, .. } if p == path)).count()
}
fn scope_harness() -> (Harness, Arc<MockState>) {
let h = harness(&[("mock", incremental_caps())]);
let s = h.launcher.state("mock");
*s.responder.lock() = Some(open_files_only(vec![]));
(h, s)
}
#[tokio::test(flavor = "multi_thread")]
async fn references_open_unopened_files_that_mention_the_name() {
let (h, s) = scope_harness();
let seen = grep_candidates(&h);
let b = h.root.join("b.mk");
let c = h.root.join("c.mk");
std::fs::write(&b, "call target\n").unwrap();
std::fs::write(&c, "nothing here\n").unwrap();
let (doc, a) = h.open("a.mk", "def target\n");
let (_, d) = h.open("d.mk", "use target\n");
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 2).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
let mut paths: Vec<PathBuf> = refs.locations.iter().map(|l| l.path.to_path_buf()).collect();
paths.sort();
assert_eq!(paths, vec![a.clone(), b.clone(), d.clone()]);
assert_eq!(refs.incomplete, None);
let q = seen.lock()[0].clone();
assert_eq!((q.word.as_str(), q.root.as_path(), q.limit), (WORD, h.root.as_path(), ide_lsp::MAX_CANDIDATES));
assert_eq!(q.languages, vec![h.lang.clone()]);
// Only the unopened candidate was opened (from disk), then closed again.
let opens = s.notified("textDocument/didOpen");
let temp: Vec<&Value> = opens.iter().filter(|p| p["textDocument"]["uri"] == uri_of(&b)).collect();
assert_eq!(temp.len(), 1);
assert_eq!(temp[0]["textDocument"]["version"], 0);
assert_eq!(temp[0]["textDocument"]["text"], "call target\n");
assert!(!uris(&opens).contains(&uri_of(&c)));
assert_eq!(uris(&opens).iter().filter(|u| **u == uri_of(&d)).count(), 1);
eventually(|| uris(&s.notified("textDocument/didClose")) == vec![uri_of(&b)]).await;
assert_eq!(s.requested("textDocument/references").len(), 2);
assert_eq!(s.docs.lock().len(), 2);
// When every candidate file is already in the answer, no second request is made.
std::fs::remove_file(&b).unwrap();
h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(s.requested("textDocument/references").len(), 3);
// Without project_wide only the server's scope counts: no project search.
std::fs::write(&b, "call target\n").unwrap();
let refs = h.mgr.references(doc, Pos::new(0, 5), true, false, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 2);
assert_eq!(seen.lock().len(), 2);
}
#[tokio::test(flavor = "multi_thread")]
async fn references_never_reopen_or_close_the_users_files() {
let h = harness(&[("mock", incremental_caps())]);
let s = h.launcher.state("mock");
grep_candidates(&h);
let (doc, _) = h.open("a.mk", "def target\n");
// Open, mentions the name, but the server does not report it.
let (_, d) = h.open("d.mk", "use target\n");
*s.responder.lock() = Some(open_files_only(vec![uri_of(&d)]));
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 2).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 1);
assert_eq!(uris(&s.notified("textDocument/didOpen")).iter().filter(|u| **u == uri_of(&d)).count(), 1);
assert!(s.notified("textDocument/didClose").is_empty());
assert_eq!(s.requested("textDocument/references").len(), 1);
assert!(s.docs.lock().contains_key(&uri_of(&d)));
}
#[tokio::test(flavor = "multi_thread")]
async fn references_report_a_capped_candidate_search() {
let (h, s) = scope_harness();
h.mgr.set_candidates_hook(Box::new(|q, _| ide_lsp::CandidateFiles {
files: vec![q.root.join("b.mk")],
limit_hit: true,
}));
std::fs::write(h.root.join("b.mk"), "target\n").unwrap();
let (doc, _) = h.open("a.mk", "def target\n");
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 2);
assert_eq!(refs.incomplete, Some(ReferencesIncomplete::TooManyFiles));
}
#[tokio::test(flavor = "multi_thread")]
async fn cancelling_a_references_search_stops_the_candidate_search_and_closes_files() {
let (h, s) = scope_harness();
h.mgr.set_candidates_hook(Box::new(|_, cancel| {
while !cancel.is_cancelled() {
std::thread::sleep(Duration::from_millis(5));
}
ide_lsp::CandidateFiles::default()
}));
let (doc, _) = h.open("a.mk", "def target\n");
h.wait_status("mock", ServerStatus::Ready).await;
let cancel = ide_core::CancellationToken::new();
let later = cancel.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(100)).await;
later.cancel();
});
let err = h.mgr.references(doc, Pos::new(0, 5), true, true, cancel).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
// Cancelled while the server answers with a file opened for the search.
let b = h.root.join("b.mk");
std::fs::write(&b, "call target\n").unwrap();
grep_candidates(&h);
let slow = uri_of(&b);
let inner = open_files_only(vec![]);
*s.responder.lock() = Some(Arc::new(move |s, method, params| {
if s.docs.lock().contains_key(&slow) {
std::thread::sleep(Duration::from_millis(600));
}
inner(s, method, params)
}));
let cancel = ide_core::CancellationToken::new();
let later = cancel.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(200)).await;
later.cancel();
});
let started = std::time::Instant::now();
let err = h.mgr.references(doc, Pos::new(0, 5), true, true, cancel).await.unwrap_err();
assert_eq!(err.kind, ide_core::error::ErrorKind::Cancelled);
assert!(started.elapsed() < Duration::from_millis(550));
eventually(|| uris(&s.notified("textDocument/didClose")) == vec![uri_of(&b)]).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn diagnostics_of_files_opened_for_a_search_stay_out_of_problems() {
let h = harness(&[("mock", incremental_caps())]);
let s = h.launcher.state("mock");
grep_candidates(&h);
let b = h.root.join("b.mk");
std::fs::write(&b, "call target\n").unwrap();
let (doc, a) = h.open("a.mk", "def target\n");
let diag = json!([{ "range": {"start":{"line":0,"character":0},"end":{"line":0,"character":1}}, "message": "e" }]);
let inner = open_files_only(vec![]);
let (temp, user, d) = (uri_of(&b), uri_of(&a), diag.clone());
*s.responder.lock() = Some(Arc::new(move |s, method, params| {
if s.docs.lock().contains_key(&temp) {
for uri in [&temp, &user] {
s.peer().notify("textDocument/publishDiagnostics", json!({ "uri": uri, "diagnostics": d })).unwrap();
}
}
inner(s, method, params)
}));
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 2);
// Published right after the didClose (analysis still running): dropped too.
s.peer().notify("textDocument/publishDiagnostics", json!({ "uri": uri_of(&b), "diagnostics": diag })).unwrap();
s.peer().notify("textDocument/publishDiagnostics", json!({ "uri": uri_of(&a), "diagnostics": [] })).unwrap();
eventually(|| diagnostics_for(&h, &a) == 2).await;
assert_eq!(diagnostics_for(&h, &b), 0);
}
#[tokio::test(flavor = "multi_thread")]
async fn opening_a_file_during_a_search_takes_it_over() {
let h = harness(&[("mock", incremental_caps())]);
let s = h.launcher.state("mock");
grep_candidates(&h);
let b = h.root.join("b.mk");
std::fs::write(&b, "call target\n").unwrap();
let (doc, _) = h.open("a.mk", "def target\n");
let slow = uri_of(&b);
let inner = open_files_only(vec![]);
*s.responder.lock() = Some(Arc::new(move |s, method, params| {
if s.docs.lock().get(&slow).is_some_and(|t| t.starts_with("call")) {
std::thread::sleep(Duration::from_millis(400));
}
inner(s, method, params)
}));
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let mgr = h.mgr.clone();
let search = tokio::spawn(async move { mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await });
eventually(|| s.docs.lock().contains_key(&uri_of(&b))).await;
let user_doc = DocId::next();
h.mgr.did_open(user_doc, &b, &h.lang, 7, "edited target\n");
search.await.unwrap().unwrap();
// The temporary copy was closed before the user's didOpen, and the user's stays open.
let events: Vec<(String, Value)> = s
.notifications
.lock()
.iter()
.filter(|(m, p)| m.starts_with("textDocument/did") && p["textDocument"]["uri"] == uri_of(&b))
.map(|(m, p)| (m.clone(), p["textDocument"]["version"].clone()))
.collect();
assert_eq!(
events,
vec![
("textDocument/didOpen".to_owned(), json!(0)),
("textDocument/didClose".to_owned(), Value::Null),
("textDocument/didOpen".to_owned(), json!(7)),
]
);
assert_eq!(s.docs.lock().get(&uri_of(&b)).map(String::as_str), Some("edited target\n"));
// Its diagnostics are the user's again.
s.peer().notify("textDocument/publishDiagnostics", json!({ "uri": uri_of(&b), "diagnostics": [] })).unwrap();
eventually(|| diagnostics_for(&h, &b) == 1).await;
}
#[tokio::test(flavor = "multi_thread")]
async fn an_empty_answer_while_indexing_is_retried_when_indexing_ends() {
let h = harness(&[("mock", incremental_caps())]);
let s = h.launcher.state("mock");
let (doc, path) = h.open("a.mk", "def target\n");
h.wait_status("mock", ServerStatus::Ready).await;
let peer = s.peer();
peer.notify("$/progress", json!({ "token": "idx", "value": { "kind": "begin", "title": "Indexing" } })).unwrap();
h.wait_status("mock", ServerStatus::Busy).await;
let (state, uri) = (s.clone(), uri_of(&path));
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(200)).await;
state.respond("textDocument/references", Value::Array(occurrences(&uri, "def target\n")));
peer.notify("$/progress", json!({ "token": "idx", "value": { "kind": "end" } })).unwrap();
});
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 1);
assert_eq!(refs.incomplete, None);
assert_eq!(s.requested("textDocument/references").len(), 2);
// While the server works, results are taken as they are; finding nothing is flagged.
s.peer()
.notify("$/progress", json!({ "token": "again", "value": { "kind": "begin", "title": "Indexing" } }))
.unwrap();
h.wait_status("mock", ServerStatus::Busy).await;
let refs = h.mgr.references(doc, Pos::new(0, 5), true, true, Default::default()).await.unwrap();
assert_eq!((refs.locations.len(), refs.incomplete), (1, None));
s.respond("textDocument/references", json!([]));
let refs = h.mgr.references(doc, Pos::new(0, 5), true, false, Default::default()).await.unwrap();
assert_eq!(refs.locations.len(), 0);
assert_eq!(refs.incomplete, Some(ReferencesIncomplete::Indexing));
}
#[tokio::test(flavor = "multi_thread")]
async fn rename_edits_files_outside_the_analysis_scope() {
let (h, s) = scope_harness();
grep_candidates(&h);
let b = h.root.join("b.mk");
std::fs::write(&b, "call target\n").unwrap();
let (doc, a) = h.open("a.mk", "def target\n");
h.wait_status("mock", ServerStatus::Ready).await;
eventually(|| s.docs.lock().len() == 1).await;
let edit = h.mgr.rename(doc, Pos::new(0, 5), "renamed".into()).await.unwrap();
let mut paths: Vec<PathBuf> = edit
.files
.iter()
.map(|f| match f {
FileEdit::Edit { path, .. } => path.to_path_buf(),
_ => panic!("unexpected {f:?}"),
})
.collect();
paths.sort();
assert_eq!(paths, vec![a, b.clone()]);
eventually(|| uris(&s.notified("textDocument/didClose")) == vec![uri_of(&b)]).await;
}
+6
Переглянути файл
@@ -406,6 +406,10 @@ impl ProcessManager {
cmd.cwd(cwd);
if env.clear {
cmd.env_clear();
} else {
for (k, v) in ide_core::process::shell_env() {
cmd.env(k, v);
}
}
cmd.env("TERM", "xterm-256color");
cmd.env("COLORTERM", "truecolor");
@@ -610,6 +614,8 @@ fn launch_env(root: &Path, config: &RunConfig) -> IdeResult<LaunchEnv> {
fn apply_env(cmd: &mut Command, env: &LaunchEnv) {
if env.clear {
cmd.env_clear();
} else {
cmd.envs(ide_core::process::shell_env());
}
cmd.envs(&env.vars);
}
+2
Переглянути файл
@@ -14,6 +14,7 @@ mod mask;
mod pattern;
mod query;
mod replace;
mod words;
pub use files::{ScopeFile, scope_files};
pub use mask::FileMask;
@@ -22,6 +23,7 @@ pub use replace::{
ReplaceEvent, ReplaceHost, ReplacePreview, ReplaceSummary, ReplaceTarget, apply_edits, preserve_case, preview,
replace_files, replacement_edits,
};
pub use words::{WordFiles, WordQuery, files_with_word};
use grep_matcher::{Captures, Matcher};
use ide_core::{CancellationToken, IdeError, IdeResult};
+118
Переглянути файл
@@ -0,0 +1,118 @@
//! Files that mention an identifier: the candidates a reference search checks.
use crate::{Overlay, PathFilter, SearchContext, SearchQuery, SearchScope};
use ide_core::{CancellationToken, IdeResult};
use std::path::PathBuf;
use std::sync::Mutex;
#[derive(Clone, Debug)]
pub struct WordQuery {
/// Matched as a whole word, case-sensitively.
pub word: String,
/// Directory searched (absolute, or relative to the search root).
pub dir: PathBuf,
/// File masks never searched (excluded roots, ignored names).
pub exclude: Vec<String>,
/// Files returned at most.
pub limit: usize,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct WordFiles {
pub files: Vec<PathBuf>,
/// More files matched than `limit`; the search stopped early.
pub limit_hit: bool,
}
/// Files under `query.dir` containing `query.word` as a whole word, in walk
/// order (unsaved buffers through `overlay`, `.gitignore`d and hidden files
/// skipped like Find in Files). Stops at `query.limit` files or when cancelled.
pub fn files_with_word(
root: &std::path::Path,
query: &WordQuery,
filter: Option<PathFilter<'_>>,
overlay: Overlay<'_>,
cancel: &CancellationToken,
) -> IdeResult<WordFiles> {
let search = SearchQuery {
pattern: query.word.clone(),
is_regex: false,
case_sensitive: true,
whole_word: true,
include: Vec::new(),
exclude: query.exclude.clone(),
scope: SearchScope::Directory { path: query.dir.clone().into() },
max_matches: u32::MAX,
context: SearchContext::Any,
};
let stop = cancel.child_token();
let found = Mutex::new(WordFiles::default());
crate::search_filtered(root, &search, filter, overlay, &stop, &|file| {
let mut found = found.lock().unwrap_or_else(|e| e.into_inner());
if found.files.len() < query.limit {
found.files.push(file.path.into_path_buf());
} else {
found.limit_hit = true;
stop.cancel();
}
})?;
Ok(found.into_inner().unwrap_or_else(|e| e.into_inner()))
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
fn query(word: &str, limit: usize) -> WordQuery {
WordQuery { word: word.into(), dir: PathBuf::from("."), exclude: vec!["build/**".into()], limit }
}
#[test]
fn whole_word_matches_in_kept_files_only() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
fs::create_dir_all(root.join("pkg/ignored")).unwrap();
fs::create_dir_all(root.join("build")).unwrap();
fs::write(root.join(".gitignore"), "ignored/\n").unwrap();
fs::write(root.join("pkg/use.py"), "x.get_value(1)\n").unwrap();
fs::write(root.join("pkg/longer.py"), "get_values()\n").unwrap();
fs::write(root.join("pkg/case.py"), "Get_Value()\n").unwrap();
fs::write(root.join("pkg/notes.txt"), "get_value\n").unwrap();
fs::write(root.join("pkg/ignored/gen.py"), "get_value\n").unwrap();
fs::write(root.join("build/out.py"), "get_value\n").unwrap();
fs::write(root.join("pkg/open.py"), "nothing on disk\n").unwrap();
let unsaved = root.join("pkg/open.py");
let overlay = |p: &std::path::Path| (p == unsaved).then(|| "get_value()".to_owned());
let py = |rel: &str| rel.ends_with(".py");
let mut found =
files_with_word(root, &query("get_value", 10), Some(&py), &overlay, &CancellationToken::new()).unwrap();
found.files.sort();
assert_eq!(
found,
WordFiles { files: vec![root.join("pkg/open.py"), root.join("pkg/use.py")], limit_hit: false }
);
}
#[test]
fn stops_at_the_limit() {
let dir = tempfile::tempdir().unwrap();
for i in 0..5 {
fs::write(dir.path().join(format!("f{i}.py")), "name\n").unwrap();
}
let found = files_with_word(dir.path(), &query("name", 2), None, &|_| None, &CancellationToken::new()).unwrap();
assert_eq!((found.files.len(), found.limit_hit), (2, true));
let all = files_with_word(dir.path(), &query("name", 5), None, &|_| None, &CancellationToken::new()).unwrap();
assert_eq!((all.files.len(), all.limit_hit), (5, false));
}
#[test]
fn a_cancelled_search_finds_nothing() {
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join("a.py"), "name\n").unwrap();
let cancel = CancellationToken::new();
cancel.cancel();
let found = files_with_word(dir.path(), &query("name", 5), None, &|_| None, &cancel).unwrap();
assert!(found.files.is_empty());
}
}
+5
Переглянути файл
@@ -507,6 +507,11 @@ impl Repo {
pub fn branch_info(&self) -> IdeResult<BranchInfo> {
refs::branch_info(self)
}
/// Current branch (short name; `None` when detached) and HEAD commit, without
/// upstream tracking (cheap enough to call for every repository on each refresh).
pub fn head(&self) -> IdeResult<(Option<String>, Option<String>)> {
refs::head(&self.gix()?)
}
/// Merge / rebase / cherry-pick… in progress (cheap: no ref walking).
pub fn operation(&self) -> IdeResult<Option<String>> {
Ok(refs::operation(&self.gix()?))
+5
Переглянути файл
@@ -30,6 +30,11 @@ pub(crate) fn branch_info(r: &Repo) -> IdeResult<BranchInfo> {
Ok(info)
}
pub(crate) fn head(repo: &gix::Repository) -> IdeResult<(Option<String>, Option<String>)> {
let name = repo.head_name().map_err(gx)?.map(|n| to_string(n.as_ref().shorten()));
Ok((name, repo.head_id().ok().map(|id| id.to_string())))
}
pub(crate) fn operation(repo: &gix::Repository) -> Option<String> {
use gix::state::InProgress::*;
let op = match repo.state()? {
+2
Переглянути файл
@@ -865,6 +865,7 @@ fn checkout_create_detached_delete_rebase() {
repo.checkout("topic", true).unwrap();
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("topic"));
assert_eq!(repo.head().unwrap(), (Some("topic".to_string()), Some(c1.clone())));
fx.write("t", "topic\n");
fx.commit_all("topic work");
repo.checkout("main", false).unwrap();
@@ -879,6 +880,7 @@ fn checkout_create_detached_delete_rebase() {
let info = repo.branch_info().unwrap();
assert_eq!(info.head, None);
assert_eq!(info.head_commit.as_deref(), Some(c1.as_str()));
assert_eq!(repo.head().unwrap(), (None, Some(c1.clone())));
assert!(
repo.log(&LogQuery { branch: Some("HEAD".into()), ..Default::default() }).unwrap()[0]
.refs
+5 -2
Переглянути файл
@@ -10,12 +10,15 @@
<body>
<div id="root"></div>
<div id="splash" class="splash" data-tauri-drag-region>
<svg viewBox="0 0 64 64" aria-hidden="true">
<svg class="splash-logo" viewBox="0 0 64 64" aria-hidden="true">
<rect width="64" height="64" rx="15" fill="#0E0E10" />
<circle cx="26" cy="32" r="11" fill="none" stroke="#FFFFFF" stroke-width="8" />
<rect x="43" y="18" width="8" height="28" rx="1.5" fill="#FF4F1A" />
</svg>
<span>OpenIDEA</span>
<!-- "OpenIDEA" in Inter 500 as outlines: the web font loads late in dev and would swap in. -->
<svg class="splash-wordmark" viewBox="0 -1984 9994 2478" role="img" aria-label="OpenIDEA">
<path fill="currentColor" d="M785.8 20Q592.6 20 440.4 -71.7Q288.2 -163.4 200.4 -334.7Q112.6 -506 112.6 -744Q112.6 -983.2 200.4 -1154.6Q288.2 -1326 440.4 -1418Q592.6 -1510 785.8 -1510Q979 -1510 1130.7 -1418Q1282.4 -1326 1369.8 -1154.6Q1457.3 -983.2 1457.3 -744Q1457.3 -505.8 1369.8 -334.5Q1282.4 -163.2 1130.7 -71.6Q979 20 785.8 20ZM785.8 -187.7Q913 -187.7 1013.5 -251.6Q1114 -315.5 1172.4 -439.9Q1230.7 -564.3 1230.7 -744Q1230.7 -925.6 1172.4 -1050Q1114 -1174.5 1013.5 -1238.4Q913 -1302.3 785.8 -1302.3Q657.9 -1302.3 557 -1238Q456.1 -1173.7 397.7 -1049.2Q339.2 -924.7 339.2 -744Q339.2 -564.3 397.7 -440.3Q456.1 -316.3 557 -252Q657.9 -187.7 785.8 -187.7ZM1717.9 418V-1118H1932.2V-935.9H1950.4Q1970 -970.8 2005.4 -1016.7Q2040.9 -1062.7 2104.6 -1097.3Q2168.3 -1132 2272.6 -1132Q2407.4 -1132 2512.7 -1064Q2617.9 -996 2678.8 -867Q2739.8 -738 2739.8 -556.4Q2739.8 -375.7 2679.8 -246.2Q2619.8 -116.7 2514.5 -47.3Q2409.1 22.2 2272.7 22.2Q2171.8 22.2 2107.4 -12.4Q2043 -47 2006.6 -93.2Q1970.2 -139.3 1950.4 -175H1937.9V418ZM2224 -165.3Q2320.1 -165.3 2384.9 -217.3Q2449.6 -269.3 2482.4 -358.3Q2515.2 -447.3 2515.2 -558Q2515.2 -668.1 2482.8 -755.4Q2450.4 -842.8 2385.7 -893.7Q2321 -944.5 2224 -944.5Q2129.6 -944.5 2065 -896.1Q2000.4 -847.7 1967.4 -761.2Q1934.4 -674.6 1934.4 -558Q1934.4 -441.7 1967.8 -353.2Q2001.2 -264.7 2066.2 -215Q2131.2 -165.3 2224 -165.3ZM3465.8 23.3Q3300.7 23.3 3181.1 -48.1Q3061.4 -119.5 2996.9 -248.5Q2932.4 -377.5 2932.4 -551.1Q2932.4 -723.3 2995.8 -854Q3059.1 -984.7 3175.1 -1058.4Q3291 -1132 3446.8 -1132Q3542.6 -1132 3632 -1100.7Q3721.4 -1069.4 3792.3 -1002.3Q3863.3 -935.2 3904.7 -828.3Q3946.2 -721.5 3946.2 -570.3V-492.2H3054.8V-656.5H3832.8L3730.1 -602.3Q3730.1 -704.7 3698.2 -783.2Q3666.3 -861.7 3603.5 -905.9Q3540.8 -950 3447.5 -950Q3354.2 -950 3288.2 -905Q3222.1 -860 3187.4 -786.5Q3152.6 -712.9 3152.6 -626.1V-514.4Q3152.6 -399.4 3192.1 -319.8Q3231.6 -240.1 3302.9 -199.4Q3374.2 -158.7 3468.1 -158.7Q3529.6 -158.7 3579.9 -176.3Q3630.2 -194 3666.5 -229.4Q3702.8 -264.9 3722.2 -317.2L3928.6 -268.5Q3902.2 -181.6 3838.6 -115.9Q3775 -50.2 3680.4 -13.4Q3585.8 23.3 3465.8 23.3ZM4406.9 -662.4V0H4186.9V-1118H4396.6L4398.9 -844.3H4376.2Q4424.9 -994.3 4517.8 -1063.1Q4610.7 -1132 4742.5 -1132Q4856.6 -1132 4942 -1084.2Q5027.5 -1036.3 5075.1 -942.5Q5122.7 -848.8 5122.7 -710.4V0H4902.7V-682.9Q4902.7 -803.7 4839.8 -872.1Q4776.9 -940.5 4667.3 -940.5Q4592.9 -940.5 4533.8 -907.9Q4474.8 -875.3 4440.8 -813.3Q4406.9 -751.2 4406.9 -662.4ZM5664.4 -1490V0H5435.9V-1490ZM6478.5 0H6109.9V-199.7H6465.8Q6635 -199.7 6747.1 -263Q6859.2 -326.3 6915 -448.6Q6970.8 -571 6970.8 -747.3Q6970.8 -922.1 6915.2 -1043.3Q6859.7 -1164.4 6750.5 -1227.4Q6641.3 -1290.3 6478.4 -1290.3H6102.2V-1490H6493Q6713.2 -1490 6869.9 -1400.9Q7026.7 -1311.8 7110.7 -1145.2Q7194.7 -978.6 7194.7 -747.3Q7194.7 -514.5 7110.4 -347.1Q7026 -179.6 6865.8 -89.8Q6705.5 0 6478.5 0ZM6222.4 -1490V0H5993.9V-1490ZM7471.9 0V-1490H8409.8V-1293.6H7700.4V-849.7H8359.5V-654.7H7700.4V-196.4H8416.4V0ZM8592.9 0 9123.5 -1490H9403.2L9942.8 0H9696.3L9406.1 -828.9Q9372.2 -930 9331.8 -1066.9Q9291.4 -1203.8 9238.4 -1395.6H9284.5Q9232.7 -1202.2 9192.5 -1063.6Q9152.4 -925.1 9121.4 -828.9L8839.9 0ZM8880.4 -392.6V-583.1H9655.3V-392.6Z" />
</svg>
<div class="splash-bar" role="progressbar" aria-label="Loading"><i></i></div>
</div>
<script type="module" src="/src/main.tsx"></script>
+1
Переглянути файл
@@ -52,6 +52,7 @@
"emmet": "2.4.11",
"immer": "^11.1.21",
"marked": "^18.1.1",
"mermaid": "12.1.0",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-resizable-panels": "^4.14.6",
Створено
+850
File diff suppressed because it is too large. Load diff
+3 -2
Переглянути файл
@@ -17,7 +17,6 @@ body, .splash { background: #e9eaee; }
gap: 14px;
padding-bottom: 38px;
box-sizing: border-box;
font: 500 15px/1.2 "Inter Variable", Inter, system-ui, -apple-system, sans-serif;
color: #6c707e;
-webkit-user-select: none;
user-select: none;
@@ -27,7 +26,9 @@ body, .splash { background: #e9eaee; }
}
.splash.splash-out { opacity: 0; pointer-events: none; }
:root[data-theme^="dark"] .splash { color: #8c8f95; }
.splash svg { width: 56px; height: 56px; }
.splash-logo { width: 56px; height: 56px; }
/* 15px Inter: 2048 units per em, the line box from ascender to descender. */
.splash-wordmark { width: 73.2px; height: 18.15px; }
.splash-bar { width: 120px; height: 2px; border-radius: 1px; overflow: hidden; background: rgb(127 127 127 / 0.18); }
/* Fake progress: eases towards ~90% over the 4 s cap; hideSplash() fills it before fading out. */
.splash-bar > i {
+11 -2
Переглянути файл
@@ -106,16 +106,25 @@ pub async fn lsp_virtual_document(
project!(window, state).lsp.virtual_document(&uri).await
}
/// References of the symbol at `pos`. `project_wide` also searches project files
/// outside the language server's analysis scope; bulk scans over many symbols
/// leave it off. Cancel with `cancel_request(request)`.
#[tauri::command]
#[specta::specta]
pub async fn lsp_references(
window: Window,
state: State<'_, AppState>,
request: RequestId,
doc: DocId,
pos: Pos,
include_declaration: bool,
) -> IdeResult<Vec<Location>> {
project!(window, state).lsp.references(doc, pos, include_declaration).await
project_wide: bool,
) -> IdeResult<References> {
let lsp = project!(window, state).lsp.clone();
let cancel = state.begin_request(request);
let result = lsp.references(doc, pos, include_declaration, project_wide, cancel).await;
state.end_request(request);
result
}
#[tauri::command]
+8 -1
Переглянути файл
@@ -41,6 +41,10 @@ pub struct VcsRoot {
pub root: ide_core::IpcPath,
/// Merge / rebase / cherry-pick / revert in progress.
pub operation: Option<String>,
/// Current branch; `None` when HEAD is detached (or unreadable).
pub head: Option<String>,
/// HEAD commit; `None` before the first commit.
pub head_commit: Option<String>,
}
/// The project's repositories, the primary one first.
@@ -53,7 +57,10 @@ pub fn vcs_roots(window: Window, state: State<'_, AppState>) -> IdeResult<Vec<Vc
all.sort_by_key(|r| Some(r.root()) != primary.as_deref());
Ok(all
.into_iter()
.map(|r| VcsRoot { root: r.root().to_path_buf().into(), operation: r.operation().ok().flatten() })
.map(|r| {
let (head, head_commit) = r.head().unwrap_or_default();
VcsRoot { root: r.root().to_path_buf().into(), operation: r.operation().ok().flatten(), head, head_commit }
})
.collect())
}
+47 -9
Переглянути файл
@@ -5,6 +5,13 @@
//! Spawning an interactive login shell costs ~1 s with typical rc files, so the
//! value is cached: a warm start uses the cached PATH immediately and refreshes
//! the cache in the background for the next launch.
//!
//! The rest of the shell's environment (API keys, provider switches, SDK homes)
//! goes to child processes through `ide_core::process::shell_env`. It stays in
//! memory, never in the cache: it may hold secrets.
#[cfg(unix)]
use std::ffi::{OsStr, OsString};
#[cfg(unix)]
/// Returns a refresh to run once the environment is final (it spawns a
@@ -22,7 +29,9 @@ pub fn inherit_login_shell_path(identifier: &str) -> Option<impl FnOnce() + use<
Some(path) => path,
None => {
// Slow shell rc files must not delay the first start indefinitely.
let fresh = read_login_path(Duration::from_secs(3))?;
let env = read_login_env(Duration::from_secs(3))?;
let fresh = login_path(&env)?;
ide_core::process::set_shell_env(env);
if let Some(cache) = &cache {
write_cache(cache, &fresh);
}
@@ -34,9 +43,11 @@ pub fn inherit_login_shell_path(identifier: &str) -> Option<impl FnOnce() + use<
let cache = cache.filter(|_| refresh)?;
Some(move || {
std::thread::spawn(move || {
if let Some(fresh) = read_login_path(Duration::from_secs(10)) {
let Some(env) = read_login_env(Duration::from_secs(10)) else { return };
if let Some(fresh) = login_path(&env) {
write_cache(&cache, &fresh);
}
ide_core::process::set_shell_env(env);
});
})
}
@@ -50,20 +61,37 @@ fn write_cache(cache: &std::path::Path, path: &str) {
}
#[cfg(unix)]
fn read_login_path(timeout: std::time::Duration) -> Option<String> {
fn login_path(env: &[(OsString, OsString)]) -> Option<String> {
env.iter().find(|(k, _)| k == "PATH").and_then(|(_, v)| v.to_str()).filter(|p| !p.is_empty()).map(str::to_owned)
}
/// Variables the shell sets for itself rather than the user's configuration.
#[cfg(unix)]
const SHELL_OWN: &[&str] = &["PWD", "OLDPWD", "SHLVL", "_"];
/// The login shell's environment; PATH included, the shell's own bookkeeping left out.
#[cfg(unix)]
fn read_login_env(timeout: std::time::Duration) -> Option<Vec<(OsString, OsString)>> {
use std::io::Read;
use std::os::unix::ffi::OsStrExt;
use std::process::{Command, Stdio};
use std::time::Instant;
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/zsh".into());
const MARK: &str = "__OPENIDEA_PATH__";
const MARK: &str = "__OPENIDEA_ENV__";
let mut child = Command::new(&shell)
.args(["-ilc", &format!("printf '{MARK}%s{MARK}' \"$PATH\"")])
.args(["-ilc", &format!("printf '{MARK}'; /usr/bin/env -0; printf '{MARK}'")])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.ok()?;
// Read while waiting: a large environment would fill the pipe and stall the shell.
let mut stdout = child.stdout.take()?;
let reader = std::thread::spawn(move || {
let mut out = Vec::new();
stdout.read_to_end(&mut out).map(|_| out)
});
let deadline = Instant::now() + timeout;
loop {
match child.try_wait() {
@@ -71,14 +99,24 @@ fn read_login_path(timeout: std::time::Duration) -> Option<String> {
Ok(None) if Instant::now() < deadline => std::thread::sleep(std::time::Duration::from_millis(20)),
_ => {
let _ = child.kill();
tracing::warn!("timed out reading PATH from {shell}");
tracing::warn!("timed out reading the environment from {shell}");
return None;
}
}
}
let mut out = String::new();
child.stdout.take()?.read_to_string(&mut out).ok()?;
out.split(MARK).nth(1).filter(|p| !p.is_empty()).map(str::to_owned)
let out = reader.join().ok()?.ok()?;
let mark = MARK.as_bytes();
let start = out.windows(mark.len()).position(|w| w == mark)? + mark.len();
let len = out[start..].windows(mark.len()).position(|w| w == mark)?;
let vars = out[start..start + len]
.split(|&b| b == 0)
.filter_map(|entry| {
let eq = entry.iter().position(|&b| b == b'=')?;
let (k, v) = (OsStr::from_bytes(&entry[..eq]), OsStr::from_bytes(&entry[eq + 1..]));
(!k.is_empty() && !SHELL_OWN.iter().any(|s| k == *s)).then(|| (k.to_owned(), v.to_owned()))
})
.collect();
Some(vars)
}
#[cfg(not(unix))]
+33
Переглянути файл
@@ -442,6 +442,12 @@ impl AppState {
content_watchers: Mutex::new(content_watchers),
_scratch_watcher: scratch_watcher,
});
{
let weak = Arc::downgrade(&project);
project.lsp.set_candidates_hook(Box::new(move |q, cancel| {
weak.upgrade().map(|p| p.reference_candidates(q, cancel)).unwrap_or_default()
}));
}
self.projects.write().insert(window.to_owned(), project.clone());
Ok(project)
}
@@ -609,6 +615,33 @@ impl Project {
out
}
/// Project files of `q.languages` under `q.root` containing `q.word` as a whole
/// word (unsaved buffers included; excluded roots, ignored names and
/// `.gitignore`d files skipped): the files a references search opens on its server.
pub fn reference_candidates(
&self,
q: &ide_lsp::CandidateQuery,
cancel: &CancellationToken,
) -> ide_lsp::CandidateFiles {
if !q.root.starts_with(&self.root) {
return ide_lsp::CandidateFiles::default();
}
let query = ide_search::WordQuery {
word: q.word.clone(),
dir: q.root.clone(),
exclude: self.search_excludes(),
limit: q.limit,
};
let filter = |rel: &str| q.languages.contains(&self.languages.detect(&self.root.join(rel), None));
match ide_search::files_with_word(&self.root, &query, Some(&filter), &|p| self.documents.text_of(p), cancel) {
Ok(found) => ide_lsp::CandidateFiles { files: found.files, limit_hit: found.limit_hit },
Err(e) => {
tracing::debug!("reference candidates: {}", e.message);
ide_lsp::CandidateFiles::default()
}
}
}
/// `files.exclude`, the ignored names and the effective excluded roots (user-marked and detected).
pub fn exclude_globs(&self) -> Vec<String> {
exclude_globs(&self.settings.effective(), &self.detected_roots.read())
+22 -1
Переглянути файл
@@ -287,7 +287,12 @@ export const commands = {
* language server returned a non-`file:` URI for. Cached per project.
*/
lspVirtualDocument: (uri: string) => typedError<VirtualDocument, IdeError>(__TAURI_INVOKE("lsp_virtual_document", { uri })),
lspReferences: (doc: DocId, pos: Pos, includeDeclaration: boolean) => typedError<Location[], IdeError>(__TAURI_INVOKE("lsp_references", { doc, pos, includeDeclaration })),
/**
* References of the symbol at `pos`. `project_wide` also searches project files
* outside the language server's analysis scope; bulk scans over many symbols
* leave it off. Cancel with `cancel_request(request)`.
*/
lspReferences: (request: RequestId, doc: DocId, pos: Pos, includeDeclaration: boolean, projectWide: boolean) => typedError<References, IdeError>(__TAURI_INVOKE("lsp_references", { request, doc, pos, includeDeclaration, projectWide })),
lspDocumentHighlights: (doc: DocId, pos: Pos) => typedError<Highlight[], IdeError>(__TAURI_INVOKE("lsp_document_highlights", { doc, pos })),
lspWorkspaceSymbols: (request: RequestId, query: string) => typedError<WorkspaceSymbol[], IdeError>(__TAURI_INVOKE("lsp_workspace_symbols", { request, query })),
lspCodeActions: (doc: DocId, range: Range, only: string[]) => typedError<CodeAction[], IdeError>(__TAURI_INVOKE("lsp_code_actions", { doc, range, only })),
@@ -4175,6 +4180,18 @@ export type RecentProject = {
branch: string | null,
};
export type References = {
locations: Location[],
incomplete: ReferencesIncomplete | null,
};
/** Why a references search may have missed usages. */
export type ReferencesIncomplete =
/** A language server was still indexing. */
"indexing" |
/** More project files mention the name than were checked. */
"tooManyFiles";
export type Remote = {
name: string,
/** Fetch URL. */
@@ -5150,6 +5167,10 @@ export type VcsRoot = {
root: IpcPath,
/** Merge / rebase / cherry-pick / revert in progress. */
operation: string | null,
/** Current branch; `None` when HEAD is detached (or unreadable). */
head: string | null,
/** HEAD commit; `None` before the first commit. */
headCommit: string | null,
};
/** Version Control (main page) and its sub-pages. */
+17 -1
Переглянути файл
@@ -37,7 +37,7 @@ import { qualifiedReference } from "./copyReference";
import { symbolChain } from "./view/outline";
import { recordClipboard } from "./clipboardHistory";
import { useDocMeta, useOutline } from "./model/document";
import { fontZoom, setFontZoom } from "./cm/prefs";
import { fontZoom, setFontZoom, stepFontZoom } from "./cm/prefs";
import { useEditorRegistry } from "@/editor/api";
import { useProject } from "@/platform/project";
import { call, commands } from "@/platform/ipc";
@@ -471,6 +471,22 @@ export function registerEditorActions(): () => void {
if (ed.view.state.field(fontZoom, false)) ed.view.dispatch({ effects: setFontZoom.of(0) });
},
},
{
id: "editor.increaseFontSize",
title: "Increase Font Size",
category: "View",
keywords: ["zoom", "font size"],
when: EDITOR_WHEN,
run: withView((view) => stepFontZoom(view, 1)),
},
{
id: "editor.decreaseFontSize",
title: "Decrease Font Size",
category: "View",
keywords: ["zoom", "font size"],
when: EDITOR_WHEN,
run: withView((view) => stepFontZoom(view, -1)),
},
{
id: "file.toggleReadOnly",
title: "Toggle Read-only Attribute",
+11 -4
Переглянути файл
@@ -343,8 +343,9 @@ export const setFontZoom = StateEffect.define<number>();
export const fontZoom = StateField.define<number>({
create: () => 0,
update: (v, tr) => tr.effects.reduce((acc, e) => (e.is(setFontZoom) ? e.value : acc), v),
// Highest precedence: its style comes after the configured font size, which it scales.
provide: (f) =>
Prec.lowest(
Prec.highest(
EditorView.editorAttributes.compute([f], (s) => {
const z = s.field(f);
const attrs: Record<string, string> = {};
@@ -355,13 +356,19 @@ export const fontZoom = StateField.define<number>({
),
});
/** Steps an editor's font zoom by `delta` px, kept within -6..36. */
export function stepFontZoom(view: EditorView, delta: number): void {
const z = view.state.field(fontZoom, false);
if (z === undefined) return;
const next = Math.max(-6, Math.min(36, z + delta));
if (next !== z) view.dispatch({ effects: setFontZoom.of(next) });
}
const wheelZoom = EditorView.domEventHandlers({
wheel(e, view) {
if (!e.metaKey && !e.ctrlKey) return false;
e.preventDefault();
const z = view.state.field(fontZoom, false) ?? 0;
const next = Math.max(-6, Math.min(36, z + (e.deltaY < 0 ? 1 : -1)));
if (next !== z) view.dispatch({ effects: setFontZoom.of(next) });
stepFontZoom(view, e.deltaY < 0 ? 1 : -1);
return true;
},
});
+4 -2
Переглянути файл
@@ -9,7 +9,7 @@ import { EditorSelection, MapMode, StateEffect, StateField, type Extension, type
import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
import { codeLenses, type CodeLens } from "@/editor/api";
import { executeAction } from "@/platform/actions";
import { commands, type OutlineItem, type SymbolKind } from "@/platform/ipc";
import { commands, nextRequestId, type OutlineItem, type SymbolKind } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { debounce, docOf, isUnavailable, lspRequest } from "./lsp";
import { posToOffset } from "./positions";
@@ -166,7 +166,9 @@ class UsagesLensPlugin {
await Promise.all(
todo.slice(i, i + CONCURRENCY).map(async (t) => {
try {
const refs = await lspRequest(() => commands.lspReferences(doc.doc, { line: t.line, col: t.col }, false));
const { locations: refs } = await lspRequest(() =>
commands.lspReferences(nextRequestId(), doc.doc, { line: t.line, col: t.col }, false, true),
);
this.cache.set(key(t), refs.length);
} catch (e) {
if (isUnavailable(e)) unavailable = true;
+41 -1
Переглянути файл
@@ -4,13 +4,16 @@ import { EditorView } from "@codemirror/view";
import type { InlayHint } from "@/bindings";
const openFile = vi.fn(async () => undefined);
const gotoTargets = vi.fn(async () => undefined);
vi.mock("./navigation", () => ({ gotoTargets }));
vi.mock("@/workbench/contributions", async (orig) => {
const actual = await orig<typeof import("@/workbench/contributions")>();
return { ...actual, maybeEditorService: () => ({ openFile }) };
});
const { inlayDecorations, inlayMenuItems } = await import("./inlay");
const { inlayDecorations, inlayExtension, inlayMenuItems } = await import("./inlay");
const { usePlatform } = await import("@/platform/platformInfo");
const { resetNavigationModifier } = await import("@/platform/navigationModifier");
const { useContextMenuStore } = await import("@/ui");
const hint: InlayHint = {
@@ -33,6 +36,7 @@ const hint: InlayHint = {
const views: EditorView[] = [];
afterEach(() => {
views.splice(0).forEach((v) => v.destroy());
resetNavigationModifier();
vi.clearAllMocks();
});
@@ -71,4 +75,40 @@ describe("inlay hints", () => {
]);
expect((inlayMenuItems("parameter")[0] as { label: string }).label).toBe("Disable Parameter name hints");
});
it("uses type declaration navigation for a plain type hint after an identifier", () => {
usePlatform.setState({ os: "macos" });
const view = editorWith([{ ...hint, label: ": Foo", parts: [] }]);
const el = view.dom.querySelector<HTMLElement>(".cm-lsp-inlay")!;
el.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0 }));
expect(gotoTargets).not.toHaveBeenCalled();
el.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0, metaKey: true }));
expect(gotoTargets).toHaveBeenCalledWith(view, "typeDefinition", 4);
expect(openFile).not.toHaveBeenCalled();
});
it("does not treat parameter hints or type hints away from an identifier as type links", () => {
const view = editorWith([
{ ...hint, kind: "parameter", parts: [] },
{ ...hint, position: { line: 0, col: 6 }, parts: [] },
]);
expect(view.dom.querySelectorAll(".cm-lsp-inlay-part")).toHaveLength(0);
});
it.each([
{ os: "macos", key: "Meta", modifier: "metaKey" },
{ os: "windows", key: "Control", modifier: "ctrlKey" },
] as const)("tracks the navigation modifier for inlay cursors on $os", ({ os, key, modifier }) => {
usePlatform.setState({ os });
const view = new EditorView({
state: EditorState.create({ doc: "let x = foo();", extensions: [inlayExtension()] }),
parent: document.body,
});
views.push(view);
expect(view.contentDOM.classList.contains("cm-lsp-navigation-modifier")).toBe(false);
window.dispatchEvent(new KeyboardEvent("keydown", { key, [modifier]: true }));
expect(view.contentDOM.classList.contains("cm-lsp-navigation-modifier")).toBe(true);
window.dispatchEvent(new KeyboardEvent("keyup", { key }));
expect(view.contentDOM.classList.contains("cm-lsp-navigation-modifier")).toBe(false);
});
});
+30 -1
Переглянути файл
@@ -8,7 +8,7 @@ import { StateEffect, StateField, type Extension } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet, type ViewUpdate } from "@codemirror/view";
import { call, commands, isTauri, type InlayHint } from "@/platform/ipc";
import { executeAction } from "@/platform/actions";
import { isNavigationGesture } from "@/platform/navigationModifier";
import { isNavigationGesture, navigationModifierHeld, onNavigationModifier } from "@/platform/navigationModifier";
import { maybeEditorService } from "@/workbench/contributions";
import { showContextMenu, type MenuItem } from "@/ui";
import { useProject } from "@/platform/project";
@@ -16,6 +16,7 @@ import { editorPrefs } from "@/platform/editorSettings";
import { debounce, docOf, isUnavailable, lspRequest } from "./lsp";
import { offsetsToRange, posToOffset } from "./positions";
import { onLspRefresh, serverBackoff } from "./availability";
import { gotoTargets } from "./navigation";
const KIND_LABEL: Record<InlayHint["kind"], string> = {
type: "Type hints",
@@ -28,6 +29,13 @@ async function setEditorSetting(key: string, value: unknown) {
useProject.setState({ settings: await call(commands.settingsSet("global", `editor.${key}`, JSON.stringify(value))) });
}
/** A type hint after an identifier can resolve that identifier's inferred type. */
function typeHintOffset(view: EditorView, at: number): number | null {
if (at <= 0 || at > view.state.doc.length) return null;
const word = view.state.wordAt(at - 1);
return word?.to === at ? word.from : null;
}
/** Right-click on a hint: turn its kind off (IDEA's "Disable '…' hints"), or open the settings. */
export function inlayMenuItems(kind: InlayHint["kind"]): MenuItem[] {
return [
@@ -81,6 +89,22 @@ class InlayWidget extends WidgetType {
el.appendChild(span);
}
} else el.textContent = this.hint.label;
// A plain type hint (basedpyright's `: Series`) names no location: ⌘-click opens the preceding identifier's type.
if (
this.hint.kind === "type" &&
!parts.some((p) => p.location) &&
typeHintOffset(view, posToOffset(view.state.doc, this.hint.position)) !== null
) {
el.classList.add("cm-lsp-inlay-part");
el.addEventListener("mousedown", (e) => {
if (e.button !== 0 || !isNavigationGesture(e)) return;
const offset = typeHintOffset(view, view.posAtDOM(el));
if (offset === null) return;
e.preventDefault();
e.stopPropagation();
void gotoTargets(view, "typeDefinition", offset);
});
}
if (this.hint.tooltip) el.title = this.hint.tooltip;
el.setAttribute("aria-hidden", "true");
el.addEventListener("contextmenu", (e) => {
@@ -131,8 +155,11 @@ const inlayPlugin = ViewPlugin.fromClass(
private refresh = debounce(() => void this.run(), 400);
private unsubscribe: () => void;
private offReady: () => void;
private offModifier: () => void;
constructor(private view: EditorView) {
this.refresh();
view.contentDOM.classList.toggle("cm-lsp-navigation-modifier", navigationModifierHeld());
this.offModifier = onNavigationModifier((held) => view.contentDOM.classList.toggle("cm-lsp-navigation-modifier", held));
this.unsubscribe = useProject.subscribe((s, prev) => {
if (s.settings?.editor?.inlayHints !== prev.settings?.editor?.inlayHints || s.settings?.editor?.inlay !== prev.settings?.editor?.inlay)
this.refresh();
@@ -167,6 +194,8 @@ const inlayPlugin = ViewPlugin.fromClass(
this.refresh.cancel();
this.unsubscribe();
this.offReady();
this.offModifier();
this.view.contentDOM.classList.remove("cm-lsp-navigation-modifier");
}
},
);
+5 -1
Переглянути файл
@@ -328,7 +328,11 @@ export const lspTheme = EditorView.theme({
userSelect: "none",
},
// A part naming a declaration (⌘-click navigates there).
".cm-lsp-inlay-part:hover": { textDecoration: "underline", textUnderlineOffset: "2px" },
".cm-lsp-navigation-modifier .cm-lsp-inlay-part:hover": {
textDecoration: "underline",
textUnderlineOffset: "2px",
cursor: "pointer",
},
// Inline completion: the suggestion as gray text at the caret.
".cm-inline-ghost": { color: "var(--fg-subtle)", whiteSpace: "pre" },
".cm-lsp-inlay-pl": { marginLeft: "4px" },
+4 -1
Переглянути файл
@@ -16,7 +16,10 @@ let outline: Answer<OutlineItem[]> = ok([]);
let references: Answer<Location[]> = ok([]);
const lspGoto = vi.fn(async () => goto());
const docOutline = vi.fn(async () => outline());
const lspReferences = vi.fn(async () => references());
const lspReferences = vi.fn(async () => {
const r = references();
return r.status === "ok" ? { status: "ok" as const, data: { locations: r.data, incomplete: null } } : r;
});
const lspCodeActions = vi.fn(async () => ({ status: "ok", data: [] }));
const lspApplyCodeAction = vi.fn(async () => ({ status: "ok", data: null }));
const docOpen = vi.fn(async (path: string) => ({ status: "ok", data: { id: 99, path } }));
+4 -3
Переглянути файл
@@ -13,7 +13,7 @@
import type { EditorView } from "@codemirror/view";
import type { Text } from "@codemirror/state";
import type { LocalSymbol, Location, OutlineItem, Pos, Range, SyntaxNode } from "@/bindings";
import { call, commands, isCancelled, isTauri } from "@/platform/ipc";
import { call, commands, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";
import { executeAction } from "@/platform/actions";
import { basename } from "@/platform/project";
import { editorsFor, whenSynced, type EditorDocContext } from "@/editor/api";
@@ -252,7 +252,7 @@ async function findUsages(ctx: EditorDocContext, target: SafeDeleteTarget): Prom
comparePos(range.start, target.range.end) > 0;
if (target.local)
return target.local.references.filter((r) => outside(ctx.path, r)).map((range) => ({ path: ctx.path, range }));
const refs = await lspRequest(() => commands.lspReferences(ctx.doc, target.at, false));
const { locations: refs } = await lspRequest(() => commands.lspReferences(nextRequestId(), ctx.doc, target.at, false, true));
return refs.filter((l) => outside(l.path, l.range));
}
@@ -517,7 +517,8 @@ export async function fileUsages(paths: readonly string[], signal?: AbortSignal)
if (signal?.aborted) return;
let refs: Location[];
try {
refs = await lspRequest(() => commands.lspReferences(doc, item.selection_range.start, false));
// Every symbol of every file: the server's own scope (a project search each would be too slow).
refs = (await lspRequest(() => commands.lspReferences(nextRequestId(), doc, item.selection_range.start, false, false))).locations;
} catch (e) {
if (isUnavailable(e)) {
reason = errorText(e);
+5 -1
Переглянути файл
@@ -28,6 +28,7 @@ import {
} from "./composerModel";
import { composerDraft, updateComposer, useAgents } from "./store";
import styles from "./Composer.module.css";
import { isImeKey } from "@/platform/ime";
const MAX_PROMPT_HEIGHT = 280;
const MAX_ITEMS = 12;
@@ -213,7 +214,7 @@ export function Composer(props: ComposerProps) {
}, [id, root]);
const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (e.nativeEvent.isComposing) return;
if (isImeKey(e.nativeEvent)) return;
if (open) {
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
@@ -320,6 +321,9 @@ export function Composer(props: ComposerProps) {
ref={ref}
className={styles.textarea}
rows={2}
spellCheck={false}
autoCorrect="off"
autoCapitalize="off"
value={text}
aria-label={tx("Message")}
placeholder={tx(props.placeholder)}
+6 -2
Переглянути файл
@@ -38,14 +38,18 @@
.headerDetail {
flex: 1 1 0;
min-width: 0;
display: flex;
align-items: center;
gap: 4px;
color: var(--fg-subtle);
}
.headerText {
min-width: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.providerIcon {
vertical-align: -2px;
margin-right: 4px;
color: var(--fg-muted);
}
.muted {
+8 -6
Переглянути файл
@@ -68,12 +68,14 @@ function Header({ task }: { task: AgentTask }) {
</span>
<span className={styles.headerDetail} title={task.cwd}>
<Icon name={providerIcon(task.provider)} size={13} className={styles.providerIcon} />
{providerName(task.provider)}
{task.model ? ` · ${task.model}` : ""}
{" · "}
{where ?? <T>Local checkout</T>}
{" · "}
<T>{statusLabel(task.status)}</T>
<span className={styles.headerText}>
{providerName(task.provider)}
{task.model ? ` · ${task.model}` : ""}
{" · "}
{where ?? <T>Local checkout</T>}
{" · "}
<T>{statusLabel(task.status)}</T>
</span>
</span>
{task.usage && <Usage task={task} />}
{busy && <IconButton icon="stop" title="Stop" size="small" onClick={() => void cancelTask(task.id)} />}
+12 -2
Переглянути файл
@@ -24,7 +24,7 @@ vi.mock("@/platform/ipc", async (orig) => {
vi.mock("./candidates", () => ({ filesMentioning: () => filesMentioning() }));
const { _addEditor } = await import("@/editor/api");
const { fetchUsages } = await import("./usages");
const { fetchUsages, incompleteNote } = await import("./usages");
const { LOCAL_NOTE, TEXT_NOTE } = await import("./syntaxUsages");
const r = (line: number, col: number, endCol: number): Range => ({ start: { line, col }, end: { line, col: endCol } });
@@ -39,11 +39,21 @@ beforeEach(() => {
describe("Find Usages fallback", () => {
it("uses the server when it answers, even with nothing", async () => {
cmd.lspReferences.mockReturnValueOnce(ok([]));
cmd.lspReferences.mockReturnValueOnce(ok({ locations: [], incomplete: null }));
expect(await fetchUsages(caret)).toEqual({ groups: [], note: null });
expect(cmd.syntaxLocals).not.toHaveBeenCalled();
});
it("searches project-wide under the given request and says when results may be incomplete", async () => {
const usage = { path: "/p/a.ts", range: r(1, 0, 1) };
cmd.lspReferences.mockReturnValueOnce(ok({ locations: [usage], incomplete: "indexing" }));
const res = await fetchUsages(caret, 42 as never);
expect(cmd.lspReferences).toHaveBeenCalledWith(42, 3, { line: 1, col: 0 }, false, true);
expect(res.groups[0]!.usages.length).toBe(1);
expect(res.note).toBe(incompleteNote("indexing", "x"));
expect(incompleteNote("tooManyFiles", "x")).toBe("May be incomplete: too many files mention 'x' to search them all");
});
it("lists a certain local's references when the server is not ready", async () => {
cmd.syntaxLocals.mockReturnValueOnce(
ok({
+47 -9
Переглянути файл
@@ -1,7 +1,7 @@
/** Find Usages (⌥F7 → "usages" tool window) and Show Usages (⌥⌘F7 → popup). */
import { create } from "zustand";
import type { Location } from "@/bindings";
import { commands, isCancelled } from "@/platform/ipc";
import type { Location, ReferencesIncomplete, RequestId } from "@/bindings";
import { commands, isCancelled, nextRequestId } from "@/platform/ipc";
import { toolWindowService } from "@/workbench/contributions";
import {
caretContext,
@@ -119,6 +119,7 @@ export function pinUsageTab(id: number, pinned: boolean) {
}
export function closeUsageTab(id: number) {
cancelSearch(id);
useUsages.setState((s) => {
const i = s.tabs.findIndex((t) => t.id === id);
const tabs = s.tabs.filter((t) => t.id !== id);
@@ -153,15 +154,25 @@ interface FetchedUsages {
note: string | null;
}
/** Why the server's answer may miss usages, for the results' note. */
export function incompleteNote(reason: ReferencesIncomplete, word: string | null): string {
if (reason === "indexing") return "May be incomplete: the language server is still indexing";
return `May be incomplete: too many files mention ${word ? `'${word}'` : "the name"} to search them all`;
}
/**
* The server's references; when it is not ready or fails, the syntax fallback
* (an empty server answer is respected). Without a fallback the server error stands.
* The server's references across the project (files outside its analysis scope
* included); when it is not ready or fails, the syntax fallback (an empty server
* answer is respected). Without a fallback the server error stands.
* Cancel with `commands.cancelRequest(request)`.
*/
export async function fetchUsages(c: CaretContext): Promise<FetchedUsages> {
export async function fetchUsages(c: CaretContext, request: RequestId = nextRequestId()): Promise<FetchedUsages> {
let locs: Location[];
let note: string | null = null;
try {
locs = await lspRequest(() => commands.lspReferences(c.doc, { line: c.line, col: c.col }, false));
const refs = await lspRequest(() => commands.lspReferences(request, c.doc, { line: c.line, col: c.col }, false, true));
locs = refs.locations;
if (refs.incomplete) note = incompleteNote(refs.incomplete, c.word);
} catch (e) {
if (isCancelled(e)) throw e;
let fb = null;
@@ -179,8 +190,22 @@ export async function fetchUsages(c: CaretContext): Promise<FetchedUsages> {
return { groups: groupUsages(locs, files), note };
}
/** In-flight server requests: of tool window searches by search id, and of the popup. */
const inflight = new Map<number, RequestId>();
let popupRequest: RequestId | null = null;
function cancelSearch(id: number) {
const request = inflight.get(id);
if (request === undefined) return;
inflight.delete(id);
void commands.cancelRequest(request).catch(() => {});
}
/** The window switched projects: results (and in-flight searches) of the previous one are dropped. */
export function resetUsages() {
for (const id of [...inflight.keys()]) cancelSearch(id);
if (popupRequest !== null) void commands.cancelRequest(popupRequest).catch(() => {});
popupRequest = null;
useUsages.setState({ tabs: [], active: null });
useUsagesPopup.setState({ open: false, symbol: null, groups: [], note: null });
}
@@ -195,15 +220,22 @@ export async function findUsages() {
const id = ++searchSeq;
const base = { id, symbol: c.word, rerun: () => void run(id) };
const loading = { ...base, loading: true, groups: [], error: null, note: null };
if (prev !== null) cancelSearch(prev);
if (prev === null || !replaceUsageTab(prev, loading)) openUsageTab(loading);
toolWindowService().show("usages");
const request = nextRequestId();
inflight.set(id, request);
try {
const { groups, note } = await fetchUsages(c);
const { groups, note } = await fetchUsages(c, request);
replaceUsageTab(id, { ...base, loading: false, groups, error: null, note });
} catch (e) {
// Cancelled here (closed tab, rerun): a newer state already replaced it.
if (isCancelled(e) && !inflight.has(id)) return;
const message = e instanceof Error ? e.message : String(e);
if (!replaceUsageTab(id, { ...base, loading: false, groups: [], error: message, note: null })) return;
reportError(e);
} finally {
if (inflight.get(id) === request) inflight.delete(id);
}
};
await run(null);
@@ -232,11 +264,15 @@ export async function showUsagesPopup() {
hint("Open a file to show usages");
return;
}
if (popupRequest !== null) void commands.cancelRequest(popupRequest).catch(() => {});
const request = nextRequestId();
popupRequest = request;
try {
const { groups, note } = await fetchUsages(c);
const { groups, note } = await fetchUsages(c, request);
const total = usageCount(groups);
if (!total) {
hint(c.word ? `No usages of '${c.word}' found` : "No usages found");
const none = c.word ? `No usages of '${c.word}' found` : "No usages found";
hint(note ? `${none}. ${note}` : none);
return;
}
if (total === 1) {
@@ -249,5 +285,7 @@ export async function showUsagesPopup() {
useUsagesPopup.setState({ open: true, anchor: caretPoint(), symbol: c.word, groups, note });
} catch (e) {
reportError(e);
} finally {
if (popupRequest === request) popupRequest = null;
}
}
+1 -1
Переглянути файл
@@ -6,7 +6,7 @@ const loc = { path: "/p/b.ts", range: { start: { line: 1, col: 4 }, end: { line:
vi.mock("./ipc", async (orig) => ({
...(await orig<typeof import("./ipc")>()),
caretContext: () => ({ doc: 1, path: "/p/a.ts", line: 0, col: 0, word: "used", view: null }),
lspRequest: async () => [loc],
lspRequest: async () => ({ locations: [loc], incomplete: null }),
readManyFileLines: async () => new Map([["/p/b.ts", ["", " used();"]]]),
openLocation: async (path: string, line: number) => void calls.push(`open ${path}:${line}`),
hint: (text: string) => void calls.push(`hint ${text}`),
+2 -1
Переглянути файл
@@ -6,6 +6,7 @@ import { sshLabel } from "./model";
import { SourceDialog } from "./SourceDialog";
import { closeDialog, useDatabase } from "./store";
import styles from "./Database.module.css";
import { isImeKey } from "@/platform/ime";
const ObjectDialogs = lazyComponent(() => import("./ObjectDialogs").then((m) => m.ObjectDialogs));
const ExportDialog = lazyComponent(() => import("./ExportDialog").then((m) => m.ExportDialog));
@@ -138,7 +139,7 @@ function ParamsDialog({
<div
className={styles.form}
onKeyDown={(e) => {
if (e.key !== "Enter" || e.nativeEvent.isComposing) return;
if (e.key !== "Enter" || isImeKey(e.nativeEvent)) return;
e.preventDefault();
done(values);
}}
+2 -1
Переглянути файл
@@ -23,6 +23,7 @@ import { colorVar, connectRemedy, fileSourceName, newSourceId, parseSourceUrl, s
import { closeDialog, loadDatabases, loadSchemas, saveSource, useDatabase } from "./store";
import { VENDORS, sourceUrl, vendorById, vendorOf } from "./vendors";
import styles from "./Database.module.css";
import { isImeKey } from "@/platform/ime";
type Tab = "general" | "options" | "ssh" | "schemas" | "advanced";
@@ -284,7 +285,7 @@ function NamePicker({
aria-label={`Add ${title} pattern`}
onChange={(e) => setPattern(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.nativeEvent.isComposing) {
if (e.key === "Enter" && !isImeKey(e.nativeEvent)) {
e.preventDefault();
add();
}
+2 -1
Переглянути файл
@@ -33,6 +33,7 @@ import { closeBreakpointPopover, useOverlays } from "./popoverStore";
import { VariablesView, type VarRoot } from "./VariablesView";
import { pushHistory, readHistory } from "./expressionHistory";
import styles from "./Overlays.module.css";
import { isImeKey } from "@/platform/ime";
export function DebuggerOverlays() {
return (
@@ -710,7 +711,7 @@ function EvaluateDialogInner({ initial }: { initial: string }) {
});
};
const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (e.nativeEvent.isComposing) return;
if (isImeKey(e.nativeEvent)) return;
const el = e.currentTarget;
if (e.key === "Enter" && e.shiftKey && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
+2 -1
Переглянути файл
@@ -21,6 +21,7 @@ import {
useMacros,
type MacroStep,
} from "./model";
import { isImeKey } from "@/platform/ime";
/** Records typing and editor keys of every text editor while a macro records. */
const recorder = [
@@ -31,7 +32,7 @@ const recorder = [
EditorView.domEventHandlers({
keydown(e) {
// Keys the IDE keymap ran as actions were recorded as those actions.
if (e.defaultPrevented || e.isComposing || !useMacros.getState().recording) return false;
if (e.defaultPrevented || isImeKey(e) || !useMacros.getState().recording) return false;
const key = editorKeyName(e);
if (key) recordStep({ kind: "key", key });
return false;
+1 -1
Переглянути файл
@@ -245,7 +245,7 @@ export async function runFileRefactoring(
} catch (e) {
notifications().notify({
level: "error",
title: `Cannot ${label.toLowerCase()} ${moves.length === 1 ? nameOf(moves[0]!.from) : `${moves.length} items`}`,
title: `${label === "Move" ? "Cannot move" : "Cannot rename"} ${moves.length === 1 ? nameOf(moves[0]!.from) : `${moves.length} items`}`,
body: e instanceof Error ? e.message : String(e),
});
return "failed";
+2 -1
Переглянути файл
@@ -57,6 +57,7 @@ import {
widenSearchEverywhere,
} from "./store";
import styles from "./SearchEverywhere.module.css";
import { isImeKey } from "@/platform/ime";
type SeScope = "allPlaces" | ProjectFileSet;
@@ -315,7 +316,7 @@ function SearchEverywhereDialog() {
};
const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.nativeEvent.isComposing) return;
if (isImeKey(e.nativeEvent)) return;
if (e.key === "Tab") {
e.preventDefault();
e.stopPropagation();
+2 -1
Переглянути файл
@@ -33,6 +33,7 @@ import { trackRuntimeSettings } from "./runtime";
import { installActionProxies, installSettingsHost } from "./window/bridge";
import { AssignShortcutOverlay, showAssignShortcut } from "./keymap/AssignShortcut";
import { settingsSearchEntries } from "./searchIndex";
import { isImeKey } from "@/platform/ime";
export { settingsWindowParent } from "./window/bridge";
export const SettingsWindow = lazyComponent(() => import("./window/SettingsWindow").then((m) => m.SettingsWindow));
@@ -165,7 +166,7 @@ function listenLaunch(): () => void {
/** Esc and ⌘W cancel, like closing the window; ⌘, stays here. */
function installWindowKeys(): () => void {
const onKey = (e: KeyboardEvent) => {
if (e.defaultPrevented || e.isComposing) return;
if (e.defaultPrevented || isImeKey(e)) return;
const mod = e.metaKey || e.ctrlKey;
if ((e.key === "Escape" && !isPopupOpen()) || (mod && !e.altKey && !e.shiftKey && e.key.toLowerCase() === "w")) {
e.preventDefault();
+2 -1
Переглянути файл
@@ -18,6 +18,7 @@ import { executeAction } from "@/platform/actions";
import { effectiveBindings, strokeOf } from "@/platform/keymap";
import { workflowSettings } from "@/platform/workflowSettings";
import { terminalRuntime } from "./loader";
import { isImeKey } from "@/platform/ime";
export type TerminalKeyResult =
| { kind: "send"; data: string }
@@ -128,7 +129,7 @@ export function isAllowedIdeShortcut(stroke: string, bindings: ReadonlyArray<rea
export function installTerminalKeys(target: Window = window): () => void {
const onKeyDown = (e: KeyboardEvent) => {
const rt = terminalRuntime();
if (e.isComposing || !rt) return;
if (isImeKey(e) || !rt) return;
// The terminal find bar: Escape closes it (instead of "focus editor"), ⌘F reselects the query.
if ((e.target as Element | null)?.closest?.("[data-terminal-find]")) {
const plain = !e.ctrlKey && !e.altKey && !e.shiftKey;
+36 -31
Переглянути файл
@@ -29,37 +29,6 @@
content: " /";
color: var(--fg-subtle);
}
.repos {
flex: none;
display: flex;
flex-wrap: wrap;
gap: 4px;
padding: 6px 8px;
border-bottom: 1px solid var(--border-popup);
}
.repoButton {
max-width: 160px;
height: 22px;
padding: 0 8px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
border: none;
border-radius: var(--radius-small);
background: transparent;
color: var(--fg-secondary);
font: inherit;
font-size: var(--fs-small);
cursor: pointer;
}
.repoButton:hover {
background: var(--bg-hover);
}
.repoSelected,
.repoSelected:hover {
background: var(--bg-selected);
color: var(--fg);
}
.operation {
color: var(--warning);
font-size: var(--fs-tiny);
@@ -75,6 +44,9 @@
flex-direction: column;
overflow: hidden;
}
.popup.wide {
width: 440px;
}
.search {
flex: none;
display: flex;
@@ -83,6 +55,9 @@
padding: 6px 6px 6px 4px;
border-bottom: 1px solid var(--border-popup);
}
.searchGrow {
flex: 1;
}
.listWrap {
display: flex;
flex-direction: column;
@@ -194,3 +169,33 @@
[role="option"]:hover .star:not(.starOn) .branchIcon {
visibility: hidden;
}
.separator {
flex: 1;
height: 1px;
margin: 0 4px;
background: var(--border-popup);
}
.repoColor {
flex: none;
width: 10px;
height: 10px;
margin: 0 2px;
border-radius: 2px;
}
.repoHead {
flex: 0 4 auto;
margin-left: auto;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-muted);
font-family: var(--font-mono);
font-size: var(--fs-small);
}
.subChevron {
flex: none;
color: var(--fg-faint);
}
.groupRow {
color: var(--fg-secondary);
}
+482 -79
Переглянути файл
@@ -2,9 +2,11 @@
import { useEffect, useMemo, useRef, useState, type KeyboardEvent, type RefObject } from "react";
import clsx from "clsx";
import { create } from "zustand";
import type { Branch, BranchInfo } from "@/bindings";
import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { shortcutLabel } from "@/platform/keymap";
import { useEditorRegistry } from "@/editor/api";
import {
BarButton,
HighlightedText,
@@ -19,10 +21,20 @@ import {
type MenuItem,
} from "@/ui";
import { buildBranchRows, type BranchRow, type PopupAction } from "./branches";
import { branchMenu, tagMenu } from "./branchMenu";
import { branchMenu, commonBranchMenu, inRepo, tagMenu } from "./branchMenu";
import { loadFavoriteBranches, recentBranches, toggleFavoriteBranch, useFavoriteBranches } from "./branchOps";
import { inProgress, operationTitle, type InProgress } from "./operations";
import { currentRepo, loadBranches, repoName, selectRepo, useVcs } from "./store";
import {
buildMultiRepoRows,
currentRepoFor,
DEFAULT_EXPANDED,
repoHeadLabel,
toggleExpanded,
widgetShowsRepo,
type RepoEntry,
type RepoRow,
} from "./repoBranches";
import { currentRepo, focusRepo, loadBranches, repoName, useVcs } from "./store";
import styles from "./BranchWidget.module.css";
export const useBranchesPopup = create<{ open: boolean }>(() => ({ open: false }));
@@ -34,14 +46,29 @@ export function headLabel(branch: { head: string | null; headCommit: string | nu
return branch.headCommit ? branch.headCommit.slice(0, 8) : "No commits";
}
/** The current repository (see `currentRepoFor`): the widget and the popup show the same one. */
function useCurrentRepo(): string | null {
const path = useEditorRegistry((s) => s.active?.ctx.path ?? null);
return useVcs((s) => currentRepoFor(path, s.roots, s.repo));
}
export function BranchWidget() {
const available = useVcs((s) => s.available);
const branch = useVcs((s) => s.branch);
// With several repositories the widget names the selected one, like IDEA's.
const repo = useVcs((s) => (s.roots.length > 1 && s.repo ? repoName(s.repo) : null));
const selected = useVcs((s) => s.branch);
const count = useVcs((s) => s.roots.length);
const current = useCurrentRepo();
// Several repositories on different branches: the widget names the current one.
const diverged = useVcs((s) => widgetShowsRepo(s.roots.map((r) => ({ head: s.heads[r]?.head ?? null }))));
// The current repository is not the selected one: its HEAD from the last scan (no upstream).
const other = useVcs((s) => (diverged && current && current !== s.repo ? (s.heads[current] ?? null) : null));
const otherOp = useVcs((s) => (current ? (s.operations[current] ?? null) : null));
const open = useBranchesPopup((s) => s.open);
const ref = useRef<HTMLButtonElement>(null);
if (!available || !branch) return null;
if (!available || !selected) return null;
const repo = diverged && current ? repoName(current) : null;
const branch: BranchInfo = other
? { head: other.head, headCommit: other.headCommit, upstream: null, ahead: 0, behind: 0, operation: otherOp }
: selected;
const op = branch.operation ? ` (${branch.operation})` : "";
const sync = [
branch.behind > 0 ? `${branch.behind} incoming` : "",
@@ -52,6 +79,7 @@ export function BranchWidget() {
(branch.upstream
? `Git branch: ${headLabel(branch)}${op}\nTracking ${branch.upstream}`
: `Git branch: ${headLabel(branch)}${op}`) +
(count > 1 && !repo ? `\nIn all ${count} repositories` : "") +
(sync.length ? `\n${sync.join(", ")} commits` : "");
return (
<>
@@ -92,6 +120,12 @@ const POPUP_ACTIONS: PopupAction[] = [
{ id: "vcs.checkoutRevision", label: "Checkout Tag or Revision…", icon: "branch" },
];
/** A single repository's own entries (its submenu in the popup with several repositories). */
const REPO_ACTIONS: PopupAction[] = [
{ id: "vcs.newBranch", label: "New Branch…", icon: "plus" },
{ id: "vcs.checkoutRevision", label: "Checkout Tag or Revision…", icon: "branch" },
];
/** Entries IDEA puts at the top of the Branches popup while an operation is stopped. */
export function operationActions(op: InProgress | null, conflicts: number): PopupAction[] {
if (!op) return [];
@@ -118,42 +152,105 @@ export function operationActions(op: InProgress | null, conflicts: number): Popu
return out;
}
const NO_BRANCHES: readonly Branch[] = [];
const INDENT = 16;
const ROW_HEIGHT = 24;
const SEPARATOR_HEIGHT = 9;
const listHeight = (rows: readonly { type: string; key: string }[]) =>
Math.min(
440,
Math.max(
ROW_HEIGHT * 3,
rows.reduce(
(h, r) => h + (r.type === "section" && r.key.startsWith("separator:") ? SEPARATOR_HEIGHT : ROW_HEIGHT),
0,
),
),
);
/** The option element of the row with `key`, to anchor a submenu on. */
function rowElement(list: HTMLElement | null, key: string): HTMLElement | null {
const el = list?.querySelector<HTMLElement>(`[data-row-key="${CSS.escape(key)}"]`);
return el ? ((el.closest('[role="option"]') as HTMLElement | null) ?? el) : null;
}
/** Caret at the end (→ opens) / start (← closes) of the search field. */
const caretAt = (e: KeyboardEvent, where: "start" | "end") => {
const input = e.target as HTMLInputElement;
if (input.selectionStart !== input.selectionEnd) return false;
return where === "end" ? input.selectionStart === input.value.length : input.selectionStart === 0;
};
function BranchesPopup({ anchor, onClose }: { anchor: RefObject<HTMLElement | null>; onClose: () => void }) {
const branches = useVcs((s) => s.branches);
const loaded = useVcs((s) => s.branchesLoaded);
const current = useVcs((s) => s.branch?.head ?? null);
const multi = useVcs((s) => s.roots.length > 1);
return (
<Popup
open
anchor={anchor}
onClose={onClose}
placement="bottom-start"
aria-label="Git Branches"
className={clsx(styles.popup, multi && styles.wide)}
>
{multi ? <MultiRepoPanel onClose={onClose} /> : <BranchesPanel onClose={onClose} actions={POPUP_ACTIONS} />}
</Popup>
);
}
interface BranchesPanelProps {
onClose: () => void;
actions: readonly PopupAction[];
/** A repository other than the selected one (the submenu of a repository): it is selected before acting. */
root?: string;
/** Its branches until the selected repository's are loaded. */
fallback?: readonly Branch[];
/** ← at the start of the search field (back to the repositories). */
onBack?: () => void;
}
/** Search, actions and the branches of one repository (the selected one, or `root`). */
function BranchesPanel({ onClose, actions: baseActions, root, fallback, onBack }: BranchesPanelProps) {
const selected = useVcs((s) => s.repo);
const live = root === undefined || selected === root;
const storeBranches = useVcs((s) => s.branches);
const storeLoaded = useVcs((s) => s.branchesLoaded);
const branches = live && (storeLoaded || !fallback) ? storeBranches : (fallback ?? NO_BRANCHES);
const loaded = (live && storeLoaded) || !!fallback;
const current = useVcs((s) =>
live ? (s.branch?.head ?? null) : root ? (s.heads[root]?.head ?? null) : (s.branch?.head ?? null),
);
const [query, setQuery] = useState("");
const [recent] = useState(recentBranches);
const [active, setActive] = useState(0);
const [menuFor, setMenuFor] = useState<{ items: MenuItem[]; label: string; el: HTMLElement } | null>(null);
const listRef = useRef<HTMLDivElement>(null);
const repo = useVcs((s) => s.repo);
const favorites = useFavoriteBranches((s) => s.names);
const [tags, setTags] = useState<string[]>([]);
useEffect(() => {
void loadBranches().catch(() => undefined);
if (root === undefined) void loadBranches().catch(() => undefined);
loadFavoriteBranches();
}, []);
}, [root]);
useEffect(() => {
let live = true;
call(commands.vcsTags(currentRepo())).then(
call(commands.vcsTags(root ?? currentRepo())).then(
(t) => live && setTags(t),
() => live && setTags([]),
);
return () => {
live = false;
};
}, [repo, branches]);
}, [root, selected, branches]);
const op = useVcs((s) => inProgress(s.branch?.operation));
const op = useVcs((s) => inProgress(root ? s.operations[root] : s.branch?.operation));
const conflicts = useVcs((s) => s.status.filter((f) => f.unstaged === "conflicted").length);
const actions = useMemo(() => [...operationActions(op, conflicts), ...POPUP_ACTIONS], [op, conflicts]);
const actions = useMemo(() => [...operationActions(op, conflicts), ...baseActions], [op, conflicts, baseActions]);
const rows = useMemo(
() => buildBranchRows(branches, recent, query, actions, favorites, tags),
[branches, recent, query, actions, favorites, tags],
);
const isSection = (r: BranchRow) => r.type === "section";
const activeIndex = rows[active] && !isSection(rows[active]!) ? active : firstSelectable(rows, isSection);
const scoped = (items: MenuItem[]) => (root ? inRepo(root, items) : items);
const closeAll = () => {
setMenuFor(null);
@@ -162,13 +259,12 @@ function BranchesPopup({ anchor, onClose }: { anchor: RefObject<HTMLElement | nu
const openMenu = (i: number) => {
const row = rows[i];
if (row?.type !== "branch" && row?.type !== "tag") return;
const el = listRef.current?.querySelector<HTMLElement>(`[data-row-key="${CSS.escape(row.key)}"]`);
const el = rowElement(listRef.current, row.key);
if (!el) return;
const anchorEl = (el.closest('[role="option"]') as HTMLElement | null) ?? el;
setMenuFor(
row.type === "branch"
? { items: branchMenu(row.branch, current, closeAll), label: `Branch ${row.branch.name}`, el: anchorEl }
: { items: tagMenu(row.tag, closeAll), label: `Tag ${row.tag}`, el: anchorEl },
? { items: scoped(branchMenu(row.branch, current, closeAll)), label: `Branch ${row.branch.name}`, el }
: { items: scoped(tagMenu(row.tag, closeAll)), label: `Tag ${row.tag}`, el },
);
};
@@ -177,7 +273,8 @@ function BranchesPopup({ anchor, onClose }: { anchor: RefObject<HTMLElement | nu
if (!row) return;
if (row.type === "action") {
onClose();
void executeAction(row.action.id, row.action.arg);
const { id, arg } = row.action;
void (root ? focusRepo(root) : Promise.resolve()).then(() => executeAction(id, arg));
} else if (row.type === "branch" || row.type === "tag") {
openMenu(i);
}
@@ -191,13 +288,17 @@ function BranchesPopup({ anchor, onClose }: { anchor: RefObject<HTMLElement | nu
}
const type = rows[activeIndex]?.type;
if (e.key === "ArrowRight" && (type === "branch" || type === "tag")) {
const input = e.target as HTMLInputElement;
if (input.selectionStart === input.value.length) {
if (caretAt(e, "end")) {
e.preventDefault();
openMenu(activeIndex);
}
return;
}
if (e.key === "ArrowLeft" && onBack && caretAt(e, "start")) {
e.preventDefault();
onBack();
return;
}
const next = listNavigate(e.key, { items: rows, active: activeIndex, isSection, wrap: true });
if (next !== null) {
e.preventDefault();
@@ -205,35 +306,26 @@ function BranchesPopup({ anchor, onClose }: { anchor: RefObject<HTMLElement | nu
}
};
const rowHeight = 24;
const height = Math.min(440, Math.max(rowHeight * 3, rows.length * rowHeight));
const label = root ? `Search branches of ${repoName(root)}` : "Search branches and actions";
return (
<Popup
open
anchor={anchor}
onClose={onClose}
placement="bottom-start"
aria-label="Git Branches"
className={styles.popup}
>
<RepositoryBar />
<>
<div className={styles.search}>
<SearchField
className={root ? styles.searchGrow : undefined}
data-autofocus
value={query}
onChange={(v) => {
setQuery(v);
setActive(0);
}}
placeholder="Search branches and actions"
aria-label="Search branches and actions"
placeholder={label}
aria-label={label}
variant="bare"
onKeyDown={onKeyDown}
/>
<IconButton icon="git-fetch" title="Fetch" size="small" action="vcs.fetch" />
{!root && <IconButton icon="git-fetch" title="Fetch" size="small" action="vcs.fetch" />}
</div>
<div ref={listRef} style={{ height }} className={styles.listWrap}>
<div ref={listRef} style={{ height: listHeight(rows) }} className={styles.listWrap}>
<List
items={rows}
getKey={(r) => r.key}
@@ -244,60 +336,371 @@ function BranchesPopup({ anchor, onClose }: { anchor: RefObject<HTMLElement | nu
onActivate={(_r, i) => activate(i)}
focusable={false}
hoverSelects
rowHeight={rowHeight}
rowHeight={ROW_HEIGHT}
aria-label="Branches"
className={styles.list}
empty={<span className={styles.empty}>{loaded ? "No matching branches" : "Loading…"}</span>}
renderItem={(r) => <BranchRowView row={r} />}
/>
</div>
{menuFor && (
<Popup
open
anchor={menuFor.el}
placement="right-start"
offset={2}
role="presentation"
autoFocus={false}
onClose={() => setMenuFor(null)}
className={styles.menuPopup}
>
<MenuList
items={menuFor.items}
onDone={() => setMenuFor(null)}
onCloseLevel={() => setMenuFor(null)}
aria-label={menuFor.label}
/>
</Popup>
)}
{menuFor && <SubMenu {...menuFor} onClose={() => setMenuFor(null)} />}
</>
);
}
function SubMenu({
items,
label,
el,
onClose,
}: {
items: MenuItem[];
label: string;
el: HTMLElement;
onClose: () => void;
}) {
return (
<Popup
open
anchor={el}
placement="right-start"
offset={2}
role="presentation"
autoFocus={false}
onClose={onClose}
className={styles.menuPopup}
>
<MenuList items={items} onDone={onClose} onCloseLevel={onClose} aria-label={label} />
</Popup>
);
}
/** Repository switcher (several repositories): branches, log and push act on the selected one. */
function RepositoryBar() {
const EXPANDED_KEY = "openidea.vcs.branchesPopup.expanded";
function loadExpanded(): Set<string> {
try {
const v: unknown = JSON.parse(localStorage.getItem(EXPANDED_KEY) ?? "null");
if (Array.isArray(v)) return new Set(v.filter((x): x is string => typeof x === "string"));
} catch {
// Storage unavailable: defaults.
}
return new Set(DEFAULT_EXPANDED);
}
function saveExpanded(expanded: ReadonlySet<string>) {
try {
localStorage.setItem(EXPANDED_KEY, JSON.stringify([...expanded]));
} catch {
// Expansion is remembered for the session only.
}
}
/**
* Branches popup of a project with several repositories: actions; the repositories,
* each opening its own branches (on hover or →); then the branches they all have
* (acting on all of them) or, when their branches differ, the current repository's.
*/
function MultiRepoPanel({ onClose }: { onClose: () => void }) {
const roots = useVcs((s) => s.roots);
const repo = useVcs((s) => s.repo);
if (roots.length < 2) return null;
const heads = useVcs((s) => s.heads);
const operations = useVcs((s) => s.operations);
const version = useVcs((s) => s.version);
const favorites = useFavoriteBranches((s) => s.names);
const current = useCurrentRepo();
const [recent] = useState(recentBranches);
const [tags, setTags] = useState<string[]>([]);
const [query, setQuery] = useState("");
const [active, setActive] = useState(0);
const [expanded, setExpanded] = useState<ReadonlySet<string>>(loadExpanded);
const [all, setAll] = useState<Record<string, Branch[]>>({});
const [menuFor, setMenuFor] = useState<{ items: MenuItem[]; label: string; el: HTMLElement } | null>(null);
const [repoMenu, setRepoMenu] = useState<{ root: string; el: HTMLElement; focus: boolean } | null>(null);
const listRef = useRef<HTMLDivElement>(null);
const searchRef = useRef<HTMLInputElement>(null);
/** Back from a repository's submenu to the search field. */
const closeRepoMenu = () => {
setRepoMenu(null);
searchRef.current?.focus();
};
useEffect(() => loadFavoriteBranches(), []);
// Every repository's branches (common ones, submenus, search); refreshed after operations.
useEffect(() => {
let live = true;
void Promise.all(
roots.map((r) =>
call(commands.vcsBranches(r)).then(
(list) => [r, list] as const,
() => [r, [] as Branch[]] as const,
),
),
).then((entries) => live && setAll(Object.fromEntries(entries)));
return () => {
live = false;
};
}, [roots, version]);
useEffect(() => {
let live = true;
if (current)
call(commands.vcsTags(current)).then(
(t) => live && setTags(t),
() => live && setTags([]),
);
return () => {
live = false;
};
}, [current, version]);
const repos = useMemo<RepoEntry[]>(
() =>
roots.map((root) => ({
root,
name: repoName(root),
head: heads[root]?.head ?? null,
headCommit: heads[root]?.headCommit ?? null,
})),
[roots, heads],
);
const op = useVcs((s) => inProgress(s.branch?.operation));
const conflicts = useVcs((s) => s.status.filter((f) => f.unstaged === "conflicted").length);
const actions = useMemo(
() => [
...operationActions(op, conflicts),
...POPUP_ACTIONS.map((a) => (a.id === "vcs.newBranch" ? { ...a, arg: { repos: roots } } : a)),
],
[op, conflicts, roots],
);
const rows = useMemo(
() => buildMultiRepoRows({ repos, branches: all, query, actions, expanded, favorites, current, recent, tags }),
[repos, all, query, actions, expanded, favorites, current, recent, tags],
);
const isSection = (r: RepoRow) => r.type === "section";
const activeIndex = rows[active] && !isSection(rows[active]!) ? active : firstSelectable(rows, isSection);
const closeAll = () => {
setMenuFor(null);
setRepoMenu(null);
onClose();
};
/** Opens the submenu of row `i`; `focus` moves the keyboard into a repository's submenu. */
const openSub = (i: number, focus: boolean) => {
const row = rows[i];
if (!row) return;
const el = rowElement(listRef.current, row.key);
if (!el) return;
if (row.type === "repo") {
setMenuFor(null);
setRepoMenu((prev) =>
prev?.root === row.repo.root && prev.el === el && prev.focus === focus
? prev
: { root: row.repo.root, el, focus },
);
return;
}
setRepoMenu(null);
if (row.type === "common") {
setMenuFor({ items: commonBranchMenu(row.branch, roots, closeAll), label: `Branch ${row.branch.name}`, el });
} else if (row.type === "branch") {
const items = inRepo(row.repo.root, branchMenu(row.branch, row.repo.head, closeAll));
setMenuFor({ items, label: `Branch ${row.branch.name} of ${row.repo.name}`, el });
} else if (row.type === "tag") {
setMenuFor({ items: inRepo(row.repo.root, tagMenu(row.tag, closeAll)), label: `Tag ${row.tag}`, el });
}
};
const setOpen = (key: string, open: boolean) =>
setExpanded((prev) => {
if (prev.has(key) === open) return prev;
const next = toggleExpanded(prev, key);
saveExpanded(next);
return next;
});
const activate = (i: number) => {
const row = rows[i];
if (!row) return;
if (row.type === "action") {
onClose();
void executeAction(row.action.id, row.action.arg);
} else if (row.type === "group") {
if (!query.trim()) setOpen(row.key, !row.expanded);
} else {
openSub(i, true);
}
};
// The pointer on a repository opens its branches right away; elsewhere it closes them.
const hover = (i: number) => {
setActive(i);
if (rows[i]?.type === "repo") openSub(i, false);
else setRepoMenu(null);
};
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === "Enter") {
e.preventDefault();
activate(activeIndex);
return;
}
const row = rows[activeIndex];
if (e.key === "ArrowRight" && row && row.type !== "action" && row.type !== "section") {
if (!caretAt(e, "end")) return;
e.preventDefault();
if (row.type === "group") {
if (!query.trim()) setOpen(row.key, true);
} else openSub(activeIndex, true);
return;
}
if (e.key === "ArrowLeft" && row?.type === "group" && row.expanded) {
if (!caretAt(e, "start") || query.trim()) return;
e.preventDefault();
setOpen(row.key, false);
return;
}
const next = listNavigate(e.key, { items: rows, active: activeIndex, isSection, wrap: true });
if (next !== null) {
e.preventDefault();
setActive(next);
}
};
return (
<div className={styles.repos} role="group" aria-label="Repository">
{roots.map((r) => (
<button
key={r}
type="button"
className={clsx(styles.repoButton, r === repo && styles.repoSelected)}
aria-pressed={r === repo}
title={r}
onClick={() => void selectRepo(r).then(() => loadBranches().catch(() => undefined))}
<>
<div className={styles.search}>
<SearchField
ref={searchRef}
className={styles.searchGrow}
data-autofocus
value={query}
onChange={(v) => {
setQuery(v);
setActive(0);
}}
placeholder="Search for branches, actions, repositories"
aria-label="Search for branches, actions, repositories"
variant="bare"
onKeyDown={onKeyDown}
/>
<IconButton icon="git-fetch" title="Fetch" size="small" action="vcs.fetch" />
<IconButton
icon="settings"
title="Git Settings"
size="small"
onClick={() => {
closeAll();
void executeAction("file.settings", "vcs.git");
}}
/>
</div>
<div ref={listRef} style={{ height: listHeight(rows) }} className={styles.listWrap}>
<List
items={rows}
getKey={(r) => r.key}
isSection={isSection}
sectionHeightOf={(r) => (r.type === "section" && !r.label ? SEPARATOR_HEIGHT : undefined)}
renderSection={(r) =>
r.type === "section" && r.label ? (
<span className={styles.section}>{r.label}</span>
) : (
<span className={styles.separator} role="separator" />
)
}
activeIndex={activeIndex}
onActiveChange={hover}
onActivate={(_r, i) => activate(i)}
focusable={false}
hoverSelects
rowHeight={ROW_HEIGHT}
aria-label="Repositories and branches"
className={styles.list}
empty={<span className={styles.empty}>No matching repositories or branches</span>}
renderItem={(r) => (
<RepoRowView row={r} operation={r.type === "repo" ? operations[r.repo.root] : undefined} />
)}
/>
</div>
{menuFor && <SubMenu {...menuFor} onClose={() => setMenuFor(null)} />}
{repoMenu && (
<Popup
open
anchor={repoMenu.el}
placement="right-start"
offset={2}
autoFocus={repoMenu.focus}
aria-label={`Branches of ${repoName(repoMenu.root)}`}
onClose={closeRepoMenu}
className={styles.popup}
>
{repoName(r)}
</button>
))}
</div>
<BranchesPanel
key={repoMenu.root}
root={repoMenu.root}
fallback={all[repoMenu.root]}
actions={REPO_ACTIONS}
onClose={closeAll}
onBack={closeRepoMenu}
/>
</Popup>
)}
</>
);
}
function BranchRowView({ row }: { row: BranchRow }) {
function RepoRowView({ row, operation }: { row: RepoRow; operation?: string }) {
switch (row.type) {
case "action":
case "branch":
case "tag":
return <BranchRowView row={row} />;
case "repo":
return (
<span className={styles.row} data-row-key={row.key}>
<span
className={styles.repoColor}
style={{ background: `var(--project-color-${row.color})` }}
aria-hidden="true"
/>
<HighlightedText className={styles.label} text={row.repo.name} indices={row.matches} tone="accent" />
{operation && <span className={styles.operation}>{operation}</span>}
<span className={styles.repoHead}>{repoHeadLabel(row.repo)}</span>
<Icon name="chevron-right" size={10} className={styles.subChevron} />
</span>
);
case "group":
return (
<span
className={clsx(styles.row, row.depth === 0 && styles.groupRow)}
data-row-key={row.key}
style={row.depth ? { paddingLeft: row.depth * INDENT } : undefined}
aria-expanded={row.expanded}
>
<Icon name={row.expanded ? "chevron-down" : "chevron-right"} size={12} className={styles.rowIcon} />
{row.depth > 0 && <Icon name="folder" size={14} className={styles.rowIcon} />}
<span className={styles.label}>{row.label}</span>
</span>
);
case "common":
return (
<span className={styles.row} data-row-key={row.key} style={{ paddingLeft: row.depth * INDENT }}>
<Icon
name={row.branch.current ? "current-branch" : row.branch.favorite ? "star" : "branch"}
size={14}
className={clsx(styles.rowIcon, row.branch.current && styles.currentIcon)}
/>
<HighlightedText
className={clsx(styles.label, styles.branchName, row.branch.current && styles.current)}
text={row.label}
indices={row.matches}
tone="accent"
/>
{row.branch.current && <span className={styles.tag}>current</span>}
<Icon name="chevron-right" size={10} className={styles.chevron} />
</span>
);
default:
return null;
}
}
function BranchRowView({ row }: { row: BranchRow | Extract<RepoRow, { type: "action" | "branch" | "tag" }> }) {
const indent = "depth" in row && row.depth ? { paddingLeft: row.depth * INDENT } : undefined;
if (row.type === "action") {
const keys = shortcutLabel(row.action.id);
return (
@@ -310,7 +713,7 @@ function BranchRowView({ row }: { row: BranchRow }) {
}
if (row.type === "tag") {
return (
<span className={styles.row} data-row-key={row.key}>
<span className={styles.row} data-row-key={row.key} style={indent}>
<Icon name="tag" size={14} className={styles.rowIcon} />
<HighlightedText
className={clsx(styles.label, styles.branchName)}
@@ -325,7 +728,7 @@ function BranchRowView({ row }: { row: BranchRow }) {
if (row.type !== "branch") return null;
const b = row.branch;
return (
<span className={styles.row} data-row-key={row.key}>
<span className={styles.row} data-row-key={row.key} style={indent}>
{b.current ? (
<Icon name="current-branch" size={14} className={clsx(styles.rowIcon, styles.currentIcon)} />
) : (
+270
Переглянути файл
@@ -0,0 +1,270 @@
import { describe, expect, it } from "vitest";
import type { Branch } from "@/bindings";
import {
buildMultiRepoRows,
commonBranches,
currentRepoFor,
DEFAULT_EXPANDED,
repoColorIndex,
repoHeadLabel,
toggleExpanded,
widgetShowsRepo,
type RepoEntry,
type RepoRow,
} from "../repoBranches";
const b = (name: string, opts: Partial<Branch> = {}): Branch => ({
name,
remote: name.startsWith("origin/") || name.startsWith("upstream/"),
current: false,
upstream: null,
ahead: 0,
behind: 0,
lastCommitMs: 0,
commit: "",
...opts,
});
const repo = (name: string, head: string | null = "dev"): RepoEntry => ({
root: `/p/${name}`,
name,
head,
headCommit: "0123456789abcdef",
});
// The reported layout: several repositories, all on `dev`.
const repos = [repo("ology-collect"), repo("ology-dependencies"), repo("ology-gateway")];
const branches: Record<string, Branch[]> = {
"/p/ology-collect": [
b("dev", { current: true }),
b("main"),
b("collect-only"),
b("origin/HEAD"),
b("origin/dev"),
b("origin/main"),
b("origin/feature/x"),
],
"/p/ology-dependencies": [b("dev", { current: true }), b("main"), b("origin/dev"), b("origin/main")],
"/p/ology-gateway": [b("dev", { current: true }), b("main"), b("origin/dev"), b("origin/main"), b("gw-fix")],
};
const actions = [
{ id: "vcs.update", label: "Update Project…" },
{ id: "vcs.newBranch", label: "New Branch…" },
];
const summary = (rows: RepoRow[]) =>
rows.map((r) => {
switch (r.type) {
case "section":
return r.label ? `# ${r.label}` : "---";
case "action":
return `> ${r.action.label}`;
case "repo":
return `repo ${r.repo.name} [${r.repo.head}] c${r.color}`;
case "group":
return `${" ".repeat(r.depth)}${r.expanded ? "v" : ">"} ${r.label}`;
case "common":
return `${" ".repeat(r.depth)}${r.label}${r.branch.current ? " (current)" : ""}`;
case "branch":
return `${" ".repeat(r.depth)}${r.repo.name}:${r.branch.name}`;
case "tag":
return `${" ".repeat(r.depth)}tag ${r.tag}`;
}
});
describe("currentRepoFor (shared by the widget and the popup)", () => {
const roots = ["/p", "/p/ology-collect", "/p/ology-collect/sub", "/p/ology-gateway"];
it.each([
[
"the innermost repository of the active file",
"/p/ology-collect/src/A.java",
"/p/ology-gateway",
"/p/ology-collect",
],
["a nested repository's file", "/p/ology-collect/sub/x.ts", null, "/p/ology-collect/sub"],
["the project's own repository", "/p/README.md", "/p/ology-gateway", "/p"],
["no active file: the selected repository", null, "/p/ology-gateway", "/p/ology-gateway"],
["a file outside every repository: the selected one", "/elsewhere/a.txt", "/p/ology-gateway", "/p/ology-gateway"],
["a selected repository that is gone: the first", null, "/gone", "/p"],
["nothing selected: the first", null, null, "/p"],
])("%s", (_name, active, selected, expected) => {
expect(currentRepoFor(active, roots, selected)).toBe(expected);
});
it("is null without repositories", () => {
expect(currentRepoFor("/p/a", [], null)).toBeNull();
});
});
describe("widgetShowsRepo", () => {
it.each([
["one repository", [{ head: "main" }], false],
["all on the same branch", [{ head: "dev" }, { head: "dev" }, { head: "dev" }], false],
["one on another branch", [{ head: "dev" }, { head: "feature" }, { head: "dev" }], true],
["one detached", [{ head: "dev" }, { head: null }], true],
["all detached", [{ head: null }, { head: null }], true],
["no repositories", [], false],
])("%s", (_name, heads, shows) => {
expect(widgetShowsRepo(heads)).toBe(shows);
});
});
describe("commonBranches", () => {
it("keeps the branches every repository has, current in all first, then favourites", () => {
const common = commonBranches(Object.values(branches));
expect(common.local.map((x) => [x.name, x.current, x.favorite])).toEqual([
["dev", true, false],
["main", false, true],
]);
expect(common.remote.map((x) => x.name)).toEqual(["origin/main", "origin/dev"]);
});
it("is current only when checked out everywhere", () => {
const common = commonBranches([[b("dev", { current: true })], [b("dev")]]);
expect(common.local).toEqual([{ name: "dev", remote: false, current: false, favorite: false }]);
});
it("does not match a local branch with a remote one of the same name", () => {
expect(commonBranches([[b("origin/x", { remote: false })], [b("origin/x")]])).toEqual({ local: [], remote: [] });
expect(commonBranches([])).toEqual({ local: [], remote: [] });
});
});
describe("buildMultiRepoRows", () => {
const input = { repos, branches, actions, expanded: new Set(DEFAULT_EXPANDED) };
it("lists actions, repositories with their branch, then the common groups", () => {
expect(summary(buildMultiRepoRows({ ...input, query: "" }))).toEqual([
"> Update Project…",
"> New Branch…",
"---",
"repo ology-collect [dev] c1",
"repo ology-dependencies [dev] c2",
"repo ology-gateway [dev] c3",
"---",
"v Common Local Branches",
" dev (current)",
" main",
"> Common Remote Branches",
]);
});
it("groups common remote branches by remote when expanded", () => {
const expanded = toggleExpanded(toggleExpanded(new Set(), "common:remote"), "common:folder:origin");
expect(summary(buildMultiRepoRows({ ...input, expanded, query: "" })).slice(-6)).toEqual([
"---",
"> Common Local Branches",
"v Common Remote Branches",
" v origin",
" main",
" dev",
]);
});
it("filters repositories and branches, expands every group and lists each repository's own matches", () => {
expect(summary(buildMultiRepoRows({ ...input, expanded: new Set(), query: "dev" }))).toEqual([
"v Common Local Branches",
" dev (current)",
"v Common Remote Branches",
" v origin",
" dev",
]);
expect(summary(buildMultiRepoRows({ ...input, query: "deps" }))).toEqual(["repo ology-dependencies [dev] c2"]);
expect(summary(buildMultiRepoRows({ ...input, query: "fix" }))).toEqual([
"# ology-gateway",
"ology-gateway:gw-fix",
]);
expect(summary(buildMultiRepoRows({ ...input, query: "collect" }))).toEqual([
"repo ology-collect [dev] c1",
"# ology-collect",
"ology-collect:collect-only",
]);
});
it("highlights the shown part of a remote branch name", () => {
const rows = buildMultiRepoRows({ ...input, query: "origin/dev" });
const dev = rows.find((r) => r.type === "common" && r.branch.name === "origin/dev");
expect(dev?.type === "common" && [dev.label, dev.matches]).toEqual(["dev", [0, 1, 2]]);
});
it("shows no common branches until every repository's branches are loaded", () => {
const partial = { "/p/ology-collect": branches["/p/ology-collect"]! };
expect(summary(buildMultiRepoRows({ ...input, branches: partial, query: "" })).at(-1)).toBe(
"repo ology-gateway [dev] c3",
);
});
});
describe("buildMultiRepoRows with repositories on different branches", () => {
const diverged = [repo("ology-collect", "release/1.0"), repo("ology-dependencies"), repo("ology-gateway")];
const own: Record<string, Branch[]> = {
...branches,
"/p/ology-collect": [
b("release/1.0", { current: true }),
b("dev"),
b("main"),
b("origin/dev"),
b("origin/release/1.0"),
],
};
const input = {
repos: diverged,
branches: own,
actions: [],
expanded: new Set(DEFAULT_EXPANDED),
recent: ["dev", "release/1.0", "gone"],
tags: ["v1.2", "v1.10"],
};
it("lists the current repository's recent, local, remote branches and tags instead of the common ones", () => {
expect(summary(buildMultiRepoRows({ ...input, current: "/p/ology-collect", query: "" }))).toEqual([
"repo ology-collect [release/1.0] c1",
"repo ology-dependencies [dev] c2",
"repo ology-gateway [dev] c3",
"---",
"> Recent Branches in ology-collect",
"v Local Branches in ology-collect",
" ology-collect:release/1.0",
" ology-collect:main",
" ology-collect:dev",
"> Remote Branches in ology-collect",
"> Tags in ology-collect",
]);
});
it("falls back to the first repository and expands the matching lists on search", () => {
const expanded = new Set(["repo:tags", "repo:recent"]);
const rows = summary(buildMultiRepoRows({ ...input, expanded, current: "/elsewhere", query: "" }));
expect(rows.slice(4)).toEqual([
"v Recent Branches in ology-collect",
" ology-collect:dev",
"> Local Branches in ology-collect",
"> Remote Branches in ology-collect",
"v Tags in ology-collect",
" tag v1.10",
" tag v1.2",
]);
// Search: the current repository's lists, then the other repositories' branches.
expect(summary(buildMultiRepoRows({ ...input, current: "/p/ology-gateway", query: "fix" }))).toEqual([
"v Local Branches in ology-gateway",
" ology-gateway:gw-fix",
]);
expect(summary(buildMultiRepoRows({ ...input, current: "/p/ology-gateway", query: "rel" }))).toEqual([
"# ology-collect",
"ology-collect:release/1.0",
"ology-collect:origin/release/1.0",
]);
});
});
describe("repository colours and heads", () => {
it("gives up to nine repositories distinct colours, then cycles", () => {
expect(Array.from({ length: 10 }, (_, i) => repoColorIndex(i))).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 1]);
});
it("names a detached HEAD by its short commit", () => {
expect(repoHeadLabel({ head: "dev", headCommit: "0123456789" })).toBe("dev");
expect(repoHeadLabel({ head: null, headCommit: "0123456789" })).toBe("01234567");
expect(repoHeadLabel({ head: null, headCommit: null })).toBe("No commits");
});
});
+6 -2
Переглянути файл
@@ -6,7 +6,7 @@ import { Menu, type MenuItem } from "@/ui";
import { editorService, maybeEditorService, notifications, toolWindowService } from "@/workbench/contributions";
import { annotationsShown, toggleAnnotations } from "./blame";
import { showBranchesPopup } from "./BranchWidget";
import { checkoutRevision, newBranch } from "./branchOps";
import { checkoutRevision, newBranch, newBranchInRepos } from "./branchOps";
import {
addToVcs,
commitChanges,
@@ -401,7 +401,11 @@ export function registerVcsActions(): () => void {
category: "Git",
icon: "plus",
when: VCS,
run: () => void newBranch(),
// `{ repos }` (Branches popup with several repositories): in each of them.
run: ({ arg }) => {
const repos = (arg as { repos?: unknown } | undefined)?.repos;
void (Array.isArray(repos) && repos.length ? newBranchInRepos(repos as string[]) : newBranch());
},
},
{
id: "vcs.checkoutRevision",
+60
Переглянути файл
@@ -7,8 +7,13 @@ import {
checkoutAndRebase,
checkoutBranch,
checkoutDetached,
checkoutInRepos,
deleteBranch,
deleteInRepos,
deleteRemoteBranch,
mergeInRepos,
newBranchInRepos,
rebaseInRepos,
loadFavoriteBranches,
mergeIntoCurrent,
newBranch,
@@ -20,6 +25,8 @@ import {
} from "./branchOps";
import { showCompareBranches } from "./CompareBranches";
import { showDiffWithWorkingTree } from "./operations";
import type { CommonBranch } from "./repoBranches";
import { focusRepo } from "./store";
export function branchMenu(b: Branch, current: string | null, done: () => void = () => {}): MenuItem[] {
const run = (fn: () => unknown) => () => {
@@ -98,3 +105,56 @@ export function tagMenu(tag: string, done: () => void = () => {}): MenuItem[] {
{ label: "Show History", icon: "history", run: run(() => executeAction("vcs.showLog", { branch: tag })) },
];
}
/** Entries for a branch common to all repositories: each acts in every one of `roots`. */
export function commonBranchMenu(b: CommonBranch, roots: readonly string[], done: () => void = () => {}): MenuItem[] {
const run = (fn: () => unknown) => () => {
done();
void fn();
};
const newFrom: MenuItem = {
label: `New Branch from '${b.name}'…`,
icon: "branch",
run: run(() => newBranchInRepos(roots, b.name)),
};
if (b.current)
return [
newFrom,
{ kind: "separator" },
{ label: "Update", icon: "git-pull", run: run(() => executeAction("vcs.update")) },
{ label: "Push…", icon: "git-push", run: run(() => executeAction("vcs.push")) },
];
const items: MenuItem[] = [
{ label: "Checkout", run: run(() => checkoutInRepos(b.name, roots)) },
newFrom,
{ kind: "separator" },
{ label: `Rebase Current onto '${b.name}'`, run: run(() => rebaseInRepos(b.name, roots)) },
{ label: `Merge '${b.name}' into Current`, run: run(() => mergeInRepos(b.name, roots)) },
];
if (!b.remote)
items.push(
{ kind: "separator" },
{ label: "Delete", danger: true, icon: "trash", run: run(() => deleteInRepos(b.name, roots)) },
);
return items;
}
/** `items` acting on repository `root`: it is selected (with its branches loaded) before each entry runs. */
export function inRepo(root: string, items: MenuItem[]): MenuItem[] {
return items.map((item): MenuItem => {
if (item.kind === "separator" || item.kind === "header") return item;
if (item.kind === "action")
return {
label: item.label ?? item.action,
icon: item.icon,
disabled: item.disabled,
run: () => void focusRepo(root).then(() => executeAction(item.action, item.arg)),
};
const run = item.run;
return {
...item,
run: run && (() => void focusRepo(root).then(run)),
submenu: item.submenu && inRepo(root, item.submenu),
};
});
}
+118 -5
Переглянути файл
@@ -9,7 +9,7 @@ import { isFavoriteBranch, pushRecent, shortRemoteName } from "./branches";
import { showCommitRange } from "./CompareBranches";
import { confirmDialog, promptText } from "./dialogs";
import { runOp, runRemote, saveAll } from "./ops";
import { conflictedFiles, currentRepo, refreshNow, useVcs } from "./store";
import { conflictedFiles, currentRepo, refreshNow, repoName, useVcs } from "./store";
const recentKey = () => `openidea.vcs.recentBranches:${useVcs.getState().root ?? ""}`;
@@ -68,18 +68,23 @@ async function askSmartCheckout(files: readonly string[]): Promise<CheckoutOptio
* to rebase that branch onto the remote or drop its commits (one that is only behind is
* fast-forwarded). Resolves true once switched.
*/
async function performCheckout(rev: string, success: () => string): Promise<boolean> {
async function performCheckout(
rev: string,
success: () => string,
repo: string | null = currentRepo(),
quiet = false,
): Promise<boolean> {
await saveAll();
let options: CheckoutOptions = { mode: "normal", diverged: null };
for (;;) {
const opts = options;
const outcome = await runOp(`Checkout ${rev}`, () => call(commands.vcsCheckout(currentRepo(), rev, false, opts)));
const outcome = await runOp(`Checkout ${rev}`, () => call(commands.vcsCheckout(repo, rev, false, opts)));
if (!outcome) return false;
// `success` may name the branch now checked out.
if (outcome.kind === "done" || outcome.kind === "conflicts") await refreshNow();
switch (outcome.kind) {
case "done":
notifications().notify({ group: "vcs", level: "info", title: success() });
if (!quiet) notifications().notify({ group: "vcs", level: "info", title: success() });
return true;
case "conflicts":
notifications().notify({
@@ -316,6 +321,109 @@ export async function updateBranch(name: string) {
await runRemote({ op: "updateBranch", branch: name }, `${name} ← ${b.upstream}`);
}
// --- several repositories ----------------------------------------------------
/** "in 3 repositories", or "in 2 of 3 repositories" when some were left out. */
function inRepos(done: number, total: number): string {
return done === total ? `in ${total} repositories` : `in ${done} of ${total} repositories`;
}
/**
* Runs `step` in each repository in turn, stopping at the first one that fails (its
* error is reported by `step`), then reports how many repositories it was done in.
*/
async function eachRepo(roots: readonly string[], step: (root: string) => Promise<boolean>, title: string) {
let done = 0;
for (const root of roots) {
if (!(await step(root))) break;
done++;
}
await refreshNow();
if (done) notifications().notify({ group: "vcs", level: "info", title: `${title} ${inRepos(done, roots.length)}` });
}
/** Checks out `name` (local, or remote: its local namesake) in every repository of `roots`. */
export async function checkoutInRepos(name: string, roots: readonly string[]) {
const label = useVcs.getState().branches.some((b) => b.remote && b.name === name) ? shortRemoteName(name) : name;
const previous = useVcs.getState().branch?.head;
await eachRepo(roots, (root) => performCheckout(name, () => "", root, true), `Checked out ${label}`);
rememberBranch(previous);
rememberBranch(useVcs.getState().branch?.head);
}
/** New Branch in every repository of `roots` (from HEAD or `from`), checked out by default. */
export async function newBranchInRepos(roots: readonly string[], from?: string) {
const r = await promptText({
title: from ? `Create New Branch from ${from}` : "Create New Branch",
label: `New branch name (in ${roots.length} repositories):`,
initial: from?.includes("/") ? shortRemoteName(from) : "",
mono: true,
okLabel: "Create",
validate: validateBranchName,
checkbox: { label: "Checkout branch", initial: true },
});
if (!r) return;
const name = r.value.trim();
if (r.checked) await saveAll();
await eachRepo(
roots,
async (root) =>
(await runOp(`Create branch ${name}`, () => call(commands.vcsCreateBranch(root, name, from ?? null, r.checked)), {
refresh: false,
})) !== undefined,
r.checked ? `Created and checked out ${name}` : `Created branch ${name}`,
);
}
/** Merges `branch` into the current branch of every repository of `roots`; stops on conflicts. */
export async function mergeInRepos(branch: string, roots: readonly string[]) {
await saveAll();
await eachRepo(
roots,
async (root) =>
(await runOp(`Merge ${branch} (${repoName(root)})`, () => call(commands.vcsMerge(root, branch)), {
refresh: false,
errorActions: conflictActions,
onError: openConflictsInstead,
})) !== undefined,
`Merged ${branch}`,
);
}
/** Rebases the current branch of every repository of `roots` onto `branch`; stops on conflicts. */
export async function rebaseInRepos(branch: string, roots: readonly string[]) {
await saveAll();
await eachRepo(
roots,
async (root) =>
(await runOp(`Rebase onto ${branch} (${repoName(root)})`, () => call(commands.vcsRebase(root, branch)), {
refresh: false,
errorActions: conflictActions,
onError: openConflictsInstead,
})) !== undefined,
`Rebased onto ${branch}`,
);
}
/** Deletes local branch `name` in every repository of `roots`. */
export async function deleteInRepos(name: string, roots: readonly string[]) {
const ok = await confirmDialog({
title: "Delete Branch",
message: `Delete branch '${name}' in ${roots.length} repositories? Unmerged commits are discarded.`,
okLabel: "Delete",
danger: true,
});
if (!ok) return;
await eachRepo(
roots,
async (root) =>
(await runOp(`Delete branch ${name} (${repoName(root)})`, () => call(commands.vcsDeleteBranch(root, name)), {
refresh: false,
})) !== undefined,
`Deleted branch ${name}`,
);
}
// --- favorites ---------------------------------------------------------------
const favoritesKey = () => `openidea.vcs.favoriteBranches:${useVcs.getState().root ?? ""}`;
@@ -341,7 +449,12 @@ export function toggleFavoriteBranch(b: Branch) {
loadFavoriteBranches();
const stored = useFavoriteBranches.getState().names;
// First edit: start from the defaults that are currently shown.
const base = stored ?? useVcs.getState().branches.filter((x) => isFavoriteBranch(x, null)).map((x) => x.name);
const base =
stored ??
useVcs
.getState()
.branches.filter((x) => isFavoriteBranch(x, null))
.map((x) => x.name);
const names = base.includes(b.name) ? base.filter((n) => n !== b.name) : [...base, b.name];
useFavoriteBranches.setState({ names });
try {
+307
Переглянути файл
@@ -0,0 +1,307 @@
/** Branches popup model for a project with several repositories (pure). */
import type { Branch } from "@/bindings";
import { fuzzyMatch } from "@/ui/match";
import { rootOf } from "./model";
import { isFavoriteBranch, MAX_RECENT, sortLocal, sortRemote, type PopupAction } from "./branches";
export interface RepoEntry {
root: string;
name: string;
/** Current branch; `null` when HEAD is detached. */
head: string | null;
headCommit: string | null;
}
/** Number of `--project-color-N` tokens repositories are coloured with. */
export const REPO_COLORS = 9;
/** Colour slot (1-based) of the repository at `index`: distinct for up to `REPO_COLORS` repositories. */
export function repoColorIndex(index: number): number {
return (index % REPO_COLORS) + 1;
}
/** Display name of a repository's HEAD: its branch, else the short commit. */
export function repoHeadLabel(r: Pick<RepoEntry, "head" | "headCommit">): string {
if (r.head) return r.head;
return r.headCommit ? r.headCommit.slice(0, 8) : "No commits";
}
/**
* The current repository, shown by the branch widget and the lower part of the Branches
* popup: the one holding the active editor's file, else the selected one, else the first.
*/
export function currentRepoFor(
activePath: string | null,
roots: readonly string[],
selected: string | null,
): string | null {
const ofFile = activePath ? rootOf(activePath, roots) : null;
return ofFile ?? (selected && roots.includes(selected) ? selected : null) ?? roots[0] ?? null;
}
/**
* Whether the branch widget names the repository besides the branch: only with several
* repositories that are not all on the same branch.
*/
export function widgetShowsRepo(repos: readonly Pick<RepoEntry, "head">[]): boolean {
if (repos.length < 2) return false;
const first = repos[0]!.head;
return !first || repos.some((r) => r.head !== first);
}
export interface CommonBranch {
name: string;
remote: boolean;
/** Checked out in every repository. */
current: boolean;
favorite: boolean;
}
/** Branches present in every repository (by name), local and remote, sorted like the single-repository lists. */
export function commonBranches(
branchesByRepo: readonly (readonly Branch[])[],
favorites: readonly string[] | null = null,
): { local: CommonBranch[]; remote: CommonBranch[] } {
if (!branchesByRepo.length) return { local: [], remote: [] };
const pick = (sorted: (list: readonly Branch[]) => Branch[]): CommonBranch[] => {
const [first, ...rest] = branchesByRepo;
const others = rest.map((list) => new Map(list.map((b) => [`${b.remote}:${b.name}`, b])));
return sorted(first!).flatMap((b) => {
const all = others.map((m) => m.get(`${b.remote}:${b.name}`));
if (all.some((x) => !x)) return [];
return [
{
name: b.name,
remote: b.remote,
current: b.current && all.every((x) => x!.current),
favorite: isFavoriteBranch(b, favorites),
},
];
});
};
const byRank = (a: CommonBranch, b: CommonBranch) =>
Number(b.current) - Number(a.current) || Number(b.favorite) - Number(a.favorite);
return {
local: pick((l) => sortLocal(l, favorites)).sort(byRank),
remote: pick((l) => sortRemote(l, favorites)).sort(byRank),
};
}
export type BranchGroupKind = "recent" | "local" | "remote";
export type RepoRow =
/** Section header; an empty label draws a separator. */
| { type: "section"; key: string; label: string }
| { type: "action"; key: string; action: PopupAction; matches: number[] | null }
| { type: "repo"; key: string; repo: RepoEntry; color: number; matches: number[] | null }
/** Collapsible group (common branches, or one of the current repository's lists) or remote folder. */
| { type: "group"; key: string; label: string; expanded: boolean; depth: number }
| {
type: "common";
key: string;
branch: CommonBranch;
/** Shown name: remote branches without their remote (it is the folder). */
label: string;
depth: number;
matches: number[] | null;
}
/** A branch of one repository. */
| {
type: "branch";
key: string;
repo: RepoEntry;
branch: Branch;
group: BranchGroupKind;
depth: number;
matches: number[] | null;
favorite: boolean;
}
| { type: "tag"; key: string; repo: RepoEntry; tag: string; depth: number; matches: number[] | null };
/**
* Initially expanded groups: the common local branches, and the current repository's
* local branches (switching a repository's branch stays one click away).
*/
export const DEFAULT_EXPANDED: readonly string[] = ["common:local", "repo:local"];
export interface MultiRepoInput {
repos: readonly RepoEntry[];
/** Root → its branches (missing while loading). */
branches: Readonly<Record<string, readonly Branch[]>>;
query: string;
actions: readonly PopupAction[];
/** Expanded group / folder keys (`common:local`, `repo:remote`, `common:folder:origin`…). */
expanded: ReadonlySet<string>;
favorites?: readonly string[] | null;
/** The current repository (of the active file), whose lists are shown when the repositories' branches differ. */
current?: string | null;
/** Recently checked-out branches (newest first). */
recent?: readonly string[];
/** Tags of the current repository. */
tags?: readonly string[];
}
/**
* Rows of the Branches popup with several repositories: actions; the repositories,
* each with its current branch and opening its own branches; then, when they are all
* on the same branch, the branches common to all of them (acting on all of them),
* otherwise the current repository's recent, local and remote branches and tags, in
* collapsible groups. A query filters actions, repositories (by name) and branches,
* expands every group, and adds the other repositories' matching branches.
*/
export function buildMultiRepoRows({
repos,
branches,
query,
actions,
expanded,
favorites = null,
current = null,
recent = [],
tags = [],
}: MultiRepoInput): RepoRow[] {
const q = query.trim();
const match = (text: string): number[] | null | false => (q ? (fuzzyMatch(text, q) ?? false) : null);
const open = (key: string) => !!q || expanded.has(key);
const blocks: RepoRow[][] = [];
const actionRows: RepoRow[] = [];
for (const a of actions) {
const m = match(a.label);
if (m !== false) actionRows.push({ type: "action", key: `action:${a.id}`, action: a, matches: m });
}
blocks.push(actionRows);
const repoRows: RepoRow[] = [];
repos.forEach((repo, i) => {
const m = match(repo.name);
if (m !== false)
repoRows.push({ type: "repo", key: `repo:${repo.root}`, repo, color: repoColorIndex(i), matches: m });
});
blocks.push(repoRows);
/** A group row followed (when expanded) by its children; nothing when it has none. */
const group = (out: RepoRow[], key: string, label: string, depth: number, children: RepoRow[]) => {
if (!children.length) return;
const expandedNow = open(key);
out.push({ type: "group", key, label, expanded: expandedNow, depth });
if (expandedNow) out.push(...children);
};
const branchRows = (repo: RepoEntry, list: readonly Branch[], kind: BranchGroupKind, depth: number) =>
list.flatMap((b): RepoRow[] => {
const m = match(b.name);
if (m === false) return [];
const key = `branch:${repo.root}:${kind}:${b.name}`;
return [
{
type: "branch",
key,
repo,
branch: b,
group: kind,
depth,
matches: m,
favorite: isFavoriteBranch(b, favorites),
},
];
});
const shared = !widgetShowsRepo(repos);
const groups: RepoRow[] = [];
let shown = new Set<string>();
const currentRepo = repos.find((r) => r.root === current) ?? repos[0];
if (shared) {
const loaded = repos.every((r) => branches[r.root]);
const common = loaded
? commonBranches(
repos.map((r) => branches[r.root]!),
favorites,
)
: { local: [], remote: [] };
shown = new Set([...common.local, ...common.remote].map((b) => `${b.remote}:${b.name}`));
const local = common.local.flatMap((b): RepoRow[] => {
const m = match(b.name);
return m === false
? []
: [{ type: "common", key: `common:${b.name}`, branch: b, label: b.name, depth: 1, matches: m }];
});
group(groups, "common:local", "Common Local Branches", 0, local);
const byRemote = new Map<string, CommonBranch[]>();
for (const b of common.remote) {
const remote = b.name.slice(0, Math.max(0, b.name.indexOf("/")));
byRemote.set(remote, [...(byRemote.get(remote) ?? []), b]);
}
const remote: RepoRow[] = [];
for (const [name, items] of byRemote) {
const leaves = items.flatMap((b): RepoRow[] => {
const m = match(b.name);
if (m === false) return [];
// Highlights are of the full name: shift them onto the shown part.
const part = m && m.map((i) => i - name.length - 1).filter((i) => i >= 0);
const label = b.name.slice(name.length + 1);
return [{ type: "common", key: `common:${b.name}`, branch: b, label, depth: 2, matches: part }];
});
group(remote, `common:folder:${name}`, name, 1, leaves);
}
group(groups, "common:remote", "Common Remote Branches", 0, remote);
} else if (currentRepo) {
const list = branches[currentRepo.root] ?? [];
const local = sortLocal(list, favorites);
const byName = new Map(local.map((b) => [b.name, b]));
const recentList = q
? []
: recent
.map((n) => byName.get(n))
.filter((b): b is Branch => !!b && !b.current)
.slice(0, MAX_RECENT);
const name = currentRepo.name;
group(groups, "repo:recent", `Recent Branches in ${name}`, 0, branchRows(currentRepo, recentList, "recent", 1));
group(groups, "repo:local", `Local Branches in ${name}`, 0, branchRows(currentRepo, local, "local", 1));
group(
groups,
"repo:remote",
`Remote Branches in ${name}`,
0,
branchRows(currentRepo, sortRemote(list, favorites), "remote", 1),
);
const tagRows = [...tags]
.sort((a, b) => b.localeCompare(a, undefined, { numeric: true }))
.flatMap((t): RepoRow[] => {
const m = match(t);
return m === false
? []
: [{ type: "tag", key: `tag:${currentRepo.root}:${t}`, repo: currentRepo, tag: t, depth: 1, matches: m }];
});
group(groups, "repo:tags", `Tags in ${name}`, 0, tagRows);
}
blocks.push(groups);
if (q) {
for (const repo of repos) {
if (!shared && repo === currentRepo) continue;
const list = branches[repo.root] ?? [];
const own = (l: Branch[]) => l.filter((b) => !shown.has(`${b.remote}:${b.name}`));
const rows = [
...branchRows(repo, own(sortLocal(list, favorites)), "local", 0),
...branchRows(repo, own(sortRemote(list, favorites)), "remote", 0),
];
if (rows.length) blocks.push([{ type: "section", key: `section:${repo.root}`, label: repo.name }, ...rows]);
}
}
const rows: RepoRow[] = [];
for (const block of blocks) {
if (!block.length) continue;
if (rows.length && block[0]!.type !== "section")
rows.push({ type: "section", key: `separator:${rows.length}`, label: "" });
rows.push(...block);
}
return rows;
}
/** Toggles a group / folder key. */
export function toggleExpanded(expanded: ReadonlySet<string>, key: string): Set<string> {
const next = new Set(expanded);
if (!next.delete(key)) next.add(key);
return next;
}
+16 -1
Переглянути файл
@@ -17,6 +17,11 @@ import { useProject } from "@/platform/project";
import { setFileDecorations } from "@/workbench/contributions";
import { effectiveKind, repoLabel, rootOf, statusDecorations, stripSlash } from "./model";
export interface RepoHead {
head: string | null;
headCommit: string | null;
}
export interface VcsState {
/** The open project is a git repository. */
available: boolean;
@@ -25,6 +30,8 @@ export interface VcsState {
roots: string[];
/** Root → merge / rebase / cherry-pick / revert in progress there. */
operations: Record<string, string>;
/** Root → its current branch (`head` null when detached) and HEAD commit. */
heads: Record<string, RepoHead>;
/** The selected repository's root (branch widget, log, push…). */
repo: string | null;
status: FileStatus[];
@@ -50,6 +57,7 @@ const initial: VcsState = {
root: null,
roots: [],
operations: {},
heads: {},
repo: null,
status: [],
statusLoaded: false,
@@ -109,6 +117,12 @@ export function selectRepo(root: string): Promise<void> {
return refreshNow();
}
/** Selects `root` and loads its branches, so branch operations act on it. */
export async function focusRepo(root: string): Promise<void> {
await selectRepo(root);
if (!useVcs.getState().branchesLoaded) await loadBranches();
}
export function conflictedFiles(status: readonly FileStatus[] = useVcs.getState().status): FileStatus[] {
return status.filter((f) => effectiveKind(f) === "conflicted");
}
@@ -180,7 +194,8 @@ export function refreshNow(): Promise<void> {
// `null` (before the first refresh) is the primary repository, listed first.
const shown = s.repo && roots.includes(s.repo) ? s.repo : (roots[0] ?? null);
const repo = attentionRepo(shown, s.operations, operations) ?? shown;
useVcs.setState({ operations });
const heads = Object.fromEntries(vcsRoots.map((r) => [r.root, { head: r.head, headCommit: r.headCommit }]));
useVcs.setState({ operations, heads });
if (repo !== s.repo || roots.join("\n") !== s.roots.join("\n")) useVcs.setState({ roots, repo });
applyStatus(status, branch);
useVcs.setState({ branches, stashes, error: null });
+29 -2
Переглянути файл
@@ -47,7 +47,7 @@
background: var(--bg-editor, var(--bg-app));
color: var(--fg);
font-family: var(--font-ui);
font-size: 14px;
font-size: calc(14px + var(--markdown-font-zoom, 0px));
line-height: 1.6;
overflow-wrap: break-word;
}
@@ -112,7 +112,7 @@
.preview :global(pre code) {
padding: 0;
background: none;
font-size: var(--fs-code);
font-size: calc(var(--fs-code) + var(--markdown-font-zoom, 0px));
}
.preview :global(blockquote) {
padding: 0 1em;
@@ -188,3 +188,30 @@
.preview :global(.tok-operator) {
color: var(--syn-punct);
}
/* Mermaid diagrams: the source stays until the diagram is drawn, and next to an error. */
.preview :global([data-mermaid]) {
margin: 0 0 1em;
}
.preview :global([data-mermaid] > pre) {
margin: 0;
}
.preview :global([data-mermaid-state="ok"] > pre) {
display: none;
}
.preview :global(.mermaid-output) {
overflow-x: auto;
text-align: center;
}
.preview :global([data-mermaid-state="error"] > .mermaid-output) {
margin-top: 6px;
padding: 6px 10px;
border-left: 3px solid var(--danger);
border-radius: var(--radius-small);
background: var(--bg-elev);
color: var(--danger);
font-family: var(--font-mono);
font-size: var(--fs-code);
text-align: left;
white-space: pre-wrap;
}
+33 -2
Переглянути файл
@@ -3,13 +3,25 @@
* side by side, switched from the floating toolbar at the top right. The
* preview follows the editor's scroll position in the split layout.
*/
import { useDeferredValue, useEffect, useLayoutEffect, useMemo, useRef, type MouseEvent, type ReactNode } from "react";
import {
useDeferredValue,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
useSyncExternalStore,
type CSSProperties,
type MouseEvent,
type ReactNode,
} from "react";
import clsx from "clsx";
import { call, commands, isTauri } from "@/platform/ipc";
import { maybeEditorService } from "@/workbench/contributions";
import { highlightInto } from "@/editor/lsp/markdown";
import { IconButton, selectableText } from "@/ui";
import { useLiveMarkdown } from "./live";
import { hasMermaid, MERMAID_SELECTOR, renderMermaidIn, subscribeTheme, themeKey } from "./mermaid";
import { modeOf, useMarkdownModes } from "./modes";
import { ANCHOR_PREFIX, previewOffsetForLine, renderMarkdown, resolveLink, slugify } from "./render";
import styles from "./Markdown.module.css";
@@ -69,11 +81,28 @@ export function MarkdownEditor({ path, children }: { path: string; tabId: string
function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
const text = useLiveMarkdown((s) => s[path]?.text);
const fontZoom = useLiveMarkdown((s) => s[path]?.fontZoom ?? 0);
const topLine = useLiveMarkdown((s) => s[path]?.topLine ?? 0);
const scrollSeq = useLiveMarkdown((s) => s[path]?.scrollSeq ?? 0);
const deferred = useDeferredValue(text ?? "");
const html = useMemo(() => renderMarkdown(deferred), [deferred]);
const ref = useRef<HTMLDivElement>(null);
const theme = useSyncExternalStore(subscribeTheme, themeKey, () => "");
const diagrams = useRef<Node[]>([]);
const [diagramsDrawn, setDiagramsDrawn] = useState(0);
// Mermaid diagrams: before paint, so cached ones don't flash their source.
useLayoutEffect(() => {
const root = ref.current;
if (!root || !hasMermaid(root)) return;
const pass = renderMermaidIn(root, diagrams.current);
let live = true;
if (pass.async) void pass.done.then(() => live && setDiagramsDrawn((n) => n + 1));
return () => {
live = false;
pass.cancel();
};
}, [html, theme]);
// Images and code highlighting after each render.
useEffect(() => {
@@ -98,6 +127,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
);
});
root.querySelectorAll<HTMLElement>("pre > code").forEach((code) => {
if (code.closest(MERMAID_SELECTOR)) return;
const lang = [...code.classList].find((c) => c.startsWith("language-"))?.slice("language-".length) ?? null;
const src = (code.textContent ?? "").replace(/\n+$/, "");
code.textContent = src;
@@ -117,7 +147,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
top: el.offsetTop,
}));
root.scrollTop = topLine <= 0 ? 0 : previewOffsetForLine(blocks, topLine, root.scrollHeight);
}, [html, topLine, scrollSeq, sync]);
}, [html, topLine, scrollSeq, sync, diagramsDrawn]);
const onClick = (e: MouseEvent) => {
const a = (e.target as Element).closest("a");
@@ -141,6 +171,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
<div
ref={ref}
className={clsx(styles.preview, selectableText)}
style={{ "--markdown-font-zoom": `${fontZoom}px` } as CSSProperties}
tabIndex={-1}
role="document"
aria-label="Markdown preview"
+7 -2
Переглянути файл
@@ -6,6 +6,7 @@
import { ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
import { create } from "zustand";
import { registerEditorContribution } from "@/editor/api";
import { fontZoom } from "@/editor/core/cm/prefs";
import { isMarkdownPath } from "../fileKinds";
export interface LiveMarkdown {
@@ -14,6 +15,8 @@ export interface LiveMarkdown {
topLine: number;
/** Bumped when the editor scrolls, so equal lines still resync. */
scrollSeq: number;
/** The editor's font zoom in px; the preview scales its text by the same amount. */
fontZoom: number;
}
export const useLiveMarkdown = create<Record<string, LiveMarkdown | undefined>>(() => ({}));
@@ -22,7 +25,7 @@ const TEXT_DELAY = 120;
function publish(path: string, patch: Partial<LiveMarkdown>) {
useLiveMarkdown.setState((s) => {
const prev = s[path] ?? { text: "", topLine: 0, scrollSeq: 0 };
const prev = s[path] ?? { text: "", topLine: 0, scrollSeq: 0, fontZoom: 0 };
return { [path]: { ...prev, ...patch } };
});
}
@@ -47,11 +50,13 @@ function livePlugin(path: string) {
};
constructor(private view: EditorView) {
publish(path, { text: view.state.doc.toString() });
publish(path, { text: view.state.doc.toString(), fontZoom: view.state.field(fontZoom, false) ?? 0 });
view.scrollDOM.addEventListener("scroll", this.onScroll, { passive: true });
}
update(u: ViewUpdate) {
const zoom = u.state.field(fontZoom, false) ?? 0;
if (zoom !== (u.startState.field(fontZoom, false) ?? 0)) publish(path, { fontZoom: zoom });
if (!u.docChanged) return;
clearTimeout(this.timer);
this.timer = setTimeout(() => publish(path, { text: this.view.state.doc.toString() }), TEXT_DELAY);
+119
Переглянути файл
@@ -0,0 +1,119 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { renderMarkdown } from "./render";
import { hasMermaid, renderMermaidIn, resetMermaidForTests } from "./mermaid";
const m = vi.hoisted(() => ({
loads: 0,
initialize: vi.fn(),
render: vi.fn(async (id: string, text: string) => {
// Like mermaid: a measuring node under <body> while rendering.
const tmp = document.createElement("div");
tmp.id = `d${id}`;
document.body.append(tmp);
if (text.includes("bad")) throw new Error("Parse error on line 2:\nbad\n^");
return { svg: `<svg id="${id}"><text>${text.split("\n")[0]}</text></svg>` };
}),
}));
vi.mock("mermaid", () => {
m.loads++;
return { default: { initialize: m.initialize, render: m.render } };
});
function preview(md: string): HTMLElement {
const root = document.createElement("div");
root.innerHTML = renderMarkdown(md);
document.body.append(root);
return root;
}
const SEQ = "```mermaid\nsequenceDiagram\n A->B:test\n```\n";
describe("mermaid in the markdown preview", () => {
beforeEach(() => {
resetMermaidForTests();
m.render.mockClear();
m.initialize.mockClear();
document.body.innerHTML = "";
});
it("emits a placeholder holding the escaped source, other code blocks unchanged", () => {
const root = preview(
`# T\n\n${SEQ}\n\`\`\`js\nlet a = 1;\n\`\`\`\n\n\`\`\`Mermaid title\ngraph TD\n a["<b>x</b>"]-->b\n\`\`\`\n`,
);
const blocks = root.querySelectorAll<HTMLElement>("[data-mermaid]");
expect(blocks).toHaveLength(2);
expect(blocks[0]!.parentElement?.dataset.line).toBe("2");
expect(blocks[0]!.querySelector("pre > code.language-mermaid")?.textContent).toBe("sequenceDiagram\n A->B:test");
expect(blocks[1]!.querySelector("code")?.textContent).toContain('a["<b>x</b>"]');
expect(blocks[1]!.querySelector("b")).toBeNull();
expect(root.querySelector("code.language-js")?.closest("[data-mermaid]")).toBeNull();
});
it("loads mermaid only for previews with a diagram", async () => {
const plain = preview("# Plain\n\n```js\n1\n```\n");
expect(hasMermaid(plain)).toBe(false);
const pass = renderMermaidIn(plain);
expect(pass.async).toBe(false);
await pass.done;
expect(m.loads).toBe(0);
const root = preview(SEQ);
expect(hasMermaid(root)).toBe(true);
await renderMermaidIn(root).done;
expect(m.loads).toBe(1);
expect(m.initialize).toHaveBeenCalledWith(
expect.objectContaining({ startOnLoad: false, securityLevel: "strict", theme: "base" }),
);
const block = root.querySelector<HTMLElement>("[data-mermaid]")!;
expect(block.getAttribute("data-mermaid-state")).toBe("ok");
expect(block.querySelector(".mermaid-output svg")).not.toBeNull();
// Temporary nodes mermaid leaves under <body> are removed.
expect(document.body.querySelector(":scope > [id^='d']")).toBeNull();
});
it("shows syntax errors inline next to the source without throwing", async () => {
const root = preview("```mermaid\nsequenceDiagram\nbad\n```\n");
await expect(renderMermaidIn(root).done).resolves.toBeUndefined();
const block = root.querySelector<HTMLElement>("[data-mermaid]")!;
expect(block.getAttribute("data-mermaid-state")).toBe("error");
expect(block.querySelector("pre code")?.textContent).toContain("bad");
const error = block.querySelector(".mermaid-output")!;
expect(error.getAttribute("role")).toBe("alert");
expect(error.textContent).toContain("Parse error on line 2");
expect(error.querySelector("svg")).toBeNull();
});
it("renders with unique ids, reuses results and keeps the old diagram while a new one renders", async () => {
const first = preview(SEQ);
await renderMermaidIn(first, []).done;
const ids = new Set(m.render.mock.calls.map(([id]) => id));
// Same source again (e.g. an edit elsewhere): drawn synchronously from the cache.
const previous: Node[] = [];
const again = preview(SEQ);
const pass = renderMermaidIn(again, previous);
expect(pass.async).toBe(false);
expect(again.querySelector("[data-mermaid-state='ok'] svg")).not.toBeNull();
expect(m.render).toHaveBeenCalledTimes(1);
// Edited diagram: the previous drawing stands in until the new one is ready.
const edited = preview(SEQ.replace("test", "edited"));
const next = renderMermaidIn(edited, previous);
expect(next.async).toBe(true);
expect(edited.querySelector(".mermaid-output svg")?.textContent).toBe("sequenceDiagram");
await next.done;
expect(m.render).toHaveBeenCalledTimes(2);
ids.add(m.render.mock.calls[1]![0]);
expect(ids.size).toBe(2);
});
it("skips superseded renders", async () => {
const root = preview(SEQ.replace("test", "stale"));
const pass = renderMermaidIn(root);
pass.cancel();
await pass.done;
expect(m.render).not.toHaveBeenCalled();
expect(root.querySelector("[data-mermaid]")?.getAttribute("data-mermaid-state")).toBe("pending");
});
});
+203
Переглянути файл
@@ -0,0 +1,203 @@
/**
* Mermaid diagrams in the Markdown preview. `renderMarkdown` emits a
* `[data-mermaid]` placeholder holding the source in `pre > code`; this module
* turns placeholders into SVG. The library is imported on first use only.
*/
import type { Mermaid } from "mermaid";
export const MERMAID_SELECTOR = "[data-mermaid]";
const OUTPUT_CLASS = "mermaid-output";
const RENDERED_ATTR = "data-mermaid-state";
type Result = { svg: string } | { error: string };
let loading: Promise<Mermaid> | null = null;
let configured = "";
let seq = 0;
/** Results by theme + source, so edits elsewhere in the file don't re-render diagrams. */
const cache = new Map<string, Result>();
const CACHE_LIMIT = 64;
/** mermaid's render isn't re-entrant across configuration changes: one at a time. */
let queue: Promise<unknown> = Promise.resolve();
function loadMermaid(): Promise<Mermaid> {
loading ??= import("mermaid").then((m) => m.default);
loading.catch(() => (loading = null));
return loading;
}
/** Theme identity: anything that changes the colours read below. */
export function themeKey(): string {
const root = document.documentElement;
return `${root.dataset.theme ?? ""}|${root.dataset.contrast ?? ""}|${root.style.getPropertyValue("--accent")}`;
}
/** Calls `cb` when the theme attributes or the accent on the root change. */
export function subscribeTheme(cb: () => void): () => void {
if (typeof MutationObserver === "undefined") return () => {};
const observer = new MutationObserver(cb);
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: ["data-theme", "data-contrast", "style"],
});
return () => observer.disconnect();
}
/** Diagram colours from the IDE tokens; values mermaid can't parse (e.g. `color-mix`) are skipped. */
function themeVariables(): Record<string, string | boolean> {
const css = getComputedStyle(document.documentElement);
const token = (...names: string[]) => {
for (const n of names) {
const v = css.getPropertyValue(n).trim();
if (/^(#[0-9a-f]{3,8}|rgba?\([^)]*\))$/i.test(v)) return v;
}
return undefined;
};
const vars: Record<string, string | undefined> = {
background: token("--bg-editor", "--bg-app"),
mainBkg: token("--bg-elev"),
primaryColor: token("--bg-elev"),
primaryBorderColor: token("--border-strong"),
primaryTextColor: token("--fg-strong", "--fg"),
secondaryColor: token("--bg-popup"),
tertiaryColor: token("--bg-hover"),
lineColor: token("--fg-secondary"),
textColor: token("--fg"),
edgeLabelBackground: token("--bg-editor", "--bg-app"),
errorBkgColor: token("--bg-elev"),
errorTextColor: token("--danger"),
};
const out: Record<string, string | boolean> = { darkMode: document.documentElement.dataset.theme !== "light" };
for (const [k, v] of Object.entries(vars)) if (v) out[k] = v;
const font = css.getPropertyValue("--font-ui").trim();
if (font) out.fontFamily = font;
return out;
}
function configure(mermaid: Mermaid, key: string) {
if (configured === key) return;
mermaid.initialize({
startOnLoad: false,
securityLevel: "strict",
suppressErrorRendering: true,
theme: "base",
themeVariables: themeVariables(),
});
configured = key;
}
function removeTemp(id: string) {
// mermaid measures in detached-from-preview nodes under <body>: `d<id>` (and `i<id>` when sandboxed).
for (const tmp of [`d${id}`, `i${id}`, id]) document.getElementById(tmp)?.remove();
}
async function renderOne(source: string, key: string): Promise<Result> {
const mermaid = await loadMermaid();
configure(mermaid, key);
const id = `openidea-mermaid-${++seq}`;
try {
const { svg } = await mermaid.render(id, source);
return { svg };
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
return { error: msg.trim() || "Invalid diagram" };
} finally {
removeTemp(id);
}
}
/** Resolves `null` when the pass was superseded before its turn came. */
function enqueue(source: string, key: string, live: () => boolean): Promise<Result | null> {
const p = queue.then(() => (live() ? renderOne(source, key) : null));
queue = p.catch(() => undefined);
return p;
}
function remember(k: string, r: Result) {
if (cache.size >= CACHE_LIMIT) cache.delete(cache.keys().next().value!);
cache.set(k, r);
}
function show(block: HTMLElement, result: Result | null, stale?: Node) {
block.querySelector(`:scope > .${OUTPUT_CLASS}`)?.remove();
const out = document.createElement("div");
out.className = OUTPUT_CLASS;
if (result && "svg" in result) {
out.innerHTML = result.svg;
block.setAttribute(RENDERED_ATTR, "ok");
} else if (result) {
out.setAttribute("role", "alert");
out.textContent = result.error;
block.setAttribute(RENDERED_ATTR, "error");
} else if (stale) {
// The diagram before this edit, until the new one is ready (no flicker while typing).
out.append(stale.cloneNode(true));
block.setAttribute(RENDERED_ATTR, "ok");
} else {
block.setAttribute(RENDERED_ATTR, "pending");
return;
}
block.append(out);
}
export const hasMermaid = (root: ParentNode) => root.querySelector(MERMAID_SELECTOR) !== null;
export interface MermaidPass {
/** Whether some diagram renders asynchronously (it changes the layout when `done`). */
async: boolean;
/** Settles when every diagram of the pass is in place (or the pass was cancelled). */
done: Promise<void>;
cancel(): void;
}
/**
* Renders the placeholders under `root`. `previous` holds the last rendered
* output per block index of the same preview (updated in place) and stands in
* while a changed diagram renders. Cached results are applied synchronously.
*/
export function renderMermaidIn(root: HTMLElement, previous: Node[] = []): MermaidPass {
const blocks = [...root.querySelectorAll<HTMLElement>(MERMAID_SELECTOR)];
let live = true;
if (!blocks.length) return { async: false, done: Promise.resolve(), cancel: () => {} };
const key = themeKey();
const pending: Promise<void>[] = [];
blocks.forEach((block, i) => {
const source = (block.querySelector("code")?.textContent ?? "").replace(/\n+$/, "");
const k = `${key}\n${source}`;
const cached = cache.get(k);
const keep = () => {
const out = block.querySelector(`:scope > .${OUTPUT_CLASS}`);
if (out && block.getAttribute(RENDERED_ATTR) === "ok") previous[i] = out.firstChild ?? out;
};
if (cached) {
show(block, cached);
keep();
return;
}
show(block, null, previous[i]);
pending.push(
enqueue(source, key, () => live).then((r) => {
if (!r) return;
remember(k, r);
if (!live) return;
show(block, r);
keep();
}),
);
});
previous.length = blocks.length;
return {
async: pending.length > 0,
done: Promise.all(pending).then(() => undefined),
cancel: () => {
live = false;
},
};
}
/** For tests. */
export function resetMermaidForTests() {
cache.clear();
configured = "";
loading = null;
}
+15 -2
Переглянути файл
@@ -2,12 +2,25 @@
* Markdown → sanitized HTML for the preview. Every top-level block is wrapped
* in an element carrying its 0-based source line (`data-line`) for scroll
* sync; images keep their source in `data-src` and are loaded by the preview
* (local files through the backend, as the CSP blocks file URLs).
* (local files through the backend, as the CSP blocks file URLs). Mermaid
* blocks become `[data-mermaid]` placeholders, drawn by `./mermaid`.
*/
import { Marked, type Token, type TokensList } from "marked";
import DOMPurify from "dompurify";
const marked = new Marked({ gfm: true, breaks: false });
const escapeHtml = (s: string) =>
s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
const marked = new Marked({
gfm: true,
breaks: false,
renderer: {
code({ text, lang }) {
if (lang?.trim().split(/\s+/)[0]?.toLowerCase() !== "mermaid") return false;
return `<div data-mermaid=""><pre><code class="language-mermaid">${escapeHtml(text)}</code></pre></div>\n`;
},
},
});
// Own instance: hooks must not leak into the hover / documentation renderer.
let purifier: ReturnType<typeof DOMPurify> | null = null;
+130
Переглянути файл
@@ -0,0 +1,130 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, render, screen } 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, setFontZoom } from "@/editor/core/cm/prefs";
import { fontExtension } from "@/editor/core/cm/setup";
import type { EditorSlot } from "@/editor/core/model/slot";
import { executeAction } from "@/platform/actions";
import { useContextKeys } from "@/platform/context";
import { intellijMacos } from "@/platform/keymaps/intellij-macos";
import { intellijWindows } from "@/platform/keymaps/intellij-windows";
import { vscodeMacos } from "@/platform/keymaps/vscode-macos";
let activeSlot: Partial<EditorSlot> | null = null;
vi.mock("@/editor/core/controller", async (importOriginal) => ({
...(await importOriginal<object>()),
editorController: () => ({
get activeSlot() {
return activeSlot;
},
}),
}));
const { registerEditorActions } = await import("@/editor/core/actions");
const { registerMarkdownLiveSource, useLiveMarkdown } = await import("./live");
const { MarkdownEditor } = await import("./MarkdownEditor");
const { useMarkdownModes } = await import("./modes");
const mdCtx: EditorDocContext = { doc: 1, path: "/p/README.md", language: "markdown", uiMode: null, readOnly: false };
const tsCtx: EditorDocContext = { doc: 2, path: "/p/a.ts", language: "typescript", uiMode: null, readOnly: false };
describe("editor font size actions", () => {
const disposers: Array<() => void> = [];
const views: EditorView[] = [];
const open = (ctx: EditorDocContext) => {
const live = editorContributions().find((c) => c.id === "viewers.markdownLive")!;
const extensions = [fontZoom, live.extensions(ctx)];
const view = new EditorView({ state: EditorState.create({ doc: "# Title", extensions }) });
const handle = { view, ctx };
_addEditor(handle);
disposers.push(() => _removeEditor(handle));
views.push(view);
return view;
};
const activate = (view: EditorView) => (activeSlot = { view, disposed: false });
const zoom = (view: EditorView) => view.state.field(fontZoom);
beforeEach(() => {
disposers.push(registerEditorActions(), registerMarkdownLiveSource());
useContextKeys.setState({ projectOpen: true, textEditorActive: true, editorFocus: true, popupOpen: true });
});
afterEach(() => {
cleanup();
for (const view of views.splice(0)) view.destroy();
for (const dispose of disposers.splice(0).reverse()) dispose();
activeSlot = null;
useLiveMarkdown.setState({}, true);
useContextKeys.setState({}, true);
});
it("zooms only the active editor, clamped to -6..36", async () => {
const md = open(mdCtx);
const ts = open(tsCtx);
activate(md);
await executeAction("editor.increaseFontSize");
await executeAction("editor.increaseFontSize");
expect(zoom(md)).toBe(2);
expect(zoom(ts)).toBe(0);
activate(ts);
await executeAction("editor.decreaseFontSize");
expect(zoom(ts)).toBe(-1);
expect(zoom(md)).toBe(2);
ts.dispatch({ effects: setFontZoom.of(36) });
await executeAction("editor.increaseFontSize");
expect(zoom(ts)).toBe(36);
ts.dispatch({ effects: setFontZoom.of(-6) });
await executeAction("editor.decreaseFontSize");
expect(zoom(ts)).toBe(-6);
});
it("scales the Markdown preview with its editor and resets with it", async () => {
const md = open(mdCtx);
activate(md);
act(() => useMarkdownModes.setState((s) => ({ byPath: { ...s.byPath, [mdCtx.path]: "split" } })));
render(
<MarkdownEditor path={mdCtx.path} tabId="t">
<div />
</MarkdownEditor>,
);
const preview = screen.getByRole("document", { name: "Markdown preview" });
expect(preview.style.getPropertyValue("--markdown-font-zoom")).toBe("0px");
await act(() => executeAction("editor.increaseFontSize"));
await act(() => executeAction("editor.increaseFontSize"));
expect(preview.style.getPropertyValue("--markdown-font-zoom")).toBe("2px");
await act(() => executeAction("editor.resetFontSize"));
expect(zoom(md)).toBe(0);
expect(preview.style.getPropertyValue("--markdown-font-zoom")).toBe("0px");
});
it("scales a configured editor font size", () => {
const settings = { fontSize: 13 } as Parameters<typeof fontExtension>[0];
const view = new EditorView({ state: EditorState.create({ extensions: [fontExtension(settings), fontZoom] }) });
views.push(view);
view.dispatch({ effects: setFontZoom.of(2) });
expect(view.dom.style.getPropertyValue("--openidea-editor-base-size")).toBe("13px");
expect(view.dom.style.getPropertyValue("--openidea-editor-font-size")).toContain("+ 2px");
});
it("leaves ⌘= / ⌘- to fold and unfold", () => {
for (const km of [intellijMacos, intellijWindows]) {
expect(km["editor.increaseFontSize"]).toEqual(["Alt+Shift+."]);
expect(km["editor.decreaseFontSize"]).toEqual(["Alt+Shift+,"]);
}
expect(intellijMacos["code.fold"]).toEqual(["Meta+-"]);
expect(intellijMacos["code.unfold"]).toEqual(["Meta+="]);
expect(intellijWindows["code.fold"]).toEqual(["Ctrl+-"]);
expect(intellijWindows["code.unfold"]).toEqual(["Ctrl+="]);
for (const km of [intellijMacos, intellijWindows, vscodeMacos]) {
const keys = [...(km["editor.increaseFontSize"] ?? []), ...(km["editor.decreaseFontSize"] ?? [])];
expect(keys.filter((k) => /^(Meta|Ctrl)\+(Shift\+)?[=-]$/.test(k))).toEqual([]);
expect(Object.keys(km).filter((id) => id.startsWith("markdown.zoom"))).toEqual([]);
}
});
});
+8
Переглянути файл
@@ -0,0 +1,8 @@
/**
* True while an input method is composing, including the key that ends it: WebKit sends the
* Enter / Space that commits a candidate after `compositionend`, with `isComposing` already
* false and keyCode 229, so a handler checking `isComposing` alone runs that Enter.
*/
export function isImeKey(e: KeyboardEvent): boolean {
return e.isComposing || e.keyCode === 229;
}
+2 -1
Переглянути файл
@@ -18,6 +18,7 @@ import { intellijWindows } from "./keymaps/intellij-windows";
import { vscodeMacos } from "./keymaps/vscode-macos";
import { vscodeWindows } from "./keymaps/vscode-windows";
import { usePlatform } from "./platformInfo";
import { isImeKey } from "./ime";
export type Keymap = Record<string, string[]>;
@@ -439,7 +440,7 @@ export function installKeyboardDispatcher(target: Window = window, now: () => nu
if (runHeldGesture(e)) return reset();
resetTap();
otherKeyAt = e.key === "Escape" || e.key === "Tab" ? -Infinity : now();
if (e.isComposing) return;
if (isImeKey(e)) return;
const stroke = strokeOf(e);
if (!stroke) return;
const chord = pending.length > 0;
+2
Переглянути файл
@@ -12,6 +12,8 @@ describe("IDEA keymap parity", () => {
["view.zoomIn", ["Ctrl+Alt+="], ["Alt+Shift+="]],
["view.zoomOut", ["Ctrl+Alt+-"], ["Alt+Shift+-"]],
["view.resetZoom", ["Ctrl+Alt+0"], ["Alt+Shift+0"]],
["editor.increaseFontSize", ["Alt+Shift+."], ["Alt+Shift+."]],
["editor.decreaseFontSize", ["Alt+Shift+,"], ["Alt+Shift+,"]],
["vcs.changelist.move", ["Meta+Shift+M"], ["Alt+Shift+M"]],
["vcs.changelist.edit", ["F2", "Shift+F6"], ["F2", "Shift+F6"]],
["code.quickDocumentation", ["F1", "Ctrl+J"], ["Ctrl+Q"]],
+2
Переглянути файл
@@ -271,6 +271,8 @@ export const intellijMacos: Record<string, string[]> = {
"view.zoomIn": ["Ctrl+Alt+="],
"view.zoomOut": ["Ctrl+Alt+-"],
"view.resetZoom": ["Ctrl+Alt+0"],
"editor.increaseFontSize": ["Alt+Shift+."],
"editor.decreaseFontSize": ["Alt+Shift+,"],
// Diff viewer (after Debug: F7 / ⇧F7 / F4 there win while a diff is focused)
"diff.nextDifference": ["F7"],
"diff.prevDifference": ["Shift+F7"],
+2
Переглянути файл
@@ -268,6 +268,8 @@ export const intellijWindows: Record<string, string[]> = {
"view.zoomIn": ["Alt+Shift+="],
"view.zoomOut": ["Alt+Shift+-"],
"view.resetZoom": ["Alt+Shift+0"],
"editor.increaseFontSize": ["Alt+Shift+."],
"editor.decreaseFontSize": ["Alt+Shift+,"],
// Diff viewer (after Debug: F7 / ⇧F7 / F4 there win while a diff is focused)
"diff.nextDifference": ["F7"],
"diff.prevDifference": ["Shift+F7"],
+2
Переглянути файл
@@ -266,6 +266,8 @@ export const vscodeMacos: Record<string, string[]> = {
"view.zoomIn": ["Meta+="],
"view.zoomOut": ["Meta+-"],
"view.resetZoom": [],
"editor.increaseFontSize": [],
"editor.decreaseFontSize": [],
// Editing extras, image viewer (keyWhen: image focused) and Markdown editor layouts
"code.cyclicExpandWord": [],
"code.cyclicExpandWordBackward": [],
+325 -49
Переглянути файл
@@ -6,7 +6,6 @@
") contain CRLF line separators and core.autocrlf is not set, so they would be committed with CRLF. Convert them with the line separator widget in the status bar, or set": ") 包含 CRLF 行分隔符且未设置 core.autocrlf,因此将以 CRLF 提交。请使用状态栏中的行分隔符组件进行转换,或设置",
", e.g.": ",例如",
", then press Tab.": ",然后按 Tab。",
"? Its query console file stays on disk.": "?其查询控制台文件会保留在磁盘上。",
"? This cannot be undone.": "?此操作无法撤消。",
"A charset in .editorconfig takes precedence. Change one file's encoding from the status bar.": ".editorconfig 中的 charset 优先。可以从状态栏更改单个文件的编码。",
"A command line, e.g. /bin/zsh --login. Leave empty to use the login shell.": "命令行,例如 /bin/zsh --login。留空则使用登录 Shell。",
@@ -30,14 +29,12 @@
"Accessibility": "辅助功能",
"Action id (bind it in Keymap)": "操作 ID(可在“按键映射”中绑定)",
"Actions": "操作",
"Add Configuration…": "添加配置…",
"Actions on Save": "保存时操作",
"Actions run when a file is saved with Save (⌘S) or Save All. Trailing spaces and the final line break are configured in": "使用“保存”(⌘S) 或“全部保存”保存文件时运行的操作。尾随空格和末尾换行符的配置位置:",
"Activate on Save": "保存时激活",
"Activate virtualenv": "激活 virtualenv",
"Add": "添加",
"Add Column": "添加列",
"Add Conditional Breakpoint…": "添加条件断点…",
"Add Field Watchpoint": "添加字段监视点",
"Add File to Git": "将文件添加到 Git",
"Add GitHub Pattern": "添加 GitHub 模式",
@@ -45,7 +42,6 @@
"Add JIRA Pattern": "添加 JIRA 模式",
"Add Keyboard Shortcut": "添加键盘快捷键",
"Add Kind": "添加类型",
"Add Logpoint…": "添加日志点…",
"Add Method Breakpoint": "添加方法断点",
"Add New Configuration": "添加新配置",
"Add Pattern": "添加模式",
@@ -61,7 +57,6 @@
"Add to VCS": "添加到 VCS",
"Add to Watches": "添加到监视",
"Add unambiguous imports on the fly": "动态添加明确的导入",
"Add variable": "添加变量",
"Added to the environment of new terminal sessions.": "添加到新终端会话的环境中。",
"Additional arguments": "附加实参",
"Adjust colors for red-green vision deficiency": "针对红绿色觉缺陷调整颜色",
@@ -239,7 +234,6 @@
"Change Signature…": "更改签名…",
"Change actions": "更改操作",
"Change font size with Command+Mouse Wheel": "使用 Command+鼠标滚轮更改字体大小",
"Change with": "更改方式:",
"Changed files": "已更改的文件",
"Changelist:": "更改列表:",
"Changes": "更改",
@@ -307,7 +301,6 @@
"Close non-modified files first": "优先关闭未修改的文件",
"Close performance overlay": "关闭性能浮层",
"Close session when it ends": "会话结束时关闭",
"Close stdin (send EOF)": "关闭 stdin(发送 EOF)",
"Closed": "已关闭",
"Closing Policy": "关闭策略",
"Code": "代码",
@@ -397,7 +390,6 @@
"Copied code keeps the editor's syntax colors and font when pasted into documents and mail.": "复制的代码粘贴到文档和邮件中时会保留编辑器的语法颜色和字体。",
"Copy": "复制",
"Copy / Paste Special": "复制/选择性粘贴",
"Copy Action ID": "复制操作 ID",
"Copy All": "全部复制",
"Copy Commit Message": "复制提交消息",
"Copy Configuration": "复制配置",
@@ -632,7 +624,6 @@
"Enabled": "已启用",
"Enabled tools appear in Find Action (⇧⌘A) under “External Tools” and can get shortcuts in Keymap. Output is shown in the Run tool window.": "已启用的工具会出现在“查找操作”(⇧⌘A) 的“外部工具”下,并可以在“按键映射”中设置快捷键。输出显示在“运行”工具窗口中。",
"Encoding of the output of processes started from Run configurations.": "从运行配置启动的进程的输出编码。",
"Engine": "引擎",
"Enhanced for loop": "增强型 for 循环",
"Ensure every saved file ends with a line break": "确保每个已保存的文件都以换行符结尾",
"Enter a tag, branch or commit hash:": "输入标签、分支或提交哈希:",
@@ -779,7 +770,6 @@
"For symbols not supported by the main font": "用于主字体不支持的符号",
"Force": "强制",
"Force (with lease)": "强制 (with lease)",
"Force Delete": "强制删除",
"Force Push": "强制推送",
"Force Run to Cursor": "强制运行到光标处",
"Force Step Into": "强制步入",
@@ -834,7 +824,6 @@
"Grey": "灰色",
"Greyscale": "灰度",
"Group": "组",
"Group by Directory": "按目录分组",
"Group by Severity": "按严重性分组",
"Groups": "组",
"Gutter Icons": "装订区域图标",
@@ -879,7 +868,7 @@
"IDE and Project Settings": "IDE 和项目设置",
"IDE font": "IDE 字体",
"IDE font size": "IDE 字体大小",
"Installed {name}": "已安装 {name}",
"Installed {name} {version}": "已安装 {name} {version}",
"Installing {name}": "正在安装 {name}",
"IPC round trip": "IPC 往返",
"Idle seconds": "空闲秒数",
@@ -896,7 +885,6 @@
"Implementation(s)": "实现",
"Imports": "导入",
"In Project": "在项目中",
"In Selection": "在所选内容中",
"Include": "包括",
"Include non-project items": "包括非项目项",
"Include untracked files": "包括未跟踪的文件",
@@ -1048,8 +1036,6 @@
"Location:": "位置:",
"Log": "日志",
"Log filters": "日志过滤器",
"Log message": "日志消息",
"Log message instead of suspending": "记录消息而不挂起",
"Long tasks": "长任务",
"Looking for references…": "正在查找引用…",
"Looks for TODO and FIXME in added lines.": "在新增的行中查找 TODO 和 FIXME。",
@@ -1201,7 +1187,6 @@
"No changes to roll back": "没有要回滚的更改",
"No changes to shelve": "没有要搁置的更改",
"No commits": "没有提交",
"No configurations. Click + to add one.": "没有配置。点击 + 添加一个。",
"No conflicts": "没有冲突",
"No coverage data": "没有覆盖率数据",
"No data sources": "没有数据源",
@@ -1248,7 +1233,6 @@
"No special permissions.": "没有特殊权限。",
"No stashes": "没有储藏",
"No structure to show": "没有可显示的结构",
"No surround templates for this language": "此语言没有包围模板",
"No tools match.": "没有匹配的工具。",
"No usages found": "未找到用法",
"No usages of '{name}' found": "未找到 '{name}' 的用法",
@@ -1261,7 +1245,6 @@
"Nothing found": "未找到任何内容",
"Nothing found in project files": "项目文件中未找到任何内容",
"Nothing here": "这里什么都没有",
"Nothing is running": "没有正在运行的内容",
"Nothing matches": "没有匹配项",
"Nothing recorded before this label": "此标签之前没有记录",
"Nothing to add: the files are already under version control": "没有要添加的内容:这些文件已受版本控制",
@@ -1364,7 +1347,7 @@
"Rerun Search": "重新运行搜索",
"Right Bottom": "右下",
"Right Top": "右上",
"Runs jdtls only, like IDEA's JDK for importer; the project keeps compiling and running with the Project JDK. jdtls needs JDK 21 or newer (recent releases 25). The jdtls executable itself is set in Language Servers.": "仅用于运行 jdtls(类似 IDEA 的「导入器 JDK」);项目仍使用项目 JDK 编译和运行。jdtls 需要 JDK 21 或更高版本(较新版本需要 25)。jdtls 可执行文件本身在「语言服务器」中设置。",
"Runs jdtls only, like IDEA's JDK for importer; the project keeps compiling and running with the Project JDK. jdtls needs JDK 21 or newer (recent releases 25); Download JDK… in the list fetches one. The jdtls executable itself is set in Language Servers.": "仅用于运行 jdtls(类似 IDEA 的「导入器 JDK」);项目仍使用项目 JDK 编译和运行。jdtls 需要 JDK 21 或更高版本(较新版本需要 25);可通过列表中的「下载 JDK…」获取。jdtls 可执行文件本身在「语言服务器」中设置。",
"Language server JDK": "语言服务器 JDK",
"Password": "密码",
"Password:": "密码:",
@@ -1476,7 +1459,6 @@
"Protected branches": "受保护的分支",
"Prune": "清理",
"Prune Docker…": "清理 Docker…",
"Prune…": "清理…",
"Public function": "公共函数",
"Pull Again": "重新拉取",
"Pull Docker Image…": "拉取 Docker 镜像…",
@@ -1582,7 +1564,6 @@
"Remove Template": "移除模板",
"Remove Watch": "移除监视",
"Remove coverage highlighting from editors and the project view": "从编辑器和项目视图中移除覆盖率高亮",
"Remove data source": "移除数据源",
"Remove from Favorites": "从收藏夹中移除",
"Remove from Recent Projects": "从最近的项目中移除",
"Remove from Recent Projects…": "从最近的项目中移除…",
@@ -1591,7 +1572,6 @@
"Remove successfully applied files from the shelf": "从搁置中移除已成功应用的文件",
"Remove trailing blank lines at the end of saved files": "移除已保存文件末尾的空行",
"Remove trailing spaces on:": "移除尾随空格:",
"Remove variable": "移除变量",
"Rename": "重命名",
"Rename File Inline": "内联重命名文件",
"Rename File…": "重命名文件…",
@@ -1725,7 +1705,6 @@
"Run Maven Build": "运行 Maven 构建",
"Run SQL Script": "运行 SQL 脚本",
"Run SQL Script…": "运行 SQL 脚本…",
"Run a configuration with": "运行配置:",
"Run a configuration with coverage to see which lines its tests execute.": "使用覆盖率运行配置,即可查看其测试执行了哪些行。",
"Run a request from an .http file with the gutter ▶ or ⌘↩.": "使用装订区域中的 ▶ 或 ⌘↩ 运行 .http 文件中的请求。",
"Run actions": "运行操作",
@@ -1757,7 +1736,6 @@
"Runs sync, builds and Maven run configurations. A chosen home is used instead of the project's mvnw.": "用于同步、构建和 Maven 运行配置。选定后将代替项目的 mvnw。",
"Runs the language server's Organize Imports action.": "运行语言服务器的“整理导入”操作。",
"Runs the language server's formatter before an explicit save (Actions on Save).": "在显式保存前运行语言服务器的格式化程序(保存时操作)。",
"Runs this project": "运行此项目",
"Search history": "搜索历史",
"Search history (⌥↑ / ⌥↓)": "搜索历史(⌥↑ / ⌥↓)",
"Searching for usages of '{symbol}'": "正在搜索 '{symbol}' 的用法",
@@ -1768,7 +1746,6 @@
"SQLite can rename or drop an existing column, not change its type, NOT NULL or default.": "SQLite 可以重命名或删除现有列,但不能更改其类型、NOT NULL 或默认值。",
"SSH authentication type": "SSH 身份验证类型",
"SSL mode": "SSL 模式",
"SSL:": "SSL:",
"Safe Delete…": "安全删除…",
"Sample plugin: inserts today's date and counts words in the active file.": "示例插件:插入今天的日期,并统计当前文件的字数。",
"Save": "保存",
@@ -1831,7 +1808,6 @@
"Select a column": "选择一列",
"Select a commit in the Git log": "在 Git 日志中选择一个提交",
"Select a commit to view changes": "选择一个提交以查看更改",
"Select a configuration": "选择一个配置",
"Select a container, image, volume or network.": "选择一个容器、镜像、卷或网络。",
"Select a group": "选择一个组",
"Select a pull request": "选择一个拉取请求",
@@ -1890,7 +1866,6 @@
"Show History for File": "显示文件的历史记录",
"Show Ignored": "显示已忽略",
"Show Infos and Hints": "显示信息和提示",
"Show Input Field": "显示输入字段",
"Show Local History": "显示本地历史记录",
"Show Log": "显示日志",
"Show Memory Indicator Details": "显示内存指示器详细信息",
@@ -1911,7 +1886,6 @@
"Show breadcrumbs for:": "为以下语言显示痕迹导航:",
"Show breadcrumbs:": "显示痕迹导航:",
"Show changed only": "仅显示已更改的",
"Show close button": "显示关闭按钮",
"Show code folding outline": "显示代码折叠轮廓",
"Show debug window on breakpoint hit": "命中断点时显示调试窗口",
"Show details": "显示详细信息",
@@ -1939,7 +1913,6 @@
"Show sticky lines while scrolling": "滚动时显示粘滞行",
"Show suggestions as you type": "输入时显示建议",
"Show table data": "显示表数据",
"Show tabs in multiple rows": "多行显示标签页",
"Show the documentation popup in": "在以下时间后显示文档弹出窗口",
"Show the parameter info popup in": "在以下时间后显示形参信息弹出窗口",
"Show the selected coverage suite in editors and the project view": "在编辑器和项目视图中显示所选覆盖率套件",
@@ -1951,7 +1924,6 @@
"Show whitespaces": "显示空白",
"Shown as the right margin guide in the editor.": "在编辑器中显示为右边距参考线。",
"Side-by-side Viewer": "并排查看器",
"Sign-off Commit": "签署提交",
"Sign-off commit": "签署提交",
"Size": "大小",
"Size:": "大小:",
@@ -1986,7 +1958,6 @@
"Squash Into…": "压缩到…",
"Stage": "暂存",
"Stage Change (git add hunk)": "暂存更改 (git add hunk)",
"Standard input": "标准输入",
"Standard library": "标准库",
"Start": "启动",
"Start Container": "启动容器",
@@ -1997,7 +1968,6 @@
"Start debugging a run configuration": "开始调试运行配置",
"Start directory": "起始目录",
"Startup": "启动",
"Stash Changes": "储藏更改",
"Stash Changes…": "储藏更改…",
"Stashes": "储藏",
"State": "状态",
@@ -2038,7 +2008,6 @@
"Surround With…": "包围方式…",
"Surround selection on typing quote or brace": "输入引号或括号时包围所选内容",
"Suspend on": "挂起时机",
"Suspends when empty": "为空时挂起",
"Switch to Auto-Commit": "切换到自动提交",
"Switcher": "切换器",
"Switcher (Backward)": "切换器(向后)",
@@ -2148,7 +2117,6 @@
"Toggle Performance Overlay (Dev)": "切换性能浮层(开发)",
"Toggle Read-only Attribute": "切换只读属性",
"Toggle Temporary Line Breakpoint": "切换临时行断点",
"Tool": "工具",
"Tool Settings": "工具设置",
"Tool Windows": "工具窗口",
"Tool windows": "工具窗口",
@@ -2252,7 +2220,6 @@
"Used by the npm run configurations detected from package.json scripts.": "供从 package.json 脚本检测到的 npm 运行配置使用。",
"Used for new files.": "用于新文件。",
"User": "用户",
"User name or email": "用户名或电子邮件",
"User settings file": "用户设置文件",
"User:": "用户:",
"Uses HostName, User, Port, IdentityFile and ProxyJump from ~/.ssh/config, and keys of the SSH agent.": "使用 ~/.ssh/config 中的 HostName、User、Port、IdentityFile 和 ProxyJump,以及 SSH 代理中的密钥。",
@@ -2304,7 +2271,6 @@
"Yellow": "黄色",
"You can also drop a folder onto this window.": "也可以将文件夹拖放到此窗口。",
"Your version": "您的版本",
"Yours (current branch)": "您的(当前分支)",
"Zoom": "缩放",
"Zoom In IDE": "放大 IDE",
"Zoom Out IDE": "缩小 IDE",
@@ -2330,9 +2296,7 @@
"found in the changed lines:": "在更改的行中找到:",
"from packageManager / lock file": "来自 packageManager / 锁文件",
"from ~/.ssh/config": "来自 ~/.ssh/config",
"func literal": "func 字面量",
"has been resolved and staged.": "已解决并暂存。",
"has uncommitted changes. Commit or roll them back before switching to auto-commit?": "有未提交的更改。切换到自动提交前要提交还是回滚这些更改?",
"host or ~/.ssh/config alias": "主机或 ~/.ssh/config 别名",
"if statement": "if 语句",
"impl block": "impl 块",
@@ -2365,7 +2329,6 @@
"not installed in this project": "此项目中未安装",
"occurrences ·": "个匹配项 ·",
"or click a line number to set a breakpoint.": "或点击行号设置断点。",
"or pick one in the toolbar.": "或在工具栏中选择一个。",
"per module, the JDK of its Java version": "按模块使用与其 Java 版本匹配的 JDK",
"the project JDK if new enough, else the first installed JDK that is": "项目 JDK 版本足够时使用它,否则使用第一个版本足够的已安装 JDK",
"pip output": "pip 输出",
@@ -2379,7 +2342,6 @@
"select all rows from a table": "从表中选择所有行",
"select specific rows from a table": "从表中选择特定行",
"select the number of specific rows in a table": "选择表中特定行的数量",
"stdin closed": "stdin 已关闭",
"surrounded text,": "被包围的文本,",
"the JavaScript debugger (vscode-js-debug)": "JavaScript 调试器 (vscode-js-debug)",
"the language server's own TypeScript": "语言服务器自带的 TypeScript",
@@ -2402,7 +2364,6 @@
"{name} is not installed": "{name} 未安装",
"· Conflicts": "· 冲突",
"· read-only": "· 只读",
"… more": "… 更多",
"↵ Open · ⇧↵ Open to the side · ⌘↵ Open in Find Window": "↵ 打开 · ⇧↵ 在侧边打开 · ⌘↵ 在查找窗口中打开",
"⌘↵ to open in Find tool window": "⌘↵ 在“查找”工具窗口中打开",
"⌥← / ⌥→ and ⌥⌫ stop at humps of camelCase names.": "⌥← / ⌥→ 和 ⌥⌫ 会在 camelCase 名称的驼峰处停止。",
@@ -2733,8 +2694,6 @@
"Client key file:": "客户端密钥文件:",
"Client Key File": "客户端密钥文件",
"schemas (databases)": "架构(数据库)",
"Show system schemas and template databases": "显示系统架构和模板数据库",
"Show system schemas": "显示系统架构",
"Load Names from Server": "从服务器加载名称",
"Driver properties": "驱动程序属性",
"Property name": "属性名称",
@@ -3055,7 +3014,7 @@
"Unresolved database references": "未解析的数据库引用",
"Reports tables, columns and aliases in query consoles that the data source's schema does not contain.": "报告查询控制台中数据源架构不包含的表、列和别名。",
"Proofreading": "校对",
"Reports misspelt words in comments, string literals and the names declarations introduce (camelCase and snake_case parts checked separately), and in plain text and Markdown. Words can be saved to the project or application dictionary (Editor › Natural Languages › Spelling).": "报告注释、字符串字面量和声明引入的名称(camelCase 和 snake_case 的各部分分别检查)以及纯文本和 Markdown 中拼写错误的单词。单词可以保存到项目词典或应用程序词典(编辑器 › 自然语言 › 拼写)。",
"Reports misspelt words in comments, string literals and the names declarations introduce (camelCase and snake_case parts checked separately), and in plain text and Markdown. Agent nouns of known words (checkpointer) and, in names, two known words run together (filepath) are accepted. Words can be saved to the project or application dictionary (Editor › Natural Languages › Spelling). Correcting a name renames the symbol and its references.": "报告注释、字符串字面量和声明引入的名称(camelCase 和 snake_case 的各部分分别检查)以及纯文本和 Markdown 中拼写错误的单词。已知单词的施动名词(checkpointer)以及名称中连写的两个已知单词(filepath)视为正确。单词可以保存到项目词典或应用程序词典(编辑器 › 自然语言 › 拼写)。更正名称会重命名该符号及其引用。",
"English (USA)": "英语(美国)",
"Bundled Hunspell dictionary (SCOWL en_US) and common programming terms.": "捆绑的 Hunspell 词典 (SCOWL en_US) 和常用编程术语。",
"Used by Proofreading › Typo": "由“校对 › 拼写错误”使用",
@@ -3233,9 +3192,7 @@
"Prune {target}": "清理{target}",
"Prune {target}…": "清理{target}…",
"Pruning {target}…": "正在清理 {target}…",
"Pruning {target}": "清理 {target}",
"Pulling {name}…": "正在拉取 {name}…",
"Pulling {name}": "拉取 {name}",
"containers": "容器",
"images": "镜像",
"volumes": "卷",
@@ -3281,7 +3238,6 @@
"Thinking": "思考过程",
"Plan": "计划",
"Message": "消息",
"The agent is working. You can type your next message.": "Agent 正在处理,可以先写下一条消息。",
"Reply to the agent": "回复 agent",
"Send": "发送",
"vs": "对比",
@@ -3289,7 +3245,6 @@
"files": "个文件",
"No changes yet": "还没有改动",
"What should the agent do?": "让 agent 做点什么?",
"Describe the task": "描述任务",
"New worktree": "新 worktree",
"Starting…": "正在启动…",
"Waiting for your answer": "等待你的回答",
@@ -3374,5 +3329,326 @@
"Attach to a Node.js process started with --inspect here or on another machine": "附加到以 --inspect 启动的 Node.js 进程(本机或其他机器)",
"Copied": "已复制",
"'{name}' can only be debugged": "'{name}' 只能调试",
"It attaches the debugger to a process started elsewhere.": "它将调试器附加到在别处启动的进程。"
"It attaches the debugger to a process started elsewhere.": "它将调试器附加到在别处启动的进程。",
"Not found, press again to search from the top": "未找到,再按一次从顶部开始搜索",
"Cannot change the setting": "无法更改该设置",
"Increase Font Size": "增大字体",
"Decrease Font Size": "减小字体",
"Cannot make {path} writable": "无法将 {path} 设为可写",
"Cannot make {path} read-only": "无法将 {path} 设为只读",
"Configure Soft Wraps…": "配置软换行…",
"Configure Gutter Icons…": "配置装订区域图标…",
"line[:column]": "行[:列]",
"Edit Source": "编辑源代码",
"Show in Documentation Tool Window": "在文档工具窗口中显示",
"No documentation": "无文档",
"Whole file": "整个文件",
"Selected text": "所选文本",
"Code Cleanup on `{ path, fixAll?, optimizeImports?, reformat? }` (all steps by default), opened first.": "对 `{ path, fixAll?, optimizeImports?, reformat? }` 执行代码清理(默认执行全部步骤),先打开该文件。",
"Shows `{ text, tone? }` as a transient hint at the caret of the active editor.": "在活动编辑器的光标处以临时提示显示 `{ text, tone? }`。",
"Inlay Hints Settings…": "嵌入提示设置…",
"Preview isn't available for this action": "此操作不支持预览",
"No changes in this file": "此文件中没有更改",
"{kind}: no language server is running for this file": "{kind}:此文件没有正在运行的语言服务器",
"Cannot find declaration of '{label}'": "找不到 '{label}' 的声明",
"Rename in place: ↵ to finish, Esc to cancel": "就地重命名:按 ↵ 完成,按 Esc 取消",
"Cannot rename safely: {why}. '{word}' was left unchanged": "无法安全重命名:{why}。'{word}' 保持不变",
"'{newName}' is not a valid identifier": "'{newName}' 不是有效的标识符",
"{note}: renamed {length} occurrence": "{note}:已重命名 {length} 处",
"{note}: renamed {length} occurrences": "{note}:已重命名 {length} 处",
"No suggestions for '{word}'": "没有 '{word}' 的建议",
"Typo: Rename to…": "拼写错误:重命名为…",
"Cannot perform refactoring: {why}": "无法执行重构:{why}",
"'{chosen}' is not a valid name; kept '{current}'": "'{chosen}' 不是有效的名称;保留 '{current}'",
"'{name}' is also used elsewhere in this file": "'{name}' 也在此文件的其他位置使用",
"Safe Delete": "安全删除",
"Replace all occurrences": "替换所有匹配项",
"↵ to finish, Esc to keep the name": "按 ↵ 完成,按 Esc 保留名称",
"Agent": "智能体",
"Isolation": "隔离方式",
"Opens the New Task page; a string `arg` pre-fills the task description.": "打开“新建任务”页面;字符串 `arg` 会预先填入任务描述。",
"Adds the editor selection (or the file) as an @ reference to the agent message typed last; a string[] `arg` sends those paths.": "将编辑器选区(或文件)作为 @ 引用添加到最近输入的智能体消息中;string[] 类型的 `arg` 会发送这些路径。",
"Files are checked by their language servers; files without one are skipped.": "文件由各自的语言服务器检查;没有语言服务器的文件将被跳过。",
"Files are cleaned up by their language servers and saved; files without one are skipped.": "文件由各自的语言服务器清理并保存;没有语言服务器的文件将被跳过。",
"Code Cleanup cancelled after {done} of {length} files": "代码清理已在处理 {done}/{length} 个文件后取消",
"Code Cleanup processed {done} files": "代码清理已处理 {done} 个文件",
"Load Maven Changes": "加载 Maven 更改",
"Load Gradle Changes": "加载 Gradle 更改",
"recent": "最近",
"Shows `{ symbol, locations }` (found elsewhere, e.g. by Safe Delete) in the Find Usages tool window.": "在“查找用法”工具窗口中显示 `{ symbol, locations }`(由其他功能找到,例如安全删除)。",
"Code insight features are unavailable for these files until it is installed.": "安装之前,这些文件无法使用代码洞察功能。",
"Coverage of '{name}': {totals} lines": "'{name}' 的覆盖率:{totals} 行",
"Show a report collected elsewhere (CI): lcov, JaCoCo XML or a Go cover profile; argument: the file path": "显示在其他地方(CI)收集的报告:lcov、JaCoCo XML 或 Go cover profile;参数:文件路径",
"Imported coverage '{name}': {total} lines": "已导入覆盖率 '{name}':{total} 行",
"The report covers no files of this project.": "该报告不包含此项目的任何文件。",
"Cannot import {file}": "无法导入 {file}",
"shown": "已显示",
"No aggregation": "不聚合",
"Sum": "求和",
"Mean": "平均值",
"Count": "计数",
"Min": "最小值",
"Max": "最大值",
"X axis": "X 轴",
"Y axis": "Y 轴",
"Aggregation": "聚合",
"Chart type": "图表类型",
"Bar": "柱状图",
"Line": "折线图",
"Chart Settings": "图表设置",
"No numeric values to plot": "没有可绘制的数值",
"Search": "搜索",
"Statements": "语句",
"No statements": "没有语句",
"Statement": "语句",
"Comma": "逗号",
"Tab": "制表符",
"Semicolon": "分号",
"Pipe": "竖线",
"Import Data from File": "从文件导入数据",
"Cannot read the file": "无法读取该文件",
"{table}: {n} row(s) imported": "{table}:已导入 {n} 行",
"Nothing was imported": "未导入任何内容",
"Choose a CSV or TSV file": "选择 CSV 或 TSV 文件",
"Choose File…": "选择文件…",
"Separator:": "分隔符:",
"Separator": "分隔符",
"First row is header (columns matched by name)": "第一行为标题(按名称匹配列)",
"Treat empty values as NULL": "将空值视为 NULL",
"Columns:": "列:",
"Export Data…": "导出数据…",
"Data extractor": "数据提取器",
"Hide Record / Value / Aggregates": "隐藏记录 / 值 / 聚合",
"Show Record / Value / Aggregates": "显示记录 / 值 / 聚合",
"Clear local filter": "清除本地筛选",
"Search values": "搜索值",
"No matching values": "没有匹配的值",
"Clear Filter": "清除筛选",
"Clear Local Filter For All Columns": "清除所有列的本地筛选",
"Value panel": "值面板",
"Aggregates": "聚合",
"Select a cell": "选择一个单元格",
"Copy to Clipboard": "复制到剪贴板",
"Export to File": "导出到文件",
"Source:": "源:",
"Extractor:": "提取器:",
"Extractor": "提取器",
"Transpose": "转置",
"Add column header": "添加列标题",
"Add row header": "添加行标题",
"Output file:": "输出文件:",
"Output file": "输出文件",
"Export preview:": "导出预览:",
"Export preview": "导出预览",
"expression": "表达式",
"Chart": "图表",
"Explain Again": "重新解释",
"Operation": "操作",
"Params": "参数",
"Query plan": "查询计划",
"Empty plan": "空计划",
"Sent as run-time parameters when connecting (any server setting, e.g. statement_timeout). application_name names the session; connect_timeout is in seconds.": "连接时作为运行时参数发送(任意服务器设置,例如 statement_timeout)。application_name 为会话命名;connect_timeout 以秒为单位。",
"Set as session variables after connecting (SET SESSION name = value). charset and collation pick the connection character set; connect_timeout is in seconds.": "连接后设置为会话变量(SET SESSION name = value)。charset 和 collation 选择连接字符集;connect_timeout 以秒为单位。",
"Applied as pragmas when opening the file (PRAGMA name = value).": "打开文件时作为 pragma 应用(PRAGMA name = value)。",
"sec.": "秒",
"default": "默认",
"<unchanged>": "<未更改>",
"Single database mode (show only the configured database)": "单数据库模式(仅显示配置的数据库)",
"databases": "数据库",
"schemas": "架构",
"Object filter:": "对象筛选:",
"e.g. order*, customers (tables, views, routines, sequences)": "例如 order*、customers(表、视图、例程、序列)",
"Show internal system schemas": "显示内部系统架构",
"Show template databases": "显示模板数据库",
"<user defined>": "<用户定义>",
"<value>": "<值>",
"{table}: {n} row(s) changed": "{table}:已更改 {n} 行",
"Import Data from File…": "从文件导入数据…",
"Explain Plan": "解释计划",
"Browse Query History": "浏览查询历史记录",
"<data source>": "<数据源>",
"Cannot explain the statement": "无法解释该语句",
"Cannot get the definition of {name}": "无法获取 {name} 的定义",
"Cannot copy the {what}": "无法复制 {what}",
"Script finished: {length} statement": "脚本已完成:{length} 条语句",
"Script finished: {length} statements": "脚本已完成:{length} 条语句",
"Import from Clipboard": "从剪贴板导入",
"No data source on the clipboard": "剪贴板中没有数据源",
"Import/Export": "导入/导出",
"{what} is not supported by {debugger}": "{debugger} 不支持{what}",
"'{name}': listening for the remote JVM on port {port}": "'{name}':正在端口 {port} 上监听远程 JVM",
"“{name}” can't be debugged": "无法调试“{name}”",
"It has no debug adapter.": "它没有调试适配器。",
"Attach the Java debugger to a JVM listening for JDWP (arg: { name, module, hostName, port, process })": "将 Java 调试器附加到监听 JDWP 的 JVM(参数:{ name, module, hostName, port, process })",
"'{name}' has compile errors; debugging the last compiled classes": "'{name}' 存在编译错误;将调试上次编译的类",
"Attach to Godot": "附加到 Godot",
"Debug the game the Godot editor is running, through the editor's debug adapter": "通过 Godot 编辑器的调试适配器调试编辑器正在运行的游戏",
"Before attaching": "附加之前",
"Cannot start debugger for {name}": "无法为 {name} 启动调试器",
"suspended": "已挂起",
"e.g. order.total > 100": "例如 order.total > 100",
"e.g. 5 or >= 3": "例如 5 或 >= 3",
"Value: {expression}": "值:{expression}",
"Cannot attach to {name} ({pid})": "无法附加到 {name} ({pid})",
"“{name}” can't be watched": "无法监视“{name}”",
"(deleted)": "(已删除)",
"'{head}' is the default branch": "'{head}' 是默认分支",
"Macro '{name}' stopped": "宏 '{name}' 已停止",
"Id": "ID",
"Enable": "启用",
"{name}: the editor is read-only": "{name}:编辑器为只读",
"{name}: no editor to insert into": "{name}:没有可插入的编辑器",
"The plugin failed to start.": "插件启动失败。",
"Move Directory…": "移动目录…",
"Cannot move {name}": "无法移动 {name}",
"Cannot rename {name}": "无法重命名 {name}",
"Store as project file (.openidea/run.toml); otherwise in the workspace (.openidea/run.local.toml)": "存储为项目文件(.openidea/run.toml);否则存储在工作区中(.openidea/run.local.toml)",
"This command line doesn't fit the type's form; it is edited as a command.": "此命令行不符合该类型的表单,将作为命令进行编辑。",
"Space separated; quote with ' or \"": "以空格分隔;可用 ' 或 \" 加引号",
"New configurations of this type start with these values.": "此类型的新配置以这些值开始。",
"To run your code, do one of the following:": "要运行代码,请执行以下操作之一:",
"The terminal is not available; turn off \"Emulate terminal in output console\" to see the output.": "终端不可用;请关闭“在输出控制台中模拟终端”以查看输出。",
"Expected": "预期",
"Actual": "实际",
"Terminate": "终止",
"Cannot run '{name}'": "无法运行 '{name}'",
"External tool '{name}' has no program": "外部工具 '{name}' 未设置程序",
"'{name}' needs an open file": "'{name}' 需要一个已打开的文件",
"Run a configuration (hold Shift to debug); the title bar widget passes \"select\" to only select one": "运行配置(按住 Shift 进行调试);标题栏小部件传入 \"select\" 时仅选择配置",
"Runs with a contributed executor (`{ executor, config? }` or `{ executor, context }`): the given or selected configuration, or the context.": "使用贡献的执行器运行(`{ executor, config? }` 或 `{ executor, context }`):给定或所选的配置,或者上下文。",
"Saves the given `RunConfig` as a user configuration and opens it in Edit Configurations.": "将给定的 `RunConfig` 保存为用户配置,并在“编辑配置”中打开。",
"No sources for this class": "此类没有源代码",
"Error running '{name}'": "运行 '{name}' 时出错",
"No JDK can run '{name}'": "没有可以运行 '{name}' 的 JDK",
"'{name}' exited with code {code}": "'{name}' 已退出,退出代码为 {code}",
"Run a Godot project's main scene or a chosen scene": "运行 Godot 项目的主场景或所选场景",
"Project directory": "项目目录",
"Project root (holds project.godot)": "项目根目录(包含 project.godot)",
"Scene": "场景",
"Main scene": "主场景",
"Godot command line options, e.g. --debug-collisions": "Godot 命令行选项,例如 --debug-collisions",
"Bookmark description": "书签描述",
"Cannot open {path}": "无法打开 {path}",
"Replace All (⇧⌥↵, ⌥A)": "全部替换 (⇧⌥↵, ⌥A)",
"Search context": "搜索上下文",
"not": "非",
"and": "与",
"or": "或",
"grouping": "分组",
"Cannot log in to {name}": "无法登录到 {name}",
"Argument: `containers`, `images`, `allImages`, `volumes`, `networks` or `system` (default).": "参数:`containers`、`images`、`allImages`、`volumes`、`networks` 或 `system`(默认)。",
"Force (also untag / remove when used by stopped containers)": "强制(被已停止的容器使用时也取消标记 / 移除)",
"Start the services of Compose files": "启动 Compose 文件中的服务",
"Saved to .openidea/settings.toml in this project; overrides the global value.": "保存到此项目的 .openidea/settings.toml 中;覆盖全局值。",
"custom": "自定义",
"Resolving the latest build…": "正在解析最新构建…",
"Download JDK": "下载 JDK",
"Download": "下载",
"Vendor:": "供应商:",
"Vendor": "供应商",
"Version:": "版本:",
"Select a version": "选择版本",
"JDK Location": "JDK 位置",
"Downloading JDK": "正在下载 JDK",
"Use ; to separate name patterns, * for any number of symbols, ? for one.": "使用 ; 分隔名称模式,* 匹配任意数量的字符,? 匹配单个字符。",
"Folders are detected from build files (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json); marking or unmarking a folder overrides detection. Excluded folders are skipped by the Project view, Find in Files and the index (reopen the project to re-index).": "文件夹根据构建文件(pom.xml、build.gradle、Cargo.toml、go.mod、pyproject.toml、package.json)检测;标记或取消标记文件夹会覆盖检测结果。项目视图、在文件中查找和索引会跳过已排除的文件夹(重新打开项目以重新索引)。",
"Project virtualenv (auto-detect)": "项目 virtualenv(自动检测)",
"<No interpreter>": "<无解释器>",
"Package name or requirement, e.g. requests or django==5.1": "软件包名称或需求,例如 requests 或 django==5.1",
"Download JDK…": "下载 JDK…",
"interpreter": "解释器",
"Side tool windows take the full height; the bottom ones fit between them": "侧边工具窗口占满整个高度;底部工具窗口位于两者之间",
"Days on which files changed; older revisions are removed when a project opens.": "按文件有更改的天数计算;打开项目时会删除更早的修订。",
"Language of menus and dialogs; untranslated text stays in English.": "菜单和对话框的语言;未翻译的文本保持英文。",
"Unix and macOS (\\n)": "Unix 和 macOS (\\n)",
"Classic Mac OS (\\r)": "经典 Mac OS (\\r)",
"Encoding of new files; decodes project files that are not valid UTF-8 and have no BOM.": "新文件的编码;也用于解码不是有效 UTF-8 且没有 BOM 的项目文件。",
"Stored in the IDE; used by projects without their own scheme.": "存储在 IDE 中;供没有自己方案的项目使用。",
"Semantic highlighting": "语义高亮",
"Local variables and parameters get a colour derived from their name (needs a language server).": "局部变量和参数使用根据其名称生成的颜色(需要语言服务器)。",
"Rainbow brackets": "彩虹括号",
"Color (), [] and {} by nesting depth; unmatched brackets use the error color.": "按嵌套深度为 ()、[] 和 {} 着色;不匹配的括号使用错误颜色。",
"Main font weight": "主字重",
"Bold font weight": "粗体字重",
"Used wherever the color scheme shows text in bold": "用于配色方案中所有以粗体显示文本的地方",
"Use ; to separate patterns. * matches every file.": "使用 ; 分隔模式。* 匹配所有文件。",
"Function and method suggestions get (); the caret goes inside unless there are no parameters.": "函数和方法建议会补全 ();除非没有参数,否则光标置于括号内。",
"Insert paired brackets (), [], {}": "插入成对括号 ()、[]、{}",
"word": "单词",
"Runs of consecutive matching lines collapse into one expandable “<N internal lines>” row.": "连续匹配的多行会折叠为一个可展开的“<N internal lines>”行。",
"Confirm closing a tab with a running process": "关闭有正在运行进程的标签页时确认",
"value": "值",
"Login shell": "登录 Shell",
"Terminal column width": "终端列宽",
"e.g. /usr/bin/env": "例如 /usr/bin/env",
"Force push is not allowed to these branches. Separate patterns with ; (wildcards * and ? are supported).": "不允许强制推送到这些分支。使用 ; 分隔模式(支持通配符 * 和 ?)。",
"Adds a Signed-off-by trailer by default; it can still be switched per commit in Commit Options.": "默认添加 Signed-off-by 尾注;仍可在“提交选项”中针对每次提交切换。",
"Configure Live Templates…": "配置实时模板…",
"Update Tag with Emmet": "使用 Emmet 更新标签",
"Created {fileName}": "已创建 {fileName}",
"No tag at the caret": "光标处没有标签",
"Cannot update the tag": "无法更新标签",
"Templates of this project only": "仅限此项目的模板",
"none": "无",
"Opens a terminal tab running the shell at `arg` (a path from `termAvailableShells`).": "打开一个运行 `arg` 处 Shell 的终端标签页(`termAvailableShells` 中的路径)。",
"Opens a terminal tab running `{ program, args, name?, cwd? }` instead of the shell.": "打开一个运行 `{ program, args, name?, cwd? }` 而不是 Shell 的终端标签页。",
"TODO items in files of a changelist": "更改列表中文件的 TODO 项",
"Too many matches; showing the first 10 000.": "匹配项过多;仅显示前 10 000 个。",
"{name} downloaded": "{name} 已下载",
"The Java language server restarts on it.": "Java 语言服务器将使用它重新启动。",
"Failed to download JDK {version}": "下载 JDK {version} 失败",
"Java Settings…": "Java 设置…",
"{name} needs JDK {version} to run": "{name} 需要 JDK {version} 才能运行",
"Failed to set the path of {command}": "设置 {command} 的路径失败",
"Search for branches, actions, repositories": "搜索分支、操作、仓库",
"Git Settings": "Git 设置",
"Repositories and branches": "仓库和分支",
"Name <email>; empty uses the configured Git user": "姓名 <邮箱>;留空则使用已配置的 Git 用户",
"Amend and Push…": "修正并推送…",
"Select revisions of one file to compare them": "选择同一文件的修订以进行比较",
"local": "本地",
"remote": "远程",
"tag": "标签",
"revision": "修订",
"{success}, with conflicts": "{success},但存在冲突",
"As new branch": "作为新分支",
"A rebase is in progress. The commit will become part of the rebased history; usually you continue the rebase instead.": "正在进行变基。此提交将成为变基后历史的一部分;通常应改为继续变基。",
"HEAD is detached: the commit won't belong to any branch and may be lost after checking out another branch. Create a branch first to keep it.": "HEAD 处于分离状态:此提交不属于任何分支,签出其他分支后可能会丢失。请先创建分支以保留它。",
"Opens the diff viewer for a `DiffData` argument (e.g. a pull request file).": "为 `DiffData` 参数打开差异查看器(例如拉取请求中的文件)。",
"From": "从",
"To": "到",
"Created worktree at {trim}": "已在 {trim} 创建工作树",
"No web URL for remote '{remote}'": "远程 '{remote}' 没有 Web URL",
"'{rev}' was not found in the log": "在日志中找不到 '{rev}'",
"Compare Versions": "比较版本",
"Select two commits to compare": "选择两个提交进行比较",
"Label '{value}' added to Local History": "已将标签 '{value}' 添加到本地历史记录",
"No {noun} in progress": "没有正在进行的 {noun}",
"{doneTitle} successful": "{doneTitle}成功",
"{file} updated in {commit}": "已在 {commit} 中更新 {file}",
"Shelved {length} file": "已搁置 {length} 个文件",
"Shelved {length} files": "已搁置 {length} 个文件",
"{what}: {length} file with conflicts": "{what}:{length} 个文件存在冲突",
"{what}: {length} files with conflicts": "{what}:{length} 个文件存在冲突",
"{what}: {n} file changed": "{what}:已更改 {n} 个文件",
"{what}: {n} files changed": "{what}:已更改 {n} 个文件",
"Built-in Preview": "内置预览",
"Cannot open the browser": "无法打开浏览器",
"Browser": "浏览器",
"Default Browser": "默认浏览器",
"Open the HTML or SVG file in the default browser through the built-in server": "通过内置服务器在默认浏览器中打开 HTML 或 SVG 文件",
"Show the HTML file rendered beside the editor": "在编辑器旁显示 HTML 文件的渲染结果",
"Project folder not found: {name}": "找不到项目文件夹:{name}",
"Cannot open {name}": "无法打开 {name}",
"Cannot reopen {name}": "无法重新打开 {name}",
"Edit inspection profile setting": "编辑检查配置文件设置",
"Disable inspection": "禁用检查",
"Change Severity": "更改严重性",
"Edit Inspection Profile Setting…": "编辑检查配置文件设置…",
"Compiler errors and warnings of the last Build Project, shown at their source positions.": "上次“构建项目”产生的编译器错误和警告,显示在对应的源代码位置。",
"Process code": "处理代码",
"Process literals": "处理字面量",
"Process comments": "处理注释",
"Distraction Free Mode": "无干扰模式",
"Exit Distraction Free Mode": "退出无干扰模式"
}
+445
Переглянути файл
@@ -0,0 +1,445 @@
// @vitest-environment node
/**
* Keeps the source-text catalogs (`locales/text/<locale>.json`) in step with the
* English text written at call sites. Their keys are the English text itself, so
* rewording a string at its call site silently drops its translation; these tests
* fail instead, and also on catalog entries whose text no longer exists.
*
* Text counts as translatable when it is a literal (or a branch of `?:` / `??` /
* `||` around one) that reaches the translation layer directly:
* - the first argument of `tx` / `txTemplate`, or of a function bound from
* `useTx()` / `useTxTemplate()` in the same file;
* - the plain-text children of `<T>` and the other `TEXT_CHILDREN` primitives;
* - a `TEXT_PROPS` attribute of a component (`<Row hint="…">`), and `data-tooltip`;
* - a `TEXT_PROPS` property of an object literal (`{ label: "…" }`): actions, menu
* items, select options, dialogs, notifications, settings pages, tool windows;
* - the text arguments of `showHint` and `showError`.
* Template literals (`Cannot open ${path}`) are checked only where the text is
* matched against `{name}` templates (`txTemplate`, hints, notification titles);
* elsewhere the lookup is exact and they cannot be translated as written.
*
* Not seen: text kept in a variable or built by a helper before it reaches `tx`,
* and text sent by the backend. Their entries count as used (not stale) as long as
* the text appears as a literal anywhere in `src/`, the Rust crates or `languages/`.
*/
import { readFileSync, readdirSync } from "node:fs";
import { fileURLToPath } from "node:url";
import ts from "typescript";
import { describe, expect, it } from "vitest";
const ROOT = fileURLToPath(new URL("../../../", import.meta.url));
const TEXT_DIR = new URL("./text/", import.meta.url);
/** Props / object keys whose string value the UI passes through `tx`. */
const TEXT_PROPS = new Set([
"aria-label",
"body",
"cancelLabel",
"category",
"checkbox",
"description",
"detail",
"emptyLabel",
"hint",
"label",
"message",
"ok",
"okLabel",
"placeholder",
"text",
"title",
"tooltip",
]);
/** Components whose plain-text children are translated. */
const TEXT_CHILDREN = new Set(["T", "Button", "Dialog"]);
const HINTS = new Set(["showHint"]);
const ERRORS = new Set(["showError"]);
const NOTIFY = new Set(["notify"]);
/** Code templates shown as written, and the in-memory backends of plain-browser development. */
const UNCHECKED_FILES = new Set([
"src/editor/core/backend.ts",
"src/features/plugins/backend.ts",
"src/features/tools/backend.ts",
"src/features/templates/files/builtins.ts",
"src/features/templates/live/builtins.ts",
"src/features/templates/live/surrounders.ts",
"src/features/templates/postfix/model.ts",
]);
/** Entries for text the code assembles from parts, which no literal spells out. */
const BUILT_AT_RUNTIME = new Set([
"Unused Containers", // `Unused ${group}` in services/ops.ts
]);
/** Text that stays as written in every locale: names, code, formats, shortcuts. */
const UNTRANSLATED = new Set<string>([
// Products, tools and formats
"Amazon Aurora MySQL",
"Amazon Redshift",
"Cargo Check",
"Clippy",
"CockroachDB",
"CodeLLDB",
"CodeLLDB (Rust, C, C++)",
"CSV",
"debugpy",
"debugpy (Python)",
"Delve",
"Delve (Go)",
"Docker",
"Docker Compose",
"Dockerfile",
"Eclipse Temurin",
"EditorConfig",
"Git",
"GitHub",
"Go",
"Godot",
"Gradle",
"Greenplum",
"Java",
"java-debug (Java)",
"js-debug (Node.js / TypeScript)",
"JSON",
"lldb-dap (C, C++, Swift)",
"MariaDB",
"Markdown",
"Maven",
"MySQL",
"Neon",
"Node.js",
"npm",
"OpenIDEA",
"PostgreSQL",
"Rust",
"Rustfmt",
"SingleStore",
"SQLite",
"Supabase",
"TiDB",
"TimescaleDB",
"TSV",
"TypeScript",
"Vim",
"YugabyteDB",
// Key names, shortcuts and terms that read the same in Chinese UIs
"<null>",
"Backspace",
"Code Vision",
"Enter",
"Fixup",
"Fixup…",
"IDE",
"mod tests",
"Windows (\\r\\n)",
// Language names, written in their own language
"English",
"简体中文 (Chinese, Simplified)",
// Terms, keywords and acronyms kept in English
"DDL",
"GOPATH",
"GOROOT",
"HEAD",
"JDK",
"JDK 1.4.x",
"JDK 5 - 8",
"LTS",
"NULL",
"ORDER BY",
"SDK",
"SSH/SSL",
"SSL",
"TODO",
"URL",
"VCS",
"WHERE",
"WIP",
// Code, commands and example values
'"value"',
"at org.example.",
"bastion.example.com",
"build --info",
"className()",
"clean install -DskipTests",
"com.example.Service#process, main.run, parse",
"docker-compose.yml; docker-compose.override.yml",
"file:src//*&&!file:*test*",
"git pull --no-rebase --ff",
"git pull --rebase",
"go env GOPATH",
"kebab-case",
"KEY=value; OTHER=value",
"NAME",
"node_modules/typescript",
"PascalCase",
"snake_case",
// Identifiers that only look like text: icon names, error codes, categories, console output
"app",
"cancelled",
"fileTypes/text",
"info",
"languageServer",
"process",
"read-only",
"Running processes requires the desktop app.\n",
"text",
]);
interface Use {
text: string;
at: string;
template: boolean;
}
function walk(dir: string, accept: (path: string) => boolean, out: string[] = []): string[] {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const path = `${dir}/${entry.name}`;
if (entry.isDirectory()) {
if (entry.name !== "node_modules" && entry.name !== "target") walk(path, accept, out);
} else if (accept(path)) out.push(path);
}
return out;
}
const isTest = (path: string) => /\.test\.tsx?$|\/__tests__\/|\/src\/test\//.test(path);
const ENTITIES: Record<string, string> = { amp: "&", apos: "'", quot: '"', lt: "<", gt: ">", nbsp: "\u00a0" };
function decodeEntities(s: string): string {
return s.replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (m, e: string) => {
if (e[0] === "#")
return String.fromCodePoint(e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : Number(e.slice(1)));
return ENTITIES[e] ?? m;
});
}
/** JSX text as React renders it: lines trimmed, blank ones dropped, the rest joined with a space. */
function jsxText(raw: string): string {
const lines = raw.split(/\r?\n/);
if (lines.length === 1) return decodeEntities(raw).trim();
return decodeEntities(
lines
.map((l) => l.trim())
.filter(Boolean)
.join(" "),
);
}
const unwrap = (e: ts.Expression): ts.Expression => (ts.isParenthesizedExpression(e) ? unwrap(e.expression) : e);
/**
* Template literal text with each `${expr}` as `{name}`; a `${c ? "a" : "b"}` part
* yields one text per branch (`Formatted {n} line` / `Formatted {n} lines`).
*/
function templateTexts(node: ts.TemplateExpression): string[] {
let out = [node.head.text];
for (const span of node.templateSpans) {
const e = unwrap(span.expression);
let parts: string[];
if (
ts.isConditionalExpression(e) &&
ts.isStringLiteralLike(unwrap(e.whenTrue)) &&
ts.isStringLiteralLike(unwrap(e.whenFalse))
)
parts = [(unwrap(e.whenTrue) as ts.StringLiteralLike).text, (unwrap(e.whenFalse) as ts.StringLiteralLike).text];
else {
const words = span.expression.getText().match(/[A-Za-z_]\w*/g) ?? ["value"];
parts = [`{${words[words.length - 1]}}`];
}
out = out.flatMap((head) => parts.map((part) => head + part + span.literal.text));
}
return out;
}
/** `{anything}` → `{}`, so templates compare regardless of placeholder names. */
const shape = (text: string) => text.replace(/\{[^{}]*\}/g, "{}");
const tagName = (node: ts.JsxOpeningLikeElement) => node.tagName.getText();
const isComponent = (tag: string) => /^[A-Z]/.test(tag) || tag.includes(".");
/** Climbs through expressions that pass a string operand through unchanged. */
function passThrough(node: ts.Node): ts.Node {
let n = node;
for (;;) {
const p = n.parent;
if (
p &&
(ts.isParenthesizedExpression(p) ||
ts.isAsExpression(p) ||
ts.isSatisfiesExpression(p) ||
(ts.isConditionalExpression(p) && p.condition !== n) ||
(ts.isBinaryExpression(p) &&
(p.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken ||
p.operatorToken.kind === ts.SyntaxKind.BarBarToken ||
(p.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken && p.right === n))))
) {
n = p;
continue;
}
return n;
}
}
function propName(name: ts.PropertyName | ts.JsxAttributeName): string | undefined {
return ts.isIdentifier(name) || ts.isStringLiteral(name) ? name.text : undefined;
}
type Sink = "exact" | "template";
const isCallTo = (call: ts.CallExpression, names: Set<string>) => {
const callee = call.expression;
const name = ts.isIdentifier(callee) ? callee.text : ts.isPropertyAccessExpression(callee) ? callee.name.text : "";
return names.has(name);
};
/**
* How the text at `node` is translated: `exact` (catalog lookup of the whole
* text), `template` (also matches `{name}` templates, see `txTemplate`), or not at all.
*/
function sinkOf(node: ts.Node, exact: Set<string>, template: Set<string>): Sink | undefined {
const top = passThrough(node);
const p = top.parent;
if (!p) return undefined;
if (ts.isCallExpression(p)) {
const i = p.arguments.indexOf(top as ts.Expression);
if (i === 0 && isCallTo(p, template)) return "template";
if (i === 0 && isCallTo(p, exact)) return "exact";
if (i === 1 && isCallTo(p, HINTS)) return "template";
if (i >= 0 && i <= 1 && isCallTo(p, ERRORS)) return "exact";
return undefined;
}
if (ts.isPropertyAssignment(p)) {
const name = propName(p.name) ?? "";
if (p.initializer !== top || !TEXT_PROPS.has(name)) return undefined;
const call = p.parent.parent;
// Notification titles go through `txTemplate`.
if (name === "title" && ts.isCallExpression(call) && isCallTo(call, NOTIFY)) return "template";
return "exact";
}
let attr: ts.Node = p;
if (ts.isJsxExpression(p)) {
if (ts.isJsxElement(p.parent)) return TEXT_CHILDREN.has(tagName(p.parent.openingElement)) ? "exact" : undefined;
attr = p.parent;
}
if (ts.isJsxAttribute(attr)) {
const name = propName(attr.name) ?? "";
if (name === "data-tooltip") return "exact";
return TEXT_PROPS.has(name) && isComponent(tagName(attr.parent.parent)) ? "exact" : undefined;
}
if (ts.isJsxElement(p)) return TEXT_CHILDREN.has(tagName(p.openingElement)) ? "exact" : undefined;
return undefined;
}
interface Scan {
/** Literals that reach the translation layer. */
translated: Use[];
/** Every string literal and JSX text, in shape form. */
literals: Set<string>;
}
function scanTypeScript(): Scan {
const translated: Use[] = [];
const literals = new Set<string>();
const files = walk(`${ROOT}src`, (p) => /\.tsx?$/.test(p) && !isTest(p) && !p.endsWith("/bindings.ts"));
for (const file of files) {
const path = file.slice(ROOT.length);
const source = readFileSync(file, "utf8");
const sf = ts.createSourceFile(
file,
source,
ts.ScriptTarget.Latest,
true,
file.endsWith("x") ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
);
const exact = new Set(["tx"]);
const template = new Set(["txTemplate"]);
for (const m of source.matchAll(/(?:const|let)\s+(\w+)\s*=\s*useTx(Template)?\(\)/g))
(m[2] ? template : exact).add(m[1]!);
const checked = !UNCHECKED_FILES.has(path);
const visit = (node: ts.Node) => {
let texts: string[] | undefined;
if (ts.isStringLiteral(node) && ts.isJsxAttribute(node.parent)) texts = [decodeEntities(node.text)];
else if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) texts = [node.text];
else if (ts.isTemplateExpression(node)) texts = templateTexts(node);
else if (ts.isJsxText(node)) texts = [jsxText(node.text)].filter(Boolean);
if (texts) {
for (const text of texts) {
literals.add(shape(text));
literals.add(shape(text.trim()));
}
const sink = checked ? sinkOf(node, exact, template) : undefined;
// A template literal only matches a catalog entry where templates are looked up.
if (sink && (sink === "template" || !ts.isTemplateExpression(node))) {
const at = `${path}:${sf.getLineAndCharacterOfPosition(node.getStart()).line + 1}`;
for (const text of texts) translated.push({ text, at, template: ts.isTemplateExpression(node) });
}
}
ts.forEachChild(node, visit);
};
visit(sf);
}
return { translated, literals };
}
/** String literals of the Rust crates and language definitions (backend messages). */
function scanBackend(literals: Set<string>) {
const files = [
...walk(`${ROOT}crates`, (p) => p.endsWith(".rs")),
...walk(`${ROOT}src-tauri/src`, (p) => p.endsWith(".rs")),
...walk(`${ROOT}languages`, (p) => p.endsWith(".toml")),
];
for (const file of files)
for (const m of readFileSync(file, "utf8").matchAll(/"((?:[^"\\]|\\.)*)"/g)) literals.add(shape(m[1]!));
}
/** Text that needs no translation: no words, a path / glob / option, or listed in `UNTRANSLATED`. */
function needsTranslation(text: string): boolean {
if (UNTRANSLATED.has(text)) return false;
const words = text.replace(/\{[^{}]*\}/g, "");
if (!/[A-Za-z]{2}/.test(words)) return false;
return !/^[-.*~/$#@]|:\/\//.test(words);
}
const scan = scanTypeScript();
scanBackend(scan.literals);
const catalogs = Object.fromEntries(
readdirSync(TEXT_DIR)
.filter((f) => f.endsWith(".json"))
.map((f) => [f.slice(0, -5), JSON.parse(readFileSync(new URL(f, TEXT_DIR), "utf8")) as Record<string, string>]),
);
/** `{name}` templates of a catalog, as `txTemplate` matches them. */
function templatePatterns(catalog: Record<string, string>): RegExp[] {
return Object.keys(catalog)
.filter((key) => /\{\w+\}/.test(key))
.map((key) => {
const parts = key.split(/\{\w+\}/).map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
return new RegExp(`^${parts.join("(.+?)")}$`, "s");
});
}
describe.each(Object.keys(catalogs))("source-text catalog %s", (locale) => {
const catalog = catalogs[locale]!;
const patterns = templatePatterns(catalog);
const has = (text: string) => Object.hasOwn(catalog, text);
// Placeholders of the source stand for any text, as the runtime values would.
const matchesTemplate = (text: string) => patterns.some((p) => p.test(text.replace(/\{[^{}]*\}/g, "\u0001")));
it("translates every literal UI text", () => {
const missing = new Map<string, string>();
for (const { text, at, template } of scan.translated)
if (!has(text) && !(template && matchesTemplate(text)) && needsTranslation(text) && !missing.has(text))
missing.set(text, at);
expect([...missing].map(([text, at]) => `${at} ${JSON.stringify(text)}`)).toEqual([]);
});
it("has no entries whose text no longer appears in the source", () => {
const stale = Object.keys(catalog).filter((key) => !scan.literals.has(shape(key)) && !BUILT_AT_RUNTIME.has(key));
expect(stale).toEqual([]);
});
});
+3 -3
Переглянути файл
@@ -95,16 +95,16 @@ a:hover {
}
/* Focus rings mark controls only, as in IDEA: lists, trees, tables, menus, popups and other
focusable containers show focus through their selected row instead of a frame. */
focusable containers show focus through their selected row instead of a frame. Text fields
aren't listed: their frame shows focus, and an outline here draws a second box inside it. */
:focus-visible {
outline: none;
}
:is(
button,
a[href],
input,
input:is([type="checkbox"], [type="radio"], [type="range"], [type="color"], [type="file"], [type="button"], [type="submit"], [type="reset"]),
select,
textarea,
summary,
[role="button"],
[role="link"],
+2 -1
Переглянути файл
@@ -8,6 +8,7 @@ import { FOCUSABLE, onWindowDeactivate, openLayer, trapTab } from "./popupState"
import { useTx } from "@/platform/i18n";
import { selectableText } from "./selectableText";
import styles from "./Dialog.module.css";
import { isImeKey } from "@/platform/ime";
/**
* `default`: filled accent button, triggered by Enter. `cancel`: Esc / close
@@ -256,7 +257,7 @@ function DialogInner({
onCloseRef.current();
} else if (e.key === "Tab") {
trapTab(e, ref.current);
} else if (e.key === "Enter" && !e.defaultPrevented && !e.isComposing && !e.shiftKey && !e.altKey) {
} else if (e.key === "Enter" && !e.defaultPrevented && !isImeKey(e) && !e.shiftKey && !e.altKey) {
const t = e.target instanceof Element ? e.target : null;
const mod = e.metaKey || e.ctrlKey;
if (t && t !== document.body && !ref.current.contains(t)) return;
+4 -1
Переглянути файл
@@ -29,6 +29,8 @@ export interface ListProps<T> {
onContextMenu?: (item: T, index: number, e: MouseEvent) => void;
rowHeight?: number;
sectionHeight?: number;
/** Height of a given section row (e.g. thin separators), else `sectionHeight`. */
sectionHeightOf?: (item: T) => number | undefined;
/** `false` when an external input drives navigation (rows still respond to the mouse). */
focusable?: boolean;
/** Move the active row with the pointer (popup choosers). */
@@ -109,6 +111,7 @@ export function List<T>({
onContextMenu,
rowHeight = 24,
sectionHeight = 24,
sectionHeightOf,
focusable = true,
hoverSelects = false,
empty,
@@ -127,7 +130,7 @@ export function List<T>({
const virtualizer = useVirtualizer({
count: items.length,
getScrollElement: () => scrollRef.current,
estimateSize: (i) => (isSection?.(items[i]!) ? sectionHeight : rowHeight),
estimateSize: (i) => (isSection?.(items[i]!) ? (sectionHeightOf?.(items[i]!) ?? sectionHeight) : rowHeight),
overscan,
getItemKey: (i) => getKey(items[i]!, i),
});
+3 -1
Переглянути файл
@@ -21,7 +21,9 @@ afterEach(() => {
describe("selectable read-only surfaces", () => {
it("Markdown preview (the reported case)", () => {
act(() =>
useLiveMarkdown.setState({ "/p/README.md": { text: "# Title\n\nSome *text*", topLine: 0, scrollSeq: 0 } }),
useLiveMarkdown.setState({
"/p/README.md": { text: "# Title\n\nSome *text*", topLine: 0, scrollSeq: 0, fontZoom: 0 },
}),
);
act(() => useMarkdownModes.setState((s) => ({ byPath: { ...s.byPath, "/p/README.md": "preview" } })));
render(