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

..
Автор SHA1 Повідомлення Дата
l0ng-ai c46c1e5b66 feat(ssh): apply LocalForward and RemoteForward from the SSH config 2026-11-27 05:01:55 +08:00
81 змінених файлів з 260 додано та 1947 видалено

No files matched your search

Створено
+1
Переглянути файл
@@ -4440,6 +4440,7 @@ dependencies = [
"serde_json",
"specta",
"tracing",
"which",
]
[[package]]
-10
Переглянути файл
@@ -486,16 +486,6 @@ pub struct LanguageCodeStyle {
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
#[serde(skip_serializing_if = "Option::is_none")]
pub identifier_case: Option<String>,
/// Java: organize imports switches to a wildcard import once this many
/// classes of one package are used (jdtls `starThreshold`; IDEA's default
/// 5; unset keeps the language server's default).
#[serde(skip_serializing_if = "Option::is_none")]
pub class_count_to_use_import_with_star: Option<u32>,
/// Java: organize imports switches to a wildcard static import once this
/// many statically imported names are used (jdtls `staticStarThreshold`;
/// IDEA's default 3; unset keeps the language server's default).
#[serde(skip_serializing_if = "Option::is_none")]
pub names_count_to_use_static_import_with_star: Option<u32>,
/// JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`.
#[serde(skip_serializing_if = "Option::is_none")]
pub semicolons: Option<String>,
-32
Переглянути файл
@@ -73,38 +73,6 @@ pub fn find_command(command: &str, search: &OsStr, root: &Path) -> Option<PathBu
dirs.into_iter().find_map(|dir| names.iter().map(|name| dir.join(name)).find(|p| is_executable(p)))
}
const GH_FALLBACK_PATHS: &[&str] = if cfg!(windows) {
&[r"C:\Program Files\GitHub CLI\gh.exe"]
} else {
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
};
/// Locates `gh` across `OPENIDEA_GH`, [`search_path`] (which includes IDE-managed tools
/// only when installed, then the user's `PATH`), and standard OS install locations.
pub fn find_gh_executable() -> Option<PathBuf> {
let explicit = std::env::var_os("OPENIDEA_GH").map(PathBuf::from);
find_gh_in(explicit.as_deref(), &search_path(), GH_FALLBACK_PATHS)
}
/// Locates a pre-installed `gh` outside [`search_path`] (`OPENIDEA_GH`, Windows Program Files,
/// Linux Snap) so tool detection reports it as available without prompting for a duplicate install.
pub fn find_gh_outside_search_path() -> Option<PathBuf> {
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| is_executable(p)) {
return Some(explicit);
}
GH_FALLBACK_PATHS.iter().map(PathBuf::from).find(|p| is_executable(p))
}
pub fn find_gh_in(explicit: Option<&Path>, search: &OsStr, fallbacks: &[&str]) -> Option<PathBuf> {
if let Some(explicit) = explicit.filter(|p| is_executable(p)) {
return Some(explicit.to_path_buf());
}
if let Some(found) = find_command("gh", search, Path::new("")) {
return Some(found);
}
fallbacks.iter().map(PathBuf::from).find(|p| is_executable(p))
}
fn is_executable(path: &Path) -> bool {
let Ok(metadata) = path.metadata() else { return false };
#[cfg(unix)]
+1
Переглянути файл
@@ -12,3 +12,4 @@ serde.workspace = true
serde_json.workspace = true
specta.workspace = true
tracing.workspace = true
which = "8"
+18 -37
Переглянути файл
@@ -16,15 +16,30 @@ use serde::{Deserialize, Serialize};
use specta::Type;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;
use std::time::Duration;
/// API calls normally answer within a few seconds.
const QUICK: Duration = Duration::from_secs(60);
/// Locates the gh executable (GUI apps on macOS have a minimal `PATH`, and the IDE can
/// install or remove a managed copy in its tools directory at runtime).
/// Locates the gh executable once per process (GUI apps on macOS have a minimal `PATH`).
pub fn gh_executable() -> Option<PathBuf> {
ide_core::tool_path::find_gh_executable()
static GH: OnceLock<Option<PathBuf>> = OnceLock::new();
GH.get_or_init(|| {
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| p.is_file()) {
return Some(explicit);
}
if let Ok(found) = which::which("gh") {
return Some(found);
}
let candidates: &[&str] = if cfg!(windows) {
&[r"C:\Program Files\GitHub CLI\gh.exe"]
} else {
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
};
candidates.iter().map(PathBuf::from).find(|p| p.is_file())
})
.clone()
}
fn command(root: &Path, args: &[&str]) -> IdeResult<Command> {
@@ -371,37 +386,3 @@ pub fn prepare_diff(
let files = repo.diff_files(&base, head_oid)?;
Ok(PrDiffRevisions { base, head: head_oid.to_owned(), files, root: ide_core::IpcPath(repo.root().to_path_buf()) })
}
#[cfg(test)]
mod tests {
#[test]
fn gh_executable_picks_up_newly_installed_binary_without_restart() {
let dir = std::env::temp_dir().join(format!("openidea-gh-test-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let search = std::env::join_paths([&dir]).unwrap();
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None);
let gh = dir.join(if cfg!(windows) { "gh.exe" } else { "gh" });
std::fs::write(&gh, "#!/bin/sh\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
}
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), Some(gh.clone()));
let explicit = dir.join(if cfg!(windows) { "custom-gh.exe" } else { "custom-gh" });
std::fs::write(&explicit, "#!/bin/sh\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&explicit, std::fs::Permissions::from_mode(0o755)).unwrap();
}
assert_eq!(ide_core::tool_path::find_gh_in(Some(&explicit), &search, &[]), Some(explicit));
std::fs::remove_file(&gh).unwrap();
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None);
let _ = std::fs::remove_dir_all(&dir);
}
}
+3 -7
Переглянути файл
@@ -29,19 +29,15 @@ fn tools(host: &Host, window: &str) -> IdeResult<Tools> {
&root,
&settings,
));
// Godot and GitHub CLI can live in app bundles / MSI / Snap folders outside the search path.
let mut found: std::collections::BTreeMap<_, _> =
ide_sdk::godot::find(None).map(|p| (ide_sdk::godot::COMMAND.to_owned(), p)).into_iter().collect();
if let Some(gh) = ide_core::tool_path::find_gh_outside_search_path() {
found.insert("gh".to_owned(), gh);
}
// Godot is usually an app bundle / Flatpak outside the search path.
let found = ide_sdk::godot::find(None).map(|p| (ide_sdk::godot::COMMAND.to_owned(), p));
let runtime = ide_sdk::apply::tool_install_environment(&root, &settings);
let work_dir = (!root.as_os_str().is_empty()).then_some(root);
Ok(Tools::new(&data)
.with_downloads(settings.tool_downloads.clone())
.with_runtime(runtime.commands, runtime.env)
.with_custom_paths(custom)
.with_found_paths(found)
.with_found_paths(found.into_iter().collect())
.with_work_dir(work_dir))
}
-1
Переглянути файл
@@ -697,7 +697,6 @@ async fn typescript() {
}
/// The latest `tsc` diagnostics of `path` (Problems › TypeScript Project Errors), `None` before any.
#[cfg(unix)]
fn tsc_errors(events: &Events, path: &Path) -> Option<Vec<String>> {
events.lock().unwrap().iter().rev().find_map(|e| match e {
IdeEvent::Diagnostics { path: p, source, items } if source == "tsc" && **p == *path => {
+1 -1
Переглянути файл
@@ -6,6 +6,7 @@ use ide_host::{Host, HostConfig};
use ide_plugin::TextQuery;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
struct Harness {
host: Arc<Host>,
@@ -509,7 +510,6 @@ async fn plugin_run_output_mode_executes_pty_and_pipes_with_input_exit_and_stop(
use ide_host::plugins::{Consent, PluginEvent, PluginHost, WindowRequest};
use ide_plugin::{Invocation, Limits};
use std::os::unix::fs::PermissionsExt;
use std::time::Duration;
let f = Harness::new();
f.host.set_project_trust(&f.root, true, false).await.unwrap();
-53
Переглянути файл
@@ -34,20 +34,6 @@ fn indent_settings(style: &LanguageCodeStyle) -> Option<Vec<(&'static str, Strin
Some(settings)
}
/// Java organize-imports thresholds as jdtls settings (IDEA's "Class count to use import with
/// '*'" and "Names count to use static import with '*'"). Unset ones are IDEA's defaults, 5 and 3:
/// jdtls' own are 99 (single imports), and it keeps a value it was sent until another one comes.
/// A threshold the server configuration sets explicitly is kept.
fn organize_imports_settings(style: Option<&LanguageCodeStyle>, inherited: &serde_json::Value) -> serde_json::Value {
let explicit = |key: &str| inherited.pointer(&format!("/java/sources/organizeImports/{key}")).cloned();
let class_count = style.and_then(|s| s.class_count_to_use_import_with_star).unwrap_or(5);
let static_count = style.and_then(|s| s.names_count_to_use_static_import_with_star).unwrap_or(3);
json!({
"starThreshold": explicit("starThreshold").unwrap_or(json!(class_count)),
"staticStarThreshold": explicit("staticStarThreshold").unwrap_or(json!(static_count)),
})
}
fn patch_profile_xml(mut xml: String, settings: &[(&'static str, String)]) -> String {
for (id, value) in settings {
let marker = format!(r#"<setting id="{id}" value=""#);
@@ -98,7 +84,6 @@ pub fn configure_formatter(
});
let mut settings = cfg.settings.take().unwrap_or_else(|| json!({}));
settings["java"]["format"]["settings"] = formatter_overrides(defaults, overrides);
settings["java"]["sources"]["organizeImports"] = organize_imports_settings(style, &inherited);
cfg.settings = Some(settings);
let Some(style) = style else { return Ok(()) };
let indent = indent_settings(style);
@@ -315,44 +300,6 @@ mod tests {
}
}
#[test]
fn organize_imports_thresholds_default_to_idea_and_keep_explicit_server_settings() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("project");
std::fs::create_dir_all(&root).unwrap();
let imports = |cfg: &LanguageServerConfig| {
crate::handler::all_settings(cfg)["java"]["sources"]["organizeImports"].clone()
};
let mut cfg = config("jdtls");
let style = LanguageCodeStyle {
class_count_to_use_import_with_star: Some(7),
names_count_to_use_static_import_with_star: Some(4),
..Default::default()
};
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
assert_eq!(imports(&cfg), json!({"starThreshold": 7, "staticStarThreshold": 4}));
// Unset: IDEA's 5 and 3, not jdtls' 99 (#6026).
let mut cfg = config("jdtls");
let style = LanguageCodeStyle { names_count_to_use_static_import_with_star: Some(2), ..Default::default() };
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
assert_eq!(imports(&cfg), json!({"starThreshold": 5, "staticStarThreshold": 2}));
let mut cfg = config("jdtls");
configure_formatter(&mut cfg, None, &root, dir.path(), None).unwrap();
assert_eq!(imports(&cfg), json!({"starThreshold": 5, "staticStarThreshold": 3}));
// A threshold set in the server configuration wins.
let mut cfg = config("jdtls");
cfg.settings = Some(json!({"java": {"sources": {"organizeImports": {"starThreshold": 99}}}}));
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
assert_eq!(imports(&cfg), json!({"starThreshold": 99, "staticStarThreshold": 2}));
let mut cfg = config("rust-analyzer");
configure_formatter(&mut cfg, None, &root, dir.path(), None).unwrap();
assert!(crate::handler::all_settings(&cfg)["java"].is_null());
}
#[test]
fn default_keeps_explicit_server_configuration_and_custom_accepts_absolute_paths() {
let dir = tempfile::tempdir().unwrap();
+5 -1
Переглянути файл
@@ -4,7 +4,7 @@
//! without network.
use crate::platform::{Arch, Os, Platform};
use crate::process::Emit;
use crate::process::{Emit, Http};
use crate::sources::Download;
use crate::{InstallEvent, InstallGuard, Tools, archive, clear_quarantine, fetch_verified};
use ide_core::error::ErrorKind;
@@ -240,6 +240,10 @@ fn unpacked_root(pkg: &Path, home: &Path) -> PathBuf {
}
impl Tools {
fn http(&self) -> IdeResult<Http> {
Http::new(&self.system_path)
}
/// Java versions `vendor` publishes.
pub fn jdk_releases(&self, vendor: &str, cancel: &CancellationToken) -> IdeResult<JdkReleases> {
vendor_or_err(vendor)?;
+4 -9
Переглянути файл
@@ -557,10 +557,6 @@ impl Tools {
&self.root
}
pub(crate) fn http(&self) -> IdeResult<Http> {
Ok(Http::new(&self.system_path)?.with_gh_from(&self.child_path))
}
/// [`Tools::command`] in the project directory.
fn command_in_project(&self, program: impl AsRef<std::ffi::OsStr>) -> Command {
let mut cmd = self.command(program);
@@ -906,7 +902,7 @@ impl Tools {
_ => (ToolStatus::Missing, None, None),
}
}
_ => match self.which(main).or_else(|| self.found.get(main).cloned()) {
_ => match self.which(main) {
Some(path) => {
let version = self.query_version(spec, &path);
(ToolStatus::OnPath, Some(path), version)
@@ -1254,8 +1250,7 @@ impl Tools {
dotnet::SDK_DOWNLOAD_URL
)));
};
let pick = self
.http()
let pick = Http::new(&self.system_path)
.and_then(|http| dotnet::pick_tool_version(package, sdk.major, |url| http.get_text(url, cancel)));
match pick {
Ok(dotnet::ToolPick::Latest) => Ok(None),
@@ -1547,7 +1542,7 @@ impl Tools {
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<()> {
let http = self.http()?;
let http = Http::new(&self.system_path)?;
let message = match source {
ReleaseSource::GitHubTag { tag, .. } => format!("Resolving release {tag}…"),
_ => "Resolving the latest release…".into(),
@@ -1688,7 +1683,7 @@ impl Tools {
fn latest_version(&self, method: Method, cancel: &CancellationToken) -> IdeResult<Option<String>> {
match method {
Method::Release { source, assets, .. } => {
let http = self.http()?;
let http = Http::new(&self.system_path)?;
Ok(Some(self.resolve_release(&http, source, assets, cancel)?.version))
}
Method::Npm { packages } => {
-11
Переглянути файл
@@ -441,17 +441,6 @@ impl Http {
self
}
/// Looks up `gh` on `search_path` (e.g. a path that includes IDE-managed tools).
pub(crate) fn with_gh_from(mut self, search_path: &std::ffi::OsStr) -> Self {
self.gh = which::which_in("gh", Some(search_path), ".").ok();
self
}
#[cfg(test)]
pub(crate) fn gh_path(&self) -> Option<&Path> {
self.gh.as_deref()
}
/// Skips `GITHUB_TOKEN` / `GH_TOKEN` / `gh auth token` (e.g. retrying a public GitHub endpoint after HTTP 401).
pub fn without_github_auth(mut self) -> Self {
self.gh = None;
-74
Переглянути файл
@@ -181,28 +181,6 @@ pub static TOOLS: &[ToolSpec] = &[
needs: NODE,
homepage: "https://github.com/devcontainers/cli",
},
ToolSpec {
name: "gh",
display: "GitHub CLI",
kind: Cli,
commands: &["gh"],
method: Method::Release {
source: ReleaseSource::GitHub { repo: "cli/cli" },
assets: &[
rule(Mac, Arm64, "gh_*_macOS_arm64.zip"),
rule(Mac, X64, "gh_*_macOS_amd64.zip"),
rule(Linux, Arm64, "gh_*_linux_arm64.tar.gz"),
rule(Linux, X64, "gh_*_linux_amd64.tar.gz"),
rule(Windows, Arm64, "gh_*_windows_arm64.zip"),
rule(Windows, X64, "gh_*_windows_amd64.zip"),
],
locate: &["gh"],
},
fallback: None,
version: ver("gh"),
needs: &[],
homepage: "https://cli.github.com",
},
ToolSpec {
name: "oxfmt",
display: "oxfmt",
@@ -1505,56 +1483,4 @@ mod tests {
let win_arm = Platform { os: Windows, arch: Arm64 };
assert_eq!(select_asset(&names, rules, win_arm), Some("kotlin-server-263.7084.0-aarch64.win.zip"));
}
#[test]
fn gh_release_picks_portable_archive_for_every_supported_platform() {
use crate::platform::{Platform, select_asset};
let names = [
"gh_2.106.0_checksums.txt",
"gh_2.106.0_linux_386.deb",
"gh_2.106.0_linux_386.tar.gz",
"gh_2.106.0_linux_amd64.deb",
"gh_2.106.0_linux_amd64.rpm",
"gh_2.106.0_linux_amd64.tar.gz",
"gh_2.106.0_linux_arm64.deb",
"gh_2.106.0_linux_arm64.tar.gz",
"gh_2.106.0_linux_armv6.tar.gz",
"gh_2.106.0_macOS_amd64.zip",
"gh_2.106.0_macOS_arm64.zip",
"gh_2.106.0_macOS_universal.pkg",
"gh_2.106.0_windows_386.zip",
"gh_2.106.0_windows_amd64.msi",
"gh_2.106.0_windows_amd64.zip",
"gh_2.106.0_windows_arm64.msi",
"gh_2.106.0_windows_arm64.zip",
];
let spec = find("gh").unwrap();
assert_eq!(spec.kind, Cli);
let rules = spec.asset_rules();
for (os, arch, expected) in [
(Mac, Arm64, "gh_2.106.0_macOS_arm64.zip"),
(Mac, X64, "gh_2.106.0_macOS_amd64.zip"),
(Linux, Arm64, "gh_2.106.0_linux_arm64.tar.gz"),
(Linux, X64, "gh_2.106.0_linux_amd64.tar.gz"),
(Windows, Arm64, "gh_2.106.0_windows_arm64.zip"),
(Windows, X64, "gh_2.106.0_windows_amd64.zip"),
] {
assert_eq!(select_asset(&names, rules, Platform { os, arch }), Some(expected));
}
let Method::Release { locate, .. } = &spec.method else { unreachable!() };
let tmp = tempfile::tempdir().unwrap();
let unix_bin = tmp.path().join("gh_2.106.0_macOS_arm64/bin/gh");
std::fs::create_dir_all(unix_bin.parent().unwrap()).unwrap();
std::fs::write(&unix_bin, "").unwrap();
let unix_names: Vec<String> = locate.iter().map(|n| (*n).to_owned()).collect();
assert_eq!(crate::archive::locate(tmp.path(), &unix_names), Some(unix_bin));
let win_dir = tempfile::tempdir().unwrap();
let win_bin = win_dir.path().join("bin/gh.exe");
std::fs::create_dir_all(win_bin.parent().unwrap()).unwrap();
std::fs::write(&win_bin, "").unwrap();
let win_names: Vec<String> = locate.iter().map(|n| format!("{n}.exe")).collect();
assert_eq!(crate::archive::locate(win_dir.path(), &win_names), Some(win_bin));
}
}
-27
Переглянути файл
@@ -147,11 +147,6 @@ fn pick_release(
let checksum_url = assets
.iter()
.find(|c| c.name == format!("{name}.sha256") || c.name == format!("{name}.sha256sum"))
.or_else(|| {
assets
.iter()
.find(|c| c.name.eq_ignore_ascii_case("checksums.txt") || c.name.ends_with("_checksums.txt"))
})
.map(|c| c.url.clone());
return Ok(Download {
version,
@@ -627,28 +622,6 @@ mod tests {
let sums = format!("{} other.zip\n{} *wanted.zip\n", "b".repeat(64), "C".repeat(64));
assert_eq!(parse_checksum(&sums, "wanted.zip"), Some("c".repeat(64)));
assert_eq!(parse_checksum(&sums, "missing.zip"), None);
let gh = serde_json::json!({
"tag_name": "v2.106.0",
"assets": [
{
"name": "gh_2.106.0_macOS_arm64.zip",
"browser_download_url": "https://github.com/cli/cli/releases/download/v2.106.0/gh_2.106.0_macOS_arm64.zip"
},
{
"name": "gh_2.106.0_checksums.txt",
"browser_download_url": "https://github.com/cli/cli/releases/download/v2.106.0/gh_2.106.0_checksums.txt"
}
]
})
.to_string();
let dl = github_pick(&gh, find("gh").unwrap().asset_rules(), MAC_ARM).unwrap();
assert_eq!(dl.version, "2.106.0");
assert_eq!(dl.name, "gh_2.106.0_macOS_arm64.zip");
assert_eq!(
dl.checksum_url.as_deref(),
Some("https://github.com/cli/cli/releases/download/v2.106.0/gh_2.106.0_checksums.txt")
);
}
#[test]
-24
Переглянути файл
@@ -1428,27 +1428,3 @@ fn a_mirror_never_installs_what_it_alone_vouches_for() {
let err = check_sha256(&archive, &dl(Some(&digest)), Some(&"0".repeat(64)), true, &emit).unwrap_err();
assert!(err.message.contains("checksum mismatch"), "{}", err.message);
}
#[cfg(unix)]
#[test]
fn managed_gh_is_detected_on_tools_bin_dirs_and_available_to_http() {
let env = Env::new();
env.script(&env.sys, "curl", "exit 0");
let app_data = env.root.parent().unwrap();
let gh_bin = env.root.join("gh/bin");
assert!(tools_bin_dirs(app_data).contains(&gh_bin));
let missing = env.tools().info("gh", &[]).unwrap();
assert_eq!(missing.kind, ToolKind::Cli);
assert_eq!(missing.status, ToolStatus::Missing);
assert!(missing.can_install);
env.script(&gh_bin, "gh", "echo 'gh version 2.106.0 (2026-11-20)'");
let installed = env.tools().info("gh", &[]).unwrap();
assert_eq!(installed.status, ToolStatus::Installed);
assert_eq!(installed.version.as_deref(), Some("2.106.0"));
assert!(installed.can_uninstall);
let http = env.tools().http().unwrap();
assert_eq!(http.gh_path(), Some(gh_bin.join("gh").as_path()));
}
+1 -33
Переглянути файл
@@ -191,35 +191,6 @@ impl DocState {
self.disk_conflict = false;
self.clean_text = (!self.large).then(|| self.doc.clone());
}
/// The bytes saving `doc` with this document's encoding, BOM and conversion would write.
fn bytes_for_save(&self, doc: &Document) -> IdeResult<Vec<u8>> {
let text = doc.text_for_save();
Ok(if self.native_to_ascii {
ide_vfs::encode_properties_ascii(&text).into_bytes()
} else {
ide_vfs::encode(&text, &self.encoding, self.has_bom)?
})
}
/// Whether the file changed on disk since the buffer last matched it. A moved stamp with the
/// same bytes (touch, a tool rewriting the file unchanged) is no change and its stamp is adopted. Reads the file
/// only when the mtime moved but the length did not; without a clean text to compare (large
/// files, a pending encoding, line-ending or BOM change, a reported conflict) a moved stamp counts.
fn changed_on_disk(&mut self, meta: &std::fs::Metadata) -> bool {
let mtime = ide_vfs::mtime_ms(meta);
if mtime == self.disk_mtime && meta.len() == self.disk_len {
return false;
}
let same_bytes = meta.len() == self.disk_len
&& self.clean_text.as_ref().is_some_and(|clean| {
self.bytes_for_save(clean).is_ok_and(|bytes| std::fs::read(&self.path).is_ok_and(|disk| disk == bytes))
});
if same_bytes {
self.disk_mtime = mtime;
}
!same_bytes
}
}
fn keys_for(path: &Path) -> Vec<PathBuf> {
@@ -953,7 +924,7 @@ impl Documents {
&& !st.disk_conflict
&& st.uri.is_none()
&& let Ok(meta) = std::fs::metadata(&st.path)
&& st.changed_on_disk(&meta)
&& (ide_vfs::mtime_ms(&meta) != st.disk_mtime || meta.len() != st.disk_len)
{
st.disk_mtime = ide_vfs::mtime_ms(&meta);
st.disk_len = meta.len();
@@ -1440,9 +1411,6 @@ impl Documents {
return Ok(());
}
if st.dirty {
if !st.changed_on_disk(&meta) {
return Ok(());
}
st.disk_mtime = mtime;
st.disk_len = meta.len();
st.disk_conflict = true;
+6 -1
Переглянути файл
@@ -314,7 +314,12 @@ fn hash_disk(hash: &mut blake3::Hasher, path: &Path, unsaved: &HashMap<PathBuf,
/// The bytes saving `state` would write.
fn saved_bytes(state: &DocState) -> IdeResult<Vec<u8>> {
state.bytes_for_save(&state.doc)
let text = state.doc.text_for_save();
Ok(if state.native_to_ascii {
ide_vfs::encode_properties_ascii(&text).into_bytes()
} else {
ide_vfs::encode(&text, &state.encoding, state.has_bom)?
})
}
/// A reverted edit may leave the dirty flag set even when all saved bytes match.
-55
Переглянути файл
@@ -350,61 +350,6 @@ fn autosave_checks_the_disk_before_the_watcher_reports_a_change() {
);
}
/// Writes `bytes` with an mtime clearly after the current one, whatever the filesystem's granularity.
fn rewrite_later(path: &Path, bytes: &[u8]) {
let mtime = fs::metadata(path).unwrap().modified().unwrap() + std::time::Duration::from_secs(2);
fs::write(path, bytes).unwrap();
fs::File::options().write(true).open(path).unwrap().set_modified(mtime).unwrap();
}
#[test]
fn rewriting_the_same_bytes_is_no_disk_conflict() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, "alpha\nbeta\n").unwrap();
let info = f.docs.open(&path).unwrap();
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
// A touch, or a tool rewriting the file unchanged: only the mtime moves.
rewrite_later(&path, b"alpha\nbeta\n");
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert!(f.docs.autosave(info.id).unwrap(), "autosave stopped on a file whose bytes did not change");
assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n");
assert!(!f.events.lock().iter().any(|e| matches!(e, IdeEvent::DocDiskConflict { .. })));
}
#[test]
fn autosave_ignores_a_rewrite_of_the_same_bytes_before_the_watcher_reports_it() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, "alpha\nbeta\n").unwrap();
let info = f.docs.open(&path).unwrap();
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
rewrite_later(&path, b"alpha\nbeta\n");
assert!(f.docs.autosave(info.id).unwrap(), "autosave stopped on a file whose bytes did not change");
assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n");
}
/// Opens `bytes`, edits the buffer, then rewrites the file as `external` (same text, other bytes).
fn assert_other_bytes_conflict(name: &str, bytes: &[u8], external: &[u8]) {
let f = fixture();
let path = f.root.join(name);
fs::write(&path, bytes).unwrap();
let info = f.docs.open(&path).unwrap();
f.docs.edit(info.id, 0, change(0, 0, "x")).unwrap();
rewrite_later(&path, external);
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert!(!f.docs.autosave(info.id).unwrap(), "{name}: autosave overwrote other bytes of the same text");
assert_eq!(fs::read(&path).unwrap(), external);
}
#[test]
fn the_same_text_in_other_bytes_is_still_a_disk_conflict() {
assert_other_bytes_conflict("crlf.txt", b"alpha\nbeta\n", b"alpha\r\nbeta\r\n");
assert_other_bytes_conflict("bom.txt", b"alpha\n", b"\xEF\xBB\xBFalpha\n");
// Same length: only the byte comparison tells them apart.
assert_other_bytes_conflict("utf16.txt", b"\xFF\xFEa\x00\n\x00", b"\xFE\xFF\x00a\x00\n");
}
#[test]
fn autosave_leaves_a_file_changed_on_disk_after_an_edit() {
let f = fixture();
+5 -6
Переглянути файл
@@ -138,18 +138,17 @@ fn rollback_keeps_a_disk_conflict_of_an_unsaved_buffer() {
let info = docs.open(&first).unwrap();
docs.edit(info.id, info.version, ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: "own".into() }] })
.unwrap();
// An external write under the unsaved buffer, warned about before the refactoring.
let mtime = std::fs::metadata(&first).unwrap().modified().unwrap() + std::time::Duration::from_secs(2);
std::fs::write(&first, "ext\n").unwrap();
std::fs::File::options().write(true).open(&first).unwrap().set_modified(mtime).unwrap();
docs.on_disk_changed(std::slice::from_ref(&first));
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&first, "new")], ..Default::default() }).unwrap();
// An external write the undo record still accepts (same bytes, new mtime) under the unsaved buffer.
std::thread::sleep(std::time::Duration::from_millis(10));
std::fs::write(&first, "old\n").unwrap();
docs.on_disk_changed(std::slice::from_ref(&first));
docs.undo_workspace_edit(undo_id(&events)).unwrap();
let snap = docs.snapshot(info.id).unwrap();
assert_eq!(snap.text, "own\n");
assert!(snap.dirty);
assert!(!docs.autosave(info.id).unwrap(), "autosave must not overwrite the external change");
assert_eq!(std::fs::read_to_string(&first).unwrap(), "ext\n");
assert_eq!(std::fs::read_to_string(&first).unwrap(), "old\n");
}
#[test]
+10 -16
Переглянути файл
@@ -114,8 +114,6 @@ All folding commands are also in **Code › Folding**. Fold regions come from th
Indentation and other style options are under **Settings › Editor › Code Style**, with a page per language. `.editorconfig` files in the project are read too.
Java has an **Imports** tab for IntelliSort-style options: **Class count to use import with '\*'** switches to a wildcard import once that many classes of one package are used, and **Names count to use static import with '\*'** does the same for statically imported names (999 keeps single imports). Both are passed through to the Java language server, whose defaults are 5 and 3, as in IDEA.
To format on every save, enable **Reformat code** (and optionally **Optimize imports**) in **Settings › Tools › Actions on Save**. Trailing spaces and the final line break on save are set in **Settings › Editor › General**, section **Save Files**.
## Tabs
@@ -147,21 +145,17 @@ With tabs placed left or right, the tab column is as wide as its longest name, u
## View options
| Action | macOS | Windows / Linux |
| ------------------------------------- | ----- | --------------- |
| **Increase Font Size** | `⌥⇧.` | `Alt+Shift+.` |
| **Decrease Font Size** | `⌥⇧,` | `Alt+Shift+,` |
| **Scroll to Center** | `⌃L` | `Ctrl+M` |
| **Scroll Up** | — | `Ctrl+Up` |
| **Scroll Down** | — | `Ctrl+Down` |
| **Scroll Up and Move if Necessary** | — | — |
| **Scroll Down and Move if Necessary** | — | — |
| **Move Up and Scroll** | — | — |
| **Move Down and Scroll** | — | — |
| **Scroll to Top** | — | — |
| **Scroll to Bottom** | — | — |
| Action | macOS | Windows / Linux |
| ---------------------- | ----- | --------------- |
| **Increase Font Size** | `⌥⇧.` | `Alt+Shift+.` |
| **Decrease Font Size** | `⌥⇧,` | `Alt+Shift+,` |
| **Scroll to Center** | `⌃L` | `Ctrl+M` |
| **Scroll Up** | — | `Ctrl+Up` |
| **Scroll Down** | — | `Ctrl+Down` |
| **Scroll to Top** | — | — |
| **Scroll to Bottom** | — | — |
**Scroll Up** and **Scroll Down** move the view by one line and leave the caret where it is, even when it scrolls out of sight. **Scroll Up and Move if Necessary** and **Scroll Down and Move if Necessary** also move the view by one line, but bring a caret the view doesn't show to its first or last line. **Move Up and Scroll** and **Move Down and Scroll** move the caret one line and the view with it, so the caret stays in the same place on screen; their **with Selection** variants select as they go. **Scroll to Top** and **Scroll to Bottom** show the start and the end of the file; the caret stays where it is too. They have no default shortcut: run them from Find Action or assign one in **Settings › Keymap**.
**Scroll Up** and **Scroll Down** move the view by one line and leave the caret where it is, even when it scrolls out of sight. **Scroll to Top** and **Scroll to Bottom** show the start and the end of the file; the caret stays where it is too. They have no default shortcut: run them from Find Action or assign one in **Settings › Keymap**.
- **View › Active Editor › Soft-Wrap** wraps long lines in the current editor. To wrap some file types by default, use **Settings › Editor › General**, section **Soft Wraps**.
- **View › Reset Font Size** undoes font zoom in the active editor or focused surface (**View › Reset Font Size in All Editors** resets every open editor). Changing the font size with `⌘` / `Ctrl` + mouse wheel (scoped to **Active editor** by default, or **All editors**) can be turned on in **Settings › Editor › General**, section **Mouse Control**.
+3 -5
Переглянути файл
@@ -9,11 +9,9 @@ OpenIDEA works with GitHub through the [GitHub CLI](https://cli.github.com) (`gh
<Steps>
<Step title="Install gh">
Install the GitHub CLI, either from OpenIDEA's **Install GitHub CLI** button (in the **Pull Requests** tool window,
**Clone Repository › GitHub**, **Settings › Agents › GitHub Copilot**, or **Settings › Languages & Frameworks ›
Language Servers › Other Tools**) or manually. OpenIDEA looks for it in `OPENIDEA_GH` (a full path), then on `PATH`
(including IDE-managed tools), then in `/opt/homebrew/bin`, `/usr/local/bin`, `/usr/bin`, `/snap/bin` (macOS/Linux)
or `C:\Program Files\GitHub CLI\gh.exe` (Windows).
Install the GitHub CLI. OpenIDEA looks for it in `OPENIDEA_GH` (a full path), then on `PATH`, then in
`/opt/homebrew/bin`, `/usr/local/bin`, `/usr/bin`, `/snap/bin` (macOS/Linux) or `C:\Program Files\GitHub CLI\gh.exe`
(Windows).
</Step>
<Step title="Sign in">
Run `gh auth login` in a terminal. If you open the **Pull Requests** tool window while signed out, it shows **Not
+1 -1
Переглянути файл
@@ -90,7 +90,7 @@ Settings › Appearance & Behavior › System Settings, unless noted.
| `dateFormat.overrideSystem` | `false` | **Override system date and time format** (Date Formats page). |
| `dateFormat.pattern` | `"dd.MM.yyyy"` | Date pattern with `dd`, `MM`, `MMM`, `yy`, `yyyy`. |
| `dateFormat.use24Hour` | `true` | 24-hour time. |
| `dateFormat.pretty` | `true` | "Today", "Yesterday", "5 min ago" (in lists with time, in the annotate gutter as the day alone). |
| `dateFormat.pretty` | `true` | "Today", "Yesterday", "5 min ago". |
### `[appearance]`
+10 -14
Переглянути файл
@@ -145,21 +145,17 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
## 显示选项
| 操作 | macOS | Windows / Linux |
| ------------------------------ | ----- | --------------- |
| **增大字体** | `⌥⇧.` | `Alt+Shift+.` |
| **减小字体** | `⌥⇧,` | `Alt+Shift+,` |
| **滚动到中央** | `⌃L` | `Ctrl+M` |
| **向上滚动** | — | `Ctrl+Up` |
| **向下滚动** | — | `Ctrl+Down` |
| **向上滚动并在必要时移动光标** | — | — |
| **向下滚动并在必要时移动光标** | — | — |
| **向上移动并滚动** | — | — |
| **向下移动并滚动** | — | — |
| **滚动到顶部** | — | — |
| **滚动到底部** | — | — |
| 操作 | macOS | Windows / Linux |
| -------------- | ----- | --------------- |
| **增大字体** | `⌥⇧.` | `Alt+Shift+.` |
| **减小字体** | `⌥⇧,` | `Alt+Shift+,` |
| **滚动到中央** | `⌃L` | `Ctrl+M` |
| **向上滚动** | — | `Ctrl+Up` |
| **向下滚动** | — | `Ctrl+Down` |
| **滚动到顶部** | — | — |
| **滚动到底部** | — | — |
**向上滚动** 和 **向下滚动** 把视图移动一行,光标保持原位,即使它因此移出可见区域。**向上滚动并在必要时移动光标** 和 **向下滚动并在必要时移动光标** 同样把视图移动一行,但会把不在视图中的光标移到视图的第一行或最后一行。**向上移动并滚动** 和 **向下移动并滚动** 把光标移动一行,视图随之滚动同样的距离,光标在屏幕上的位置保持不变;对应的 **并选择** 版本边移动边选择。**滚动到顶部** 和 **滚动到底部** 显示文件的开头和结尾;光标同样保持原位。它们默认没有快捷键:在查找操作中运行,或在 **设置 › 按键映射** 中指定。
**向上滚动** 和 **向下滚动** 把视图移动一行,光标保持原位,即使它因此移出可见区域。**滚动到顶部** 和 **滚动到底部** 显示文件的开头和结尾;光标同样保持原位。它们默认没有快捷键:在查找操作中运行,或在 **设置 › 按键映射** 中指定。
- **视图 › 活动编辑器 › 软换行** 让当前编辑器的长行自动折行。想让某些文件类型默认软换行,在 **设置 › 编辑器 › 常规** 的 **软换行** 一节中设置。
- **视图 › 重置字体大小** 撤销当前编辑器或焦点区域的字体缩放(**视图 › 重置所有编辑器中的字体大小** 会重置所有打开的编辑器)。用 `⌘` / `Ctrl` + 鼠标滚轮调整字号的功能默认关闭,可在 **设置 › 编辑器 › 常规** 的 **鼠标控制** 一节中打开,并可选择作用于 **当前编辑器**(默认)或 **所有编辑器**。
+3 -4
Переглянути файл
@@ -9,10 +9,9 @@ OpenIDEA 通过 [GitHub CLI](https://cli.github.com)(`gh`)对接 GitHub:
<Steps>
<Step title="安装 gh">
安装 GitHub CLI:可以直接点击 OpenIDEA 里的 **安装 GitHub CLI** 按钮(位于 **拉取请求** 工具窗口、**克隆仓库 ›
GitHub**、**设置 › 智能体 › GitHub Copilot** 或 **设置 › 语言与框架 › 语言服务器 › 其他工具**),也可以手动安装。
OpenIDEA 依次在 `OPENIDEA_GH`(完整路径)、`PATH`(包含 IDE 管理的工具目录),以及 `/opt/homebrew/bin`、
`/usr/local/bin`、`/usr/bin`、`/snap/bin`(macOS/Linux)或 `C:\Program Files\GitHub CLI\gh.exe`(Windows)中查找。
安装 GitHub CLI。OpenIDEA 依次在 `OPENIDEA_GH`(完整路径)、`PATH`,以及
`/opt/homebrew/bin`、`/usr/local/bin`、`/usr/bin`、`/snap/bin`(macOS/Linux)或 `C:\Program Files\GitHub
CLI\gh.exe`(Windows)中查找。
</Step>
<Step title="登录">
在终端运行 `gh auth login`。未登录时打开 **拉取请求** 工具窗口,会显示 **未登录 GitHub** 和 **运行 gh auth login**
+1 -1
Переглянути файл
@@ -90,7 +90,7 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"]
| `dateFormat.overrideSystem` | `false` | **覆盖系统日期和时间格式**(日期格式页)。 |
| `dateFormat.pattern` | `"dd.MM.yyyy"` | 日期格式,可用 `dd`、`MM`、`MMM`、`yy`、`yyyy`。 |
| `dateFormat.use24Hour` | `true` | 使用 24 小时制。 |
| `dateFormat.pretty` | `true` | 显示“今天”“昨天”“5 分钟前”这类相对时间(列表中带时间,注解装订区域仅显示日期)。 |
| `dateFormat.pretty` | `true` | 显示“今天”“昨天”“5 分钟前”这类相对时间。 |
### `[appearance]`
+8 -34
Переглянути файл
@@ -4,11 +4,10 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
await page.setViewportSize({ width: 1080, height: 700 });
await stubDesktop(page);
await page.evaluate(async () => {
const path = "/dev/acme-api/status.png";
// A black 128 × 96 PNG.
const path = "/dev/acme-api/status.svg";
const image =
"iVBORw0KGgoAAAANSUhEUgAAAIAAAABgCAYAAADVenpJAAAAtklEQVR42u3SQREAAAyDMPyb3oQ0jxjgqDqmiWAADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABkAEA2AADIABMAAGwAAYgAUPjHPSwnYk55QAAAAASUVORK5CYII=";
window.__ipc.handlers.fs_read_image = () => "data:image/png;base64," + image;
'<svg xmlns="http://www.w3.org/2000/svg" width="128" height="96"><rect width="128" height="96"/></svg>';
window.__ipc.handlers.fs_read_image = () => "data:image/svg+xml," + encodeURIComponent(image);
window.__ipc.handlers.fs_probe = () => ({ size: 4096, binary: false, tooLarge: false });
const contributions = "/src/workbench/contributions.ts";
const { editorService } = await import(/* @vite-ignore */ contributions);
@@ -19,8 +18,9 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
const zoomIn = toolbar.getByRole("button", { name: "Zoom In", exact: true });
const actualSize = toolbar.getByRole("button", { name: "Actual Size", exact: true });
const chessboard = toolbar.getByRole("button", { name: "Show Chessboard", exact: true });
const showText = toolbar.getByRole("button", { name: "Open as Text", exact: true });
const dimensions = toolbar.getByText(/128\s*×\s*96/);
await expect(page.getByRole("img", { name: "status.png", exact: true })).toBeVisible();
await expect(page.getByRole("img", { name: "status.svg", exact: true })).toBeVisible();
await expect(dimensions).toBeVisible();
const wideHeight = (await toolbar.boundingBox())!.height;
@@ -31,7 +31,8 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
expect((await toolbar.boundingBox())!.height).toBeGreaterThan(wideHeight);
expect((await dimensions.boundingBox())!.y).toBeGreaterThan((await zoomIn.boundingBox())!.y);
await expect(dimensions).toHaveCSS("font-size", "13px");
for (const item of [zoomIn, actualSize, chessboard, dimensions]) {
await expect(showText).toHaveCSS("white-space", "nowrap");
for (const item of [zoomIn, actualSize, chessboard, showText, dimensions]) {
await expect(item).toBeInViewport({ ratio: 1 });
}
await expect(toolbar.getByText("4.0 KB", { exact: true })).toBeVisible();
@@ -42,33 +43,6 @@ test("image controls and metadata stay readable in a narrow editor", async ({ wo
await expect(toolbar.getByText("100%", { exact: true })).toBeVisible();
await chessboard.click();
await expect(chessboard).toHaveAttribute("aria-pressed", "false");
});
test("an SVG file opens as its source with the image beside it", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async () => {
window.__ipc.handlers.fs_probe = () => ({ size: 96, binary: false, tooLarge: false });
const contributions = "/src/workbench/contributions.ts";
const { editorService } = await import(/* @vite-ignore */ contributions);
await editorService().openFile("/dev/acme-api/status.svg");
});
const toolbar = page.getByRole("toolbar", { name: "Image viewer", exact: true });
// Not an SVG yet: the preview says so, and draws the source once it is typed.
await expect(page.getByText("The SVG source is not valid.", { exact: true })).toBeVisible();
await page.locator(".cm-content").click();
await page.keyboard.press("ControlOrMeta+A");
await page.keyboard.insertText(
'<svg xmlns="http://www.w3.org/2000/svg" width="128" height="96"><rect width="128" height="96"/></svg>',
);
await expect(page.getByRole("img", { name: "status.svg", exact: true })).toBeVisible();
await expect(toolbar.getByText(/128\s*×\s*96/)).toBeVisible();
await expect(toolbar.getByRole("button", { name: "Open as Text", exact: true })).toHaveCount(0);
const layout = page.getByRole("toolbar", { name: "SVG editor layout", exact: true });
await layout.getByRole("button", { name: "Preview Only", exact: true }).click();
await expect(page.locator(".cm-content")).toBeHidden();
await expect(page.getByRole("img", { name: "status.svg", exact: true })).toBeVisible();
await layout.getByRole("button", { name: "Editor Only", exact: true }).click();
await expect(toolbar).toHaveCount(0);
await showText.click();
await expect(page.locator(".cm-content")).toBeVisible();
});
-24
Переглянути файл
@@ -9162,18 +9162,6 @@ export type LanguageCodeStyle_Deserialize = {
keywordCase?: string | null,
/** SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`. */
identifierCase?: string | null,
/**
* Java: organize imports switches to a wildcard import once this many
* classes of one package are used (jdtls `starThreshold`; IDEA's default
* 5; unset keeps the language server's default).
*/
classCountToUseImportWithStar?: number | null,
/**
* Java: organize imports switches to a wildcard static import once this
* many statically imported names are used (jdtls `staticStarThreshold`;
* IDEA's default 3; unset keeps the language server's default).
*/
namesCountToUseStaticImportWithStar?: number | null,
/** JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`. */
semicolons?: string | null,
/** JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`. */
@@ -9204,18 +9192,6 @@ export type LanguageCodeStyle_Serialize = {
keywordCase?: string | null,
/** SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`. */
identifierCase?: string | null,
/**
* Java: organize imports switches to a wildcard import once this many
* classes of one package are used (jdtls `starThreshold`; IDEA's default
* 5; unset keeps the language server's default).
*/
classCountToUseImportWithStar?: number | null,
/**
* Java: organize imports switches to a wildcard static import once this
* many statically imported names are used (jdtls `staticStarThreshold`;
* IDEA's default 3; unset keeps the language server's default).
*/
namesCountToUseStaticImportWithStar?: number | null,
/** JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`. */
semicolons?: string | null,
/** JavaScript / TypeScript › Punctuation › Quotes: `auto` | `single` | `double`. */
+1 -32
Переглянути файл
@@ -81,12 +81,10 @@ import {
cursorParagraphBackward,
cursorParagraphForward,
scrollDown,
scrollDownAndMove,
scrollToBottom,
scrollToCenter,
scrollToTop,
scrollUp,
scrollUpAndMove,
selectCodeBlockEnd,
selectCodeBlockStart,
selectPageBottom,
@@ -97,14 +95,7 @@ import {
} from "./cm/caretCommands";
import { isOverwrite, toggleOverwrite } from "./cm/overwrite";
import { isColumnMode, toggleColumnMode } from "./cm/columnMode";
import {
cloneCaretAbove,
cloneCaretBelow,
moveDownAndScroll,
moveDownAndScrollWithSelection,
moveUpAndScroll,
moveUpAndScrollWithSelection,
} from "./cm/verticalMotion";
import { cloneCaretAbove, cloneCaretBelow } from "./cm/verticalMotion";
import { pasteAsPlainText, pasteFromHistory, unwrapAtCaret } from "./extras";
import { cyclicExpandWord } from "./wordCompletion";
import { copyReferenceToClipboard, declaredName, qualifiedReference, referenceOffset } from "./copyReference";
@@ -1068,28 +1059,6 @@ export function registerEditorActions(): () => void {
caret("editor.scrollToCenter", "Scroll to Center", (v) => scrollToCenter(v), { category: "Editor Actions" }),
caret("editor.scrollUp", "Scroll Up", (v) => scrollUp(v), { category: "Editor Actions" }),
caret("editor.scrollDown", "Scroll Down", (v) => scrollDown(v), { category: "Editor Actions" }),
caret("editor.scrollUpAndMove", "Scroll Up and Move if Necessary", (v) => scrollUpAndMove(v), {
category: "Editor Actions",
}),
caret("editor.scrollDownAndMove", "Scroll Down and Move if Necessary", (v) => scrollDownAndMove(v), {
category: "Editor Actions",
}),
caret("editor.moveUpAndScroll", "Move Up and Scroll", (v) => moveUpAndScroll(v), { category: "Editor Actions" }),
caret("editor.moveDownAndScroll", "Move Down and Scroll", (v) => moveDownAndScroll(v), {
category: "Editor Actions",
}),
caret(
"editor.moveUpAndScrollWithSelection",
"Move Up and Scroll with Selection",
(v) => moveUpAndScrollWithSelection(v),
{ category: "Editor Actions" },
),
caret(
"editor.moveDownAndScrollWithSelection",
"Move Down and Scroll with Selection",
(v) => moveDownAndScrollWithSelection(v),
{ category: "Editor Actions" },
),
caret("editor.scrollToTop", "Scroll to Top", (v) => scrollToTop(v), { category: "Editor Actions" }),
caret("editor.scrollToBottom", "Scroll to Bottom", (v) => scrollToBottom(v), { category: "Editor Actions" }),
caret("editor.moveToPageTop", "Move Caret to Page Top", (v) => cursorPageTop(v), { category: "Editor Actions" }),
+1 -101
Переглянути файл
@@ -1,7 +1,7 @@
import { afterEach, beforeAll, describe, expect, it } from "vitest";
import { EditorSelection, EditorState, StateEffect } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { codeFolding, foldEffect, indentService, type LanguageSupport } from "@codemirror/language";
import { indentService, type LanguageSupport } from "@codemirror/language";
import { languages } from "@codemirror/language-data";
import { addCursorAbove, insertBlankLine, selectLine, toggleTabFocusMode } from "@codemirror/commands";
import {
@@ -14,11 +14,9 @@ import {
nextParagraphBoundary,
previousParagraphBoundary,
scrollDown,
scrollDownAndMove,
scrollToBottom,
scrollToTop,
scrollUp,
scrollUpAndMove,
selectPageBottom,
selectPageTop,
selectParagraphForward,
@@ -253,104 +251,6 @@ describe("Move Caret to Page Top / Bottom", () => {
});
});
describe("Scroll Up / Down and Move if Necessary", () => {
/** jsdom has no layout: a scroller `height` line heights tall, scrolled to `top` line heights. */
function scroller(view: EditorView, top: number, height: number) {
const line = view.lineBlockAt(0).height;
let px = top * line;
Object.defineProperty(view.scrollDOM, "scrollTop", {
configurable: true,
get: () => px,
set: (v: number) => (px = Math.max(0, v)),
});
Object.defineProperty(view, "documentTop", { configurable: true, get: () => -px });
Object.defineProperty(view.scrollDOM, "clientHeight", { configurable: true, get: () => height * line });
return () => px / line;
}
const lines = (marked: Record<number, string>) =>
Array.from({ length: 10 }, (_, i) => marked[i] ?? `line ${i} text`).join("\n");
const lineOf = (view: EditorView) => view.state.selection.ranges.map((r) => view.state.doc.lineAt(r.head).number - 1);
const columnOf = (view: EditorView) =>
view.state.selection.ranges.map((r) => r.head - view.state.doc.lineAt(r.head).from);
it("scrolls one line and keeps a caret that stays in view where it is", () => {
const view = make(lines({ 4: "line 4 te|xt" }));
const top = scroller(view, 2, 4);
const before = view.state.selection;
expect(scrollDownAndMove(view)).toBe(true);
expect(top()).toBe(3);
expect(view.state.selection.eq(before)).toBe(true);
expect(scrollUpAndMove(view)).toBe(true);
expect(top()).toBe(2);
expect(view.state.selection.eq(before)).toBe(true);
});
it("brings a caret that scrolls off the top down to the first line, keeping its column", () => {
const view = make(lines({ 2: "line 2 te|xt" }));
scroller(view, 2, 4);
scrollDownAndMove(view);
expect([lineOf(view), columnOf(view)]).toEqual([[3], [9]]);
});
it("brings a caret that scrolls off the bottom up to the last line, keeping its column", () => {
const view = make(lines({ 5: "li|ne 5 text" }));
scroller(view, 2, 4);
scrollUpAndMove(view);
expect([lineOf(view), columnOf(view)]).toEqual([[4], [2]]);
});
it("moves a caret already out of view to the nearest edge", () => {
const view = make(lines({ 9: "line 9 |text" }));
scroller(view, 0, 4);
scrollDownAndMove(view);
expect([lineOf(view), columnOf(view)]).toEqual([[4], [7]]);
});
it("drops the selection of a caret it moves and keeps the others", () => {
const view = make(lines({ 0: "|line 0 text" }));
const at = (line: number, col: number) => view.state.doc.line(line + 1).from + col;
view.dispatch({
selection: EditorSelection.create(
[EditorSelection.range(at(2, 0), at(2, 4)), EditorSelection.range(at(4, 0), at(4, 4))],
1,
),
});
scroller(view, 2, 4);
scrollDownAndMove(view);
expect(view.state.selection.ranges.map((r) => [r.anchor, r.head])).toEqual([
[at(3, 4), at(3, 4)],
[at(4, 0), at(4, 4)],
]);
expect(view.state.selection.mainIndex).toBe(1);
});
it("keeps a caret at the end of a folded block the view shows", () => {
const view = make(lines({ 7: "line 7 text|" }));
const { doc } = view.state;
view.dispatch({
effects: [
StateEffect.appendConfig.of(codeFolding()),
foldEffect.of({ from: doc.line(6).to, to: doc.line(8).to }),
],
});
expect(view.lineBlockAt(doc.line(8).to).from).toBe(doc.line(6).from);
const before = view.state.selection;
scroller(view, 1, 4);
scrollDownAndMove(view);
expect(view.state.selection.eq(before)).toBe(true);
});
it("only scrolls at the top of the file when the caret stays in view", () => {
const view = make(lines({ 1: "|line 1 text" }));
const top = scroller(view, 0, 4);
const before = view.state.selection;
scrollUpAndMove(view);
expect(top()).toBe(0);
expect(view.state.selection.eq(before)).toBe(true);
expect(view.state.doc.toString()).toBe(lines({}));
});
});
describe("code block navigation", () => {
let js: LanguageSupport;
beforeAll(async () => {
+5 -40
Переглянути файл
@@ -1,4 +1,4 @@
/** IDEA caret commands that CodeMirror has no equivalent for: Split Line, Scroll to Center / Up / Down / Top / Bottom, Scroll Up / Down and Move if Necessary, Page Top / Bottom, code block, brace and paragraph navigation. */
/** IDEA caret commands that CodeMirror has no equivalent for: Split Line, Scroll to Center / Up / Down / Top / Bottom, Page Top / Bottom, code block, brace and paragraph navigation. */
import { countColumn, EditorSelection, findColumn, type EditorState, type Transaction } from "@codemirror/state";
import { EditorView, type Command } from "@codemirror/view";
import { insertNewlineAndIndent } from "@codemirror/commands";
@@ -66,21 +66,15 @@ function pageEdgeLine(view: EditorView, edge: "top" | "bottom"): number {
return block.top >= bottom || (block.bottom > bottom && previous.top >= top) ? previous.from : block.from;
}
/** `head` moved to the line starting at `lineStart`, keeping its visual column. */
function sameColumnOn(state: EditorState, head: number, lineStart: number): number {
const line = state.doc.lineAt(head);
const target = state.doc.lineAt(lineStart);
const column = countColumn(line.text, state.tabSize, head - line.from);
return target.from + findColumn(target.text, column, state.tabSize);
}
/** Move Caret to Page Top / Bottom (with Selection): every caret to that line, keeping its column. */
function moveToPageEdge(edge: "top" | "bottom", extend = false): Command {
return (view) => {
const { state } = view;
const target = pageEdgeLine(view, edge);
const target = state.doc.lineAt(pageEdgeLine(view, edge));
const ranges = state.selection.ranges.map((r) => {
const head = sameColumnOn(state, r.head, target);
const line = state.doc.lineAt(r.head);
const column = countColumn(line.text, state.tabSize, r.head - line.from);
const head = target.from + findColumn(target.text, column, state.tabSize);
return extend ? EditorSelection.range(r.anchor, head) : EditorSelection.cursor(head);
});
view.dispatch({
@@ -96,35 +90,6 @@ export const cursorPageBottom = moveToPageEdge("bottom");
export const selectPageTop = moveToPageEdge("top", true);
export const selectPageBottom = moveToPageEdge("bottom", true);
/**
* Scroll Up / Down and Move if Necessary: move the viewport by one line, then bring
* a caret outside the lines the view shows whole to the first or last of them,
* keeping its column. Carets in view keep their place and selection.
*/
const scrollByLineAndMove =
(lines: number): Command =>
(view) => {
scrollByLine(lines)(view);
const { state } = view;
const first = pageEdgeLine(view, "top");
const last = view.lineBlockAt(pageEdgeLine(view, "bottom"));
let moved = false;
const ranges = state.selection.ranges.map((r) => {
if (r.head >= first && r.head <= last.to) return r;
moved = true;
return EditorSelection.cursor(sameColumnOn(state, r.head, r.head < first ? first : last.from));
});
if (moved) {
view.dispatch({
selection: EditorSelection.create(ranges, state.selection.mainIndex),
userEvent: "select.navigate",
});
}
return true;
};
export const scrollUpAndMove = scrollByLineAndMove(-1);
export const scrollDownAndMove = scrollByLineAndMove(1);
const NOT_CODE = /String|Comment|Regexp|Char|Template/;
/** `{` / `}` at `pos` when it is code (not inside a string or comment, as far as the syntax tree knows). */
+2 -125
Переглянути файл
@@ -1,16 +1,12 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it } from "vitest";
import { EditorSelection, EditorState, StateEffect } from "@codemirror/state";
import { Decoration, EditorView, WidgetType } from "@codemirror/view";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import {
cloneCaretAbove,
cloneCaretBelow,
cursorLineDown,
cursorLineUp,
moveDownAndScroll,
moveDownAndScrollWithSelection,
moveUpAndScroll,
moveUpAndScrollWithSelection,
selectLineDown,
visibleGoalColumns,
} from "./verticalMotion";
@@ -110,122 +106,3 @@ describe("Clone Caret Above / Below in visible columns", () => {
expect(cloneCaretAbove(v)).toBe(false);
});
});
describe("Move Up / Down and Scroll", () => {
/** jsdom has no layout: record what the command asks the scroller for, and whether it scrolled to the caret. */
function track(v: EditorView, start: number) {
let top = start;
Object.defineProperty(v.scrollDOM, "scrollTop", {
configurable: true,
get: () => top,
set: (x: number) => (top = x),
});
const scrolledToCaret: boolean[] = [];
v.dispatch({
effects: StateEffect.appendConfig.of(
EditorView.updateListener.of((u) => u.transactions.forEach((tr) => scrolledToCaret.push(tr.scrollIntoView))),
),
});
scrolledToCaret.length = 0;
return { top: () => top, scrolledToCaret };
}
const rowGap = (v: EditorView, from: number, to: number) =>
v.lineBlockAt(v.state.doc.line(to).from).top - v.lineBlockAt(v.state.doc.line(from).from).top;
it("moves the caret one line and scrolls the view by the same amount", () => {
const v = make("abcdef\nabcdef\nabcdef\nabcdef", 7 + 3);
const t = track(v, 100);
const gap = rowGap(v, 2, 3);
expect(gap).toBeGreaterThan(0);
expect(moveDownAndScroll(v)).toBe(true);
expect(heads(v)).toEqual([14 + 3]);
expect(t.top()).toBe(100 + gap);
expect(moveUpAndScroll(v)).toBe(true);
expect(moveUpAndScroll(v)).toBe(true);
expect(heads(v)).toEqual([3]);
expect(t.top()).toBe(100 - rowGap(v, 1, 2));
expect(v.state.selection.main.empty).toBe(true);
});
it("keeps the goal column across a short line", () => {
const v = make("abcdefgh\n张\nabcdefgh", 6);
track(v, 0);
moveDownAndScroll(v);
moveDownAndScroll(v);
expect(heads(v)).toEqual([11 + 6]);
});
it("with Selection extends from the anchor", () => {
const v = make("abcd\nabcd\nabcd", 5 + 2);
const t = track(v, 40);
moveDownAndScrollWithSelection(v);
expect([v.state.selection.main.anchor, v.state.selection.main.head]).toEqual([7, 12]);
moveUpAndScrollWithSelection(v);
moveUpAndScrollWithSelection(v);
expect([v.state.selection.main.anchor, v.state.selection.main.head]).toEqual([7, 2]);
expect(t.top()).toBe(40 - rowGap(v, 1, 2));
});
it("moves every caret and scrolls with the primary one", () => {
const v = make("ab\nab\nab\nab", 0);
v.dispatch({ selection: EditorSelection.create([EditorSelection.cursor(1), EditorSelection.cursor(7)], 1) });
const t = track(v, 0);
moveDownAndScroll(v);
expect(heads(v)).toEqual([4, 10]);
expect(v.state.selection.mainIndex).toBe(1);
expect(t.top()).toBe(rowGap(v, 3, 4));
});
it("leaves scrolling to itself: never scrolls a caret out of view back into it", () => {
const v = make("ab\nab\nab", 1);
const t = track(v, 500);
moveDownAndScroll(v);
expect(t.scrolledToCaret).toEqual([false]);
expect(t.top()).toBe(500 + rowGap(v, 1, 2));
});
it("drops a selection and moves one line from its caret", () => {
const v = make("abcd\nabcd\nabcd\nabcd", 0);
v.dispatch({ selection: { anchor: 15 + 2, head: 2 } });
const t = track(v, 0);
moveDownAndScroll(v);
expect(v.state.selection.main.empty).toBe(true);
expect(heads(v)).toEqual([5 + 2]);
expect(t.top()).toBe(rowGap(v, 1, 2));
});
it("measures to the text of a line below a block widget (code lens)", () => {
class Lens extends WidgetType {
toDOM() {
return document.createElement("div");
}
get estimatedHeight() {
return 40;
}
}
const v = make("ab\nab\nab", 1);
const lens = Decoration.widget({ widget: new Lens(), block: true, side: -1 }).range(3);
v.dispatch({ effects: StateEffect.appendConfig.of(EditorView.decorations.of(Decoration.set([lens]))) });
const t = track(v, 0);
const line = v.lineBlockAt(0).height;
expect(v.lineBlockAt(3).height).toBeGreaterThan(line);
moveDownAndScroll(v);
expect(heads(v)).toEqual([4]);
expect(t.top()).toBe(v.lineBlockAt(3).bottom - line);
moveUpAndScroll(v);
expect(t.top()).toBe(0);
});
it("does not scroll at the document edge", () => {
const v = make("ab\ncd", 1);
const t = track(v, 0);
expect(moveUpAndScroll(v)).toBe(true);
expect(heads(v)).toEqual([0]);
expect(moveUpAndScroll(v)).toBe(false);
v.dispatch({ selection: { anchor: 4 } });
expect(moveDownAndScroll(v)).toBe(true);
expect(moveDownAndScroll(v)).toBe(false);
expect(heads(v)).toEqual([5]);
expect(t.top()).toBe(0);
});
});
+4 -41
Переглянути файл
@@ -6,7 +6,7 @@
* CodeMirror's pixel motion between their visual rows.
*/
import { EditorSelection, StateEffect, StateField, type EditorState, type SelectionRange } from "@codemirror/state";
import { BlockType, type BlockInfo, type Command, type EditorView } from "@codemirror/view";
import type { Command, EditorView } from "@codemirror/view";
import { offsetAtVisibleColumn, visibleColumn } from "./visibleColumn";
/** Goal visible column per caret head, kept while only these commands move the carets. */
@@ -52,12 +52,11 @@ export function verticalHead(view: EditorView, head: number, forward: boolean, g
return moved === head ? null : moved;
}
/** `fromHead`: drop a selection and move its caret on from the head, as IDEA's caret-relative moves do. */
function moveCarets(view: EditorView, forward: boolean, extend: boolean, fromHead = false): boolean {
function moveCarets(view: EditorView, forward: boolean, extend: boolean): boolean {
const { state } = view;
const goals = new Map<number, number>();
const ranges = state.selection.ranges.map((r): SelectionRange => {
if (!extend && !fromHead && !r.empty) return EditorSelection.cursor(forward ? r.to : r.from);
if (!extend && !r.empty) return EditorSelection.cursor(forward ? r.to : r.from);
const goal = goalOf(state, r.head);
let head = verticalHead(view, r.head, forward, goal);
if (head === null) head = forward ? state.doc.lineAt(r.head).to : state.doc.lineAt(r.head).from;
@@ -66,8 +65,7 @@ function moveCarets(view: EditorView, forward: boolean, extend: boolean, fromHea
});
const selection = EditorSelection.create(ranges, state.selection.mainIndex);
if (selection.eq(state.selection)) return false;
// The caret-relative moves scroll the view themselves and may leave the caret out of view.
view.dispatch({ selection, effects: setGoals.of(goals), scrollIntoView: !fromHead, userEvent: "select" });
view.dispatch({ selection, effects: setGoals.of(goals), scrollIntoView: true, userEvent: "select" });
return true;
}
@@ -76,41 +74,6 @@ export const cursorLineDown: Command = (view) => moveCarets(view, true, false);
export const selectLineUp: Command = (view) => moveCarets(view, false, true);
export const selectLineDown: Command = (view) => moveCarets(view, true, true);
/** Top of the text of the line at `pos`, in document coordinates: below any block widgets (code lens, inline diff) joined to its line block. */
function lineTextTop(view: EditorView, pos: number): number {
const block = view.lineBlockAt(pos);
if (!Array.isArray(block.type)) return block.top;
const parts = block.type as readonly BlockInfo[];
return (parts.find((b) => b.type === BlockType.Text && b.from <= pos && pos <= b.to) ?? block).top;
}
/** Screen top of the caret's visual row when soft wrap splits lines into rows and the caret is drawn; otherwise null. */
function caretRowTop(view: EditorView): number | null {
if (!view.lineWrapping) return null;
const { head, assoc } = view.state.selection.main;
return view.coordsAtPos(head, assoc || 1)?.top ?? null;
}
/**
* Move Up / Down and Scroll (with Selection), as IDEA: the carets move one line and
* the view scrolls by as much, so the primary caret keeps its place on screen.
*/
function moveAndScroll(view: EditorView, forward: boolean, extend: boolean): boolean {
const before = { row: caretRowTop(view), line: lineTextTop(view, view.state.selection.main.head) };
if (!moveCarets(view, forward, extend, true)) return false;
const row = before.row === null ? null : caretRowTop(view);
view.scrollDOM.scrollTop +=
row !== null && before.row !== null
? row - before.row
: lineTextTop(view, view.state.selection.main.head) - before.line;
return true;
}
export const moveUpAndScroll: Command = (view) => moveAndScroll(view, false, false);
export const moveDownAndScroll: Command = (view) => moveAndScroll(view, true, false);
export const moveUpAndScrollWithSelection: Command = (view) => moveAndScroll(view, false, true);
export const moveDownAndScrollWithSelection: Command = (view) => moveAndScroll(view, true, true);
/** Clone Caret Above / Below: a caret on the next line at each caret's goal column. */
function cloneCaret(view: EditorView, forward: boolean): boolean {
const { state } = view;
-56
Переглянути файл
@@ -24,22 +24,6 @@ import { installKeyboardDispatcher } from "@/platform/keymap";
import { TEXT_WHEN } from "./actions";
import { EDITOR_WHEN } from "@/editor/lsp/actions";
import { setShownLine } from "@/editor/api";
import { registerProjectActions } from "@/features/project-tree/actions";
/** `isTauri` is a spy (File Color writes need it true); the settings commands stand in for the backend. */
const ipc = vi.hoisted(() => ({
isTauri: vi.fn(() => false),
settingsSet: vi.fn(async () => ({ status: "ok" as const, data: {} })),
settingsGet: vi.fn(async () => ({})),
}));
vi.mock("@/platform/ipc", async (orig) => {
const real = await orig<typeof import("@/platform/ipc")>();
return {
...real,
isTauri: ipc.isTauri,
commands: { ...real.commands, settingsSet: ipc.settingsSet, settingsGet: ipc.settingsGet },
};
});
let ctrl: EditorController | null = null;
@@ -438,46 +422,6 @@ describe("EditorController", () => {
expect(pane().tabs.map((t) => t.input.path)).toEqual(["/p/a.ts", "/p/c.ts"]);
});
it("offers the project view's File Color submenu through actions", async () => {
useProject.setState({
project: { name: "p", root: "/p", trusted: true, isGit: false, settings: {} } as never,
settings: {} as never,
});
ipc.isTauri.mockReturnValue(true);
const disposeActions = registerProjectActions();
try {
ctrl = new EditorController(createMemoryBackend({ "/p/a.ts": "", "/p/b.ts": "", "/elsewhere/c.ts": "" }));
ctrl.start();
await ctrl.openFile("/p/a.ts", { focus: false });
const pane = () => useTabs.getState().panes[useTabs.getState().activePane]!;
const raw = ctrl!.tabMenu(pane().id, pane().tabs[0]!);
const entry = raw.find((i) => "label" in i && i.label === "File Color");
expect(entry).toBeDefined();
const items = resolveMenuItems((entry as { submenu: typeof raw }).submenu);
expect(items.filter((i) => i.kind === "item").map((i) => i.label)).toEqual([
"Blue",
"Green",
"Orange",
"Rose",
"Violet",
"Yellow",
"Gray",
"Edit File Colors…",
]);
items.find((i) => i.label === "Blue")!.run!();
await vi.waitFor(() => expect(ipc.settingsSet).toHaveBeenCalledTimes(2));
expect(ipc.settingsSet).toHaveBeenNthCalledWith(1, "project", "scopes", expect.stringContaining('"file:a.ts"'));
expect(ipc.settingsSet).toHaveBeenNthCalledWith(2, "project", "fileColors", expect.stringContaining("blue"));
// A file outside the project has no File Color, as in the project view.
await ctrl.openFile("/elsewhere/c.ts", { focus: false });
const outside = pane().tabs.find((t) => t.input.path === "/elsewhere/c.ts")!;
expect(ctrl.tabMenu(pane().id, outside).some((i) => "label" in i && i.label === "File Color")).toBe(false);
ipc.isTauri.mockReturnValue(false);
useProject.setState({ project: null, settings: null });
} finally {
disposeActions();
}
});
it("keeps editor tabs and unsaved documents through attach and detach", async () => {
const settings = {};
useProject.setState({
+1 -25
Переглянути файл
@@ -12,7 +12,7 @@ import { create } from "zustand";
import { setContext } from "@/platform/context";
import { formatBinding, hostBinding, shortcutLabel } from "@/platform/keymap";
import { isSameOrInside } from "@/platform/paths";
import { basename, dirname, relativePath, useProject } from "@/platform/project";
import { basename, dirname, useProject } from "@/platform/project";
import { editorPrefs } from "@/platform/editorSettings";
import {
_emitEditorEvent,
@@ -60,7 +60,6 @@ import { isUntitledUri, untitledTitle } from "@/platform/virtualDocs";
import { isRemoteWindow, projectLocation } from "@/platform/remote";
import { auxiliaryWindow } from "@/platform/auxWindow";
import { fileIconName, showContextMenu, type MenuItem } from "@/ui";
import { FILE_COLOR_NAMES, ownFileColor } from "@/platform/fileColors";
import { canOpenWithSystemApp, canRevealInFileManager, fileManagerName } from "@/platform/fileManager";
import {
activateTab,
@@ -2551,9 +2550,6 @@ export class EditorController implements SlotHost {
{ kind: "separator" },
...(path
? ([
...(inProject && path !== project!.root
? ([{ label: "File Color", submenu: fileColorMenuItems(path) }, { kind: "separator" }] as MenuItem[])
: []),
{
label: "Copy Path/Reference…",
submenu: [
@@ -2642,26 +2638,6 @@ export class EditorController implements SlotHost {
}
}
/**
* File Color submenu of a file tab: the project view's File Color rows as action items carrying
* the path (features/project-tree owns the model and the titles), so both menus agree.
*/
function fileColorMenuItems(path: string): MenuItem[] {
const { project, settings } = useProject.getState();
const current = project ? ownFileColor(relativePath(project.root, path), false, settings)?.toLowerCase() : null;
return [
...FILE_COLOR_NAMES.map((name): MenuItem => ({
kind: "action",
action: `file.${name}`,
arg: path,
checked: current === name,
})),
{ kind: "separator" },
...(current ? [{ kind: "action" as const, action: "file.clearColor", arg: path }] : []),
{ kind: "action", action: "file.editColors" },
];
}
/** Open In › for a file: Project View, Finder / Explorer / Files, associated app, Terminal. */
function openInMenu(path: string, lines?: { line: number; endLine?: number }): MenuItem {
return {
+1 -3
Переглянути файл
@@ -307,13 +307,11 @@ export function NavChildrenPopup({
segment,
anchor,
openAbove = true,
label,
onClose,
}: {
segment: NavSegment;
anchor: HTMLElement;
openAbove?: boolean;
label?: string;
onClose: () => void;
}) {
const [stack, setStack] = useState<NavSegment[]>([segment]);
@@ -368,7 +366,7 @@ export function NavChildrenPopup({
anchor={anchor}
placement={openAbove ? "top-start" : "bottom-start"}
onClose={onClose}
aria-label={label ?? top.label}
aria-label={top.label}
className={styles.childPopup}
>
{stack.length > 1 && (
+7 -50
Переглянути файл
@@ -14,7 +14,6 @@ import {
Menu,
Popup,
SelectListbox,
showContextMenu,
badgeKind,
fileIconName,
revealHorizontally,
@@ -34,7 +33,6 @@ import { editorController, isTextInput, useEditorStatus, useGotoLine, useTabs }
import { languageInfo } from "../cm/languages";
import { useDocMeta, useOutline, type DocMeta } from "../model/document";
import { symbolChain } from "./outline";
import { siblingSegment } from "./navBar";
import { NavChildrenPopup } from "./NavBarPopup";
import type { NavSegment } from "./navBar";
import styles from "./EditorArea.module.css";
@@ -168,15 +166,9 @@ function updateBreadcrumbEdges(row: HTMLDivElement) {
function BreadcrumbStrip({
trail,
activateOnDown = false,
onActivateAltDown,
children,
...props
}: ComponentPropsWithoutRef<"nav"> & {
trail: string;
activateOnDown?: boolean;
/** Alt+Down on a focused crumb opens its chooser (the crumb's element is passed). */
onActivateAltDown?: (crumb: HTMLElement) => void;
}) {
}: ComponentPropsWithoutRef<"nav"> & { trail: string; activateOnDown?: boolean }) {
const strip = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const row = strip.current;
@@ -197,16 +189,10 @@ function BreadcrumbStrip({
<nav
{...props}
onKeyDown={(e) => {
if (e.altKey || e.ctrlKey || e.metaKey) return;
const buttons = [...(strip.current?.querySelectorAll("button") ?? [])];
const index = buttons.indexOf(e.target as HTMLButtonElement);
if (index < 0) return;
if (e.altKey && !e.ctrlKey && !e.metaKey && e.key === "ArrowDown" && onActivateAltDown) {
e.preventDefault();
e.stopPropagation();
onActivateAltDown?.(buttons[index]!);
return;
}
if (e.altKey || e.ctrlKey || e.metaKey) return;
let next: number;
if (e.key === "ArrowLeft") next = Math.max(0, index - 1);
else if (e.key === "ArrowRight") next = Math.min(buttons.length - 1, index + 1);
@@ -368,7 +354,6 @@ export function CodeBreadcrumbs({
const editorSettings = useProject((s) => s.settings?.editor);
const language = useDocMeta((s) => s[path]?.language);
const outline = useOutline((s) => s[path]);
const [popup, setPopup] = useState<{ nav: NavSegment; anchor: HTMLElement } | null>(null);
let chain = useCaretSymbols(path, outline);
if (!chain) {
// Not the active editor (another split): its own caret, as of this render.
@@ -388,56 +373,28 @@ export function CodeBreadcrumbs({
? monoFontFamily(family, fallbackFont, "var(--font-mono)")
: undefined;
const fontSize = editorSettings?.fontSize ?? undefined;
const navigate = (item: OutlineItem) =>
void editorController().openFile(path, {
selection: { line: item.selection_range.start.line, col: item.selection_range.start.col },
});
// IDEA's breadcrumb chooser lives off the click: right-click or Alt+Down on a
// crumb lists its siblings (Navigation Bar only).
const chooseSiblings = (i: number, anchor: HTMLElement) => {
if (!outline) return;
setPopup({ nav: siblingSegment(path, chain, i), anchor });
};
const crumbMenu = (
i: number,
crumb: HTMLElement,
e: { clientX: number; clientY: number; preventDefault: () => void },
) => {
e.preventDefault();
if (outline)
showContextMenu(e, [{ id: "chooseSymbol", label: "Choose Symbol…", run: () => chooseSiblings(i, crumb) }]);
};
return (
<BreadcrumbStrip
trail={JSON.stringify([path, fontFamily, fontSize, ...chain.map((item) => item.name)])}
style={{ fontFamily, fontSize }}
className={clsx(styles.codeCrumbs, position === "top" ? styles.codeCrumbsTop : styles.codeCrumbsBottom)}
aria-label={tx("Code breadcrumbs")}
onActivateAltDown={(crumb) => chooseSiblings(Number(crumb.dataset.crumbIndex), crumb)}
>
{chain.map((item, i) => (
<BarButton
key={`${item.name}:${item.detail ?? ""}:${item.selection_range.start.line}:${item.selection_range.start.col}`}
data-crumb-index={i}
className={styles.crumbButton}
tooltip={item.detail ?? item.name}
aria-current={i === chain.length - 1 ? "location" : undefined}
onClick={() => navigate(item)}
onContextMenu={(e) => crumbMenu(i, e.currentTarget, e)}
onClick={() =>
void editorController().openFile(path, {
selection: { line: item.selection_range.start.line, col: item.selection_range.start.col },
})
}
>
<span className={styles.crumbLabel}>{item.name}</span>
</BarButton>
))}
{popup && (
<NavChildrenPopup
key={`${popup.nav.kind}:${popup.nav.path}:${popup.nav.label}`}
segment={popup.nav}
anchor={popup.anchor}
openAbove={position === "bottom"}
label={tx("Choose a symbol")}
onClose={() => setPopup(null)}
/>
)}
</BreadcrumbStrip>
);
}
-11
Переглянути файл
@@ -67,17 +67,6 @@ export function symbolChildren(path: string, items: readonly OutlineItem[]): Nav
return items.map((item) => ({ kind: "symbol", path, label: item.name, item }));
}
/**
* The segment whose children are the siblings of `chain[index]` (IDEA / PyCharm
* breadcrumb chooser): the file for a top-level symbol, else its enclosing symbol.
*/
export function siblingSegment(path: string, chain: readonly OutlineItem[], index: number): NavSegment {
const parent = index > 0 ? chain[index - 1]! : null;
return parent
? { kind: "symbol", path, label: parent.name, item: parent }
: { kind: "file", path, label: nameOf(path) };
}
export function iconOf(x: NavSegment | NavChild): string {
if (x.kind === "dir") return "root" in x && x.root ? "module" : "folder";
if (x.kind === "file") return fileIconName(x.label);
+3 -81
Переглянути файл
@@ -1,15 +1,13 @@
import { Profiler } from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
import type { OutlineItem, Settings } from "@/platform/ipc";
import type { EditorStatus } from "../controller";
const { openFile } = vi.hoisted(() => ({ openFile: vi.fn(async () => {}) }));
vi.mock("../controller", async () => {
const { create } = await import("zustand");
return {
editorController: () => ({ openFile, slots: new Map() }),
editorController: () => ({ openFile: vi.fn(), slots: new Map() }),
useEditorStatus: create<{ status: EditorStatus | null }>(() => ({ status: null })),
useGotoLine: create(() => ({ open: false })),
useTabs: create(() => ({ panes: {}, activePane: "" })),
@@ -23,7 +21,6 @@ const { useProject } = await import("@/platform/project");
const { clearProjectViewLead, setProjectViewLead } = await import("@/workbench/contributions");
const { Breadcrumbs, CodeBreadcrumbs } = await import("./StatusItems");
const { NavBarPopup, openNavBarPopup, useNavBarPopup } = await import("./NavBarPopup");
const { useContextMenuStore } = await import("@/ui");
const PATH = "/p/Orders.ts";
const span = (from: number, to: number) => ({ start: { line: from, col: 0 }, end: { line: to, col: 0 } });
@@ -310,78 +307,3 @@ it("elides the middle of a deep path without a duplicate React key", () => {
view.unmount();
useProject.setState({ project: null, settings: null });
});
describe("code breadcrumb symbol chooser", () => {
beforeEach(() => {
openFile.mockClear();
useProject.setState({
settings: {
editor: { breadcrumbs: { show: true, placement: "bottom", disabledLanguages: [] } },
} as unknown as Settings,
});
useEditorStatus.setState({ status: caret(3, 4) });
});
it("navigates to the crumb's symbol on plain click, as the IDE does", async () => {
// Orders class with place/cancel methods; caret sits inside `place`.
useOutline.setState({ [PATH]: [item("Orders", 0, 40, [item("place", 2, 10), item("cancel", 12, 20)])] });
const view = render(<CodeBreadcrumbs path={PATH} tabId="t1" position="bottom" />);
const crumbs = screen.getAllByRole("button");
// The last crumb is the innermost symbol (place).
const place = crumbs[crumbs.length - 1]!;
expect(place.getAttribute("aria-haspopup")).toBeNull();
fireEvent.click(place);
await waitFor(() => expect(openFile).toHaveBeenCalledWith(PATH, { selection: { line: 2, col: 0 } }));
// No chooser opened with the click: that belongs to the context menu / Alt+Down.
expect(screen.queryByRole("listbox")).toBeNull();
view.unmount();
});
it("opens the sibling chooser from the crumb's context menu", async () => {
useOutline.setState({ [PATH]: [item("Orders", 0, 40, [item("place", 2, 10), item("cancel", 12, 20)])] });
const view = render(<CodeBreadcrumbs path={PATH} tabId="t1" position="bottom" />);
const crumbs = screen.getAllByRole("button");
fireEvent.contextMenu(crumbs[crumbs.length - 1]!);
const menuItem = useContextMenuStore
.getState()
.menu?.items.find((i) => "label" in i && i.label === "Choose Symbol…") as { run?: () => void } | undefined;
expect(menuItem?.run).toBeTruthy();
act(() => menuItem!.run!());
const list = await screen.findByRole("listbox", { name: "Orders" });
expect(list.querySelectorAll('[role="option"]').length).toBeGreaterThan(0);
// Selecting a sibling navigates.
fireEvent.click(screen.getByRole("option", { name: "cancel" }));
await waitFor(() =>
expect(openFile).toHaveBeenCalledWith(PATH, {
selection: { line: 12, col: 0 },
focus: true,
}),
);
view.unmount();
});
it("opens the sibling chooser with Alt+Down while the strip has focus", async () => {
useOutline.setState({ [PATH]: [item("Orders", 0, 40, [item("place", 2, 10), item("cancel", 12, 20)])] });
const view = render(<CodeBreadcrumbs path={PATH} tabId="t1" position="bottom" />);
const crumbs = screen.getAllByRole("button");
const place = crumbs[crumbs.length - 1]!;
place.focus();
fireEvent.keyDown(place, { key: "ArrowDown", altKey: true });
await screen.findByRole("listbox", { name: "Orders" });
fireEvent.click(screen.getByRole("option", { name: "cancel" }));
await waitFor(() =>
expect(openFile).toHaveBeenCalledWith(PATH, {
selection: { line: 12, col: 0 },
focus: true,
}),
);
view.unmount();
});
it("hides the bar when there is no outline chain", () => {
useOutline.setState({ [PATH]: [] });
const view = render(<CodeBreadcrumbs path={PATH} tabId="t1" position="bottom" />);
expect(screen.queryByRole("navigation", { name: "Code breadcrumbs" })).toBeNull();
view.unmount();
});
});
-9
Переглянути файл
@@ -188,15 +188,6 @@ it("hands the window's whole list to the backend before startup, even after a fa
);
});
it("leaves the backend alone while no project is open", async () => {
loadBreakpoints(null);
await vi.advanceTimersByTimeAsync(200);
expect(ipc.debugReplaceBreakpoints).not.toHaveBeenCalled();
loadBreakpoints("/p");
await vi.advanceTimersByTimeAsync(0);
expect(ipc.debugReplaceBreakpoints).toHaveBeenCalledOnce();
});
it("flushes persisted breakpoints immediately after project loading", async () => {
ipc.debugSetBreakpoints.mockResolvedValue({ status: "ok", data: [] });
localStorage.setItem(
+2 -4
Переглянути файл
@@ -138,10 +138,8 @@ async function drainBreakpoints() {
/** Makes this window's whole list the backend's: files it no longer lists are cleared there. */
async function replaceBreakpoints() {
// Without a project (before one opens, after it closes) the backend holds no breakpoints for
// this window and has none to clear.
const { root, byFile, muted } = useBreakpoints.getState();
if (!isTauri() || root === null || useProject.getState().project?.trusted === false) return;
if (!isTauri() || useProject.getState().project?.trusted === false) return;
const { byFile, muted } = useBreakpoints.getState();
const files = Object.fromEntries(Object.entries(byFile).map(([path, list]) => [path, toBackend(list, muted, path)]));
await call(commands.debugReplaceBreakpoints(files));
}
+1 -24
Переглянути файл
@@ -2,18 +2,13 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
const ghAccountRepos = vi.fn();
const toolsList = vi.fn();
vi.mock("@/platform/ipc", async (importOriginal) => ({
...(await importOriginal<typeof import("@/platform/ipc")>()),
isTauri: () => true,
commands: {
ghAccountRepos: () => ghAccountRepos(),
toolsList: () => toolsList(),
},
commands: { ghAccountRepos: () => ghAccountRepos() },
}));
import type { GhAccountRepo } from "@/bindings";
import { registerAction } from "@/platform/actions";
import { GitHubCloneSource, matchRepos } from "./GitHubCloneSource";
const repo = (nameWithOwner: string, extra: Partial<GhAccountRepo> = {}): GhAccountRepo => ({
@@ -30,7 +25,6 @@ const repos = [repo("me/app", { private: true, description: "The app" }), repo("
afterEach(() => {
cleanup();
ghAccountRepos.mockReset();
toolsList.mockReset();
});
describe("GitHub clone source", () => {
@@ -70,21 +64,4 @@ describe("GitHub clone source", () => {
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
await waitFor(() => expect(screen.getByRole("option", { name: /me\/app/ })).toBeInTheDocument());
});
it("installs GitHub CLI in-app when missing and reloads repositories", async () => {
const install = vi.fn().mockResolvedValue(undefined);
const dispose = registerAction({ id: "tools.install", title: "Install", run: install });
ghAccountRepos.mockResolvedValueOnce({ status: "ok", data: { kind: "notInstalled" } });
toolsList.mockResolvedValue({ status: "ok", data: [{ name: "gh", status: "installed" }] });
ghAccountRepos.mockResolvedValueOnce({ status: "ok", data: { kind: "ready", login: "me", repos } });
try {
render(<GitHubCloneSource url="" onUrl={() => {}} onClone={() => {}} disabled={false} />);
expect(await screen.findByText("GitHub CLI is not installed")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Install GitHub CLI" }));
await waitFor(() => expect(install).toHaveBeenCalledWith(expect.objectContaining({ arg: "gh" })));
await waitFor(() => expect(screen.getByRole("option", { name: /me\/app/ })).toBeInTheDocument());
} finally {
dispose();
}
});
});
+11 -35
Переглянути файл
@@ -1,9 +1,8 @@
/** Clone Repository › GitHub: the repositories of the account gh is signed in to. */
import { useEffect, useMemo, useState, type KeyboardEvent } from "react";
import type { GhAccountRepo, GhAccountRepos } from "@/bindings";
import { GH_MANUAL_INSTALL_URL, installGhTool } from "@/platform/ghTool";
import { tx } from "@/platform/i18n";
import { call, commands, isCancelled } from "@/platform/ipc";
import { call, commands } from "@/platform/ipc";
import {
Button,
EmptyState,
@@ -38,8 +37,6 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource
const [state, setState] = useState<GhAccountRepos | null>(null);
const [query, setQuery] = useState("");
const [attempt, setAttempt] = useState(0);
const [installingGh, setInstallingGh] = useState(false);
const [installError, setInstallError] = useState<string | null>(null);
useEffect(() => {
let alive = true;
@@ -53,26 +50,14 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource
const rows = useMemo(() => (state?.kind === "ready" ? matchRepos(state.repos, query) : []), [state, query]);
const active = rows.findIndex((r) => r.repo.cloneUrl === url);
const reload = () => {
setInstallError(null);
setState(null);
setAttempt((n) => n + 1);
};
const installGh = () => {
if (installingGh) return;
setInstallingGh(true);
setInstallError(null);
void installGhTool()
.promise.then((installed) => {
if (installed) reload();
})
.catch((e: unknown) => {
if (!isCancelled(e)) setInstallError(e instanceof Error ? e.message : String(e));
})
.finally(() => setInstallingGh(false));
};
const retry = (
<Button size="small" onClick={reload}>
<Button
size="small"
onClick={() => {
setState(null);
setAttempt((n) => n + 1);
}}
>
<T>Retry</T>
</Button>
);
@@ -92,24 +77,15 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource
title="GitHub CLI is not installed"
actions={
<>
<Button size="small" variant="primary" disabled={installingGh} onClick={installGh}>
{installingGh ? (
<>
<Spinner size={12} /> <T>Installing…</T>
</>
) : (
<T>Install GitHub CLI</T>
)}
</Button>
<Button size="small" onClick={() => void openInBrowser(GH_MANUAL_INSTALL_URL)}>
<T>Download manually…</T>
<Button size="small" onClick={() => void openInBrowser("https://cli.github.com")}>
<T>Install gh…</T>
</Button>
{retry}
</>
}
>
<T>GitHub repositories are listed with the</T> <code>gh</code> <T>command line tool. Install it, then run</T>{" "}
<code>gh auth login</code>.{installError && <div className={styles.muted}>{installError}</div>}
<code>gh auth login</code>.
</EmptyState>
);
if (state.kind === "notLoggedIn")
+3 -29
Переглянути файл
@@ -7,8 +7,6 @@
import { useEffect, useRef, useState, type RefObject } from "react";
import type { GhAvailability } from "@/platform/ipc";
import { executeAction } from "@/platform/actions";
import { GH_MANUAL_INSTALL_URL, installGhTool } from "@/platform/ghTool";
import { isCancelled } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { Button, EmptyState, IconButton, Select, Spinner, Tabs, T, showContextMenu, type MenuItem } from "@/ui";
import { CreatePanel } from "../create/CreatePanel";
@@ -30,21 +28,6 @@ import { closeTab, selectTab, tabId, useGhTabs, type GhTabId } from "./store";
import styles from "./ToolWindow.module.css";
function Unavailable({ availability }: { availability: GhAvailability }) {
const [installingGh, setInstallingGh] = useState(false);
const [installError, setInstallError] = useState<string | null>(null);
const installGh = () => {
if (installingGh) return;
setInstallingGh(true);
setInstallError(null);
void installGhTool()
.promise.then((installed) => {
if (installed) void refreshConnection();
})
.catch((e: unknown) => {
if (!isCancelled(e)) setInstallError(e instanceof Error ? e.message : String(e));
})
.finally(() => setInstallingGh(false));
};
const retry = (
<Button size="small" onClick={() => void refreshConnection()}>
<T>Retry</T>
@@ -57,24 +40,15 @@ function Unavailable({ availability }: { availability: GhAvailability }) {
title="GitHub CLI is not installed"
actions={
<>
<Button size="small" variant="primary" disabled={installingGh} onClick={installGh}>
{installingGh ? (
<>
<Spinner size={12} /> <T>Installing…</T>
</>
) : (
<T>Install GitHub CLI</T>
)}
</Button>
<Button size="small" onClick={() => void openInBrowser(GH_MANUAL_INSTALL_URL)}>
<T>Download manually…</T>
<Button size="small" onClick={() => void openInBrowser("https://cli.github.com")}>
<T>Install gh…</T>
</Button>
{retry}
</>
}
>
<T>Pull requests use the</T> <code>gh</code> <T>command line tool. Install it, then run</T>{" "}
<code>gh auth login</code>.{installError && <div className={styles.hint}>{installError}</div>}
<code>gh auth login</code>.
</EmptyState>
);
case "notLoggedIn":
+6 -18
Переглянути файл
@@ -1,13 +1,12 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { getAction, registerAction } from "@/platform/actions";
import { act, render, screen } from "@testing-library/react";
import { getAction } from "@/platform/actions";
import { getContext } from "@/platform/context";
import * as ipc from "@/platform/ipc";
import { provideToolWindowService, useContributions, type ToolWindowService } from "@/workbench/contributions";
import { activate } from "../index";
import { setCurrentRepository } from "../api/client";
import type { GHRepository, GHUser } from "../api/types";
import * as repositoryData from "../data/repository";
import { useGhRepository } from "../data/repository";
import { PullRequestsTabs, PullRequestsToolWindow } from "./PullRequestsToolWindow";
import {
@@ -123,21 +122,10 @@ describe("tool window", () => {
expect(show).toHaveBeenCalledWith("pullRequests", true);
});
it("shows gh's state when it is not ready and installs gh on click", async () => {
const install = vi.fn().mockResolvedValue(undefined);
const dispose = registerAction({ id: "tools.install", title: "Install", run: install });
const refresh = vi.spyOn(repositoryData, "refreshConnection").mockResolvedValue(undefined);
try {
useGhRepository.setState({ availability: { kind: "notInstalled" } });
render(<PullRequestsToolWindow />);
expect(screen.getByText("GitHub CLI is not installed")).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "Install GitHub CLI" }));
await waitFor(() => expect(install).toHaveBeenCalledWith(expect.objectContaining({ arg: "gh" })));
await waitFor(() => expect(refresh).toHaveBeenCalledOnce());
} finally {
refresh.mockRestore();
dispose();
}
it("shows gh's state when it is not ready", () => {
useGhRepository.setState({ availability: { kind: "notInstalled" } });
render(<PullRequestsToolWindow />);
expect(screen.getByText("GitHub CLI is not installed")).toBeTruthy();
});
it("offers the repository selector for several GitHub remotes", () => {
+1 -26
Переглянути файл
@@ -1,15 +1,13 @@
/** Actions of the project view (Find Action, keymap, other features via `executeAction`). */
import { activeEditor } from "@/editor/api";
import { executeAction, getAction, registerActions, type Action } from "@/platform/actions";
import { getAction, registerActions, type Action } from "@/platform/actions";
import { getContext } from "@/platform/context";
import { FILE_COLOR_NAMES } from "@/platform/fileColors";
import { canRevealInFileManager, revealInFileManagerLabel } from "@/platform/fileManager";
import { dirname, useProject } from "@/platform/project";
import { showContextMenu, type MenuItem } from "@/ui";
import { maybeEditorService, menuGroupItems, toolWindowService } from "@/workbench/contributions";
import { OPTION_LABELS, SORT_LABELS, flipToggle, isToggled } from "./HeaderActions";
import { compareTarget, newMenuItems, revealLabel } from "./contextMenu";
import { LABELS, setFileColor } from "./fileColor";
import { openNewPopup } from "./newPopupModel";
import type { ProjectNode } from "./model";
import {
@@ -589,28 +587,5 @@ export function registerProjectActions(): () => void {
...toggles,
...modes,
...sorts,
// File Color of a single path (the project view's submenu; the editor tab menu references
// these ids with a path argument instead of importing this feature).
...FILE_COLOR_NAMES.map((name): Action => ({
id: `file.${name}`,
title: LABELS[name],
category: "Project View",
hidden: true,
run: ({ arg }) => void setFileColor(String(arg), false, name),
})),
{
id: "file.clearColor",
title: "Clear File Color",
category: "Project View",
hidden: true,
run: ({ arg }) => void setFileColor(String(arg), false, null),
},
{
id: "file.editColors",
title: "Edit File Colors…",
category: "Project View",
hidden: true,
run: () => void executeAction("file.settings", "fileColors"),
},
]);
}
+1 -2
Переглянути файл
@@ -8,8 +8,7 @@ import { call, commands, isTauri } from "@/platform/ipc";
import { loadSettings, relativePath, useProject } from "@/platform/project";
import type { MenuItem } from "@/ui";
/** English title per colour, also the title of its `file.<colour>` action (the editor tab menu). */
export const LABELS: Record<(typeof FILE_COLOR_NAMES)[number], string> = {
const LABELS: Record<(typeof FILE_COLOR_NAMES)[number], string> = {
blue: "Blue",
green: "Green",
orange: "Orange",
-66
Переглянути файл
@@ -1,66 +0,0 @@
import { useMemo, type ComponentType } from "react";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useProject } from "@/platform/project";
import { PageContext } from "../components/context";
import { DEFAULT_SETTINGS } from "../model/schema";
import { openSettings, stagedValue, useSettingsDialog } from "../model/staging";
import { codeStyleLanguagePages } from "../pages/editor/codeStyle";
const mocks = vi.hoisted(() => ({ languages: vi.fn() }));
vi.mock("@/platform/ipc", async (original) => {
const actual = await original<typeof import("@/platform/ipc")>();
return {
...actual,
isTauri: () => true,
commands: {
...actual.commands,
languages: mocks.languages,
},
};
});
beforeEach(() => {
mocks.languages.mockResolvedValue([
{ id: "java", name: "Java", indent: { tabSize: 4, insertSpaces: true } },
{ id: "rust", name: "Rust" },
]);
useProject.setState({ settings: structuredClone(DEFAULT_SETTINGS), project: null });
openSettings("editor.codeStyle.java");
});
afterEach(cleanup);
function CodeStylePage({ id, Page }: { id: string; Page: ComponentType }) {
const value = useMemo(() => ({ pageId: id, scope: "global" as const }), [id]);
return (
<PageContext.Provider value={value}>
<Page />
</PageContext.Provider>
);
}
async function page(language: string) {
const pages = await codeStyleLanguagePages();
const spec = pages.find((p) => p.id === `editor.codeStyle.${language}`)!;
render(<CodeStylePage id={spec.id} Page={spec.component!} />);
}
const value = () => stagedValue(useSettingsDialog.getState(), "global", "editor.codeStyle.languages");
describe("Java Imports (IntelliSort)", () => {
it("stages the class-count and static-count options on the Java code style", async () => {
await page("java");
fireEvent.click(screen.getByRole("tab", { name: "Imports" }));
fireEvent.change(screen.getByLabelText("Class count to use import with *"), { target: { value: "7" } });
fireEvent.change(screen.getByLabelText("Names count to use static import with *"), { target: { value: "2" } });
expect(value()).toEqual({
java: { classCountToUseImportWithStar: 7, namesCountToUseStaticImportWithStar: 2 },
});
fireEvent.click(screen.getByRole("button", { name: "Reset to Language Defaults" }));
expect(value()).toEqual({});
});
it("keeps the Imports tab specific to Java", async () => {
await page("rust");
expect(screen.queryByRole("tab", { name: "Imports" })).toBeNull();
});
});
+1 -48
Переглянути файл
@@ -157,11 +157,6 @@ const COMMENTS = {
keywords: ["Line comment at first column", "Add a space at line comment start"],
};
const CASE = { id: "case", label: "Case", keywords: ["Keywords", "Identifiers", "To upper", "To lower"] };
const IMPORTS = {
id: "imports",
label: "Imports",
keywords: ["imports", "static imports", "wildcard", "class count", "import with *"],
};
const SPACES = { id: "spaces", label: "Spaces", keywords: ["Space", "Around binary operators", "Within braces"] };
const PUNCTUATION = { id: "punctuation", label: "Punctuation", keywords: ["Semicolons", "Quotes"] };
@@ -303,41 +298,6 @@ function LanguageStyle({ lang }: { lang: LanguageInfo }) {
),
});
}
if (lang.id === "java") {
tabs.push({
...IMPORTS,
content: (
<FormGroup>
<Row
label="Class count to use import with '*'"
hint="Use a wildcard import once this many classes of one package are used (5 by default; 999 keeps single-class imports)."
>
<NumberInput
value={own.classCountToUseImportWithStar ?? 5}
onChange={(n) => set({ classCountToUseImportWithStar: n })}
min={1}
max={999}
integer
aria-label="Class count to use import with *"
/>
</Row>
<Row
label="Names count to use static import with '*'"
hint="Use a wildcard static import once this many names are imported statically (3 by default; 999 keeps single imports)."
>
<NumberInput
value={own.namesCountToUseStaticImportWithStar ?? 3}
onChange={(n) => set({ namesCountToUseStaticImportWithStar: n })}
min={1}
max={999}
integer
aria-label="Names count to use static import with *"
/>
</Row>
</FormGroup>
),
});
}
if (TS_STYLE_LANGUAGES.has(lang.id)) {
tabs.push(
{
@@ -541,14 +501,7 @@ export async function codeStyleLanguagePages(): Promise<PageSpec[]> {
...keywords,
]),
...(lang.id === "java"
? [
"Formatting profile",
"IntelliJ IDEA",
"Custom Eclipse formatter XML",
"Eclipse formatter XML",
IMPORTS.label,
...IMPORTS.keywords,
]
? ["Formatting profile", "IntelliJ IDEA", "Custom Eclipse formatter XML", "Eclipse formatter XML"]
: []),
...(lang.id === "php" ? ["Alignment", "Align key-value pairs", "Align consecutive assignments"] : []),
...(lang.id === "sql" ? [CASE.label, ...CASE.keywords, "Do not change"] : []),
-21
Переглянути файл
@@ -276,27 +276,6 @@ describe("annotate Options", () => {
const hidden = (v: EditorView) =>
["date", "author", "revision"].filter((c) => v.dom.classList.contains(`cm-vcs-blame-hide-${c}`));
it("prints Today/Yesterday in the date cell when pretty formatting is on", async () => {
const today = Date.now();
const yesterday = today - 86_400_000;
const recentLines: BlameLine[] = [
{ commit: sha, author: "Aleks Zlateski", timeMs: today, summary: "today" },
{ commit: otherSha, author: "Dan Crankshaw", timeMs: yesterday, summary: "yesterday" },
];
mocks.blame.mockResolvedValue({ status: "ok", data: recentLines });
useProject.setState({ settings: { general: { dateFormat: { pretty: true } } } });
const created = new EditorView({
parent: document.body,
state: EditorState.create({ doc: "first\nsecond\nthird", extensions: [blameSlot()] }),
});
view = created;
await toggleAnnotations(created, "/repo/src/main.py");
const cell = (commit: string) =>
created.dom.querySelector<HTMLElement>(`.cm-vcs-blame [data-commit="${commit}"] .cm-vcs-blame-date`)?.textContent;
expect(cell(sha)).toBe("Today");
expect(cell(otherSha)).toBe("Yesterday");
});
it("shows date and author by default and adds the revision from Options", async () => {
view = await annotated();
expect(
+2 -2
Переглянути файл
@@ -11,7 +11,7 @@ import { onWorkflowSettingsChange, workflowSettings } from "@/platform/workflowS
import { showContextMenu, type MenuItem } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { closeBlamePopup, scheduleCloseBlamePopup, scheduleOpenBlamePopup } from "./BlamePopup";
import { formatPrettyDay } from "@/platform/dateFormat";
import { formatDate } from "./model";
import { saveVcsSetting } from "./settingsUi";
import { useVcs } from "./store";
@@ -318,7 +318,7 @@ function build(lines: BlameLine[], doc: Text): BlameState {
let label = labels.get(line.commit);
if (!label && !isUncommitted(line)) {
label = {
date: line.timeMs ? formatPrettyDay(line.timeMs) : "",
date: formatDate(line.timeMs),
author: shortAuthorName(line.author, names),
revision: line.commit.slice(0, 8),
};
+26 -51
Переглянути файл
@@ -1,8 +1,7 @@
/**
* Image editor kind (IDEA's image viewer): zoom in / out / fit / actual size,
* ⌘/Ctrl+wheel zoom, transparency chessboard, dimensions and file size.
* Images are read by the backend as `data:` URLs (the CSP allows those). As the preview of an SVG
* file it shows the source as typed instead (`source`), drawn as an image so its scripts never run.
* Images are read by the backend as `data:` URLs (the CSP allows those).
*/
import {
useCallback,
@@ -60,19 +59,9 @@ export function toggleChessboard() {
}
const PADDING = 32;
const NO_FOCUS_TARGET = { current: null };
const INVALID_SVG = "invalid-svg";
/** An SVG source as an image URL. */
export const svgDataUrl = (source: string) => `data:image/svg+xml;charset=utf-8,${encodeURIComponent(source)}`;
/**
* `source`: the SVG text to show instead of the file on disk (the SVG editor's preview); null while
* it isn't known yet.
*/
export function ImageViewer({ input, source }: { input: EditorInput; source?: string | null }) {
export function ImageViewer({ input }: { input: EditorInput }) {
const path = input.path!;
const live = source !== undefined;
const [src, setSrc] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [size, setSize] = useState<number | null>(null);
@@ -86,27 +75,18 @@ export function ImageViewer({ input, source }: { input: EditorInput; source?: st
const canvasRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (live) return;
let current = true;
let live = true;
Promise.all([call(commands.fsReadImage(path)), call(commands.fsProbe(path))])
.then(([url, probe]) => {
if (!current) return;
if (!live) return;
setSrc(url);
setSize(probe.size);
})
.catch((e: unknown) => current && setError(e instanceof Error ? e.message : String(e)));
.catch((e: unknown) => live && setError(e instanceof Error ? e.message : String(e)));
return () => {
current = false;
live = false;
};
}, [path, reload, live]);
// The typed source: each edit is drawn again, so an invalid SVG recovers once it's valid.
const liveSrc = useMemo(() => (source ? svgDataUrl(source) : null), [source]);
const liveSize = useMemo(() => (source ? new TextEncoder().encode(source).length : null), [source]);
const [invalidSrc, setInvalidSrc] = useState<string | null>(null);
const shownSrc = live ? liveSrc : src;
const shownSize = live ? liveSize : size;
const shownError = live ? (invalidSrc !== null && invalidSrc === liveSrc ? INVALID_SVG : null) : error;
}, [path, reload]);
const available = useCallback(() => {
const el = canvasRef.current;
@@ -153,8 +133,7 @@ export function ImageViewer({ input, source }: { input: EditorInput; source?: st
};
}, [handle]);
// Beside the source editor, the preview leaves the editor's focus alone.
useForwardFocus(live ? NO_FOCUS_TARGET : rootRef);
useForwardFocus(rootRef);
const onLoad = (img: HTMLImageElement) => {
// SVGs without intrinsic size report 0×0; show them at a usable size.
@@ -183,7 +162,7 @@ export function ImageViewer({ input, source }: { input: EditorInput; source?: st
};
el.addEventListener("wheel", onWheel, { passive: false });
return () => el.removeEventListener("wheel", onWheel);
}, [shownError, shownSrc]);
}, [error, src]);
const onPointerDown = (e: ReactPointerEvent) => {
if (e.button !== 0 && e.button !== 1) return;
@@ -225,17 +204,15 @@ export function ImageViewer({ input, source }: { input: EditorInput; source?: st
<div className={styles.imageActions}>
<div className={styles.imageActionGroup}>
<IconButton icon="chessboard" size="small" action="image.toggleChessboard" pressed={chessboard} />
{!live && (
<IconButton
icon="refresh"
size="small"
title="Reload from Disk"
onClick={() => {
setError(null);
setReload((n) => n + 1);
}}
/>
)}
<IconButton
icon="refresh"
size="small"
title="Reload from Disk"
onClick={() => {
setError(null);
setReload((n) => n + 1);
}}
/>
</div>
<div className={styles.imageActionGroup}>
<IconButton icon="zoom-in" size="small" action="image.zoomIn" />
@@ -244,7 +221,7 @@ export function ImageViewer({ input, source }: { input: EditorInput; source?: st
<IconButton icon="maximize" size="small" action="image.fitToWindow" />
</div>
</div>
{svg && !live && (
{svg && (
<button
type="button"
className={styles.textButton}
@@ -253,18 +230,16 @@ export function ImageViewer({ input, source }: { input: EditorInput; source?: st
<T>Open as Text</T>
</button>
)}
{(natural || shownSize !== null || view) && (
{(natural || size !== null || view) && (
<div className={styles.imageInfo}>
{natural && <span>{`${natural.w} × ${natural.h}`}</span>}
{shownSize !== null && <span>{formatSize(shownSize)}</span>}
{size !== null && <span>{formatSize(size)}</span>}
{view && <span>{zoomLabel(z)}</span>}
</div>
)}
</div>
{shownError ? (
<div className={styles.message}>
{shownError === INVALID_SVG ? tx("The SVG source is not valid.") : tx`Cannot show the image: ${shownError}`}
</div>
{error ? (
<div className={styles.message}>{tx`Cannot show the image: ${error}`}</div>
) : (
<div
data-wheel-scroll
@@ -275,9 +250,9 @@ export function ImageViewer({ input, source }: { input: EditorInput; source?: st
onPointerUp={endDrag}
onPointerCancel={endDrag}
>
{shownSrc && (
{src && (
<img
src={shownSrc}
src={src}
alt={path.slice(path.lastIndexOf("/") + 1)}
draggable={false}
className={clsx(styles.image, chessboard && styles.chessboard, z >= 4 && styles.pixelated)}
@@ -291,7 +266,7 @@ export function ImageViewer({ input, source }: { input: EditorInput; source?: st
: { visibility: "hidden" }
}
onLoad={(e) => onLoad(e.currentTarget)}
onError={() => (live ? setInvalidSrc(shownSrc) : setError("the file is not a valid image"))}
onError={() => setError("the file is not a valid image")}
/>
)}
</div>
-38
Переглянути файл
@@ -1,38 +0,0 @@
import { IconButton } from "@/ui";
import type { LayoutMode } from "./layoutModes";
import styles from "./markdown/Markdown.module.css";
/** Editor Only / Editor and Preview / Preview Only buttons of a text editor with a preview. */
export function LayoutActions({ tabId, mode, label }: { tabId: string; mode: LayoutMode; label: string }) {
return (
<div className={styles.layoutActions} role="toolbar" aria-label={label}>
<IconButton
icon="editor-only"
iconSize={16}
size="small"
title="Editor Only"
action="markdown.editorOnly"
actionArg={tabId}
pressed={mode === "editor"}
/>
<IconButton
icon="editor-preview"
iconSize={16}
size="small"
title="Editor and Preview"
action="markdown.editorAndPreview"
actionArg={tabId}
pressed={mode === "split"}
/>
<IconButton
icon="preview-only"
iconSize={16}
size="small"
title="Preview Only"
action="markdown.previewOnly"
actionArg={tabId}
pressed={mode === "preview"}
/>
</div>
);
}
+9 -38
Переглянути файл
@@ -1,7 +1,7 @@
/**
* Non-text editors and the Markdown preview: images open in an image viewer,
* binary and very large files in a read-only hex view (both through file
* editor providers consulted by `openFile`), and Markdown and SVG files get IDEA's
* editor providers consulted by `openFile`), and Markdown files get IDEA's
* Editor / Editor and Preview / Preview layouts around the text editor.
*/
import { registerActions, type Action } from "@/platform/actions";
@@ -29,16 +29,12 @@ import {
imageInput,
isImagePath,
isMarkdownPath,
isSvgPath,
wantsHexView,
} from "./fileKinds";
import { ImageViewer, toggleChessboard, useImageViewers } from "./ImageViewer";
import { HexViewer } from "./HexViewer";
import { registerMarkdownLiveSource } from "./markdown/live";
import { setMarkdownMode, useMarkdownModes, useMarkdownSourceHidden } from "./markdown/modes";
import type { LayoutMode } from "./layoutModes";
import { registerSvgLiveSource } from "./svg/live";
import { SvgLayoutActions, svgModes } from "./svg/SvgEditor";
import { setMarkdownMode, useMarkdownSourceHidden, type MarkdownMode } from "./markdown/modes";
import { MarkdownLayoutActions } from "./markdown/MarkdownLayoutActions";
import { canExtractImages, extractImages, EXTRACT_IMAGES, EXTRACT_IMAGES_TITLE } from "./markdown/extractImages";
@@ -69,35 +65,19 @@ function imageActions(): Action[] {
];
}
/**
* The tab whose layout an Editor Only / Editor and Preview / Preview Only action sets: the one its
* tab button passes, else the focused editor's when it's a Markdown or SVG file.
*/
function layoutTarget(arg: unknown): { tabId: string; set: (tabId: string, mode: LayoutMode) => void } | null {
if (typeof arg === "string") {
return { tabId: arg, set: svgModes.useModes.getState().byTab[arg] ? svgModes.set : setMarkdownMode };
}
const editor = activeEditor();
const path = editor?.ctx.path ?? "";
if (!editor?.tabId) return null;
if (isSvgPath(path)) return { tabId: editor.tabId, set: svgModes.set };
if (isMarkdownPath(path) || useMarkdownModes.getState().byTab[editor.tabId])
return { tabId: editor.tabId, set: setMarkdownMode };
return null;
}
function markdownActions(): Action[] {
const mode = (id: string, title: string, m: LayoutMode, icon: string): Action => ({
const mode = (id: string, title: string, m: MarkdownMode, icon: string): Action => ({
id,
title,
category: "Markdown",
icon,
keywords: ["markdown", "svg", "preview", "layout"],
when: "textEditorActive",
enabled: ({ arg }) => !!layoutTarget(arg),
keywords: ["markdown", "preview", "layout"],
when: "textEditorActive && editorLangId == markdown",
run: ({ arg }) => {
const target = layoutTarget(arg);
target?.set(target.tabId, m);
// The tab's layout buttons pass their tab; the keyboard acts on the focused editor's.
const editor = activeEditor();
const tabId = typeof arg === "string" ? arg : isMarkdownPath(editor?.ctx.path ?? "") ? editor?.tabId : undefined;
if (tabId) setMarkdownMode(tabId, m);
},
});
return [
@@ -163,15 +143,6 @@ export function activate(): () => void {
useSourceHidden: useMarkdownSourceHidden,
}),
registerMarkdownLiveSource(),
registerTextEditorWrapper({
id: "viewers.svg",
fallback: true,
matches: isSvgPath,
component: lazyComponent(() => import("./svg/SvgEditor").then((m) => m.SvgEditor)),
tabActions: SvgLayoutActions,
useSourceHidden: svgModes.useSourceHidden,
}),
registerSvgLiveSource(),
registerMenuGroup({
id: EXTRACT_IMAGES,
menus: ["editor"],
-56
Переглянути файл
@@ -1,56 +0,0 @@
/**
* Layout of a text editor with a preview (IDEA's TextEditorWithPreview): Editor Only / Editor and
* Preview / Preview Only, per editor tab. Split panes showing the same file each keep their own;
* tabs opened later take the layout chosen last for that kind of file.
*/
import { create, type StoreApi, type UseBoundStore } from "zustand";
export type LayoutMode = "editor" | "split" | "preview";
const MODES: readonly LayoutMode[] = ["editor", "split", "preview"];
export interface LayoutModesState {
byTab: Record<string, LayoutMode>;
/** Mode of tabs opened since: the last one chosen. */
fallback: LayoutMode;
}
export const modeOf = (s: LayoutModesState, tabId: string): LayoutMode => s.byTab[tabId] ?? s.fallback;
export interface LayoutModes {
useModes: UseBoundStore<StoreApi<LayoutModesState>>;
/** Preview Only hides the source editor of `tabId`. */
useSourceHidden: (tabId: string) => boolean;
/** Fixes a shown tab's mode, so choosing one in another tab doesn't change it. */
pin: (tabId: string) => void;
set: (tabId: string, mode: LayoutMode) => void;
}
/** The layouts of one kind of file, the last one chosen kept under `storageKey`. */
export function createLayoutModes(storageKey: string): LayoutModes {
const stored = (): LayoutMode => {
try {
const v = localStorage.getItem(storageKey);
return MODES.includes(v as LayoutMode) ? (v as LayoutMode) : "split";
} catch {
return "split";
}
};
const useModes = create<LayoutModesState>(() => ({ byTab: {}, fallback: stored() }));
return {
useModes,
useSourceHidden: (tabId) => useModes((s) => modeOf(s, tabId) === "preview"),
pin: (tabId) => {
if (useModes.getState().byTab[tabId]) return;
useModes.setState((s) => ({ byTab: { ...s.byTab, [tabId]: s.fallback } }));
},
set: (tabId, mode) => {
useModes.setState((s) => ({ byTab: { ...s.byTab, [tabId]: mode }, fallback: mode }));
try {
localStorage.setItem(storageKey, mode);
} catch {
// Per-viewer convenience only.
}
},
};
}
+33 -2
Переглянути файл
@@ -1,8 +1,39 @@
import { IconButton } from "@/ui";
import { tx } from "@/platform/i18n";
import { LayoutActions } from "../LayoutActions";
import { modeOf, useMarkdownModes } from "./modes";
import styles from "./Markdown.module.css";
export function MarkdownLayoutActions({ tabId }: { path: string; tabId: string }) {
const mode = useMarkdownModes((s) => modeOf(s, tabId));
return <LayoutActions tabId={tabId} mode={mode} label={tx("Markdown editor layout")} />;
return (
<div className={styles.layoutActions} role="toolbar" aria-label={tx("Markdown editor layout")}>
<IconButton
icon="editor-only"
iconSize={16}
size="small"
title="Editor Only"
action="markdown.editorOnly"
actionArg={tabId}
pressed={mode === "editor"}
/>
<IconButton
icon="editor-preview"
iconSize={16}
size="small"
title="Editor and Preview"
action="markdown.editorAndPreview"
actionArg={tabId}
pressed={mode === "split"}
/>
<IconButton
icon="preview-only"
iconSize={16}
size="small"
title="Preview Only"
action="markdown.previewOnly"
actionArg={tabId}
pressed={mode === "preview"}
/>
</div>
);
}
+44 -9
Переглянути файл
@@ -1,12 +1,47 @@
/** Markdown editor layout per editor tab: Editor only / Editor and Preview / Preview only. */
import { createLayoutModes, modeOf, type LayoutMode } from "../layoutModes";
/**
* Markdown editor layout per editor tab: Editor only / Editor and Preview / Preview only. Split
* panes showing the same file each keep their own.
*/
import { create } from "zustand";
export type MarkdownMode = LayoutMode;
export { modeOf };
export type MarkdownMode = "editor" | "split" | "preview";
const markdown = createLayoutModes("openidea.markdown.defaultMode");
const DEFAULT_KEY = "openidea.markdown.defaultMode";
const MODES: readonly MarkdownMode[] = ["editor", "split", "preview"];
export const useMarkdownModes = markdown.useModes;
export const useMarkdownSourceHidden = markdown.useSourceHidden;
export const pinMarkdownMode = markdown.pin;
export const setMarkdownMode = markdown.set;
function storedDefault(): MarkdownMode {
try {
const v = localStorage.getItem(DEFAULT_KEY);
return MODES.includes(v as MarkdownMode) ? (v as MarkdownMode) : "split";
} catch {
return "split";
}
}
interface ModesState {
byTab: Record<string, MarkdownMode>;
/** Mode of tabs opened since: the last one chosen. */
fallback: MarkdownMode;
}
export const useMarkdownModes = create<ModesState>(() => ({ byTab: {}, fallback: storedDefault() }));
export const modeOf = (s: ModesState, tabId: string): MarkdownMode => s.byTab[tabId] ?? s.fallback;
/** Preview Only hides the source editor of `tabId`. */
export const useMarkdownSourceHidden = (tabId: string) => useMarkdownModes((s) => modeOf(s, tabId) === "preview");
/** Fixes a shown tab's mode, so choosing one in another tab doesn't change it. */
export function pinMarkdownMode(tabId: string) {
if (useMarkdownModes.getState().byTab[tabId]) return;
useMarkdownModes.setState((s) => ({ byTab: { ...s.byTab, [tabId]: s.fallback } }));
}
export function setMarkdownMode(tabId: string, mode: MarkdownMode) {
useMarkdownModes.setState((s) => ({ byTab: { ...s.byTab, [tabId]: mode }, fallback: mode }));
try {
localStorage.setItem(DEFAULT_KEY, mode);
} catch {
// Per-viewer convenience only.
}
}
-95
Переглянути файл
@@ -1,95 +0,0 @@
/**
* SVG files as IDEA opens them: the source with the image viewer beside it (Editor Only / Editor and
* Preview / Preview Only), the preview redrawn from the source as it's typed.
*/
import { useEffect, useRef, type ReactNode } from "react";
import clsx from "clsx";
import { editorsFor } from "@/editor/api";
import { tx } from "@/platform/i18n";
import { FloatingToolbar, SplitGroup, SplitHandle, SplitPanel } from "@/ui";
import { imageInput } from "../fileKinds";
import { ImageViewer } from "../ImageViewer";
import { LayoutActions } from "../LayoutActions";
import { createLayoutModes, modeOf } from "../layoutModes";
import { useLiveSvg } from "./live";
import styles from "../markdown/Markdown.module.css";
export const svgModes = createLayoutModes("openidea.svg.defaultMode");
const SPLIT_STORAGE_KEY = "openidea.svg.split";
const DEFAULT_SPLIT_LAYOUT = { editor: 50, preview: 50 };
export function SvgLayoutActions({ tabId }: { path: string; tabId: string }) {
const mode = svgModes.useModes((s) => modeOf(s, tabId));
return <LayoutActions tabId={tabId} mode={mode} label={tx("SVG editor layout")} />;
}
function SvgPreview({ path }: { path: string }) {
const source = useLiveSvg((s) => s[path]) ?? null;
return <ImageViewer input={imageInput(path)} source={source} />;
}
export function SvgEditor({
path,
tabId,
children,
actionsInTabs = false,
}: {
path: string;
tabId: string;
children: ReactNode;
actionsInTabs?: boolean;
}) {
const mode = svgModes.useModes((s) => modeOf(s, tabId));
useEffect(() => svgModes.pin(tabId), [tabId]);
const ref = useRef<HTMLDivElement>(null);
const editorRef = useRef<HTMLDivElement>(null);
// CodeMirror skips resizes right after a view update; re-measure on drags and mode changes.
useEffect(() => {
const el = editorRef.current;
if (!el || typeof ResizeObserver === "undefined") return;
let width = el.clientWidth;
const ro = new ResizeObserver(() => {
const next = el.clientWidth;
if (next === width) return;
width = next;
if (next <= 0) return;
for (const ed of editorsFor(path)) {
if (!ed.tabId || ed.tabId === tabId) ed.view.requestMeasure();
}
});
ro.observe(el);
return () => ro.disconnect();
}, [path, tabId]);
const splitBounds = mode === "split" ? { minSize: "10%", maxSize: "90%" } : {};
return (
<div ref={ref} className={clsx(styles.split, styles[`mode-${mode}`])}>
<SplitGroup
orientation="horizontal"
className={styles.group}
storageKey={mode === "split" ? SPLIT_STORAGE_KEY : undefined}
defaultLayout={mode === "split" ? DEFAULT_SPLIT_LAYOUT : undefined}
>
{/* Hidden but mounted in Preview Only, so the document stays open (see MarkdownEditor). */}
<SplitPanel id="editor" style={{ overflow: "hidden" }} disabled={mode === "preview"} {...splitBounds}>
<div ref={editorRef} className={styles.editor}>
{children}
</div>
</SplitPanel>
{mode === "split" && <SplitHandle aria-label={tx("Resize SVG preview")} />}
{mode !== "editor" && (
<SplitPanel id="preview" style={{ overflow: "hidden", display: "flex" }} {...splitBounds}>
<SvgPreview path={path} />
</SplitPanel>
)}
</SplitGroup>
{!actionsInTabs && (
<FloatingToolbar targetRef={ref}>
<SvgLayoutActions path={path} tabId={tabId} />
</FloatingToolbar>
)}
</div>
);
}
-38
Переглянути файл
@@ -1,38 +0,0 @@
/** The SVG source as typed, per file, for the preview beside it (redrawn shortly after typing stops). */
import { ViewPlugin, type EditorView, type ViewUpdate } from "@codemirror/view";
import { create } from "zustand";
import { registerEditorContribution } from "@/editor/api";
import { isSvgPath } from "../fileKinds";
export const useLiveSvg = create<Record<string, string | undefined>>(() => ({}));
const TEXT_DELAY = 300;
const publish = (path: string, text: string) =>
useLiveSvg.getState()[path] === text || useLiveSvg.setState({ [path]: text });
function livePlugin(path: string) {
return ViewPlugin.fromClass(
class {
private timer: ReturnType<typeof setTimeout> | undefined;
constructor(view: EditorView) {
publish(path, view.state.doc.toString());
}
update(u: ViewUpdate) {
if (!u.docChanged) return;
clearTimeout(this.timer);
this.timer = setTimeout(() => publish(path, u.view.state.doc.toString()), TEXT_DELAY);
}
destroy() {
clearTimeout(this.timer);
}
},
);
}
export function registerSvgLiveSource(): () => void {
return registerEditorContribution({
id: "viewers.svgLive",
extensions: (ctx) => (!ctx.virtual && isSvgPath(ctx.path) ? [livePlugin(ctx.path)] : []),
});
}
-98
Переглянути файл
@@ -1,98 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import { useEffect } from "react";
import { executeAction } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { setMarkdownMode, useMarkdownModes } from "../markdown/modes";
import { activate as activateViewers } from "../index";
import { ImageViewer, svgDataUrl } from "../ImageViewer";
import { imageInput } from "../fileKinds";
import { useLiveSvg } from "./live";
import { SvgEditor, svgModes } from "./SvgEditor";
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return {
...real,
call: vi.fn(() => Promise.reject(new Error("no backend"))),
};
});
const PATH = "/p/icon.svg";
// Hidden until it has loaded (jsdom never loads it), so found by tag rather than role.
const image = () => document.querySelector("img")!;
describe("SVG editor", () => {
beforeEach(() => {
localStorage.clear();
svgModes.useModes.setState({ byTab: {}, fallback: "split" });
useMarkdownModes.setState({ byTab: {}, fallback: "split" });
useLiveSvg.setState({ [PATH]: '<svg xmlns="http://www.w3.org/2000/svg" width="4" height="2"/>' });
});
afterEach(() => {
cleanup();
localStorage.clear();
});
it("shows the source and the image side by side, switching layouts without reopening the editor", () => {
let mounts = 0;
function Source() {
useEffect(() => {
mounts++;
}, []);
return <div data-testid="source" />;
}
render(
<SvgEditor path={PATH} tabId="t">
<Source />
</SvgEditor>,
);
expect(screen.getByRole("separator", { name: "Resize SVG preview" })).toBeInTheDocument();
expect(image().src).toBe(svgDataUrl(useLiveSvg.getState()[PATH]!));
// Beside the source the image viewer can't reload from disk or open the file a second time.
expect(screen.queryByRole("button", { name: "Open as Text" })).toBeNull();
expect(screen.queryByRole("button", { name: "Reload from Disk" })).toBeNull();
act(() => svgModes.set("t", "editor"));
expect(document.querySelector("img")).toBeNull();
act(() => svgModes.set("t", "preview"));
expect(image()).toBeInTheDocument();
expect(screen.getByTestId("source")).toBeInTheDocument();
expect(mounts).toBe(1);
});
it("redraws the image as the source is typed, and recovers from invalid SVG", () => {
const { rerender } = render(<ImageViewer input={imageInput(PATH)} source="<svg" />);
fireEvent.error(image());
expect(screen.getByText("The SVG source is not valid.")).toBeInTheDocument();
const fixed = '<svg xmlns="http://www.w3.org/2000/svg"/>';
rerender(<ImageViewer input={imageInput(PATH)} source={fixed} />);
expect(image().src).toBe(svgDataUrl(fixed));
expect(screen.queryByText("The SVG source is not valid.")).toBeNull();
});
it("keeps the SVG layout apart from Markdown's, and the layout actions set the tab's own", async () => {
const off = activateViewers();
setContext("textEditorActive", true);
try {
render(
<SvgEditor path={PATH} tabId="svg-tab">
<div />
</SvgEditor>,
);
setMarkdownMode("md-tab", "preview");
expect(svgModes.useModes.getState().fallback).toBe("split");
await act(() => executeAction("markdown.editorOnly", "svg-tab"));
expect(svgModes.useModes.getState().byTab["svg-tab"]).toBe("editor");
expect(useMarkdownModes.getState().byTab["md-tab"]).toBe("preview");
expect(useMarkdownModes.getState().byTab["svg-tab"]).toBeUndefined();
// The last layout chosen for an SVG is the one the next SVG opens in.
expect(localStorage.getItem("openidea.svg.defaultMode")).toBe("editor");
} finally {
setContext("textEditorActive", false);
off();
}
});
});
+1 -6
Переглянути файл
@@ -84,13 +84,8 @@ describe("file kinds", () => {
component: () => null,
});
try {
// SVG files open as text with the image viewer beside it; a plugin's wrapper wins over it.
expect(await resolveFileEditor("/p/icon.svg")).toBeNull();
expect(await resolveFileEditor("/p/logo.png").then((r) => r?.input.kind)).toBe("image");
expect((await resolveFileEditor("/p/icon.svg"))?.input.kind).toBe("image");
expect(await resolveFileEditor("/p/arch.diagram.svg")).toBeNull();
const wrappers = useTextEditorWrappers.getState().wrappers;
expect(textEditorWrapperFor(wrappers, "/p/icon.svg")?.id).toBe("viewers.svg");
expect(textEditorWrapperFor(wrappers, "/p/arch.diagram.svg")?.id).toBe("plugin.acme.diagram.canvas");
} finally {
offWrapper();
offViewers();
-14
Переглянути файл
@@ -5,7 +5,6 @@ import {
formatDateTime,
formatDay,
formatPattern,
formatPrettyDay,
formatTimestamp,
} from "./dateFormat";
@@ -34,19 +33,6 @@ describe("dateFormat", () => {
expect(formatTimestamp(d.getTime(), now, custom)).toBe("05.11.2026 09:07");
});
it("shows Today/Yesterday without a clock time for blame, older dates keep the short date", () => {
const now = new Date(2026, 10, 13, 12, 0).getTime();
const pretty = { ...system, pretty: true };
const older = new Date(2026, 10, 5, 9, 7);
const short = { year: "2-digit", month: "2-digit", day: "2-digit" } as const;
expect(formatPrettyDay(new Date(2026, 10, 13, 9, 7).getTime(), now, pretty)).toBe("Today");
expect(formatPrettyDay(new Date(2026, 10, 12, 23, 30).getTime(), now, pretty)).toBe("Yesterday");
expect(formatPrettyDay(older.getTime(), now, pretty)).toBe(older.toLocaleDateString(undefined, short));
expect(formatPrettyDay(new Date(2026, 10, 13, 9, 7).getTime(), now, { ...system, pretty: false })).toBe(
new Date(2026, 10, 13, 9, 7).toLocaleDateString(undefined, short),
);
});
it("formats another date with the same cached formatter", () => {
const e = new Date(2025, 0, 31);
formatDay(d, system);
-13
Переглянути файл
@@ -99,16 +99,3 @@ export function formatTimestamp(ms: number, now = Date.now(), o: DateFormatOptio
}
return formatDateTime(d, o);
}
/**
* Day without clock time (blame gutter): "Today" / "Yesterday" when pretty
* formatting is on, as IDEA's annotate shows; older dates keep the short date.
*/
export function formatPrettyDay(ms: number, now = Date.now(), o: DateFormatOptions = dateFormatOptions()): string {
const d = new Date(ms);
if (o.pretty) {
if (d.toDateString() === new Date(now).toDateString()) return tx("Today");
if (d.toDateString() === new Date(now - 86_400_000).toDateString()) return tx("Yesterday");
}
return formatDay(d, o, true);
}
-4
Переглянути файл
@@ -47,10 +47,6 @@ export interface LanguageCodeStyle {
/** SQL › Case: Reformat Code's case for keywords and unquoted identifiers. */
keywordCase?: SqlWordCase;
identifierCase?: SqlWordCase;
/** Java: organize imports switches to a wildcard import once this many classes of one package are used (jdtls passthrough). */
classCountToUseImportWithStar?: number;
/** Java: organize imports switches to a wildcard static import once this many names are used (jdtls passthrough). */
namesCountToUseStaticImportWithStar?: number;
/** JavaScript / TypeScript › Punctuation (unset: tsserver's default, `ignore` / `auto`). */
semicolons?: "ignore" | "insert" | "remove";
quotes?: "auto" | "single" | "double";
-55
Переглянути файл
@@ -1,55 +0,0 @@
/**
* Optional GitHub CLI (`gh`) installer shared by GitHub Pull Requests,
* Clone Repository › GitHub, and Settings › Agents › GitHub Copilot.
* Uses the `tools.install` action when available (workbench window, for
* status-bar progress and notifications) and falls back to `commands.toolsInstall`
* directly in standalone windows such as Settings.
*/
import { Channel } from "@tauri-apps/api/core";
import { executeAction, getAction } from "./actions";
import { call, commands, isTauri, nextRequestId, type InstallEvent, type ToolInfo } from "./ipc";
const GH_TOOL_NAME = "gh";
export const GH_MANUAL_INSTALL_URL = "https://cli.github.com";
interface GhInstallHandle {
promise: Promise<boolean>;
/** Cancels a direct install; null when delegated to the `tools.install` task queue. */
cancel: (() => void) | null;
}
/** Returns the `ide-tools` entry for `gh`, or null outside the desktop app or on lookup error. */
async function getGhToolInfo(): Promise<ToolInfo | null> {
if (!isTauri()) return null;
try {
const tools = await call(commands.toolsList());
return tools.find((tool) => tool.name === GH_TOOL_NAME) ?? null;
} catch {
return null;
}
}
/**
* Installs `gh` into OpenIDEA's managed tools directory. Resolves to `true` when
* `gh` is available afterwards, or `false` if cancelled or not installed.
* Propagates errors when running directly (the `tools.install` action reports
* its own errors via notifications).
*/
export function installGhTool(onEvent?: (event: InstallEvent) => void): GhInstallHandle {
if (getAction("tools.install")) {
const promise = (async () => {
await executeAction("tools.install", GH_TOOL_NAME);
const info = await getGhToolInfo();
return info ? info.status !== "missing" : true;
})();
return { promise, cancel: null };
}
const request = nextRequestId();
const channel = new Channel<InstallEvent>();
channel.onmessage = (event) => onEvent?.(event);
const promise = call(commands.toolsInstall(GH_TOOL_NAME, request, channel)).then((info) => info.status !== "missing");
return {
promise,
cancel: () => void commands.cancelRequest(request).catch(() => {}),
};
}
-6
Переглянути файл
@@ -120,12 +120,6 @@ export const IDEA_ACTIONS: Readonly<Record<string, string>> = {
ToggleZenMode: "view.toggleZenMode",
EditorScrollUp: "editor.scrollUp",
EditorScrollDown: "editor.scrollDown",
EditorScrollUpAndMove: "editor.scrollUpAndMove",
EditorScrollDownAndMove: "editor.scrollDownAndMove",
EditorMoveUpAndScroll: "editor.moveUpAndScroll",
EditorMoveDownAndScroll: "editor.moveDownAndScroll",
EditorMoveUpAndScrollWithSelection: "editor.moveUpAndScrollWithSelection",
EditorMoveDownAndScrollWithSelection: "editor.moveDownAndScrollWithSelection",
EditorScrollTop: "editor.scrollToTop",
EditorScrollBottom: "editor.scrollToBottom",
EditorMoveToPageTop: "editor.moveToPageTop",
-20
Переглянути файл
@@ -92,26 +92,6 @@ describe("IntelliJ IDEA keymap import", () => {
expect(k.unknownActions).toEqual([]);
});
it("maps Scroll Up / Scroll Down and Move if Necessary", () => {
const k = parseIdeaKeymap(
`<keymap name="E" parent="$default"><action id="EditorScrollUpAndMove"><keyboard-shortcut first-keystroke="alt UP"/></action><action id="EditorScrollDownAndMove"><keyboard-shortcut first-keystroke="alt DOWN"/></action></keymap>`,
);
expect(k.overrides["editor.scrollUpAndMove"]).toEqual([normalizeBinding("Alt+Up")]);
expect(k.overrides["editor.scrollDownAndMove"]).toEqual([normalizeBinding("Alt+Down")]);
expect(k.unknownActions).toEqual([]);
});
it("maps Move Up / Down and Scroll (with Selection)", () => {
const k = parseIdeaKeymap(
`<keymap name="E" parent="$default"><action id="EditorMoveUpAndScroll"><keyboard-shortcut first-keystroke="ctrl alt UP"/></action><action id="EditorMoveDownAndScroll"><keyboard-shortcut first-keystroke="ctrl alt DOWN"/></action><action id="EditorMoveUpAndScrollWithSelection"><keyboard-shortcut first-keystroke="ctrl alt shift UP"/></action><action id="EditorMoveDownAndScrollWithSelection"><keyboard-shortcut first-keystroke="ctrl alt shift DOWN"/></action></keymap>`,
);
expect(k.overrides["editor.moveUpAndScroll"]).toEqual([normalizeBinding("Ctrl+Alt+Up")]);
expect(k.overrides["editor.moveDownAndScroll"]).toEqual([normalizeBinding("Ctrl+Alt+Down")]);
expect(k.overrides["editor.moveUpAndScrollWithSelection"]).toEqual([normalizeBinding("Ctrl+Alt+Shift+Up")]);
expect(k.overrides["editor.moveDownAndScrollWithSelection"]).toEqual([normalizeBinding("Ctrl+Alt+Shift+Down")]);
expect(k.unknownActions).toEqual([]);
});
it("maps Scroll to Top / Scroll to Bottom", () => {
const k = parseIdeaKeymap(
`<keymap name="X" parent="Mac OS X 10.5+"><action id="EditorScrollTop"><keyboard-shortcut first-keystroke="HOME"/></action><action id="EditorScrollBottom"><keyboard-shortcut first-keystroke="END"/></action></keymap>`,
-6
Переглянути файл
@@ -64,12 +64,6 @@ describe("IDEA keymap parity", () => {
// `Mac OS X 10.5+` removes the ⌘↑ / ⌘↓ it would inherit from `Mac OS X`.
["editor.scrollUp", [], ["Ctrl+Up"]],
["editor.scrollDown", [], ["Ctrl+Down"]],
["editor.scrollUpAndMove", [], []],
["editor.scrollDownAndMove", [], []],
["editor.moveUpAndScroll", [], []],
["editor.moveDownAndScroll", [], []],
["editor.moveUpAndScrollWithSelection", [], []],
["editor.moveDownAndScrollWithSelection", [], []],
// Only IDEA's Xcode keymap binds these (Home / End).
["editor.scrollToTop", [], []],
["editor.scrollToBottom", [], []],
-6
Переглянути файл
@@ -138,12 +138,6 @@ export const intellijMacos: Record<string, string[]> = {
"editor.scrollToCenter": ["Ctrl+L"],
"editor.scrollUp": [],
"editor.scrollDown": [],
"editor.scrollUpAndMove": [],
"editor.scrollDownAndMove": [],
"editor.moveUpAndScroll": [],
"editor.moveDownAndScroll": [],
"editor.moveUpAndScrollWithSelection": [],
"editor.moveDownAndScrollWithSelection": [],
"editor.scrollToTop": [],
"editor.scrollToBottom": [],
"editor.moveToPageTop": ["Meta+PageUp"],
-6
Переглянути файл
@@ -139,12 +139,6 @@ export const intellijWindows: Record<string, string[]> = {
"editor.scrollToCenter": ["Ctrl+M"],
"editor.scrollUp": ["Ctrl+Up"],
"editor.scrollDown": ["Ctrl+Down"],
"editor.scrollUpAndMove": [],
"editor.scrollDownAndMove": [],
"editor.moveUpAndScroll": [],
"editor.moveDownAndScroll": [],
"editor.moveUpAndScrollWithSelection": [],
"editor.moveDownAndScrollWithSelection": [],
"editor.scrollToTop": [],
"editor.scrollToBottom": [],
"editor.moveToPageTop": ["Ctrl+PageUp"],
-6
Переглянути файл
@@ -254,12 +254,6 @@ export const vscodeMacos: Record<string, string[]> = {
"editor.scrollToCenter": [],
"editor.scrollUp": [],
"editor.scrollDown": [],
"editor.scrollUpAndMove": [],
"editor.scrollDownAndMove": [],
"editor.moveUpAndScroll": [],
"editor.moveDownAndScroll": [],
"editor.moveUpAndScrollWithSelection": [],
"editor.moveDownAndScrollWithSelection": [],
"editor.scrollToTop": [],
"editor.scrollToBottom": [],
"editor.moveToPageTop": [],
+1 -15
Переглянути файл
@@ -1643,8 +1643,6 @@
"Status Bar Widget": "Status Bar Widget",
"Show main toolbar": "Show main toolbar",
"Navigation bar": "Navigation bar",
"Choose a symbol": "Choose a symbol",
"Choose Symbol…": "Choose Symbol…",
"Don't show": "Don't show",
"Don't Show": "Don't Show",
"Show status bar": "Show status bar",
@@ -4120,13 +4118,6 @@
"Run '{command}' in '{rel}' to install them.": "Run '{command}' in '{rel}' to install them.",
"Run '{command}' to install them.": "Run '{command}' to install them.",
"Install Node.js Dependencies": "Install Node.js Dependencies",
"Imports": "Imports",
"Class count to use import with '*'": "Class count to use import with '*'",
"Use a wildcard import once this many classes of one package are used (5 by default; 999 keeps single-class imports).": "Use a wildcard import once this many classes of one package are used (5 by default; 999 keeps single-class imports).",
"Class count to use import with *": "Class count to use import with *",
"Names count to use static import with '*'": "Names count to use static import with '*'",
"Use a wildcard static import once this many names are imported statically (3 by default; 999 keeps single imports).": "Use a wildcard static import once this many names are imported statically (3 by default; 999 keeps single imports).",
"Names count to use static import with *": "Names count to use static import with *",
"Watch for changes": "Watch for changes",
"Rerun Automatically": "Rerun Automatically",
"Debug runs the tests once, without watching.": "Debug runs the tests once, without watching.",
@@ -4175,10 +4166,5 @@
"Where Clause": "Where Clause",
"SQL INSERT": "SQL INSERT",
"SQL UPDATE": "SQL UPDATE",
"SQL DELETE": "SQL DELETE",
"SVG editor layout": "SVG editor layout",
"Resize SVG preview": "Resize SVG preview",
"The SVG source is not valid.": "The SVG source is not valid.",
"Install GitHub CLI": "Install GitHub CLI",
"Download manually…": "Download manually…"
"SQL DELETE": "SQL DELETE"
}
+1
Переглянути файл
@@ -1081,6 +1081,7 @@
"Install a plugin folder with": "Instala una carpeta de complemento con",
"Install and Debug": "Instalar y depurar",
"Reinstall and Debug": "Reinstalar y depurar",
"Install gh…": "Instalar gh…",
"Installed": "Instalados",
"Installed packages": "Paquetes instalados",
"Installed plugins": "Complementos instalados",
+1
Переглянути файл
@@ -1019,6 +1019,7 @@
"Install a plugin folder with": "Installez un dossier de plugin avec",
"Install and Debug": "Installer et déboguer",
"Reinstall and Debug": "Réinstaller et déboguer",
"Install gh…": "Installer gh…",
"Installed": "Installés",
"Installed packages": "Paquets installés",
"Installed plugins": "Plugins installés",
+1
Переглянути файл
@@ -1117,6 +1117,7 @@
"Install a plugin folder with": "다음으로 플러그인 폴더 설치",
"Install and Debug": "설치 및 디버그",
"Reinstall and Debug": "다시 설치 및 디버그",
"Install gh…": "gh 설치…",
"Installed": "설치됨",
"Installed packages": "설치된 패키지",
"Installed plugins": "설치된 플러그인",
+1
Переглянути файл
@@ -1073,6 +1073,7 @@
"Install a plugin folder with": "Zainstaluj folder wtyczki za pomocą",
"Install and Debug": "Zainstaluj i debuguj",
"Reinstall and Debug": "Zainstaluj ponownie i debuguj",
"Install gh…": "Zainstaluj gh…",
"Installed": "Zainstalowane",
"Installed packages": "Zainstalowane pakiety",
"Installed plugins": "Zainstalowane wtyczki",
+1
Переглянути файл
@@ -1073,6 +1073,7 @@
"Install a plugin folder with": "Instalar uma pasta de plugin com",
"Install and Debug": "Instalar e depurar",
"Reinstall and Debug": "Reinstalar e depurar",
"Install gh…": "Instalar gh…",
"Installed": "Instalados",
"Installed packages": "Pacotes instalados",
"Installed plugins": "Plugins instalados",
+1
Переглянути файл
@@ -2144,6 +2144,7 @@
"Install a plugin folder with": "Установить папку плагина с",
"Install and Debug": "Установить и отладить",
"Reinstall and Debug": "Переустановить и отладить",
"Install gh…": "Установить gh…",
"Installed": "Установлено",
"Installed packages": "Установленные пакеты",
"Installed plugins": "Установленные плагины",
+1
Переглянути файл
@@ -3839,6 +3839,7 @@
"Install a plugin folder with": "Şu klasörden eklenti yükle:",
"Install and Debug": "Yükle ve Hata Ayıkla",
"Reinstall and Debug": "Yeniden Yükle ve Hata Ayıkla",
"Install gh…": "gh Yükle…",
"Installed": "Yüklü",
"Installed packages": "Yüklü paketler",
"Installed plugins": "Yüklü eklentiler",
+1 -6
Переглянути файл
@@ -693,12 +693,6 @@
"Scroll to Center": "捲動到中央",
"Scroll Up": "向上捲動",
"Scroll Down": "向下捲動",
"Scroll Up and Move if Necessary": "向上捲動並在必要時移動游標",
"Scroll Down and Move if Necessary": "向下捲動並在必要時移動游標",
"Move Up and Scroll": "向上移動並捲動",
"Move Down and Scroll": "向下移動並捲動",
"Move Up and Scroll with Selection": "向上移動並捲動並選擇",
"Move Down and Scroll with Selection": "向下移動並捲動並選擇",
"Scroll to Top": "捲動到頂部",
"Scroll to Bottom": "捲動到底部",
"Move Caret to Page Top": "將游標移至頁面頂部",
@@ -1765,6 +1759,7 @@
"Install a plugin folder with": "安裝外掛資料夾:",
"Install and Debug": "安裝並偵錯",
"Reinstall and Debug": "重新安裝並偵錯",
"Install gh…": "安裝 gh…",
"Installed": "已安裝",
"Installed packages": "已安裝的軟體包",
"Installed plugins": "已安裝的外掛",
+2 -20
Переглянути файл
@@ -1054,12 +1054,6 @@
"Scroll to Center": "滚动到中央",
"Scroll Up": "向上滚动",
"Scroll Down": "向下滚动",
"Scroll Up and Move if Necessary": "向上滚动并在必要时移动光标",
"Scroll Down and Move if Necessary": "向下滚动并在必要时移动光标",
"Move Up and Scroll": "向上移动并滚动",
"Move Down and Scroll": "向下移动并滚动",
"Move Up and Scroll with Selection": "向上移动并滚动并选择",
"Move Down and Scroll with Selection": "向下移动并滚动并选择",
"Scroll to Top": "滚动到顶部",
"Scroll to Bottom": "滚动到底部",
"Move Caret to Page Top": "将光标移至页面顶部",
@@ -2220,6 +2214,7 @@
"Install a plugin folder with": "安装插件文件夹:",
"Install and Debug": "安装并调试",
"Reinstall and Debug": "重新安装并调试",
"Install gh…": "安装 gh…",
"Installed": "已安装",
"Installed packages": "已安装的软件包",
"Installed plugins": "已安装的插件",
@@ -2423,8 +2418,6 @@
"Navigation": "导航",
"Navigation Bar": "导航栏",
"Navigation bar": "导航栏",
"Choose a symbol": "选择符号",
"Choose Symbol…": "选择符号…",
"Never": "从不",
"New": "新建",
"New Branch…": "新建分支…",
@@ -10569,12 +10562,6 @@
"Run with {title}": "使用 {title} 运行",
"Debug with {title}": "使用 {title} 调试",
"Launches the selected configuration with the Java agent of {pluginName}": "使用 {pluginName} 的 Java 代理启动所选配置",
"Class count to use import with '*'": "使用通配符导入的类数",
"Use a wildcard import once this many classes of one package are used (5 by default; 999 keeps single-class imports).": "当同一个包使用达到该数量的类时使用通配符导入;默认为 5,999 表示始终保留单类导入。",
"Class count to use import with *": "使用通配符导入的类数",
"Names count to use static import with '*'": "使用通配符静态导入的名称数",
"Use a wildcard static import once this many names are imported statically (3 by default; 999 keeps single imports).": "静态导入的名称达到该数量时使用通配符静态导入;默认为 3,999 表示始终保留单条导入。",
"Names count to use static import with *": "使用通配符静态导入的名称数",
"Watch for changes": "监视更改",
"Rerun Automatically": "自动重新运行",
"Debug runs the tests once, without watching.": "调试时测试只运行一次,不监视更改。",
@@ -10624,10 +10611,5 @@
"SQL INSERT": "SQL INSERT 语句",
"SQL UPDATE": "SQL UPDATE 语句",
"SQL DELETE": "SQL DELETE 语句",
"Column comment": "列注释",
"SVG editor layout": "SVG 编辑器布局",
"Resize SVG preview": "调整 SVG 预览大小",
"The SVG source is not valid.": "SVG 源代码无效。",
"Install GitHub CLI": "安装 GitHub CLI",
"Download manually…": "手动下载…"
"Column comment": "列注释"
}
+2 -9
Переглянути файл
@@ -706,8 +706,6 @@ export async function openFileExternally(path: string): Promise<boolean> {
export interface TextEditorWrapperContribution {
keepAlive?: boolean;
id: string;
/** Yields to any other wrapper matching the file (a plugin's editor for `*.diagram.svg`). */
fallback?: boolean;
matches(path: string): boolean;
component: ComponentType<{ path: string; tabId: string; children: ReactNode; actionsInTabs?: boolean }>;
/** Layout controls in the tab strip; the wrapper supplies a floating fallback when tabs are hidden. */
@@ -735,13 +733,8 @@ export function textEditorWrapperFor(
wrappers: ReadonlyMap<string, TextEditorWrapperContribution>,
path: string,
): TextEditorWrapperContribution | undefined {
let fallback: TextEditorWrapperContribution | undefined;
for (const w of wrappers.values()) {
if (!w.matches(path)) continue;
if (!w.fallback) return w;
fallback ??= w;
}
return fallback;
for (const w of wrappers.values()) if (w.matches(path)) return w;
return undefined;
}
/**