дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-27 21:12:34 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
efbb48c3cb | ||
|
|
bb9486c758 | ||
|
|
5c0c3a009c | ||
|
|
ef667f6e21 | ||
|
|
81b43a52b4 | ||
|
|
0bb730039d | ||
|
|
709e1eb855 | ||
|
|
4473324822 | ||
|
|
5d5b3e4791 | ||
|
|
c5b4b71e30 | ||
|
|
0e299ad936 | ||
|
|
5b8e0b9659 | ||
|
|
3d8a6f07b4 |
No files matched your search
Створено
+26
-26
@@ -3962,7 +3962,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -3976,7 +3976,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
@@ -3991,7 +3991,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"serde",
|
||||
@@ -4003,7 +4003,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4017,7 +4017,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jsonrpc",
|
||||
@@ -4034,7 +4034,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"futures",
|
||||
@@ -4054,7 +4054,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4067,7 +4067,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4081,7 +4081,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot",
|
||||
@@ -4099,7 +4099,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4121,7 +4121,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"ide-core",
|
||||
@@ -4136,7 +4136,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4188,7 +4188,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"globset",
|
||||
@@ -4211,7 +4211,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4229,7 +4229,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4242,7 +4242,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4260,7 +4260,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"ide-core",
|
||||
@@ -4277,7 +4277,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"globset",
|
||||
@@ -4296,7 +4296,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4311,7 +4311,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4324,7 +4324,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4336,7 +4336,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -4356,7 +4356,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"gix",
|
||||
@@ -4373,7 +4373,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -4393,7 +4393,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5817,7 +5817,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"dunce",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*", "src-tauri"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.9"
|
||||
version = "0.1.11"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
+9
-1
@@ -9,13 +9,21 @@
|
||||
The IDE you know, rebuilt in Rust.
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/l0ng-ai/openidea/releases/latest"><b>Download</b></a>
|
||||
·
|
||||
<a href="#benchmark">Benchmark</a>
|
||||
·
|
||||
<a href="#build">Build</a>
|
||||
</p>
|
||||
|
||||
https://github.com/user-attachments/assets/234dd54c-1255-4b3a-b35c-533d78d737c0
|
||||
|
||||
OpenIDEA brings the IntelliJ IDEA way of working — its keymap, its tool windows,
|
||||
its search-everything habits — to a native app with a Rust core.
|
||||
|
||||
Editor, code insight, debugger, Git, terminal, database and HTTP clients,
|
||||
for 60+ languages.
|
||||
for 60+ languages. Builds for macOS, Windows and Linux.
|
||||
|
||||
## Benchmark
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ pub mod event;
|
||||
pub mod ids;
|
||||
pub mod ignored;
|
||||
pub mod ipc_path;
|
||||
pub mod process;
|
||||
pub mod project_dir;
|
||||
pub mod settings;
|
||||
pub mod text;
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
//! Child-process helpers shared by every crate that spawns tools.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
/// Keeps a console child (java, node, curl, a language server, ...) from
|
||||
/// opening its own console window on Windows. Release builds use the GUI
|
||||
/// subsystem, so without this every spawn flashes a `cmd` window. A no-op
|
||||
/// elsewhere. For a `tokio::process::Command`, pass `cmd.as_std_mut()`.
|
||||
pub fn no_window(cmd: &mut Command) -> &mut Command {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
|
||||
cmd.creation_flags(CREATE_NO_WINDOW);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
@@ -204,7 +204,7 @@ pub fn collect(spec: &CoverageReportSpec) -> IdeResult<CoverageSuite> {
|
||||
CoverageReportSpec::Exported { runner, argv, cwd, env, lcov } => {
|
||||
let (program, args) =
|
||||
argv.split_first().ok_or_else(|| IdeError::invalid("empty coverage export command"))?;
|
||||
let out = Command::new(program)
|
||||
let out = ide_core::process::no_window(&mut Command::new(program))
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.envs(env)
|
||||
|
||||
@@ -233,7 +233,9 @@ pub async fn prepare_debugpy(spec: &mut AdapterSpec) -> IdeResult<()> {
|
||||
let Some(python) = tokio::task::spawn_blocking(move || resolve_binary(&command, &cwd)).await.ok().flatten() else {
|
||||
return Ok(()); // Reported as a missing adapter when it is started.
|
||||
};
|
||||
let probe = Command::new(&python)
|
||||
let mut probe = Command::new(&python);
|
||||
ide_core::process::no_window(probe.as_std_mut());
|
||||
let probe = probe
|
||||
.args(["-c", "import debugpy.adapter"])
|
||||
.current_dir(&spec.cwd)
|
||||
.stdin(Stdio::null())
|
||||
@@ -335,6 +337,7 @@ impl AdapterLauncher for ProcessLauncher {
|
||||
None => spec.args.clone(),
|
||||
};
|
||||
let mut cmd = Command::new(&binary);
|
||||
ide_core::process::no_window(cmd.as_std_mut());
|
||||
cmd.args(&args)
|
||||
.envs(spec.env.iter().map(|(k, v)| (k, v)))
|
||||
.current_dir(&spec.cwd)
|
||||
|
||||
@@ -55,6 +55,7 @@ pub async fn build(
|
||||
) -> IdeResult<PathBuf> {
|
||||
let cargo = find_binary("cargo", cwd).ok_or_else(|| IdeError::unavailable("`cargo` not found on PATH"))?;
|
||||
let mut cmd = tokio::process::Command::new(cargo);
|
||||
ide_core::process::no_window(cmd.as_std_mut());
|
||||
cmd.args(args)
|
||||
.arg("--message-format=json-render-diagnostics")
|
||||
.current_dir(cwd)
|
||||
|
||||
@@ -390,6 +390,7 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
|
||||
return Err("runInTerminal without args".into());
|
||||
};
|
||||
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);
|
||||
if let Some(cwd) = args.get("cwd").and_then(Value::as_str).filter(|c| !c.is_empty()) {
|
||||
cmd.current_dir(cwd);
|
||||
|
||||
@@ -241,6 +241,7 @@ impl Peer {
|
||||
) -> std::io::Result<Self> {
|
||||
use std::process::Stdio;
|
||||
let mut cmd = tokio::process::Command::new(command);
|
||||
ide_core::process::no_window(cmd.as_std_mut());
|
||||
cmd.args(args)
|
||||
.current_dir(cwd)
|
||||
.envs(env.iter().map(|(k, v)| (k.as_str(), v.as_str())))
|
||||
|
||||
@@ -72,7 +72,7 @@ fn resolve_rustup_proxy(command: &str, binary: PathBuf) -> PathBuf {
|
||||
if !is_proxy || command.contains('/') {
|
||||
return binary;
|
||||
}
|
||||
let works = std::process::Command::new(&binary)
|
||||
let works = ide_core::process::no_window(&mut std::process::Command::new(&binary))
|
||||
.arg("--version")
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
|
||||
@@ -161,7 +161,7 @@ pub fn collect(spec: &ProfileSpec) -> IdeResult<Profile> {
|
||||
if !data.is_file() {
|
||||
return Err(nothing_recorded("perf wrote no data"));
|
||||
}
|
||||
let out = Command::new(perf)
|
||||
let out = ide_core::process::no_window(&mut Command::new(perf))
|
||||
.args(["script", "-i"])
|
||||
.arg(data.as_ref() as &Path)
|
||||
.current_dir(cwd)
|
||||
|
||||
@@ -93,7 +93,7 @@ pub fn find_tool(name: &str, config: &RunConfig, dir: &Path, root: &Path) -> Opt
|
||||
pub fn probe(argv: &[String], dir: &Path, config: &RunConfig) -> bool {
|
||||
let Some((program, args)) = argv.split_first() else { return false };
|
||||
let program = resolve(program, config);
|
||||
Command::new(program)
|
||||
ide_core::process::no_window(&mut Command::new(program))
|
||||
.args(args)
|
||||
.current_dir(dir)
|
||||
.envs(&config.env)
|
||||
|
||||
@@ -44,7 +44,7 @@ pub(crate) fn which(name: &str) -> Option<PathBuf> {
|
||||
/// Runs `program args` and returns trimmed stdout (stderr when stdout is empty)
|
||||
/// on success; `None` on failure or after `timeout`.
|
||||
pub(crate) fn query(program: &Path, args: &[&str], timeout: Duration) -> Option<String> {
|
||||
let mut child = Command::new(program)
|
||||
let mut child = ide_core::process::no_window(&mut Command::new(program))
|
||||
.args(args)
|
||||
.env("PATH", search_path())
|
||||
.stdin(Stdio::null())
|
||||
@@ -96,6 +96,7 @@ pub(crate) fn stream(
|
||||
on_line: &dyn Fn(String),
|
||||
) -> IdeResult<String> {
|
||||
let mut cmd = Command::new(program);
|
||||
ide_core::process::no_window(&mut cmd);
|
||||
cmd.args(args).env("PATH", search_path()).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
cmd.envs(env.iter().map(|(k, v)| (k, v)));
|
||||
if let Some(cwd) = cwd {
|
||||
|
||||
@@ -113,7 +113,7 @@ fn extract_zip(archive: &Path, dest: &Path) -> IdeResult<()> {
|
||||
/// `.tar.xz` goes through the system `tar` (bsdtar on macOS/Windows, GNU tar + xz on Linux).
|
||||
fn extract_tar_xz(archive: &Path, dest: &Path) -> IdeResult<()> {
|
||||
let tar = which::which("tar").map_err(|_| IdeError::unavailable("`tar` is required to unpack .tar.xz archives"))?;
|
||||
let out = std::process::Command::new(tar)
|
||||
let out = ide_core::process::no_window(&mut std::process::Command::new(tar))
|
||||
.arg("-xJf")
|
||||
.arg(archive)
|
||||
.arg("-C")
|
||||
|
||||
@@ -311,7 +311,7 @@ impl Tools {
|
||||
|
||||
fn command(&self, program: impl AsRef<std::ffi::OsStr>) -> Command {
|
||||
let mut cmd = Command::new(program);
|
||||
cmd.env("PATH", &self.child_path);
|
||||
ide_core::process::no_window(&mut cmd).env("PATH", &self.child_path);
|
||||
cmd
|
||||
}
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ pub fn run_streamed(cmd: Command, cancel: &CancellationToken, emit: Emit) -> Ide
|
||||
/// Like [`run_streamed`] but returns `(success, output, status text)` instead of failing on a non-zero exit.
|
||||
pub fn run_collect(mut cmd: Command, cancel: &CancellationToken, emit: Emit) -> IdeResult<(bool, String, String)> {
|
||||
emit(InstallEvent::Line { text: format!("$ {}", describe(&cmd)) });
|
||||
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
ide_core::process::no_window(&mut cmd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
let mut child = cmd.spawn().map_err(|e| IdeError::unavailable(format!("cannot run {}: {e}", describe(&cmd))))?;
|
||||
let (tx, rx) = mpsc::channel::<String>();
|
||||
let pipes: [Option<Box<dyn Read + Send>>; 2] = [
|
||||
@@ -94,7 +94,7 @@ pub fn run_collect(mut cmd: Command, cancel: &CancellationToken, emit: Emit) ->
|
||||
|
||||
/// Runs `cmd` to completion within `timeout`; returns (success, stdout + stderr).
|
||||
pub fn run_quiet(mut cmd: Command, timeout: Duration) -> Option<(bool, String)> {
|
||||
cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
ide_core::process::no_window(&mut cmd).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped());
|
||||
let mut child = cmd.spawn().ok()?;
|
||||
let mut stdout = child.stdout.take()?;
|
||||
let mut stderr = child.stderr.take()?;
|
||||
@@ -161,6 +161,7 @@ impl Http {
|
||||
|
||||
fn base(&self, url: &str) -> Command {
|
||||
let mut cmd = Command::new(&self.curl);
|
||||
ide_core::process::no_window(&mut cmd);
|
||||
cmd.args(["-fsSL", "--retry", "2", "--connect-timeout", "20", "-A", "openidea"]);
|
||||
if url.starts_with("https://api.github.com/")
|
||||
&& let Ok(token) = std::env::var("GITHUB_TOKEN").or_else(|_| std::env::var("GH_TOKEN"))
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "openidea",
|
||||
"private": true,
|
||||
"description": "An open-source IDE inspired by IntelliJ IDEA",
|
||||
"version": "0.1.9",
|
||||
"version": "0.1.11",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -239,6 +239,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
window::app_log_location,
|
||||
window::app_build_info,
|
||||
window::app_check_update,
|
||||
window::app_startup_update_check,
|
||||
window::app_install_update,
|
||||
debug::debug_exception_filters,
|
||||
debug::debug_set_exception_breakpoints,
|
||||
|
||||
@@ -268,6 +268,26 @@ pub async fn app_check_update(app: AppHandle) -> IdeResult<UpdateCheck> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The background check made once per process when the first window starts;
|
||||
/// later calls (other windows) and debug builds get `None`. Failures are logged,
|
||||
/// not reported: the user didn't ask for this check.
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn app_startup_update_check(app: AppHandle) -> Option<UpdateInfo> {
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
static DONE: AtomicBool = AtomicBool::new(false);
|
||||
if cfg!(debug_assertions) || DONE.swap(true, Ordering::SeqCst) {
|
||||
return None;
|
||||
}
|
||||
match app_check_update(app).await {
|
||||
Ok(check) => check.update,
|
||||
Err(e) => {
|
||||
tracing::warn!("startup update check failed: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Downloads and installs the available update, then quits through every
|
||||
/// window's unsaved-changes check and relaunches. If a window cancels the quit,
|
||||
/// the update applies on the next start.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "OpenIDEA",
|
||||
"version": "0.1.9",
|
||||
"version": "0.1.11",
|
||||
"identifier": "ai.l0ng.openidea",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
@@ -36,6 +36,7 @@
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": "all",
|
||||
"createUpdaterArtifacts": true,
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
@@ -56,8 +57,8 @@
|
||||
"mainBinaryName": "openidea",
|
||||
"plugins": {
|
||||
"updater": {
|
||||
"pubkey": "",
|
||||
"endpoints": []
|
||||
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDFCOUU0MUFFOUY4NzZCNkQKUldSdGE0ZWZya0dlRzNnRFJUR2loUVdNZ1BmamxkNzFoaWNPUTBsRmI0cjhxZFRqQURybkMwakEK",
|
||||
"endpoints": ["https://github.com/l0ng-ai/openidea/releases/latest/download/latest.json"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -459,6 +459,17 @@ export const commands = {
|
||||
appLogLocation: () => typedError<LogLocation, IdeError>(__TAURI_INVOKE("app_log_location")),
|
||||
appBuildInfo: () => __TAURI_INVOKE<BuildInfo>("app_build_info"),
|
||||
appCheckUpdate: () => typedError<UpdateCheck, IdeError>(__TAURI_INVOKE("app_check_update")),
|
||||
/**
|
||||
* The background check made once per process when the first window starts;
|
||||
* later calls (other windows) and debug builds get `None`. Failures are logged,
|
||||
* not reported: the user didn't ask for this check.
|
||||
*/
|
||||
appStartupUpdateCheck: () => __TAURI_INVOKE<{
|
||||
version: string,
|
||||
currentVersion: string,
|
||||
notes: string | null,
|
||||
date: string | null,
|
||||
} | null>("app_startup_update_check"),
|
||||
/**
|
||||
* Downloads and installs the available update, then quits through every
|
||||
* window's unsaved-changes check and relaunches. If a window cancels the quit,
|
||||
|
||||
@@ -81,35 +81,56 @@ export function languageForPath(path: string): string | null {
|
||||
return LanguageDescription.matchFilename(languages, name)?.name ?? null;
|
||||
}
|
||||
|
||||
/** Replaces `el`'s text with highlighted spans (no-op when the language is unknown). */
|
||||
export async function highlightInto(el: HTMLElement, text: string, language: string | null): Promise<void> {
|
||||
export interface CodeToken {
|
||||
from: number;
|
||||
to: number;
|
||||
/** Lezer `classHighlighter` classes (`tok-string` …). */
|
||||
cls: string;
|
||||
}
|
||||
|
||||
/** Highlighted ranges of `text`; empty when the language is unknown or its grammar fails to load. */
|
||||
export async function highlightTokens(text: string, language: string | null): Promise<CodeToken[]> {
|
||||
const desc = language ? findLanguage(language) : null;
|
||||
if (!desc) return;
|
||||
if (!desc) return [];
|
||||
try {
|
||||
const support = desc.support ?? (await desc.load());
|
||||
const tree = support.language.parser.parse(text);
|
||||
const frag = document.createDocumentFragment();
|
||||
const out: CodeToken[] = [];
|
||||
let pos = 0;
|
||||
highlightCode(
|
||||
text,
|
||||
tree,
|
||||
classHighlighter,
|
||||
(t, cls) => {
|
||||
if (!cls) frag.appendChild(document.createTextNode(t));
|
||||
else {
|
||||
const span = document.createElement("span");
|
||||
span.className = cls;
|
||||
span.textContent = t;
|
||||
frag.appendChild(span);
|
||||
}
|
||||
if (cls) out.push({ from: pos, to: pos + t.length, cls });
|
||||
pos += t.length;
|
||||
},
|
||||
() => frag.appendChild(document.createTextNode("\n")),
|
||||
() => pos++,
|
||||
);
|
||||
el.replaceChildren(frag);
|
||||
return out;
|
||||
} catch {
|
||||
// Grammar failed to load: keep the plain text.
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** Replaces `el`'s text with highlighted spans (no-op when the language is unknown). */
|
||||
export async function highlightInto(el: HTMLElement, text: string, language: string | null): Promise<void> {
|
||||
const tokens = await highlightTokens(text, language);
|
||||
if (!tokens.length) return;
|
||||
const frag = document.createDocumentFragment();
|
||||
let pos = 0;
|
||||
for (const t of tokens) {
|
||||
if (t.from > pos) frag.appendChild(document.createTextNode(text.slice(pos, t.from)));
|
||||
const span = document.createElement("span");
|
||||
span.className = t.cls;
|
||||
span.textContent = text.slice(t.from, t.to);
|
||||
frag.appendChild(span);
|
||||
pos = t.to;
|
||||
}
|
||||
if (pos < text.length) frag.appendChild(document.createTextNode(text.slice(pos)));
|
||||
el.replaceChildren(frag);
|
||||
}
|
||||
|
||||
function highlightBlocks(root: HTMLElement, fallback: string | null) {
|
||||
root.querySelectorAll<HTMLElement>("pre > code").forEach((code) => {
|
||||
const cls = [...code.classList].find((c) => c.startsWith("language-"));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Action } from "@/platform/actions";
|
||||
import { t } from "@/platform/i18n";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { call, commands, isTauri, type UpdateInfo } from "@/platform/ipc";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { showAbout } from "./AboutDialog";
|
||||
import { quitApp } from "./closeGuard";
|
||||
@@ -42,28 +42,39 @@ export async function checkForUpdates(): Promise<void> {
|
||||
key: "app.update",
|
||||
});
|
||||
} else {
|
||||
notifications().notify({
|
||||
level: "info",
|
||||
title: t("app.update.available", { version: r.update.version }),
|
||||
body: r.update.notes ?? undefined,
|
||||
sticky: true,
|
||||
key: "app.update",
|
||||
actions: [
|
||||
{
|
||||
label: t("app.update.install"),
|
||||
run: () =>
|
||||
void call(commands.appInstallUpdate()).catch((e) =>
|
||||
notifications().notify({ level: "error", title: t("app.update.installFailed"), body: errorText(e) }),
|
||||
),
|
||||
},
|
||||
],
|
||||
});
|
||||
notifyUpdate(r.update);
|
||||
}
|
||||
} catch (e) {
|
||||
notifications().notify({ level: "error", title: t("app.update.failed"), body: errorText(e), key: "app.update" });
|
||||
}
|
||||
}
|
||||
|
||||
/** Silent check once per app start; only an available update is shown. */
|
||||
export async function checkForUpdatesOnStartup(): Promise<void> {
|
||||
if (!isTauri()) return;
|
||||
const update = await commands.appStartupUpdateCheck().catch(() => null);
|
||||
if (update) notifyUpdate(update);
|
||||
}
|
||||
|
||||
function notifyUpdate(update: UpdateInfo) {
|
||||
notifications().notify({
|
||||
level: "info",
|
||||
title: t("app.update.available", { version: update.version }),
|
||||
body: update.notes ?? undefined,
|
||||
sticky: true,
|
||||
key: "app.update",
|
||||
actions: [
|
||||
{
|
||||
label: t("app.update.install"),
|
||||
run: () =>
|
||||
void call(commands.appInstallUpdate()).catch((e) =>
|
||||
notifications().notify({ level: "error", title: t("app.update.installFailed"), body: errorText(e) }),
|
||||
),
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit menu items on Windows/Linux (macOS uses native roles). They act on the
|
||||
* focused element like the native commands would; CodeMirror handles the
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
import { registerOverlay } from "@/workbench/contributions";
|
||||
import { AboutOverlay } from "./AboutDialog";
|
||||
import { appActions, updateActions } from "./appActions";
|
||||
import { appActions, checkForUpdatesOnStartup, updateActions } from "./appActions";
|
||||
import { installCloseGuard } from "./closeGuard";
|
||||
import { InvalidateCachesOverlay, registerInvalidateCachesActions } from "./InvalidateCaches";
|
||||
import { buildInfo } from "./host";
|
||||
@@ -32,7 +32,9 @@ export function activate(): () => void {
|
||||
];
|
||||
let disposed = false;
|
||||
void buildInfo().then((b) => {
|
||||
if (b?.updates && !disposed) disposers.push(registerLocalizedActions(updateActions));
|
||||
if (!b?.updates || disposed) return;
|
||||
disposers.push(registerLocalizedActions(updateActions));
|
||||
void checkForUpdatesOnStartup();
|
||||
});
|
||||
return () => {
|
||||
disposed = true;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/** "usages" tool window: Find Usages results grouped by file with line previews. */
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { formatMessage, useTx } from "@/platform/i18n";
|
||||
import { basename, relativeDir, useProject } from "@/platform/project";
|
||||
import { EmptyState, Icon, IconButton, Spinner, Tabs, Tree, fileIconName, type TreeRowState, T } from "@/ui";
|
||||
import { openLocation } from "./ipc";
|
||||
@@ -24,9 +25,10 @@ export function UsagePreview({ usage }: { usage: Usage }) {
|
||||
|
||||
/** Tool window header: the current search as a content tab (`Usages of 'foo'`). */
|
||||
export function UsagesTabs() {
|
||||
const tx = useTx();
|
||||
const search = useUsages((s) => s.search);
|
||||
if (!search) return null;
|
||||
const label = search.symbol ? `Usages of '${search.symbol}'` : "Usages";
|
||||
const label = search.symbol ? formatMessage(tx("Usages of '{symbol}'"), { symbol: search.symbol }) : tx("Usages");
|
||||
return (
|
||||
<Tabs
|
||||
variant="compact"
|
||||
@@ -42,6 +44,7 @@ export function UsagesTabs() {
|
||||
const SUMMARY_KEY = "\u0000summary";
|
||||
|
||||
export function UsagesView() {
|
||||
const tx = useTx();
|
||||
const search = useUsages((s) => s.search);
|
||||
const root = useProject((s) => s.project?.root ?? "");
|
||||
const [collapsed, setCollapsed] = useState<{ id: number | null; keys: ReadonlySet<string> }>({
|
||||
@@ -86,7 +89,7 @@ export function UsagesView() {
|
||||
<T>Found usages</T>
|
||||
</span>
|
||||
<span className={styles.count}>
|
||||
{total} {total === 1 ? "result" : "results"}
|
||||
{total} {tx(total === 1 ? "result" : "results")}
|
||||
</span>
|
||||
{search.note && <span className={styles.note}>{search.note}</span>}
|
||||
</span>
|
||||
@@ -99,7 +102,7 @@ export function UsagesView() {
|
||||
<span className={styles.file}>{basename(path)}</span>
|
||||
<span className={styles.muted}>{relativeDir(root, path)}</span>
|
||||
<span className={styles.count}>
|
||||
{n.group.usages.length} {n.group.usages.length === 1 ? "usage" : "usages"}
|
||||
{n.group.usages.length} {tx(n.group.usages.length === 1 ? "usage" : "usages")}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
@@ -117,7 +120,7 @@ export function UsagesView() {
|
||||
<div className={styles.toolbar} role="toolbar" aria-orientation="vertical" aria-label="Usages actions">
|
||||
<IconButton
|
||||
icon="rerun"
|
||||
title="Rerun Find Usages"
|
||||
title={tx("Rerun Find Usages")}
|
||||
size="small"
|
||||
iconSize={16}
|
||||
disabled={!search.rerun}
|
||||
@@ -132,7 +135,11 @@ export function UsagesView() {
|
||||
<div className={styles.summary} role="status" aria-live="polite">
|
||||
{search.loading ? (
|
||||
<>
|
||||
<Spinner size={12} /> Searching for usages{search.symbol ? ` of '${search.symbol}'` : ""}…
|
||||
<Spinner size={12} />{" "}
|
||||
{search.symbol
|
||||
? formatMessage(tx("Searching for usages of '{symbol}'"), { symbol: search.symbol })
|
||||
: tx("Searching for usages")}
|
||||
…
|
||||
</>
|
||||
) : (
|
||||
<span className={styles.error}>{search.error}</span>
|
||||
@@ -145,7 +152,7 @@ export function UsagesView() {
|
||||
roots={roots}
|
||||
getKey={(n) => n.key}
|
||||
getLabel={(n) =>
|
||||
n.kind === "summary" ? "Found usages" : n.kind === "file" ? basename(n.group.path) : n.usage.text.trim()
|
||||
n.kind === "summary" ? tx("Found usages") : n.kind === "file" ? basename(n.group.path) : n.usage.text.trim()
|
||||
}
|
||||
getChildren={getChildren}
|
||||
isExpandable={(n) => n.kind !== "usage"}
|
||||
|
||||
@@ -3,6 +3,7 @@ import clsx from "clsx";
|
||||
import { BarButton, Icon, IconButton, Menu, type MenuItem } from "@/ui";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { useContextKeys } from "@/platform/context";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { runExecutors, useRunExecutors } from "@/workbench/contributions";
|
||||
import { configIcon } from "./configs";
|
||||
@@ -11,6 +12,7 @@ import styles from "./Run.module.css";
|
||||
|
||||
/** Title bar: configuration chooser, Run / Debug, and Rerun / Stop while running. */
|
||||
export function RunWidget() {
|
||||
const tx = useTx();
|
||||
const configs = useRun((s) => s.configs);
|
||||
const selectedId = useRun((s) => s.selectedId);
|
||||
const sessions = useRun((s) => s.sessions);
|
||||
@@ -48,7 +50,7 @@ export function RunWidget() {
|
||||
<BarButton
|
||||
variant="title"
|
||||
className={styles.widgetChooser}
|
||||
tooltip="Run/Debug Configurations"
|
||||
tooltip={tx("Run/Debug Configurations")}
|
||||
shortcut={shortcutLabel("run.chooseConfig")}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={chooserOpen}
|
||||
@@ -59,10 +61,14 @@ export function RunWidget() {
|
||||
// IDEA: the configuration's type icon, with a status dot on its top-right corner while active.
|
||||
<span className={styles.widgetConfigIcon}>
|
||||
<Icon name={configIcon(selected)} size={16} />
|
||||
{active && <span className={styles.widgetStatusDot} aria-label={debugging ? "Debugging" : "Running"} role="img" />}
|
||||
{active && (
|
||||
<span className={styles.widgetStatusDot} aria-label={debugging ? "Debugging" : "Running"} role="img" />
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
<span className={styles.widgetName}>{selected?.name ?? (configs.length ? "Select Configuration" : "Add Configuration…")}</span>
|
||||
<span className={styles.widgetName}>
|
||||
{selected?.name ?? tx(configs.length ? "Select Configuration" : "Add Configuration…")}
|
||||
</span>
|
||||
<Icon name="chevron-down" size={14} className={styles.widgetChevron} />
|
||||
</BarButton>
|
||||
<span className={styles.widgetButtons}>
|
||||
@@ -156,7 +162,13 @@ export function RunWidget() {
|
||||
aria-expanded={moreOpen}
|
||||
onClick={() => setMoreOpen((v) => !v)}
|
||||
/>
|
||||
<Menu open={moreOpen} anchor={moreRef} items={moreItems} placement="bottom-end" onClose={() => setMoreOpen(false)} />
|
||||
<Menu
|
||||
open={moreOpen}
|
||||
anchor={moreRef}
|
||||
items={moreItems}
|
||||
placement="bottom-end"
|
||||
onClose={() => setMoreOpen(false)}
|
||||
/>
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -34,7 +34,8 @@ vi.mock("../find/windowStore", async (orig) => ({
|
||||
const { allActions } = await import("@/platform/actions");
|
||||
(globalThis as unknown as { __actions: typeof allActions }).__actions = allActions;
|
||||
const { SearchEverywhereOverlay } = await import("../everywhere/SearchEverywhere");
|
||||
const { showSearchEverywhere, hideSearchEverywhere, useSearchEverywhere } = await import("../everywhere/store");
|
||||
const { showSearchEverywhere, hideSearchEverywhere, useSearchEverywhere, pushSearchHistory, searchHistory } =
|
||||
await import("../everywhere/store");
|
||||
const { FindInFilesOverlay } = await import("../find/FindInFiles");
|
||||
const { showFindPopup, hideFindPopup } = await import("../find/store");
|
||||
|
||||
@@ -62,10 +63,10 @@ describe("Search Everywhere dialog", () => {
|
||||
await tick();
|
||||
const results = within(document.getElementById("se-results")!);
|
||||
expect(results.queryByText("Files")).toBeNull();
|
||||
expect(screen.getByText("src/OrderController.kt")).toBeInTheDocument();
|
||||
|
||||
// ↓ moves from the file row to the action row.
|
||||
// All mixes sources by relevance: the shorter prefix hit (the action) leads.
|
||||
fireEvent.keyDown(input, { key: "ArrowDown" });
|
||||
expect(screen.getByText("src/OrderController.kt")).toBeInTheDocument();
|
||||
fireEvent.keyDown(input, { key: "ArrowUp" });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
await tick();
|
||||
expect(useSearchEverywhere.getState().open).toBe(false);
|
||||
@@ -73,6 +74,56 @@ describe("Search Everywhere dialog", () => {
|
||||
dispose();
|
||||
});
|
||||
|
||||
it("the preview toggle is remembered", async () => {
|
||||
render(<SearchEverywhereOverlay />);
|
||||
act(() => showSearchEverywhere("all"));
|
||||
await tick();
|
||||
const toggle = screen.getByRole("button", { name: "Preview" });
|
||||
expect(toggle).toHaveAttribute("aria-pressed", "false");
|
||||
fireEvent.click(toggle);
|
||||
expect(useSearchEverywhere.getState().preview).toBe(true);
|
||||
expect(toggle).toHaveAttribute("aria-pressed", "true");
|
||||
expect(localStorage.getItem("openidea.search.everywherePreview.v1")).toBe("true");
|
||||
fireEvent.click(toggle);
|
||||
expect(useSearchEverywhere.getState().preview).toBe(false);
|
||||
});
|
||||
|
||||
it("/ lists scope commands; picking one or typing '/files q' switches the tab", async () => {
|
||||
render(<SearchEverywhereOverlay />);
|
||||
act(() => showSearchEverywhere("all", { query: "" }));
|
||||
await tick();
|
||||
const input = screen.getByLabelText("Search query");
|
||||
fireEvent.change(input, { target: { value: "/fi" } });
|
||||
await tick();
|
||||
expect(within(document.getElementById("se-results")!).getByText("/files")).toBeInTheDocument();
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
expect(useSearchEverywhere.getState()).toMatchObject({ tab: "files", query: "", open: true });
|
||||
|
||||
fireEvent.change(input, { target: { value: "/text order" } });
|
||||
expect(useSearchEverywhere.getState()).toMatchObject({ tab: "text", query: "order" });
|
||||
});
|
||||
|
||||
it("⌥↑ / ⌥↓ browse the tab's search history and restore the draft", async () => {
|
||||
localStorage.removeItem("openidea.search.everywhereHistory.v1");
|
||||
pushSearchHistory("all", "older");
|
||||
pushSearchHistory("all", "newer");
|
||||
pushSearchHistory("files", "other tab");
|
||||
render(<SearchEverywhereOverlay />);
|
||||
act(() => showSearchEverywhere("all", { query: "draft" }));
|
||||
await tick();
|
||||
const input = screen.getByLabelText("Search query");
|
||||
const key = (k: string) => fireEvent.keyDown(input, { key: k, altKey: true });
|
||||
key("ArrowUp");
|
||||
expect(useSearchEverywhere.getState().query).toBe("newer");
|
||||
key("ArrowUp");
|
||||
key("ArrowUp");
|
||||
expect(useSearchEverywhere.getState().query).toBe("older");
|
||||
key("ArrowDown");
|
||||
key("ArrowDown");
|
||||
expect(useSearchEverywhere.getState().query).toBe("draft");
|
||||
expect(searchHistory("all")).toEqual(["newer", "older"]);
|
||||
});
|
||||
|
||||
it("⇥ cycles scopes and repeating the scope action toggles non-project items", async () => {
|
||||
render(<SearchEverywhereOverlay />);
|
||||
act(() => showSearchEverywhere("all"));
|
||||
|
||||
@@ -6,8 +6,10 @@ import {
|
||||
fileItem,
|
||||
matchActions,
|
||||
mergeSymbols,
|
||||
parseCommand,
|
||||
sectionsFor,
|
||||
stableIndex,
|
||||
symbolItem,
|
||||
textItems,
|
||||
topResultSettled,
|
||||
type SectionId,
|
||||
@@ -132,10 +134,10 @@ describe("items and rows", () => {
|
||||
expect(f.line).toBe(41);
|
||||
});
|
||||
|
||||
it("textItems trims indentation and shifts ranges", () => {
|
||||
const [t] = textItems("/p/a.kt", "a.kt", [{ line: 4, text: " val order = 1", ranges: [[8, 13]], textOffset: 0 }]);
|
||||
expect(t!.text).toBe("val order = 1");
|
||||
expect(t!.indices).toEqual([4, 5, 6, 7, 8]);
|
||||
it("textItems collapses indentation and shifts ranges", () => {
|
||||
const [t] = textItems("/p/a.kt", "a.kt", [{ line: 4, text: "\t\t val order = 1", ranges: [[8, 13]], textOffset: 0 }]);
|
||||
expect(t!.text).toBe(" val order = 1");
|
||||
expect(t!.indices).toEqual([6, 7, 8, 9, 10]);
|
||||
expect([t!.col, t!.endCol]).toEqual([8, 13]);
|
||||
});
|
||||
|
||||
@@ -150,6 +152,28 @@ describe("items and rows", () => {
|
||||
expect(buildRows(sections, { headers: false }).map((r) => r.kind)).toEqual(["file", "more", "action"]);
|
||||
});
|
||||
|
||||
it("buildRows interleaves the All tab by relevance, keeping each source's order", () => {
|
||||
const file = (rel: string) => fileItem({ path: `/p/${rel}`, relPath: rel, indices: [] });
|
||||
const sections = new Map<SectionId, SectionState>([
|
||||
["files", { items: [file("src/upload_gray.py"), file("src/upgrade.py")], hasMore: true, loading: false }],
|
||||
["symbols", { items: [symbolItem(sym("upgrade", "function", "/p/m.py", 3))], hasMore: false, loading: false }],
|
||||
["text", { items: textItems("/p/a.md", "a.md", [{ line: 0, text: "upgrade", ranges: [[0, 3]], textOffset: 0 }]), hasMore: false, loading: false }],
|
||||
]);
|
||||
const rows = buildRows(sections, { headers: false, mix: "upg" });
|
||||
expect(rows.map((r) => (r.kind === "more" ? `more:${r.section}` : (r as { section: SectionId }).section))).toEqual([
|
||||
"symbols",
|
||||
"files",
|
||||
"files",
|
||||
"text",
|
||||
"more:files",
|
||||
]);
|
||||
// The index ranked upload_gray first; mixing must not reorder within files.
|
||||
expect(rows.filter((r) => r.kind === "file").map((r) => (r as { name: string }).name)).toEqual([
|
||||
"upload_gray.py",
|
||||
"upgrade.py",
|
||||
]);
|
||||
});
|
||||
|
||||
it("stableIndex keeps the selected key while rows stream in", () => {
|
||||
const sections = new Map<SectionId, SectionState>([
|
||||
["files", { items: [fileItem({ path: "/p/A.kt", relPath: "A.kt", indices: [] }), fileItem({ path: "/p/B.kt", relPath: "B.kt", indices: [] })], hasMore: false, loading: false }],
|
||||
@@ -184,7 +208,41 @@ describe("topResultSettled", () => {
|
||||
expect(topResultSettled(new Map([["classes", sec(false)], ["files", sec(false, 1)], ["text", sec(true)]]))).toBe(true);
|
||||
});
|
||||
|
||||
it("with mixing waits for every source but a text search the top row already beats", () => {
|
||||
const strong = { items: [fileItem({ path: "/p/upgrade.py", relPath: "upgrade.py", indices: [] })], hasMore: false, loading: false };
|
||||
expect(topResultSettled(new Map([["files", strong], ["symbols", sec(true)]]), "upg")).toBe(false);
|
||||
expect(topResultSettled(new Map([["files", strong], ["text", sec(true)]]), "upg")).toBe(true);
|
||||
const weak = { ...strong, items: [fileItem({ path: "/p/xuxpxg.py", relPath: "xuxpxg.py", indices: [] })] };
|
||||
expect(topResultSettled(new Map([["files", weak], ["text", sec(true)]]), "upg")).toBe(false);
|
||||
});
|
||||
|
||||
it("is settled when everything finished empty", () => {
|
||||
expect(topResultSettled(new Map([["files", sec(false)]]))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseCommand", () => {
|
||||
it("lists scope commands matching the typed prefix", () => {
|
||||
const c = parseCommand("/");
|
||||
expect(c?.kind === "list" && c.rows.map((r) => (r as { name: string }).name)).toEqual([
|
||||
"/classes",
|
||||
"/files",
|
||||
"/symbols",
|
||||
"/actions",
|
||||
"/text",
|
||||
]);
|
||||
const fi = parseCommand("/FI");
|
||||
expect(fi?.kind === "list" && fi.rows.map((r) => r.key)).toEqual(["cmd:files"]);
|
||||
});
|
||||
|
||||
it("runs a complete command followed by a space", () => {
|
||||
expect(parseCommand("/files upg")).toEqual({ kind: "run", tab: "files", rest: "upg" });
|
||||
expect(parseCommand("/text ")).toEqual({ kind: "run", tab: "text", rest: "" });
|
||||
});
|
||||
|
||||
it("leaves paths and other queries alone", () => {
|
||||
expect(parseCommand("/Users/me/a.py")).toBeNull();
|
||||
expect(parseCommand("/fil x")).toBeNull();
|
||||
expect(parseCommand("upg")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,17 @@
|
||||
.dialog {
|
||||
--se-bg-header: var(--bg-frame, var(--bg-app));
|
||||
max-height: 72vh;
|
||||
max-height: 80vh;
|
||||
margin-top: 9vh;
|
||||
background: var(--bg-popup, var(--bg-elev));
|
||||
font-family: var(--font-ui);
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
/* The list shrinks to fit (the footer stays visible) instead of the dialog body scrolling. */
|
||||
.dialog > :global([data-dialog-body]) {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
.header {
|
||||
flex: none;
|
||||
display: flex;
|
||||
@@ -50,6 +56,9 @@
|
||||
flex: none;
|
||||
color: var(--fg);
|
||||
}
|
||||
.scope {
|
||||
color: var(--fg);
|
||||
}
|
||||
.headerButton {
|
||||
flex: none;
|
||||
}
|
||||
@@ -72,8 +81,23 @@
|
||||
}
|
||||
.magnifier {
|
||||
flex: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 1px;
|
||||
height: 22px;
|
||||
padding: 0 2px;
|
||||
border: none;
|
||||
border-radius: var(--radius-small);
|
||||
background: none;
|
||||
color: var(--fg-subtle);
|
||||
}
|
||||
.magnifier:hover {
|
||||
background: var(--bg-hover);
|
||||
color: var(--fg);
|
||||
}
|
||||
.magnifier:focus-visible {
|
||||
outline: 2px solid var(--focus-ring, var(--accent));
|
||||
}
|
||||
.query {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
@@ -105,6 +129,12 @@
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
.preview {
|
||||
flex: none;
|
||||
display: flex;
|
||||
height: 220px;
|
||||
border-top: 1px solid var(--border-popup);
|
||||
}
|
||||
.section {
|
||||
font-family: var(--font-ui);
|
||||
}
|
||||
@@ -142,6 +172,45 @@
|
||||
}
|
||||
.code {
|
||||
font-family: var(--font-ui);
|
||||
color: var(--fg);
|
||||
tab-size: 2;
|
||||
}
|
||||
/* Lezer classHighlighter tokens of text hits (same colours as the Markdown preview). */
|
||||
.code :global(.tok-keyword),
|
||||
.code :global(.tok-modifier),
|
||||
.code :global(.tok-controlKeyword),
|
||||
.code :global(.tok-operatorKeyword) {
|
||||
color: var(--syn-keyword);
|
||||
}
|
||||
.code :global(.tok-string),
|
||||
.code :global(.tok-string2) {
|
||||
color: var(--syn-string);
|
||||
}
|
||||
.code :global(.tok-number),
|
||||
.code :global(.tok-bool),
|
||||
.code :global(.tok-atom) {
|
||||
color: var(--syn-number);
|
||||
}
|
||||
.code :global(.tok-typeName),
|
||||
.code :global(.tok-className),
|
||||
.code :global(.tok-namespace) {
|
||||
color: var(--syn-type);
|
||||
}
|
||||
.code :global(.tok-comment) {
|
||||
color: var(--syn-comment);
|
||||
}
|
||||
.code :global(.tok-meta),
|
||||
.code :global(.tok-macroName) {
|
||||
color: var(--syn-annotation);
|
||||
}
|
||||
.code :global(.tok-propertyName) {
|
||||
color: var(--syn-property);
|
||||
}
|
||||
.code :global(.tok-variableName.tok-definition) {
|
||||
color: var(--syn-function);
|
||||
}
|
||||
.repeat {
|
||||
color: var(--fg-faint);
|
||||
}
|
||||
.lineSuffix {
|
||||
color: var(--fg-muted);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, useState, type KeyboardEvent, type MouseEve
|
||||
import clsx from "clsx";
|
||||
import { actionToggled, executeAction, getAction } from "@/platform/actions";
|
||||
import type { ProjectFileSet } from "@/platform/ipc";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { hasPrimaryModifier, shortcutLabel } from "@/platform/keymap";
|
||||
import {
|
||||
Checkbox,
|
||||
@@ -21,8 +22,10 @@ import {
|
||||
T,
|
||||
} from "@/ui";
|
||||
import { useFileDecoration } from "@/workbench/contributions";
|
||||
import { highlightTokens, languageForPath, type CodeToken } from "@/editor/lsp/markdown";
|
||||
import { badgeKind, basename, openLocation, relDir } from "../common/open";
|
||||
import { parseLocationQuery } from "../common/query";
|
||||
import { CodePreview, type PreviewHighlight } from "../find/parts";
|
||||
import { SeController, type SeSnapshot } from "./controller";
|
||||
import { ipcDeps } from "./deps";
|
||||
import {
|
||||
@@ -32,13 +35,21 @@ import {
|
||||
TABS,
|
||||
buildRows,
|
||||
isSectionRow,
|
||||
parseCommand,
|
||||
stableIndex,
|
||||
topResultSettled,
|
||||
type SeRow,
|
||||
type SeTab,
|
||||
type SectionId,
|
||||
} from "./model";
|
||||
import { hideSearchEverywhere, pushRecentAction, useSearchEverywhere } from "./store";
|
||||
import {
|
||||
hideSearchEverywhere,
|
||||
pushRecentAction,
|
||||
pushSearchHistory,
|
||||
searchHistory,
|
||||
setSearchEverywherePreview,
|
||||
useSearchEverywhere,
|
||||
} from "./store";
|
||||
import styles from "./SearchEverywhere.module.css";
|
||||
|
||||
type SeScope = "allPlaces" | ProjectFileSet;
|
||||
@@ -51,7 +62,10 @@ const SE_SCOPES: Array<{ value: SeScope; label: string }> = [
|
||||
];
|
||||
|
||||
const ROW = 24;
|
||||
const MAX_LIST = 528;
|
||||
const MAX_LIST = 672;
|
||||
const MIN_LIST = 10 * ROW;
|
||||
/** List cap while the preview pane takes the lower part of the popup. */
|
||||
const MAX_LIST_PREVIEW = 312;
|
||||
const DEBOUNCE_MS = 60;
|
||||
|
||||
export function SearchEverywhereOverlay() {
|
||||
@@ -62,12 +76,14 @@ export function SearchEverywhereOverlay() {
|
||||
type Selection = { key: string | null; index: number; moved: boolean };
|
||||
|
||||
function SearchEverywhereDialog() {
|
||||
const tx = useTx();
|
||||
const tab = useSearchEverywhere((s) => s.tab);
|
||||
const query = useSearchEverywhere((s) => s.query);
|
||||
const includeNonProject = useSearchEverywhere((s) => s.includeNonProject);
|
||||
const fileSet = useSearchEverywhere((s) => s.fileSet);
|
||||
const session = useSearchEverywhere((s) => s.session);
|
||||
const ctx = useSearchEverywhere((s) => s.ctx);
|
||||
const preview = useSearchEverywhere((s) => s.preview);
|
||||
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
@@ -76,7 +92,13 @@ function SearchEverywhereDialog() {
|
||||
const [snap, setSnap] = useState<SeSnapshot | null>(null);
|
||||
const [controller] = useState(() => new SeController(ipcDeps(ctx), setSnap));
|
||||
const [sel, setSel] = useState<Selection>({ key: null, index: -1, moved: false });
|
||||
const [menu, setMenu] = useState<{ anchor: Element; items: MenuItem[] } | null>(null);
|
||||
const [menu, setMenu] = useState<{
|
||||
anchor: Element;
|
||||
items: MenuItem[];
|
||||
placement: "right-start" | "bottom-start";
|
||||
} | null>(null);
|
||||
/** Position in the tab's history while ⌥↑/⌥↓ browse it (-1 = the typed draft). */
|
||||
const history = useRef({ pos: -1, draft: "" });
|
||||
const [toggleTick, setToggleTick] = useState(0);
|
||||
const bumpToggles = () => setToggleTick((t) => t + 1);
|
||||
|
||||
@@ -96,28 +118,67 @@ function SearchEverywhereDialog() {
|
||||
setSel({ key: null, index: -1, moved: false });
|
||||
}
|
||||
|
||||
// "/fi" lists scope commands instead of searching.
|
||||
const listing = useMemo(() => {
|
||||
const c = parseCommand(query);
|
||||
return c?.kind === "list" ? c.rows : null;
|
||||
}, [query]);
|
||||
const searchQuery = parseCommand(debounced)?.kind === "list" ? "" : debounced;
|
||||
|
||||
useEffect(() => {
|
||||
controller.run({ query: debounced, tab, includeNonProject, fileSet: tab === "all" ? null : fileSet, extra });
|
||||
}, [controller, debounced, tab, includeNonProject, fileSet, extra]);
|
||||
controller.run({ query: searchQuery, tab, includeNonProject, fileSet: tab === "all" ? null : fileSet, extra });
|
||||
}, [controller, searchQuery, tab, includeNonProject, fileSet, extra]);
|
||||
|
||||
useEffect(() => {
|
||||
inputRef.current?.select();
|
||||
}, [session]);
|
||||
|
||||
const parsed = useMemo(() => parseLocationQuery(debounced), [debounced]);
|
||||
const parsed = useMemo(() => parseLocationQuery(searchQuery), [searchQuery]);
|
||||
// The All tab interleaves its sources by relevance once there is a query.
|
||||
const mix = tab === "all" ? parsed.text : undefined;
|
||||
const rows = useMemo(
|
||||
() => (snap ? buildRows(snap.sections, { headers: !parsed.text.trim() }) : []),
|
||||
[snap, parsed.text],
|
||||
() => listing ?? (snap ? buildRows(snap.sections, { headers: !parsed.text.trim(), mix }) : []),
|
||||
[listing, snap, parsed.text, mix],
|
||||
);
|
||||
const active = stableIndex(rows, sel.key, sel.index, sel.moved);
|
||||
const activeRow = active >= 0 ? rows[active] : undefined;
|
||||
// Rows still answer an older query (debounce / in-flight search): Enter must wait.
|
||||
const settled =
|
||||
!!snap && query === debounced && snap.query === debounced && snap.tab === tab && topResultSettled(snap.sections);
|
||||
!!snap &&
|
||||
query === debounced &&
|
||||
snap.query === debounced &&
|
||||
snap.tab === tab &&
|
||||
topResultSettled(snap.sections, mix);
|
||||
const pendingEnter = useRef<{ side: boolean } | null>(null);
|
||||
|
||||
const select = (index: number) => setSel({ key: rows[index]?.key ?? null, index, moved: true });
|
||||
/** Typed or picked query; "/files foo" switches to Files with "foo". */
|
||||
const setQuery = (value: string) => {
|
||||
history.current.pos = -1;
|
||||
const c = parseCommand(value);
|
||||
useSearchEverywhere.setState(c?.kind === "run" ? { tab: c.tab, query: c.rest } : { query: value });
|
||||
};
|
||||
const browseHistory = (dir: 1 | -1) => {
|
||||
const h = searchHistory(tab);
|
||||
const cur = history.current;
|
||||
const pos = Math.max(-1, Math.min(h.length - 1, cur.pos + dir));
|
||||
if (pos === cur.pos) return;
|
||||
if (cur.pos < 0) cur.draft = query;
|
||||
cur.pos = pos;
|
||||
useSearchEverywhere.setState({ query: pos < 0 ? cur.draft : h[pos]! });
|
||||
};
|
||||
const openHistory = (anchor: Element) => {
|
||||
const h = searchHistory(tab).slice(0, 15);
|
||||
const items: MenuItem[] = h.length
|
||||
? [
|
||||
{ kind: "header", label: "Recent Searches" },
|
||||
...h.map((q) => ({ label: q, verbatim: true, run: () => setQuery(q) })),
|
||||
]
|
||||
: [{ label: "No recent searches", disabled: true, run: () => {} }];
|
||||
setMenu({ anchor, items, placement: "bottom-start" });
|
||||
};
|
||||
const setTab = (t: SeTab) => {
|
||||
history.current.pos = -1;
|
||||
useSearchEverywhere.setState({ tab: t });
|
||||
inputRef.current?.focus();
|
||||
};
|
||||
@@ -135,9 +196,15 @@ function SearchEverywhereDialog() {
|
||||
|
||||
const activate = (row: SeRow | undefined, side = false) => {
|
||||
if (!row) return;
|
||||
const isResult = row.kind !== "section" && row.kind !== "more" && row.kind !== "command";
|
||||
if (isResult && !(row.kind === "action" && !row.enabled)) pushSearchHistory(tab, query);
|
||||
switch (row.kind) {
|
||||
case "section":
|
||||
return;
|
||||
case "command":
|
||||
useSearchEverywhere.setState({ tab: row.tab, query: "" });
|
||||
inputRef.current?.focus();
|
||||
return;
|
||||
case "more": {
|
||||
const step = tab === "all" ? MORE_STEP_ALL : MORE_STEP_TAB;
|
||||
setExtra((e) => ({ ...e, [row.section]: (e[row.section] ?? 0) + step }));
|
||||
@@ -179,7 +246,7 @@ function SearchEverywhereDialog() {
|
||||
|
||||
const openIntentions = () => {
|
||||
const row = activeRow;
|
||||
if (!row || row.kind === "section" || row.kind === "more") return;
|
||||
if (!row || row.kind === "section" || row.kind === "more" || row.kind === "command") return;
|
||||
const anchor = listRef.current?.querySelector('[aria-selected="true"]') ?? inputRef.current;
|
||||
if (!anchor) return;
|
||||
const copy = (text: string) => void navigator.clipboard?.writeText(text).catch(() => {});
|
||||
@@ -206,7 +273,7 @@ function SearchEverywhereDialog() {
|
||||
]
|
||||
: []),
|
||||
];
|
||||
setMenu({ anchor, items });
|
||||
setMenu({ anchor, items, placement: "right-start" });
|
||||
};
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
|
||||
@@ -222,10 +289,16 @@ function SearchEverywhereDialog() {
|
||||
if (e.altKey) openIntentions();
|
||||
else if (hasPrimaryModifier(e) && tab === "text")
|
||||
closeThen(() => void executeAction("find.inPath", { query: parsed.text }));
|
||||
else if (listing) activate(activeRow);
|
||||
else if (!settled && !sel.moved) pendingEnter.current = { side: e.shiftKey };
|
||||
else activate(activeRow, e.shiftKey);
|
||||
return;
|
||||
}
|
||||
if (e.altKey && (e.key === "ArrowUp" || e.key === "ArrowDown")) {
|
||||
e.preventDefault();
|
||||
browseHistory(e.key === "ArrowUp" ? 1 : -1);
|
||||
return;
|
||||
}
|
||||
if (!["ArrowDown", "ArrowUp", "PageDown", "PageUp"].includes(e.key)) return;
|
||||
const next = listNavigate(e.key, { items: rows, active, isSection: isSectionRow, wrap: true, pageSize: 10 });
|
||||
if (next === null) return;
|
||||
@@ -233,11 +306,14 @@ function SearchEverywhereDialog() {
|
||||
select(next);
|
||||
};
|
||||
|
||||
const listHeight = Math.min(MAX_LIST, rows.length * ROW);
|
||||
const maxList = preview ? MAX_LIST_PREVIEW : MAX_LIST;
|
||||
// While a query is typed the list keeps a minimum height so the popup doesn't jump with every keystroke.
|
||||
const minList = parsed.text.trim() && !listing ? MIN_LIST : 0;
|
||||
const listHeight = Math.min(maxList, Math.max(minList, rows.length * ROW));
|
||||
const previewTarget = previewOf(activeRow);
|
||||
const emptyQuery = !parsed.text.trim();
|
||||
const showEmpty = !rows.length && snap && !snap.loading && (!emptyQuery || tab !== "all");
|
||||
const canSplit =
|
||||
!!activeRow && activeRow.kind !== "section" && activeRow.kind !== "more" && activeRow.kind !== "action";
|
||||
const canSplit = activeRow?.kind === "file" || activeRow?.kind === "symbol" || activeRow?.kind === "text";
|
||||
const onTabKey = (e: KeyboardEvent<HTMLDivElement>) => {
|
||||
if (e.key !== "ArrowRight" && e.key !== "ArrowLeft") return;
|
||||
e.preventDefault();
|
||||
@@ -248,14 +324,14 @@ function SearchEverywhereDialog() {
|
||||
<Dialog
|
||||
open
|
||||
onClose={close}
|
||||
width={670}
|
||||
width={760}
|
||||
position="top"
|
||||
transparentBackdrop
|
||||
aria-label="Search Everywhere"
|
||||
aria-label={tx("Search Everywhere")}
|
||||
className={styles.dialog}
|
||||
>
|
||||
<div className={styles.header}>
|
||||
<div role="tablist" aria-label="Search scope" className={styles.tabs} onKeyDown={onTabKey}>
|
||||
<div role="tablist" aria-label={tx("Search scope")} className={styles.tabs} onKeyDown={onTabKey}>
|
||||
{TABS.map((t) => (
|
||||
<button
|
||||
key={t.id}
|
||||
@@ -267,7 +343,7 @@ function SearchEverywhereDialog() {
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => setTab(t.id)}
|
||||
>
|
||||
{t.label}
|
||||
<T>{t.label}</T>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
@@ -284,7 +360,8 @@ function SearchEverywhereDialog() {
|
||||
) : (
|
||||
// IDEA's scope chooser of the Classes / Files / Symbols / Text tabs.
|
||||
<Select<SeScope>
|
||||
className={styles.include}
|
||||
variant="ghost"
|
||||
className={clsx(styles.include, styles.scope)}
|
||||
value={includeNonProject ? "allPlaces" : fileSet}
|
||||
options={SE_SCOPES}
|
||||
onChange={(v) => {
|
||||
@@ -297,17 +374,36 @@ function SearchEverywhereDialog() {
|
||||
/>
|
||||
)}
|
||||
<IconButton
|
||||
icon="external-link"
|
||||
icon="list"
|
||||
size="small"
|
||||
className={styles.headerButton}
|
||||
title="Open in Find Tool Window"
|
||||
title={tx("Preview")}
|
||||
pressed={preview}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => setSearchEverywherePreview(!preview)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="open-in-tool-window"
|
||||
size="small"
|
||||
className={styles.headerButton}
|
||||
title={tx("Open in Find Tool Window")}
|
||||
shortcut={tab === "text" ? "⌘↵" : undefined}
|
||||
onClick={() => closeThen(() => void executeAction("find.inPath", { query: parsed.text }))}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.queryRow}>
|
||||
<div className={styles.field}>
|
||||
<Icon name="search" size={16} className={styles.magnifier} />
|
||||
<button
|
||||
type="button"
|
||||
className={styles.magnifier}
|
||||
aria-label={tx("Search history")}
|
||||
title={tx("Search history (⌥↑ / ⌥↓)")}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={(e) => openHistory(e.currentTarget)}
|
||||
>
|
||||
<Icon name="search" size={16} />
|
||||
<Icon name="chevron-down" size={10} />
|
||||
</button>
|
||||
<input
|
||||
id="se-query"
|
||||
ref={inputRef}
|
||||
@@ -322,14 +418,16 @@ function SearchEverywhereDialog() {
|
||||
aria-expanded
|
||||
aria-controls="se-results"
|
||||
aria-autocomplete="list"
|
||||
aria-label="Search query"
|
||||
onChange={(e) => useSearchEverywhere.setState({ query: e.target.value })}
|
||||
aria-label={tx("Search query")}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
/>
|
||||
{snap?.loading && !emptyQuery && <Spinner size={14} className={styles.spinner} />}
|
||||
<span className={styles.hint} aria-hidden>
|
||||
{hintFor(tab)}
|
||||
</span>
|
||||
{hintFor(tab) && (
|
||||
<span className={styles.hint} aria-hidden>
|
||||
<T>{hintFor(tab)}</T>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{(rows.length > 0 || showEmpty) && (
|
||||
@@ -344,7 +442,9 @@ function SearchEverywhereDialog() {
|
||||
items={rows}
|
||||
getKey={(r) => r.key}
|
||||
isSection={isSectionRow}
|
||||
renderSection={(r) => <span className={styles.section}>{r.kind === "section" ? r.title : ""}</span>}
|
||||
renderSection={(r) => (
|
||||
<span className={styles.section}>{r.kind === "section" ? <T>{r.title}</T> : ""}</span>
|
||||
)}
|
||||
activeIndex={active}
|
||||
onActiveChange={select}
|
||||
onActivate={(r, _i, e) => activate(r, (e as MouseEvent).shiftKey)}
|
||||
@@ -352,20 +452,37 @@ function SearchEverywhereDialog() {
|
||||
rowHeight={ROW}
|
||||
sectionHeight={ROW}
|
||||
className={styles.list}
|
||||
aria-label="Results"
|
||||
aria-label={tx("Results")}
|
||||
renderItem={(r, state) => (
|
||||
<ResultRow row={r} active={state.active} toggleTick={toggleTick} onToggled={bumpToggles} />
|
||||
<ResultRow
|
||||
row={r}
|
||||
active={state.active}
|
||||
repeat={sameFile(rows[state.index - 1], r)}
|
||||
toggleTick={toggleTick}
|
||||
onToggled={bumpToggles}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
{showEmpty && (
|
||||
<div className={styles.empty}>
|
||||
{emptyQuery ? "Type to search" : includeNonProject ? "Nothing found" : "Nothing found in project files"}
|
||||
{tx(
|
||||
emptyQuery ? "Type to search" : includeNonProject ? "Nothing found" : "Nothing found in project files",
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!rows.length && !showEmpty && <div id="se-results" ref={listRef} hidden />}
|
||||
{preview && rows.length > 0 && (
|
||||
<div className={styles.preview}>
|
||||
<CodePreview
|
||||
path={previewTarget?.path ?? null}
|
||||
line={previewTarget?.line ?? 0}
|
||||
highlights={previewTarget?.highlights ?? []}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{rows.length > 0 && (
|
||||
<footer className={styles.footer}>
|
||||
<span className={styles.footerInfo}>{describe(activeRow)}</span>
|
||||
@@ -380,7 +497,7 @@ function SearchEverywhereDialog() {
|
||||
open={!!menu}
|
||||
anchor={menu?.anchor ?? null}
|
||||
items={menu?.items ?? []}
|
||||
placement="right-start"
|
||||
placement={menu?.placement ?? "right-start"}
|
||||
onClose={() => {
|
||||
setMenu(null);
|
||||
inputRef.current?.focus();
|
||||
@@ -395,6 +512,7 @@ function describe(row: SeRow | undefined): string {
|
||||
switch (row.kind) {
|
||||
case "section":
|
||||
case "more":
|
||||
case "command":
|
||||
return "";
|
||||
case "action": {
|
||||
const a = getAction(row.id);
|
||||
@@ -408,14 +526,31 @@ function describe(row: SeRow | undefined): string {
|
||||
}
|
||||
}
|
||||
|
||||
function previewOf(row: SeRow | undefined): { path: string; line: number; highlights: PreviewHighlight[] } | null {
|
||||
switch (row?.kind) {
|
||||
case "file":
|
||||
return { path: row.path, line: row.line ?? 0, highlights: [] };
|
||||
case "symbol":
|
||||
return {
|
||||
path: row.path,
|
||||
line: row.line,
|
||||
highlights: [{ line: row.line, ranges: [[row.col, row.col + row.name.length]] }],
|
||||
};
|
||||
case "text":
|
||||
return { path: row.path, line: row.line, highlights: [{ line: row.line, ranges: [[row.col, row.endCol]] }] };
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function hintFor(tab: SeTab): string {
|
||||
switch (tab) {
|
||||
case "all":
|
||||
return "Type / to see commands";
|
||||
case "text":
|
||||
return "⌘↵ to open in Find tool window";
|
||||
case "files":
|
||||
return "Type file name, path or file:42";
|
||||
default:
|
||||
return "⇥ to switch scope";
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -424,23 +559,47 @@ function dirOf(path: string) {
|
||||
return i > 0 ? path.slice(0, i) : path;
|
||||
}
|
||||
|
||||
/** A text hit in the same file as the row above (its file name is dimmed, like IDEA). */
|
||||
function sameFile(prev: SeRow | undefined, row: SeRow): boolean {
|
||||
return row.kind === "text" && prev?.kind === "text" && prev.path === row.path;
|
||||
}
|
||||
|
||||
function ResultRow({
|
||||
row,
|
||||
active,
|
||||
repeat,
|
||||
toggleTick,
|
||||
onToggled,
|
||||
}: {
|
||||
row: SeRow;
|
||||
active: boolean;
|
||||
repeat: boolean;
|
||||
toggleTick: number;
|
||||
onToggled: () => void;
|
||||
}) {
|
||||
const tx = useTx();
|
||||
const tone = "strong";
|
||||
switch (row.kind) {
|
||||
case "section":
|
||||
return null;
|
||||
case "command":
|
||||
return (
|
||||
<>
|
||||
<Icon name="search" size={16} className={styles.icon} />
|
||||
<span className={styles.main}>
|
||||
<span className={styles.name}>{row.name}</span>
|
||||
</span>
|
||||
<span className={styles.right}>
|
||||
<T>{row.label}</T>
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
case "more":
|
||||
return <span className={clsx(styles.name, styles.more)}>… more {SECTION_TITLES[row.section].toLowerCase()}</span>;
|
||||
return (
|
||||
<span className={clsx(styles.name, styles.more)}>
|
||||
… {tx("more")} {tx(SECTION_TITLES[row.section]).toLowerCase()}
|
||||
</span>
|
||||
);
|
||||
case "file":
|
||||
return <FileRow path={row.path} name={row.name} dir={row.dir} indices={row.nameIndices} line={row.line} />;
|
||||
case "symbol":
|
||||
@@ -496,24 +655,62 @@ function ResultRow({
|
||||
return (
|
||||
<>
|
||||
<span className={styles.icon}>
|
||||
<Icon name={fileIconName(basename(row.rel))} size={16} />
|
||||
<Icon name="text-match" size={16} />
|
||||
</span>
|
||||
<span className={styles.main}>
|
||||
<HighlightedText
|
||||
className={clsx(styles.name, styles.code)}
|
||||
text={row.text}
|
||||
indices={row.indices}
|
||||
tone={tone}
|
||||
/>
|
||||
<CodeText path={row.path} text={row.text} indices={row.indices} />
|
||||
</span>
|
||||
<span className={clsx(styles.right, active && styles.rightActive)}>
|
||||
{basename(row.rel)} {row.line + 1}
|
||||
<span className={clsx(repeat && !active && styles.repeat)}>{basename(row.rel)}</span> {row.line + 1}
|
||||
</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const tokenCache = new Map<string, CodeToken[]>();
|
||||
|
||||
/** A text hit's line, syntax-coloured by the file's language (one line parsed on its own). */
|
||||
function CodeText({ path, text, indices }: { path: string; text: string; indices: readonly number[] }) {
|
||||
const language = useMemo(() => languageForPath(path), [path]);
|
||||
const key = `${language}\u0000${text}`;
|
||||
const [loaded, setLoaded] = useState<{ key: string; tokens: CodeToken[] } | null>(null);
|
||||
const tokens = tokenCache.get(key) ?? (loaded?.key === key ? loaded.tokens : null);
|
||||
useEffect(() => {
|
||||
if (tokens || !language) return;
|
||||
let alive = true;
|
||||
void highlightTokens(text, language).then((t) => {
|
||||
tokenCache.set(key, t);
|
||||
if (tokenCache.size > 500) tokenCache.delete(tokenCache.keys().next().value!);
|
||||
if (alive) setLoaded({ key, tokens: t });
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [key, language, text, tokens]);
|
||||
|
||||
const parts: Array<[number, number, string]> = [];
|
||||
let pos = 0;
|
||||
for (const t of tokens ?? []) {
|
||||
if (t.from > pos) parts.push([pos, t.from, ""]);
|
||||
parts.push([t.from, t.to, t.cls]);
|
||||
pos = t.to;
|
||||
}
|
||||
if (pos < text.length) parts.push([pos, text.length, ""]);
|
||||
return (
|
||||
<span className={clsx(styles.name, styles.code)}>
|
||||
{parts.map(([s, e, cls]) => (
|
||||
<HighlightedText
|
||||
key={s}
|
||||
className={cls || undefined}
|
||||
text={text.slice(s, e)}
|
||||
indices={indices.filter((i) => i >= s && i < e).map((i) => i - s)}
|
||||
/>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function FileRow({
|
||||
path,
|
||||
name,
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
import type { Action } from "@/platform/actions";
|
||||
import type { FileMatch, LineMatch, SymbolMatch, WorkspaceSymbol } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { basename, isTypeKind, relDir, symbolDisplayName } from "../common/open";
|
||||
import { byScore, matchText } from "../common/rank";
|
||||
|
||||
@@ -110,7 +111,7 @@ export interface TextItem {
|
||||
line: number;
|
||||
col: number;
|
||||
endCol: number;
|
||||
/** Preview with leading whitespace removed. */
|
||||
/** The line with its indentation collapsed to at most two spaces. */
|
||||
text: string;
|
||||
indices: number[];
|
||||
}
|
||||
@@ -119,6 +120,7 @@ export type SeItem = FileItem | SymbolItem | ActionItem | TextItem;
|
||||
|
||||
export type SeRow =
|
||||
| { kind: "section"; key: string; section: SectionId; title: string }
|
||||
| { kind: "command"; key: string; name: string; tab: SeTab; label: string }
|
||||
| { kind: "more"; key: string; section: SectionId }
|
||||
| (SeItem & { section: SectionId });
|
||||
|
||||
@@ -131,7 +133,11 @@ export interface SectionState {
|
||||
// ---------------------------------------------------------------------------
|
||||
// Item builders
|
||||
|
||||
export function fileItem(m: Pick<FileMatch, "path" | "relPath" | "indices">, line: number | null = null, col: number | null = null): FileItem {
|
||||
export function fileItem(
|
||||
m: Pick<FileMatch, "path" | "relPath" | "indices">,
|
||||
line: number | null = null,
|
||||
col: number | null = null,
|
||||
): FileItem {
|
||||
const name = basename(m.relPath);
|
||||
const nameStart = m.relPath.length - name.length;
|
||||
return {
|
||||
@@ -239,12 +245,19 @@ export function matchActions(
|
||||
if (!enabled && opts.includeDisabled === false) continue;
|
||||
let score: number;
|
||||
let indices: number[] = [];
|
||||
const title = matchText(a.title, q, { wordAligned: true });
|
||||
const translated = tx(a.title);
|
||||
const title = matchText(translated, q, { wordAligned: true });
|
||||
// The English title still matches; its indices don't apply to the translated text.
|
||||
const english = title || translated === a.title ? undefined : matchText(a.title, q, { wordAligned: true });
|
||||
if (title) {
|
||||
score = title.score;
|
||||
indices = title.indices;
|
||||
} else if (english) {
|
||||
score = english.score;
|
||||
} else {
|
||||
const extra = [a.category, a.description, ...(a.keywords ?? [])].filter((s): s is string => !!s);
|
||||
const extra = [a.category ? tx(a.category) : "", a.description, ...(a.keywords ?? [])].filter(
|
||||
(s): s is string => !!s,
|
||||
);
|
||||
const best = Math.max(-Infinity, ...extra.map((s) => matchText(s, q, { wordAligned: true })?.score ?? -Infinity));
|
||||
const idHit = a.id.toLowerCase().includes(q.toLowerCase()) ? 0 : -Infinity;
|
||||
score = Math.max(best, idHit) - 400;
|
||||
@@ -257,8 +270,8 @@ export function matchActions(
|
||||
kind: "action",
|
||||
key: `a:${a.id}`,
|
||||
id: a.id,
|
||||
title: a.title,
|
||||
category: a.category,
|
||||
title: translated,
|
||||
category: a.category ? tx(a.category) : a.category,
|
||||
icon: a.icon,
|
||||
enabled,
|
||||
indices,
|
||||
@@ -273,8 +286,8 @@ export function actionItem(a: Action, enabled: boolean): ActionItem {
|
||||
kind: "action",
|
||||
key: `a:${a.id}`,
|
||||
id: a.id,
|
||||
title: a.title,
|
||||
category: a.category,
|
||||
title: tx(a.title),
|
||||
category: a.category ? tx(a.category) : a.category,
|
||||
icon: a.icon,
|
||||
enabled,
|
||||
indices: [],
|
||||
@@ -285,10 +298,14 @@ export function actionItem(a: Action, enabled: boolean): ActionItem {
|
||||
export function textItems(path: string, rel: string, matches: readonly LineMatch[]): TextItem[] {
|
||||
const out: TextItem[] = [];
|
||||
for (const m of matches) {
|
||||
const lead = m.text.length - m.text.trimStart().length;
|
||||
const text = m.text.slice(lead).trimEnd();
|
||||
const ws = m.text.length - m.text.trimStart().length;
|
||||
// Like IDEA: a hint of indentation shows nesting without wasting the row.
|
||||
const indent = " ".repeat(Math.min(ws, 2));
|
||||
const lead = ws - indent.length;
|
||||
const text = indent + m.text.slice(ws).trimEnd();
|
||||
const indices: number[] = [];
|
||||
for (const [s, e] of m.ranges) for (let i = Math.max(s, lead); i < e; i++) if (i - lead < text.length) indices.push(i - lead);
|
||||
for (const [s, e] of m.ranges)
|
||||
for (let i = Math.max(s, ws); i < e; i++) if (i - lead < text.length) indices.push(i - lead);
|
||||
const first = m.ranges[0] ?? [0, 0];
|
||||
out.push({
|
||||
kind: "text",
|
||||
@@ -308,11 +325,71 @@ export function textItems(path: string, rel: string, matches: readonly LineMatch
|
||||
// ---------------------------------------------------------------------------
|
||||
// Rows
|
||||
|
||||
/** Sections the All tab mixes into one relevance-ordered list. */
|
||||
const MIXED: readonly SectionId[] = ["classes", "files", "symbols", "actions", "text"];
|
||||
|
||||
/**
|
||||
* Weight of a text hit: a literal substring in a line ranks below name
|
||||
* matches that start a word but above scattered name subsequences.
|
||||
*/
|
||||
export const TEXT_WEIGHT = 350;
|
||||
|
||||
/** Comparable match degree of an item's name against the query (IDEA's `MatchingDegree`). */
|
||||
export function itemWeight(item: SeItem, query: string): number {
|
||||
const name = (text: string) => matchText(text, query)?.score;
|
||||
switch (item.kind) {
|
||||
case "file":
|
||||
return name(item.name) ?? (name(item.rel) ?? 0) - 200;
|
||||
case "symbol":
|
||||
return name(item.name) ?? (item.container ? name(`${item.container}.${item.name}`) : undefined) ?? 0;
|
||||
case "action":
|
||||
return item.score;
|
||||
case "text":
|
||||
return TEXT_WEIGHT;
|
||||
}
|
||||
}
|
||||
|
||||
interface Mixed {
|
||||
item: SeItem;
|
||||
section: SectionId;
|
||||
weight: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The All tab's results interleaved by weight. Within a section the source's
|
||||
* order wins (the index already ranks with recency etc.), so weights are
|
||||
* clamped to be non-increasing; ties keep the section order.
|
||||
*/
|
||||
export function mixItems(sections: ReadonlyMap<SectionId, SectionState>, query: string): Mixed[] {
|
||||
const out: Array<Mixed & { rank: number }> = [];
|
||||
MIXED.forEach((id, rank) => {
|
||||
let cap = Infinity;
|
||||
for (const item of sections.get(id)?.items ?? []) {
|
||||
cap = Math.min(cap, itemWeight(item, query));
|
||||
out.push({ item, section: id, weight: cap, rank });
|
||||
}
|
||||
});
|
||||
return out
|
||||
.map((m, i) => ({ m, i }))
|
||||
.sort((a, b) => b.m.weight - a.m.weight || a.m.rank - b.m.rank || a.i - b.i)
|
||||
.map(({ m }) => m);
|
||||
}
|
||||
|
||||
/**
|
||||
* Flat rows the dialog renders. With `mix` (the All tab's query) results are
|
||||
* interleaved by relevance and "more" rows follow them; otherwise sections
|
||||
* keep their fixed order.
|
||||
*/
|
||||
export function buildRows(
|
||||
sections: ReadonlyMap<SectionId, SectionState>,
|
||||
opts: { headers: boolean },
|
||||
opts: { headers: boolean; mix?: string },
|
||||
): SeRow[] {
|
||||
const rows: SeRow[] = [];
|
||||
if (opts.mix?.trim()) {
|
||||
for (const m of mixItems(sections, opts.mix.trim())) rows.push({ ...m.item, section: m.section });
|
||||
for (const id of MIXED) if (sections.get(id)?.hasMore) rows.push({ kind: "more", key: `+${id}`, section: id });
|
||||
return rows;
|
||||
}
|
||||
for (const id of SECTION_ORDER) {
|
||||
const s = sections.get(id);
|
||||
if (!s || !s.items.length) continue;
|
||||
@@ -325,12 +402,47 @@ export function buildRows(
|
||||
|
||||
export const isSectionRow = (r: SeRow) => r.kind === "section";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// "/" commands
|
||||
|
||||
export const COMMANDS: ReadonlyArray<{ name: string; tab: SeTab; label: string }> = TABS.filter(
|
||||
(t) => t.id !== "all",
|
||||
).map((t) => ({ name: `/${t.id}`, tab: t.id, label: t.label }));
|
||||
|
||||
export type ParsedCommand = { kind: "list"; rows: SeRow[] } | { kind: "run"; tab: SeTab; rest: string };
|
||||
|
||||
/**
|
||||
* `/` or `/fi` lists the matching scope commands; `/files foo` switches to
|
||||
* Files and searches `foo`. Anything else (e.g. an absolute path) is a query.
|
||||
*/
|
||||
export function parseCommand(query: string): ParsedCommand | null {
|
||||
const m = /^\/(\S*)(?:\s+([\s\S]*))?$/.exec(query);
|
||||
if (!m) return null;
|
||||
const word = m[1]!.toLowerCase();
|
||||
if (m[2] !== undefined) {
|
||||
const cmd = COMMANDS.find((c) => c.name === `/${word}`);
|
||||
return cmd ? { kind: "run", tab: cmd.tab, rest: m[2] } : null;
|
||||
}
|
||||
const rows: SeRow[] = COMMANDS.filter((c) => c.name.startsWith(`/${word}`)).map((c) => ({
|
||||
kind: "command",
|
||||
key: `cmd:${c.tab}`,
|
||||
...c,
|
||||
}));
|
||||
return rows.length ? { kind: "list", rows } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the top result is final: every section above the first one with
|
||||
* items has finished. Enter typed before that waits (IDEA opens the first
|
||||
* result of the new query, never a stale row of the previous one).
|
||||
* With `mix`, any section can still outrank the top row; only a slow text
|
||||
* search is not waited for once the top row beats every text hit.
|
||||
*/
|
||||
export function topResultSettled(sections: ReadonlyMap<SectionId, SectionState>): boolean {
|
||||
export function topResultSettled(sections: ReadonlyMap<SectionId, SectionState>, mix?: string): boolean {
|
||||
if (mix?.trim()) {
|
||||
const top = mixItems(sections, mix.trim())[0]?.weight ?? -Infinity;
|
||||
return MIXED.every((id) => !sections.get(id)?.loading || (id === "text" && top > TEXT_WEIGHT));
|
||||
}
|
||||
for (const id of SECTION_ORDER) {
|
||||
const s = sections.get(id);
|
||||
if (!s) continue;
|
||||
|
||||
@@ -15,8 +15,12 @@ interface SeState {
|
||||
ctx: ContextKeys;
|
||||
/** Bumped on every (re)open so the field re-selects its text. */
|
||||
session: number;
|
||||
/** Code preview of the selected result under the list (remembered). */
|
||||
preview: boolean;
|
||||
}
|
||||
|
||||
const PREVIEW_KEY = "openidea.search.everywherePreview.v1";
|
||||
|
||||
export const useSearchEverywhere = create<SeState>(() => ({
|
||||
open: false,
|
||||
tab: "all",
|
||||
@@ -25,8 +29,14 @@ export const useSearchEverywhere = create<SeState>(() => ({
|
||||
fileSet: "all",
|
||||
ctx: {},
|
||||
session: 0,
|
||||
preview: loadJson<unknown>(PREVIEW_KEY, false) === true,
|
||||
}));
|
||||
|
||||
export function setSearchEverywherePreview(preview: boolean) {
|
||||
useSearchEverywhere.setState({ preview });
|
||||
saveJson(PREVIEW_KEY, preview);
|
||||
}
|
||||
|
||||
/** Opens (or re-targets) the dialog. Re-invoking the same scope toggles "include non-project items", like IDEA. */
|
||||
export function showSearchEverywhere(tab: SeTab, opts: { query?: string; toggleOnRepeat?: boolean } = {}) {
|
||||
const s = useSearchEverywhere.getState();
|
||||
@@ -64,3 +74,32 @@ export function recentActions(): string[] {
|
||||
export function pushRecentAction(id: string) {
|
||||
saveJson(RECENT_ACTIONS_KEY, [id, ...recentActions().filter((x) => x !== id)].slice(0, MAX_RECENT_ACTIONS));
|
||||
}
|
||||
|
||||
const HISTORY_KEY = "openidea.search.everywhereHistory.v1";
|
||||
const MAX_HISTORY = 50;
|
||||
|
||||
interface HistoryEntry {
|
||||
tab: SeTab;
|
||||
query: string;
|
||||
}
|
||||
|
||||
function loadHistory(): HistoryEntry[] {
|
||||
const v = loadJson<unknown>(HISTORY_KEY, []);
|
||||
return Array.isArray(v)
|
||||
? v.filter((x): x is HistoryEntry => typeof x?.tab === "string" && typeof x?.query === "string")
|
||||
: [];
|
||||
}
|
||||
|
||||
/** Queries that led somewhere in `tab`, newest first. */
|
||||
export function searchHistory(tab: SeTab): string[] {
|
||||
return loadHistory()
|
||||
.filter((e) => e.tab === tab)
|
||||
.map((e) => e.query);
|
||||
}
|
||||
|
||||
export function pushSearchHistory(tab: SeTab, query: string) {
|
||||
const q = query.trim();
|
||||
if (!q) return;
|
||||
const rest = loadHistory().filter((e) => e.tab !== tab || e.query !== q);
|
||||
saveJson(HISTORY_KEY, [{ tab, query: q }, ...rest].slice(0, MAX_HISTORY));
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
setLocale,
|
||||
t,
|
||||
tx,
|
||||
txTemplate,
|
||||
useI18n,
|
||||
} from "./i18n";
|
||||
import en from "./locales/en.json";
|
||||
@@ -116,6 +117,16 @@ describe("t / locales", () => {
|
||||
expect(tx(undefined)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("matches source-text templates, translating the substituted text", async () => {
|
||||
expect(txTemplate("Push failed")).toBe("Push failed");
|
||||
await setLocale("zh");
|
||||
expect(txTemplate("ruff is not installed")).toBe("ruff 未安装");
|
||||
expect(txTemplate("Language server 'gopls' is not installed")).toBe("语言服务器 'gopls' 未安装");
|
||||
expect(txTemplate("Retry failed")).toBe(`${tx("Retry")}失败`);
|
||||
expect(txTemplate("Sync with OS")).toBe("与操作系统同步");
|
||||
expect(txTemplate("Something else entirely")).toBe("Something else entirely");
|
||||
});
|
||||
|
||||
it("lists keys by prefix", () => {
|
||||
const keys = keysWithPrefix("menu.");
|
||||
expect(keys).toContain("menu.file.save");
|
||||
@@ -133,6 +144,12 @@ describe("catalogs", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("keep the placeholders of source-text templates", () => {
|
||||
const names = (m: string) => [...m.matchAll(/\{(\w+)\}/g)].map((x) => x[1]).sort();
|
||||
for (const [source, text] of Object.entries(zhText as Record<string, string>))
|
||||
expect(names(text), source).toEqual(names(source));
|
||||
});
|
||||
|
||||
it("have the same keys", () => {
|
||||
expect(Object.keys(zh).sort()).toEqual(Object.keys(en).sort());
|
||||
});
|
||||
|
||||
@@ -178,6 +178,62 @@ export function useTx(): typeof tx {
|
||||
}, [texts]);
|
||||
}
|
||||
|
||||
type Template = { pattern: RegExp; names: string[]; translation: string; literal: number };
|
||||
|
||||
const templateCache = new WeakMap<Catalog, Template[]>();
|
||||
|
||||
/** Source-text entries with `{name}` placeholders, e.g. `"{name} is not installed"`. */
|
||||
function templatesOf(texts: Catalog): Template[] {
|
||||
let templates = templateCache.get(texts);
|
||||
if (templates) return templates;
|
||||
templates = [];
|
||||
for (const [source, translation] of Object.entries(texts)) {
|
||||
const names: string[] = [];
|
||||
const parts = source.split(/\{(\w+)\}/);
|
||||
if (parts.length < 2) continue;
|
||||
const pattern = parts
|
||||
.map((part, i) => (i % 2 ? (names.push(part), "(.+?)") : part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")))
|
||||
.join("");
|
||||
templates.push({
|
||||
pattern: new RegExp(`^${pattern}$`),
|
||||
names,
|
||||
translation,
|
||||
literal: source.length - names.join("").length,
|
||||
});
|
||||
}
|
||||
// Most specific first: `Language server '{name}' is not installed` before `{name} is not installed`.
|
||||
templates.sort((a, b) => b.literal - a.literal);
|
||||
templateCache.set(texts, templates);
|
||||
return templates;
|
||||
}
|
||||
|
||||
function translateText(texts: Catalog, text: string): string {
|
||||
const exact = texts[text];
|
||||
if (exact !== undefined) return exact;
|
||||
for (const { pattern, names, translation } of templatesOf(texts)) {
|
||||
const m = pattern.exec(text);
|
||||
if (!m) continue;
|
||||
const params: MessageParams = {};
|
||||
names.forEach((name, i) => (params[name] = texts[m[i + 1]!] ?? m[i + 1]));
|
||||
return formatMessage(translation, params);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/**
|
||||
* `tx` for text built at runtime (notification titles): also matches source-text
|
||||
* templates such as `"{name} failed"`, translating the substituted parts as text.
|
||||
*/
|
||||
export function txTemplate(text: string): string {
|
||||
return translateText(useI18n.getState().texts, text);
|
||||
}
|
||||
|
||||
/** `txTemplate` bound to the current locale; components re-render when it changes. */
|
||||
export function useTxTemplate(): (text: string) => string {
|
||||
const texts = useI18n((s) => s.texts);
|
||||
return useCallback((text: string) => translateText(texts, text), [texts]);
|
||||
}
|
||||
|
||||
/** All keys with `prefix`, across the active catalog and the English fallback. */
|
||||
export function keysWithPrefix(prefix: string): string[] {
|
||||
const keys = new Set<string>();
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
"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": "保存时激活",
|
||||
@@ -154,6 +155,7 @@
|
||||
"Bookmarks": "书签",
|
||||
"Bottom": "底部",
|
||||
"Branch": "分支",
|
||||
"Branch '{name}' has no tracked branch": "分支 '{name}' 没有跟踪分支",
|
||||
"Branch, %": "分支,%",
|
||||
"Branch, tag or commit hash": "分支、标签或提交哈希",
|
||||
"Branches": "分支",
|
||||
@@ -189,18 +191,23 @@
|
||||
"Cannot annotate": "无法注解",
|
||||
"Cannot change line separators": "无法更改行分隔符",
|
||||
"Cannot commit": "无法提交",
|
||||
"Cannot connect to {target}": "无法连接到 {target}",
|
||||
"Cannot convert encoding": "无法转换编码",
|
||||
"Cannot create scratch file": "无法创建临时文件",
|
||||
"Cannot create the HTTP request file": "无法创建 HTTP 请求文件",
|
||||
"Cannot duplicate the data source": "无法复制数据源",
|
||||
"Cannot execute": "无法执行",
|
||||
"Cannot execute on {target}": "无法在 {target} 上执行",
|
||||
"Cannot export data": "无法导出数据",
|
||||
"Cannot find usages of '{name}'": "无法查找 '{name}' 的用法",
|
||||
"Cannot generate the DDL": "无法生成 DDL",
|
||||
"Cannot get the DDL of {name}": "无法获取 {name} 的 DDL",
|
||||
"Cannot open file": "无法打开文件",
|
||||
"Cannot open library class": "无法打开库类",
|
||||
"Cannot open link": "无法打开链接",
|
||||
"Cannot open the query console": "无法打开查询控制台",
|
||||
"Cannot open the response": "无法打开响应",
|
||||
"Cannot profile '{name}'": "无法分析 '{name}'",
|
||||
"Cannot put label": "无法添加标签",
|
||||
"Cannot read data sources": "无法读取数据源",
|
||||
"Cannot read the file:": "无法读取文件:",
|
||||
@@ -211,6 +218,7 @@
|
||||
"Cannot reload with encoding": "无法使用该编码重新加载",
|
||||
"Cannot remove recent project": "无法移除最近的项目",
|
||||
"Cannot roll back": "无法回滚",
|
||||
"Cannot run '{name}' with coverage": "无法使用覆盖率运行 '{name}'",
|
||||
"Cannot run the script": "无法运行脚本",
|
||||
"Cannot save run configurations": "无法保存运行配置",
|
||||
"Cannot save setting": "无法保存设置",
|
||||
@@ -235,6 +243,7 @@
|
||||
"Changes were not submitted": "更改未提交",
|
||||
"Check TODO": "检查 TODO",
|
||||
"Check out a branch to create a pull request from": "请先签出一个分支,再从它创建拉取请求",
|
||||
"Checked out pull request #{number}": "已检出拉取请求 #{number}",
|
||||
"Checking installed tools…": "正在检查已安装的工具…",
|
||||
"Checking tools": "正在检查工具",
|
||||
"Checkout": "签出",
|
||||
@@ -666,6 +675,8 @@
|
||||
"External tools": "外部工具",
|
||||
"External tools actions": "外部工具操作",
|
||||
"Extract Method…": "提取方法…",
|
||||
"Failed to install {name}": "安装 {name} 失败",
|
||||
"Failed to uninstall {name}": "卸载 {name} 失败",
|
||||
"FIXME comment": "FIXME 注释",
|
||||
"Failed": "失败",
|
||||
"Failed to restart language server": "重启语言服务器失败",
|
||||
@@ -853,6 +864,8 @@
|
||||
"IDE Updates": "IDE 更新",
|
||||
"IDE font": "IDE 字体",
|
||||
"IDE font size": "IDE 字体大小",
|
||||
"Installed {name}": "已安装 {name}",
|
||||
"Installing {name}": "正在安装 {name}",
|
||||
"IPC round trip": "IPC 往返",
|
||||
"Idle seconds": "空闲秒数",
|
||||
"Ignore files and folders": "忽略文件和文件夹",
|
||||
@@ -962,6 +975,7 @@
|
||||
"Language": "语言",
|
||||
"Language Defaults": "语言默认值",
|
||||
"Language Server": "语言服务器",
|
||||
"Language server '{name}' is not installed": "语言服务器 '{name}' 未安装",
|
||||
"Language Servers": "语言服务器",
|
||||
"Language Servers…": "语言服务器…",
|
||||
"Language Services": "语言服务",
|
||||
@@ -1139,12 +1153,15 @@
|
||||
"Next Occurrence": "下一个匹配项",
|
||||
"Next Page": "下一页",
|
||||
"Next error action goes to high priority problems only": "“下一个错误”操作仅转到高优先级问题",
|
||||
"No coverage data for '{name}'": "没有 '{name}' 的覆盖率数据",
|
||||
"No Environment": "无环境",
|
||||
"No GitHub repository": "没有 GitHub 仓库",
|
||||
"No Gradle projects": "没有 Gradle 项目",
|
||||
"No HTTP request at the caret": "光标处没有 HTTP 请求",
|
||||
"No Maven projects": "没有 Maven 项目",
|
||||
"No profile for '{name}'": "没有 '{name}' 的分析数据",
|
||||
"No Python found": "未找到 Python",
|
||||
"No recent searches": "无最近搜索",
|
||||
"No TODO items found": "未找到 TODO 项",
|
||||
"No TODO items in this file": "此文件中没有 TODO 项",
|
||||
"No active editor": "没有活动编辑器",
|
||||
@@ -1209,6 +1226,7 @@
|
||||
"No surround templates for this language": "此语言没有包围模板",
|
||||
"No tools match.": "没有匹配的工具。",
|
||||
"No usages found": "未找到用法",
|
||||
"No usages of '{name}' found": "未找到 '{name}' 的用法",
|
||||
"Node interpreter": "Node 解释器",
|
||||
"None": "无",
|
||||
"None configured": "未配置",
|
||||
@@ -1216,6 +1234,7 @@
|
||||
"Not logged in to GitHub": "未登录 GitHub",
|
||||
"Not null": "非空",
|
||||
"Nothing found": "未找到任何内容",
|
||||
"Nothing found in project files": "项目文件中未找到任何内容",
|
||||
"Nothing here": "这里什么都没有",
|
||||
"Nothing is running": "没有正在运行的内容",
|
||||
"Nothing matches": "没有匹配项",
|
||||
@@ -1466,6 +1485,7 @@
|
||||
"Rebase the current branch on top of incoming changes": "将当前分支变基到传入的更改之上",
|
||||
"Rebuild Last": "重新构建上一次",
|
||||
"Rebuild Project": "重新构建项目",
|
||||
"Recent Actions": "最近的操作",
|
||||
"Recent Files": "最近的文件",
|
||||
"Recent Locations": "最近的位置",
|
||||
"Recent Projects": "最近的项目",
|
||||
@@ -1475,6 +1495,7 @@
|
||||
"Recent files": "最近的文件",
|
||||
"Recent locations": "最近的位置",
|
||||
"Recent projects": "最近的项目",
|
||||
"Recent Searches": "最近搜索",
|
||||
"Recently Viewed Files": "最近查看的文件",
|
||||
"Record": "记录",
|
||||
"Red": "红色",
|
||||
@@ -1610,6 +1631,8 @@
|
||||
"Restore Size": "恢复大小",
|
||||
"Restore detected roots": "恢复检测到的根",
|
||||
"Result": "结果",
|
||||
"result": "个结果",
|
||||
"results": "个结果",
|
||||
"Results": "结果",
|
||||
"Resume Program": "恢复程序",
|
||||
"Retry": "重试",
|
||||
@@ -1625,6 +1648,7 @@
|
||||
"Review comment": "审查评论",
|
||||
"Review comments": "审查评论",
|
||||
"Review requested": "请求审查",
|
||||
"Review submitted on #{number}": "已在 #{number} 上提交审查",
|
||||
"Review ▾": "审查 ▾",
|
||||
"Reviewers": "审查者",
|
||||
"Revision": "修订",
|
||||
@@ -1643,6 +1667,7 @@
|
||||
"Run Code › Analyze Code › Locate Duplicates… to find copied code": "运行“代码 › 分析代码 › 查找重复项…”以查找复制的代码",
|
||||
"Run Code › Inspect Code… to analyse files": "运行“代码 › 检查代码…”以分析文件",
|
||||
"Run Command in Terminal": "在终端中运行命令",
|
||||
"Run `pnpm tauri dev` to use the file system.": "运行 `pnpm tauri dev` 以使用文件系统。",
|
||||
"Run Configuration": "运行配置",
|
||||
"Run Context Configuration": "运行上下文配置",
|
||||
"Run Context Configuration with Coverage": "使用覆盖率运行上下文配置",
|
||||
@@ -1684,6 +1709,9 @@
|
||||
"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}' 的用法",
|
||||
"SQL Inserts": "SQL Insert 语句",
|
||||
"SQL Script Template": "SQL 脚本模板",
|
||||
"SQL Scripts": "SQL 脚本",
|
||||
@@ -1821,6 +1849,7 @@
|
||||
"Show TODO Items in Current File": "显示当前文件中的 TODO 项",
|
||||
"Show Tool Window Names": "显示工具窗口名称",
|
||||
"Show Usage Results": "显示用法结果",
|
||||
"Select Configuration": "选择配置",
|
||||
"Show Usages": "显示用法",
|
||||
"Show Warnings": "显示警告",
|
||||
"Show all output": "显示所有输出",
|
||||
@@ -1935,6 +1964,7 @@
|
||||
"Stop Request": "停止请求",
|
||||
"Stop and Rerun": "停止并重新运行",
|
||||
"Stop to Edit": "停止以编辑",
|
||||
"Stopped after {count} matches": "匹配 {count} 处后停止",
|
||||
"Strikeout": "删除线",
|
||||
"Struct": "结构体",
|
||||
"Struct type": "结构体类型",
|
||||
@@ -1966,6 +1996,7 @@
|
||||
"System Settings": "系统设置",
|
||||
"System default": "系统默认",
|
||||
"System-Dependent": "取决于系统",
|
||||
"Tests failed: {detail}": "测试失败:{detail}",
|
||||
"TODO comment": "TODO 注释",
|
||||
"TODO filters": "TODO 过滤器",
|
||||
"TODO items": "TODO 项",
|
||||
@@ -2081,12 +2112,14 @@
|
||||
"Trust and Connect": "信任并连接",
|
||||
"Tx: Auto": "事务:自动",
|
||||
"Tx: Manual": "事务:手动",
|
||||
"Type / to see commands": "输入 / 查看命令",
|
||||
"Type Declaration": "类型声明",
|
||||
"Type Hierarchy": "类型层次结构",
|
||||
"Type an expression followed by": "输入表达式,后跟",
|
||||
"Type hierarchy": "类型层次结构",
|
||||
"Type to filter by file name or code": "输入以按文件名或代码过滤",
|
||||
"Type to filter symbols": "输入以过滤符号",
|
||||
"Type to search": "输入以搜索",
|
||||
"TypeScript version": "TypeScript 版本",
|
||||
"Types": "类型",
|
||||
"Typography Settings": "排版设置",
|
||||
@@ -2094,6 +2127,7 @@
|
||||
"UI elements take up less screen space": "UI 元素占用更少的屏幕空间",
|
||||
"UI font": "UI 字体",
|
||||
"UI font size": "UI 字体大小",
|
||||
"Uninstalled {name}": "已卸载 {name}",
|
||||
"URL:": "URL:",
|
||||
"Unchecked values are inherited from the scheme.": "未勾选的值继承自方案。",
|
||||
"Uncommitted changes are stashed before the update and restored afterwards.": "更新前会储藏未提交的更改,并在之后恢复。",
|
||||
@@ -2128,9 +2162,14 @@
|
||||
"Upgrade": "升级",
|
||||
"Uptime": "运行时间",
|
||||
"Usage searches": "用法搜索",
|
||||
"Usage search did not finish; nothing was deleted": "用法搜索未完成;未删除任何内容",
|
||||
"usage": "处用法",
|
||||
"usages": "处用法",
|
||||
"more": "更多",
|
||||
"Usages": "用法",
|
||||
"Usages Detected": "检测到用法",
|
||||
"Usages actions": "用法操作",
|
||||
"Usages of '{symbol}'": "'{symbol}' 的用法",
|
||||
"Usages of element at caret": "光标处元素的用法",
|
||||
"Use \"CamelHumps\" words": "使用“驼峰”单词",
|
||||
"Use 24-hour time format": "使用 24 小时制",
|
||||
@@ -2297,10 +2336,16 @@
|
||||
"with BOM under Windows, with no BOM otherwise": "在 Windows 下带 BOM,其他系统不带 BOM",
|
||||
"with NO BOM": "不带 BOM",
|
||||
"with statement": "with 语句",
|
||||
"{count} rows exported": "已导出 {count} 行",
|
||||
"{name} failed": "{name}失败",
|
||||
"{name} has unsaved changes": "{name} 有未保存的更改",
|
||||
"{name} installed": "{name} 已安装",
|
||||
"{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 名称的驼峰处停止。",
|
||||
"Specify commit message": "请填写提交信息",
|
||||
"Author:": "作者:",
|
||||
|
||||
@@ -38,6 +38,8 @@ export type MenuItem =
|
||||
kind?: "item";
|
||||
id?: string;
|
||||
label: string;
|
||||
/** User text (e.g. a past query): shown as is, never looked up in the catalog. */
|
||||
verbatim?: boolean;
|
||||
icon?: IconName | (string & {});
|
||||
shortcut?: string;
|
||||
disabled?: boolean;
|
||||
@@ -86,7 +88,12 @@ export function resolveMenuItems(items: MenuItem[]): Resolved[] {
|
||||
});
|
||||
return;
|
||||
}
|
||||
out.push({ ...item, label: tx(item.label), kind: "item", key: item.id ?? `${i}:${item.label}` });
|
||||
out.push({
|
||||
...item,
|
||||
label: item.verbatim ? item.label : tx(item.label),
|
||||
kind: "item",
|
||||
key: item.id ?? `${i}:${item.label}`,
|
||||
});
|
||||
});
|
||||
while (out.length && out[out.length - 1]!.kind === "separator") out.pop();
|
||||
return out;
|
||||
|
||||
@@ -178,6 +178,8 @@ const ICONS = {
|
||||
regex: "inline/regex",
|
||||
case: "inline/matchCase",
|
||||
word: "inline/exactWords",
|
||||
"text-match": "openidea/nodes/textMatch",
|
||||
"open-in-tool-window": "general/openInToolWindow",
|
||||
"preserve-case": "openidea/inline/preserveCase",
|
||||
filter: "general/filter",
|
||||
refresh: "general/refresh",
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
<!-- OpenIDEA: text occurrence (Search Everywhere › Text) -->
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect x="2.5" y="2.5" width="11" height="11" rx="2" stroke="#6C707E"/><path d="M5.5 5.5H10.5M8 5.5V10.5" stroke="#6C707E" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
Після Ширина: | Висота: | Розмір: 314 B |
@@ -1,5 +1,6 @@
|
||||
import { executeAction, useActions } from "@/platform/actions";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { T } from "@/ui";
|
||||
import { useWorkbenchSlots } from "./contributions";
|
||||
import { ErrorBoundary, Slot } from "./ErrorBoundary";
|
||||
import styles from "./EditorArea.module.css";
|
||||
@@ -26,10 +27,10 @@ export function EmptyEditor() {
|
||||
<dt>
|
||||
{runnable ? (
|
||||
<button type="button" className={styles.hintButton} onClick={() => void executeAction(h.action!)}>
|
||||
{h.label}
|
||||
<T>{h.label}</T>
|
||||
</button>
|
||||
) : (
|
||||
h.label
|
||||
<T>{h.label}</T>
|
||||
)}
|
||||
</dt>
|
||||
{keys && <dd className={styles.keys}>{keys}</dd>}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTxTemplate } from "@/platform/i18n";
|
||||
import { EmptyState, IconButton, Toast, T } from "@/ui";
|
||||
import {
|
||||
BALLOON_TIMEOUT,
|
||||
@@ -21,6 +22,7 @@ function timeLabel(t: number) {
|
||||
|
||||
function Balloon({ n }: { n: IdeNotification }) {
|
||||
const [hover, setHover] = useState(false);
|
||||
const txt = useTxTemplate();
|
||||
useEffect(() => {
|
||||
const ms = BALLOON_TIMEOUT[n.level];
|
||||
if (n.sticky || ms === null || hover) return;
|
||||
@@ -31,10 +33,10 @@ function Balloon({ n }: { n: IdeNotification }) {
|
||||
<Toast
|
||||
className={styles.balloon}
|
||||
level={n.level}
|
||||
title={n.title}
|
||||
title={txt(n.title)}
|
||||
body={n.body}
|
||||
actions={n.actions?.map((a) => ({
|
||||
label: a.label,
|
||||
label: txt(a.label),
|
||||
run: () => {
|
||||
dismissBalloon(n.id);
|
||||
a.run();
|
||||
@@ -73,6 +75,7 @@ function useListVisible() {
|
||||
|
||||
/** The Notifications tool window (right stripe, as in IDEA): history, newest first. */
|
||||
export function NotificationsToolWindow() {
|
||||
const txt = useTxTemplate();
|
||||
const all = useNotifications((s) => s.items);
|
||||
const items = all.filter((n) => n.logged);
|
||||
const visible = useListVisible();
|
||||
@@ -92,10 +95,10 @@ export function NotificationsToolWindow() {
|
||||
key={n.id}
|
||||
className={styles.entry}
|
||||
level={n.level}
|
||||
title={n.title}
|
||||
title={txt(n.title)}
|
||||
body={n.body}
|
||||
meta={timeLabel(n.time)}
|
||||
actions={n.actions}
|
||||
actions={n.actions?.map((a) => ({ ...a, label: txt(a.label) }))}
|
||||
onClose={() => removeNotification(n.id)}
|
||||
/>
|
||||
))
|
||||
|
||||
Reference in new issue
Заблокувати користувача