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

..
Автор SHA1 Повідомлення Дата
Deng Liu 62dcdce77f feat(tools,github): add optional managed GitHub CLI installer 2026-11-26 14:15:56 -08:00
Vladislav Kuzmin 5fa953eddd fix(ci): scope Unix-only integration test declarations for Windows Clippy (#6259)
Windows Clippy (-D warnings) built two integration-test declarations whose only
users are Unix-only tests: tsc_errors in language_smoke.rs (used by the
TypeScript project-errors test) and the file-level Duration import in
plugin_workbench.rs (used by the PTY run-output test). Scope tsc_errors to unix
and move the import into the Unix-only test.

Fixes #6258

Co-authored-by: principalwater <[email protected]>
2026-11-27 06:06:41 +08:00
Mansur Akhmadiтаmansur-akhmadi 031f1acd07 feat(editor): Move Up / Down and Scroll actions (#6268)
Adds Move Up / Down and Scroll and their with-Selection variants as Editor
Actions (IDEA's EditorMoveUpAndScroll family, reachable from Find Action,
imported keymaps and IdeaVim :action). The carets move one line from the head,
dropping a selection unless extending, and the view scrolls by the distance the
primary caret moved (text line top below block widgets, or the visual row with
soft wrap), so the caret keeps its place on screen. Unbound by default, as in
IDEA's keymaps.

Closes #6267

Co-authored-by: mansur-akhmadi <[email protected]>
2026-11-27 06:04:03 +08:00
l0ng-ai add23fe97f feat(viewers): open SVG files as source with a live image preview (#6266)
SVG files open in the text editor with the image viewer beside it and the
Editor Only / Editor and Preview / Preview Only switch Markdown has. The preview
is redrawn from the source as it is typed, reports invalid SVG and recovers once
it is valid; it is drawn as an image, so scripts never run. The SVG layout is
remembered apart from Markdown's, raster images keep the image viewer, and text
editor wrappers gain `fallback` so a plugin's editor for a more specific SVG
pattern still wins.

Fixes #6234
2026-11-27 05:32:32 +08:00
l0ng-ai 3d2b0946de fix(debugger): don't sync breakpoints to the backend while no project is open (#6215)
Before a project opens (a web page booting, a welcome window) and after one
closes, loadBreakpoints(null) asked the backend to replace this window's
breakpoints; with no project the call failed with "no project is open in this
window" and logged debugReplaceBreakpoints failed on every such load. Without a
project the backend holds no breakpoints for the window, so the sync now waits
until a project root is loaded.
2026-11-27 05:18:36 +08:00
Muuтаmuutot 6c7282b442 feat(editor): choose sibling symbols from a code breadcrumb (#6106)
Clicking a code breadcrumb still navigates to its symbol. Right-clicking a crumb
offers "Choose Symbol..." and Alt+Down on a focused crumb opens the same
chooser: the existing Navigation Bar children popup, anchored on the crumb and
listing the symbol's siblings (children of the enclosing symbol, or of the file
for a top-level symbol).

Co-authored-by: muutot <[email protected]>
2026-11-27 05:17:28 +08:00
57 змінених файлів з 1264 додано та 214 видалено

No files matched your search

Створено
-1
Переглянути файл
@@ -4440,7 +4440,6 @@ dependencies = [
"serde_json",
"specta",
"tracing",
"which",
]
[[package]]
+32
Переглянути файл
@@ -73,6 +73,38 @@ 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,4 +12,3 @@ serde.workspace = true
serde_json.workspace = true
specta.workspace = true
tracing.workspace = true
which = "8"
+37 -18
Переглянути файл
@@ -16,30 +16,15 @@ 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 once per process (GUI apps on macOS have a minimal `PATH`).
/// 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).
pub fn gh_executable() -> Option<PathBuf> {
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()
ide_core::tool_path::find_gh_executable()
}
fn command(root: &Path, args: &[&str]) -> IdeResult<Command> {
@@ -386,3 +371,37 @@ 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);
}
}
+7 -3
Переглянути файл
@@ -29,15 +29,19 @@ fn tools(host: &Host, window: &str) -> IdeResult<Tools> {
&root,
&settings,
));
// 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));
// 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);
}
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.into_iter().collect())
.with_found_paths(found)
.with_work_dir(work_dir))
}
+1
Переглянути файл
@@ -697,6 +697,7 @@ 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,7 +6,6 @@ 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>,
@@ -510,6 +509,7 @@ 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();
+1 -5
Переглянути файл
@@ -4,7 +4,7 @@
//! without network.
use crate::platform::{Arch, Os, Platform};
use crate::process::{Emit, Http};
use crate::process::Emit;
use crate::sources::Download;
use crate::{InstallEvent, InstallGuard, Tools, archive, clear_quarantine, fetch_verified};
use ide_core::error::ErrorKind;
@@ -240,10 +240,6 @@ 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)?;
+9 -4
Переглянути файл
@@ -557,6 +557,10 @@ 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);
@@ -902,7 +906,7 @@ impl Tools {
_ => (ToolStatus::Missing, None, None),
}
}
_ => match self.which(main) {
_ => match self.which(main).or_else(|| self.found.get(main).cloned()) {
Some(path) => {
let version = self.query_version(spec, &path);
(ToolStatus::OnPath, Some(path), version)
@@ -1250,7 +1254,8 @@ impl Tools {
dotnet::SDK_DOWNLOAD_URL
)));
};
let pick = Http::new(&self.system_path)
let pick = self
.http()
.and_then(|http| dotnet::pick_tool_version(package, sdk.major, |url| http.get_text(url, cancel)));
match pick {
Ok(dotnet::ToolPick::Latest) => Ok(None),
@@ -1542,7 +1547,7 @@ impl Tools {
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<()> {
let http = Http::new(&self.system_path)?;
let http = self.http()?;
let message = match source {
ReleaseSource::GitHubTag { tag, .. } => format!("Resolving release {tag}…"),
_ => "Resolving the latest release…".into(),
@@ -1683,7 +1688,7 @@ impl Tools {
fn latest_version(&self, method: Method, cancel: &CancellationToken) -> IdeResult<Option<String>> {
match method {
Method::Release { source, assets, .. } => {
let http = Http::new(&self.system_path)?;
let http = self.http()?;
Ok(Some(self.resolve_release(&http, source, assets, cancel)?.version))
}
Method::Npm { packages } => {
+11
Переглянути файл
@@ -441,6 +441,17 @@ 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,6 +181,28 @@ 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",
@@ -1483,4 +1505,56 @@ 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,6 +147,11 @@ 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,
@@ -622,6 +627,28 @@ 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,3 +1428,27 @@ 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()));
}
+3 -1
Переглянути файл
@@ -156,10 +156,12 @@ With tabs placed left or right, the tab column is as wide as its longest name, u
| **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** | — | — |
**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. **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 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**.
- **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**.
+5 -3
Переглянути файл
@@ -9,9 +9,11 @@ OpenIDEA works with GitHub through the [GitHub CLI](https://cli.github.com) (`gh
<Steps>
<Step title="Install gh">
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).
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).
</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
+3 -1
Переглянути файл
@@ -154,10 +154,12 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
| **向下滚动** | — | `Ctrl+Down` |
| **向上滚动并在必要时移动光标** | — | — |
| **向下滚动并在必要时移动光标** | — | — |
| **向上移动并滚动** | — | — |
| **向下移动并滚动** | — | — |
| **滚动到顶部** | — | — |
| **滚动到底部** | — | — |
**向上滚动** 和 **向下滚动** 把视图移动一行,光标保持原位,即使它因此移出可见区域。**向上滚动并在必要时移动光标** 和 **向下滚动并在必要时移动光标** 同样把视图移动一行,但会把不在视图中的光标移到视图的第一行或最后一行。**滚动到顶部** 和 **滚动到底部** 显示文件的开头和结尾;光标同样保持原位。它们默认没有快捷键:在查找操作中运行,或在 **设置 › 按键映射** 中指定。
**向上滚动** 和 **向下滚动** 把视图移动一行,光标保持原位,即使它因此移出可见区域。**向上滚动并在必要时移动光标** 和 **向下滚动并在必要时移动光标** 同样把视图移动一行,但会把不在视图中的光标移到视图的第一行或最后一行。**向上移动并滚动** 和 **向下移动并滚动** 把光标移动一行,视图随之滚动同样的距离,光标在屏幕上的位置保持不变;对应的 **并选择** 版本边移动边选择。**滚动到顶部** 和 **滚动到底部** 显示文件的开头和结尾;光标同样保持原位。它们默认没有快捷键:在查找操作中运行,或在 **设置 › 按键映射** 中指定。
- **视图 › 活动编辑器 › 软换行** 让当前编辑器的长行自动折行。想让某些文件类型默认软换行,在 **设置 › 编辑器 › 常规** 的 **软换行** 一节中设置。
- **视图 › 重置字体大小** 撤销当前编辑器或焦点区域的字体缩放(**视图 › 重置所有编辑器中的字体大小** 会重置所有打开的编辑器)。用 `⌘` / `Ctrl` + 鼠标滚轮调整字号的功能默认关闭,可在 **设置 › 编辑器 › 常规** 的 **鼠标控制** 一节中打开,并可选择作用于 **当前编辑器**(默认)或 **所有编辑器**。
+4 -3
Переглянути файл
@@ -9,9 +9,10 @@ OpenIDEA 通过 [GitHub CLI](https://cli.github.com)(`gh`)对接 GitHub:
<Steps>
<Step title="安装 gh">
安装 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)中查找。
安装 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)中查找。
</Step>
<Step title="登录">
在终端运行 `gh auth login`。未登录时打开 **拉取请求** 工具窗口,会显示 **未登录 GitHub** 和 **运行 gh auth login**
+34 -8
Переглянути файл
@@ -4,10 +4,11 @@ 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.svg";
const path = "/dev/acme-api/status.png";
// A black 128 × 96 PNG.
const 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);
"iVBORw0KGgoAAAANSUhEUgAAAIAAAABgCAYAAADVenpJAAAAtklEQVR42u3SQREAAAyDMPyb3oQ0jxjgqDqmiWAADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABsAAGAADYAAMgAEwAAbAABgAA2AADIABMAAGwAAYAANgAAyAATAABkAEA2AADIABMAAGwAAYgAUPjHPSwnYk55QAAAAASUVORK5CYII=";
window.__ipc.handlers.fs_read_image = () => "data:image/png;base64," + 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);
@@ -18,9 +19,8 @@ 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.svg", exact: true })).toBeVisible();
await expect(page.getByRole("img", { name: "status.png", exact: true })).toBeVisible();
await expect(dimensions).toBeVisible();
const wideHeight = (await toolbar.boundingBox())!.height;
@@ -31,8 +31,7 @@ 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");
await expect(showText).toHaveCSS("white-space", "nowrap");
for (const item of [zoomIn, actualSize, chessboard, showText, dimensions]) {
for (const item of [zoomIn, actualSize, chessboard, dimensions]) {
await expect(item).toBeInViewport({ ratio: 1 });
}
await expect(toolbar.getByText("4.0 KB", { exact: true })).toBeVisible();
@@ -43,6 +42,33 @@ 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");
await showText.click();
});
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 expect(page.locator(".cm-content")).toBeVisible();
});
+24 -1
Переглянути файл
@@ -97,7 +97,14 @@ import {
} from "./cm/caretCommands";
import { isOverwrite, toggleOverwrite } from "./cm/overwrite";
import { isColumnMode, toggleColumnMode } from "./cm/columnMode";
import { cloneCaretAbove, cloneCaretBelow } from "./cm/verticalMotion";
import {
cloneCaretAbove,
cloneCaretBelow,
moveDownAndScroll,
moveDownAndScrollWithSelection,
moveUpAndScroll,
moveUpAndScrollWithSelection,
} from "./cm/verticalMotion";
import { pasteAsPlainText, pasteFromHistory, unwrapAtCaret } from "./extras";
import { cyclicExpandWord } from "./wordCompletion";
import { copyReferenceToClipboard, declaredName, qualifiedReference, referenceOffset } from "./copyReference";
@@ -1067,6 +1074,22 @@ export function registerEditorActions(): () => void {
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" }),
+125 -2
Переглянути файл
@@ -1,12 +1,16 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { EditorSelection, EditorState, StateEffect } from "@codemirror/state";
import { Decoration, EditorView, WidgetType } from "@codemirror/view";
import {
cloneCaretAbove,
cloneCaretBelow,
cursorLineDown,
cursorLineUp,
moveDownAndScroll,
moveDownAndScrollWithSelection,
moveUpAndScroll,
moveUpAndScrollWithSelection,
selectLineDown,
visibleGoalColumns,
} from "./verticalMotion";
@@ -106,3 +110,122 @@ 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);
});
});
+41 -4
Переглянути файл
@@ -6,7 +6,7 @@
* CodeMirror's pixel motion between their visual rows.
*/
import { EditorSelection, StateEffect, StateField, type EditorState, type SelectionRange } from "@codemirror/state";
import type { Command, EditorView } from "@codemirror/view";
import { BlockType, type BlockInfo, type Command, type EditorView } from "@codemirror/view";
import { offsetAtVisibleColumn, visibleColumn } from "./visibleColumn";
/** Goal visible column per caret head, kept while only these commands move the carets. */
@@ -52,11 +52,12 @@ export function verticalHead(view: EditorView, head: number, forward: boolean, g
return moved === head ? null : moved;
}
function moveCarets(view: EditorView, forward: boolean, extend: boolean): boolean {
/** `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 {
const { state } = view;
const goals = new Map<number, number>();
const ranges = state.selection.ranges.map((r): SelectionRange => {
if (!extend && !r.empty) return EditorSelection.cursor(forward ? r.to : r.from);
if (!extend && !fromHead && !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;
@@ -65,7 +66,8 @@ function moveCarets(view: EditorView, forward: boolean, extend: boolean): boolea
});
const selection = EditorSelection.create(ranges, state.selection.mainIndex);
if (selection.eq(state.selection)) return false;
view.dispatch({ selection, effects: setGoals.of(goals), scrollIntoView: true, userEvent: "select" });
// 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" });
return true;
}
@@ -74,6 +76,41 @@ 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;
+3 -1
Переглянути файл
@@ -307,11 +307,13 @@ 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]);
@@ -366,7 +368,7 @@ export function NavChildrenPopup({
anchor={anchor}
placement={openAbove ? "top-start" : "bottom-start"}
onClose={onClose}
aria-label={top.label}
aria-label={label ?? top.label}
className={styles.childPopup}
>
{stack.length > 1 && (
+50 -7
Переглянути файл
@@ -14,6 +14,7 @@ import {
Menu,
Popup,
SelectListbox,
showContextMenu,
badgeKind,
fileIconName,
revealHorizontally,
@@ -33,6 +34,7 @@ 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";
@@ -166,9 +168,15 @@ function updateBreadcrumbEdges(row: HTMLDivElement) {
function BreadcrumbStrip({
trail,
activateOnDown = false,
onActivateAltDown,
children,
...props
}: ComponentPropsWithoutRef<"nav"> & { trail: string; activateOnDown?: boolean }) {
}: 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;
}) {
const strip = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const row = strip.current;
@@ -189,10 +197,16 @@ 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);
@@ -354,6 +368,7 @@ 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.
@@ -373,28 +388,56 @@ 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={() =>
void editorController().openFile(path, {
selection: { line: item.selection_range.start.line, col: item.selection_range.start.col },
})
}
onClick={() => navigate(item)}
onContextMenu={(e) => crumbMenu(i, e.currentTarget, e)}
>
<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,6 +67,17 @@ 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);
+81 -3
Переглянути файл
@@ -1,13 +1,15 @@
import { Profiler } from "react";
import { describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } 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: vi.fn(), slots: new Map() }),
editorController: () => ({ openFile, slots: new Map() }),
useEditorStatus: create<{ status: EditorStatus | null }>(() => ({ status: null })),
useGotoLine: create(() => ({ open: false })),
useTabs: create(() => ({ panes: {}, activePane: "" })),
@@ -21,6 +23,7 @@ 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 } });
@@ -307,3 +310,78 @@ 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();
});
});
+24 -1
Переглянути файл
@@ -2,13 +2,18 @@ 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() },
commands: {
ghAccountRepos: () => ghAccountRepos(),
toolsList: () => toolsList(),
},
}));
import type { GhAccountRepo } from "@/bindings";
import { registerAction } from "@/platform/actions";
import { GitHubCloneSource, matchRepos } from "./GitHubCloneSource";
const repo = (nameWithOwner: string, extra: Partial<GhAccountRepo> = {}): GhAccountRepo => ({
@@ -25,6 +30,7 @@ const repos = [repo("me/app", { private: true, description: "The app" }), repo("
afterEach(() => {
cleanup();
ghAccountRepos.mockReset();
toolsList.mockReset();
});
describe("GitHub clone source", () => {
@@ -64,4 +70,21 @@ 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();
}
});
});
+35 -11
Переглянути файл
@@ -1,8 +1,9 @@
/** 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 } from "@/platform/ipc";
import { call, commands, isCancelled } from "@/platform/ipc";
import {
Button,
EmptyState,
@@ -37,6 +38,8 @@ 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;
@@ -50,14 +53,26 @@ 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={() => {
setState(null);
setAttempt((n) => n + 1);
}}
>
<Button size="small" onClick={reload}>
<T>Retry</T>
</Button>
);
@@ -77,15 +92,24 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource
title="GitHub CLI is not installed"
actions={
<>
<Button size="small" onClick={() => void openInBrowser("https://cli.github.com")}>
<T>Install gh…</T>
<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>
{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>.
<code>gh auth login</code>.{installError && <div className={styles.muted}>{installError}</div>}
</EmptyState>
);
if (state.kind === "notLoggedIn")
+29 -3
Переглянути файл
@@ -7,6 +7,8 @@
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";
@@ -28,6 +30,21 @@ 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>
@@ -40,15 +57,24 @@ function Unavailable({ availability }: { availability: GhAvailability }) {
title="GitHub CLI is not installed"
actions={
<>
<Button size="small" onClick={() => void openInBrowser("https://cli.github.com")}>
<T>Install gh…</T>
<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>
{retry}
</>
}
>
<T>Pull requests use the</T> <code>gh</code> <T>command line tool. Install it, then run</T>{" "}
<code>gh auth login</code>.
<code>gh auth login</code>.{installError && <div className={styles.hint}>{installError}</div>}
</EmptyState>
);
case "notLoggedIn":
+18 -6
Переглянути файл
@@ -1,12 +1,13 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, render, screen } from "@testing-library/react";
import { getAction } from "@/platform/actions";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { getAction, registerAction } 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 {
@@ -122,10 +123,21 @@ describe("tool window", () => {
expect(show).toHaveBeenCalledWith("pullRequests", true);
});
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("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("offers the repository selector for several GitHub remotes", () => {
+51 -26
Переглянути файл
@@ -1,7 +1,8 @@
/**
* 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).
* 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.
*/
import {
useCallback,
@@ -59,9 +60,19 @@ export function toggleChessboard() {
}
const PADDING = 32;
const NO_FOCUS_TARGET = { current: null };
const INVALID_SVG = "invalid-svg";
export function ImageViewer({ input }: { input: EditorInput }) {
/** 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 }) {
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);
@@ -75,18 +86,27 @@ export function ImageViewer({ input }: { input: EditorInput }) {
const canvasRef = useRef<HTMLDivElement>(null);
useEffect(() => {
let live = true;
if (live) return;
let current = true;
Promise.all([call(commands.fsReadImage(path)), call(commands.fsProbe(path))])
.then(([url, probe]) => {
if (!live) return;
if (!current) return;
setSrc(url);
setSize(probe.size);
})
.catch((e: unknown) => live && setError(e instanceof Error ? e.message : String(e)));
.catch((e: unknown) => current && setError(e instanceof Error ? e.message : String(e)));
return () => {
live = false;
current = false;
};
}, [path, reload]);
}, [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;
const available = useCallback(() => {
const el = canvasRef.current;
@@ -133,7 +153,8 @@ export function ImageViewer({ input }: { input: EditorInput }) {
};
}, [handle]);
useForwardFocus(rootRef);
// Beside the source editor, the preview leaves the editor's focus alone.
useForwardFocus(live ? NO_FOCUS_TARGET : rootRef);
const onLoad = (img: HTMLImageElement) => {
// SVGs without intrinsic size report 0×0; show them at a usable size.
@@ -162,7 +183,7 @@ export function ImageViewer({ input }: { input: EditorInput }) {
};
el.addEventListener("wheel", onWheel, { passive: false });
return () => el.removeEventListener("wheel", onWheel);
}, [error, src]);
}, [shownError, shownSrc]);
const onPointerDown = (e: ReactPointerEvent) => {
if (e.button !== 0 && e.button !== 1) return;
@@ -204,15 +225,17 @@ export function ImageViewer({ input }: { input: EditorInput }) {
<div className={styles.imageActions}>
<div className={styles.imageActionGroup}>
<IconButton icon="chessboard" size="small" action="image.toggleChessboard" pressed={chessboard} />
<IconButton
icon="refresh"
size="small"
title="Reload from Disk"
onClick={() => {
setError(null);
setReload((n) => n + 1);
}}
/>
{!live && (
<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" />
@@ -221,7 +244,7 @@ export function ImageViewer({ input }: { input: EditorInput }) {
<IconButton icon="maximize" size="small" action="image.fitToWindow" />
</div>
</div>
{svg && (
{svg && !live && (
<button
type="button"
className={styles.textButton}
@@ -230,16 +253,18 @@ export function ImageViewer({ input }: { input: EditorInput }) {
<T>Open as Text</T>
</button>
)}
{(natural || size !== null || view) && (
{(natural || shownSize !== null || view) && (
<div className={styles.imageInfo}>
{natural && <span>{`${natural.w} × ${natural.h}`}</span>}
{size !== null && <span>{formatSize(size)}</span>}
{shownSize !== null && <span>{formatSize(shownSize)}</span>}
{view && <span>{zoomLabel(z)}</span>}
</div>
)}
</div>
{error ? (
<div className={styles.message}>{tx`Cannot show the image: ${error}`}</div>
{shownError ? (
<div className={styles.message}>
{shownError === INVALID_SVG ? tx("The SVG source is not valid.") : tx`Cannot show the image: ${shownError}`}
</div>
) : (
<div
data-wheel-scroll
@@ -250,9 +275,9 @@ export function ImageViewer({ input }: { input: EditorInput }) {
onPointerUp={endDrag}
onPointerCancel={endDrag}
>
{src && (
{shownSrc && (
<img
src={src}
src={shownSrc}
alt={path.slice(path.lastIndexOf("/") + 1)}
draggable={false}
className={clsx(styles.image, chessboard && styles.chessboard, z >= 4 && styles.pixelated)}
@@ -266,7 +291,7 @@ export function ImageViewer({ input }: { input: EditorInput }) {
: { visibility: "hidden" }
}
onLoad={(e) => onLoad(e.currentTarget)}
onError={() => setError("the file is not a valid image")}
onError={() => (live ? setInvalidSrc(shownSrc) : setError("the file is not a valid image"))}
/>
)}
</div>
+38
Переглянути файл
@@ -0,0 +1,38 @@
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>
);
}
+38 -9
Переглянути файл
@@ -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 files get IDEA's
* editor providers consulted by `openFile`), and Markdown and SVG files get IDEA's
* Editor / Editor and Preview / Preview layouts around the text editor.
*/
import { registerActions, type Action } from "@/platform/actions";
@@ -29,12 +29,16 @@ 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, useMarkdownSourceHidden, type MarkdownMode } from "./markdown/modes";
import { setMarkdownMode, useMarkdownModes, useMarkdownSourceHidden } from "./markdown/modes";
import type { LayoutMode } from "./layoutModes";
import { registerSvgLiveSource } from "./svg/live";
import { SvgLayoutActions, svgModes } from "./svg/SvgEditor";
import { MarkdownLayoutActions } from "./markdown/MarkdownLayoutActions";
import { canExtractImages, extractImages, EXTRACT_IMAGES, EXTRACT_IMAGES_TITLE } from "./markdown/extractImages";
@@ -65,19 +69,35 @@ 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: MarkdownMode, icon: string): Action => ({
const mode = (id: string, title: string, m: LayoutMode, icon: string): Action => ({
id,
title,
category: "Markdown",
icon,
keywords: ["markdown", "preview", "layout"],
when: "textEditorActive && editorLangId == markdown",
keywords: ["markdown", "svg", "preview", "layout"],
when: "textEditorActive",
enabled: ({ arg }) => !!layoutTarget(arg),
run: ({ arg }) => {
// 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);
const target = layoutTarget(arg);
target?.set(target.tabId, m);
},
});
return [
@@ -143,6 +163,15 @@ 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
Переглянути файл
@@ -0,0 +1,56 @@
/**
* 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.
}
},
};
}
+2 -33
Переглянути файл
@@ -1,39 +1,8 @@
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 (
<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>
);
return <LayoutActions tabId={tabId} mode={mode} label={tx("Markdown editor layout")} />;
}
+9 -44
Переглянути файл
@@ -1,47 +1,12 @@
/**
* 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";
/** Markdown editor layout per editor tab: Editor only / Editor and Preview / Preview only. */
import { createLayoutModes, modeOf, type LayoutMode } from "../layoutModes";
export type MarkdownMode = "editor" | "split" | "preview";
export type MarkdownMode = LayoutMode;
export { modeOf };
const DEFAULT_KEY = "openidea.markdown.defaultMode";
const MODES: readonly MarkdownMode[] = ["editor", "split", "preview"];
const markdown = createLayoutModes("openidea.markdown.defaultMode");
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.
}
}
export const useMarkdownModes = markdown.useModes;
export const useMarkdownSourceHidden = markdown.useSourceHidden;
export const pinMarkdownMode = markdown.pin;
export const setMarkdownMode = markdown.set;
+95
Переглянути файл
@@ -0,0 +1,95 @@
/**
* 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
Переглянути файл
@@ -0,0 +1,38 @@
/** 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
Переглянути файл
@@ -0,0 +1,98 @@
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();
}
});
});
+6 -1
Переглянути файл
@@ -84,8 +84,13 @@ describe("file kinds", () => {
component: () => null,
});
try {
expect((await resolveFileEditor("/p/icon.svg"))?.input.kind).toBe("image");
// 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/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();
+55
Переглянути файл
@@ -0,0 +1,55 @@
/**
* 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(() => {}),
};
}
+4
Переглянути файл
@@ -122,6 +122,10 @@ export const IDEA_ACTIONS: Readonly<Record<string, string>> = {
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",
+11
Переглянути файл
@@ -101,6 +101,17 @@ describe("IntelliJ IDEA keymap import", () => {
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>`,
+4
Переглянути файл
@@ -66,6 +66,10 @@ describe("IDEA keymap parity", () => {
["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", [], []],
+4
Переглянути файл
@@ -140,6 +140,10 @@ export const intellijMacos: Record<string, string[]> = {
"editor.scrollDown": [],
"editor.scrollUpAndMove": [],
"editor.scrollDownAndMove": [],
"editor.moveUpAndScroll": [],
"editor.moveDownAndScroll": [],
"editor.moveUpAndScrollWithSelection": [],
"editor.moveDownAndScrollWithSelection": [],
"editor.scrollToTop": [],
"editor.scrollToBottom": [],
"editor.moveToPageTop": ["Meta+PageUp"],
+4
Переглянути файл
@@ -141,6 +141,10 @@ export const intellijWindows: Record<string, string[]> = {
"editor.scrollDown": ["Ctrl+Down"],
"editor.scrollUpAndMove": [],
"editor.scrollDownAndMove": [],
"editor.moveUpAndScroll": [],
"editor.moveDownAndScroll": [],
"editor.moveUpAndScrollWithSelection": [],
"editor.moveDownAndScrollWithSelection": [],
"editor.scrollToTop": [],
"editor.scrollToBottom": [],
"editor.moveToPageTop": ["Ctrl+PageUp"],
+4
Переглянути файл
@@ -256,6 +256,10 @@ export const vscodeMacos: Record<string, string[]> = {
"editor.scrollDown": [],
"editor.scrollUpAndMove": [],
"editor.scrollDownAndMove": [],
"editor.moveUpAndScroll": [],
"editor.moveDownAndScroll": [],
"editor.moveUpAndScrollWithSelection": [],
"editor.moveDownAndScrollWithSelection": [],
"editor.scrollToTop": [],
"editor.scrollToBottom": [],
"editor.moveToPageTop": [],
+8 -1
Переглянути файл
@@ -1643,6 +1643,8 @@
"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",
@@ -4173,5 +4175,10 @@
"Where Clause": "Where Clause",
"SQL INSERT": "SQL INSERT",
"SQL UPDATE": "SQL UPDATE",
"SQL DELETE": "SQL DELETE"
"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…"
}
-1
Переглянути файл
@@ -1081,7 +1081,6 @@
"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,7 +1019,6 @@
"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,7 +1117,6 @@
"Install a plugin folder with": "다음으로 플러그인 폴더 설치",
"Install and Debug": "설치 및 디버그",
"Reinstall and Debug": "다시 설치 및 디버그",
"Install gh…": "gh 설치…",
"Installed": "설치됨",
"Installed packages": "설치된 패키지",
"Installed plugins": "설치된 플러그인",
-1
Переглянути файл
@@ -1073,7 +1073,6 @@
"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,7 +1073,6 @@
"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,7 +2144,6 @@
"Install a plugin folder with": "Установить папку плагина с",
"Install and Debug": "Установить и отладить",
"Reinstall and Debug": "Переустановить и отладить",
"Install gh…": "Установить gh…",
"Installed": "Установлено",
"Installed packages": "Установленные пакеты",
"Installed plugins": "Установленные плагины",
-1
Переглянути файл
@@ -3839,7 +3839,6 @@
"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",
+4 -1
Переглянути файл
@@ -695,6 +695,10 @@
"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": "將游標移至頁面頂部",
@@ -1761,7 +1765,6 @@
"Install a plugin folder with": "安裝外掛資料夾:",
"Install and Debug": "安裝並偵錯",
"Reinstall and Debug": "重新安裝並偵錯",
"Install gh…": "安裝 gh…",
"Installed": "已安裝",
"Installed packages": "已安裝的軟體包",
"Installed plugins": "已安裝的外掛",
+12 -2
Переглянути файл
@@ -1056,6 +1056,10 @@
"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": "将光标移至页面顶部",
@@ -2216,7 +2220,6 @@
"Install a plugin folder with": "安装插件文件夹:",
"Install and Debug": "安装并调试",
"Reinstall and Debug": "重新安装并调试",
"Install gh…": "安装 gh…",
"Installed": "已安装",
"Installed packages": "已安装的软件包",
"Installed plugins": "已安装的插件",
@@ -2420,6 +2423,8 @@
"Navigation": "导航",
"Navigation Bar": "导航栏",
"Navigation bar": "导航栏",
"Choose a symbol": "选择符号",
"Choose Symbol…": "选择符号…",
"Never": "从不",
"New": "新建",
"New Branch…": "新建分支…",
@@ -10619,5 +10624,10 @@
"SQL INSERT": "SQL INSERT 语句",
"SQL UPDATE": "SQL UPDATE 语句",
"SQL DELETE": "SQL DELETE 语句",
"Column comment": "列注释"
"Column comment": "列注释",
"SVG editor layout": "SVG 编辑器布局",
"Resize SVG preview": "调整 SVG 预览大小",
"The SVG source is not valid.": "SVG 源代码无效。",
"Install GitHub CLI": "安装 GitHub CLI",
"Download manually…": "手动下载…"
}
+9 -2
Переглянути файл
@@ -706,6 +706,8 @@ 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. */
@@ -733,8 +735,13 @@ export function textEditorWrapperFor(
wrappers: ReadonlyMap<string, TextEditorWrapperContribution>,
path: string,
): TextEditorWrapperContribution | undefined {
for (const w of wrappers.values()) if (w.matches(path)) return w;
return 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;
}
/**