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

...
Автор SHA1 Повідомлення Дата
l0ng-ai 1982f22005 fix(search): start Find in Files from the selection in its preview
Find in Files and Search Everywhere took the selection only from the active
editor tab, so text selected in the Find in Files preview (or another
focused editor, such as a diff pane) was ignored when the action ran again.
The focused editor's selection now comes first, then the active editor's.

Fixes #6992
2026-11-30 20:02:17 +08:00
Muuтаmuutot f47a83828c feat(structure): temporarily enable filters to find matches (#6934)
With Narrow down on typing on, a File Structure query that matches nothing now turns on the unchecked filters (Show fields, Show non-public, Show inherited members) one at a time until a match appears. Filters enabled this way are restored as the query gets shorter and when the popup closes, and are never saved; a checkbox the user changes by hand keeps its new state, and the cascade stops right after a backspace restores a filter.

Co-authored-by: muutot <[email protected]>
2026-11-30 19:58:05 +08:00
薛纪克таxuejike 4d5ee2d01c feat(agents): drag and delete the whole task list selection (#6933)
In the Agents task list, dragging a row of a multi-selection moves every selected task (into a group, Pinned, a status group, or before or after a task, keeping their order), and Delete deletes the selection while the list has focus. Tree collapsed the selection to the pressed row on mouse down, before a drag could start; a press on a selected row now narrows the selection only on a release without movement. agents.deleteTasks gets a list-focus key binding like agents.archiveTasks, and a click or arrow key opens the session without taking focus from the list; Enter and double-click still focus it.

Closes #6932

Co-authored-by: xuejike <[email protected]>
2026-11-30 19:56:24 +08:00
l0ng-ai 2ecb44098a fix(debugger): drop lldb-dap pseudo paths on Windows too (#7030)
A referenced source's pseudo path such as /usr/lib/swift/libswiftCore.dylib`swift_willThrow was kept on Windows, where a path with a root but no drive is not absolute, so frames_drop_pseudo_paths_of_referenced_sources failed on Rust (windows-latest) since #6961. A rooted path now counts.
2026-11-30 19:48:37 +08:00
Mollo-i b1039bc175 feat(search): select Search Everywhere results in the Project view (#6955)
File, symbol and text results in Search Everywhere get Select in Project View, in the Alt+Enter menu and in a new right-click menu on the row: it closes the popup and selects the result in the Project tool window. This helps with files that open in another application, such as a .doc, where choosing the result leaves no trace of where the file lives. The item is offered only for paths inside the project. One item list now feeds both menus, and Open to the Side is disabled for folders.

Co-authored-by: Greenker <[email protected]>
2026-11-30 19:43:10 +08:00
薛纪克таxuejike 182c7c1dbb feat(editor): double-click the empty tab strip to maximize the editor (#6969)
A double click on the empty part of an editor tab strip (not on a tab, a button or trailing content) now maximizes the editor by hiding all tool windows, the same as a double click on a regular tab; doing it again restores them. Tabs gets an onBlankDoubleClick callback that fires only for the strip itself or its scroller.

Closes #6968

Co-authored-by: xuejike <[email protected]>
2026-11-30 19:42:00 +08:00
l0ng-ai c8dc613485 fix(projects): offer New Tab when opening a remote project or from a remote window (#7017)
The Open Project prompt gated Attach and New Tab on one flag that required a local project in a local window, so opening an SSH/WSL project, or any project from a remote window, offered only New Window and This Window, and "Open project in: tab" fell back to a new window. Attach still needs a local project in a local window, but a project tab is a window of its own joined to this window's group, so it now applies whenever this window has a project: a remote project opens in a new window that joins the group.

Fixes #6923
2026-11-30 18:36:46 +08:00
audichuang 88a6bbca14 perf(vcs): run Git outside the log index lock so commit details and one-commit queries do not wait for a history walk (#7006)
history::log held the log index lock for its whole run, so every Git subprocess it started (file history, path selection, range ids, rev-list, the --grep text filter) ran under the lock, and commit details plus the one-commit queries behind inline blame waited for the whole walk. The lock is now taken per phase: Git runs unlocked and only in-memory work holds the guard. update_head_reachable runs under the guard that builds the rows, and the shared nodes are used only when they were built for the query's shallow set, rebuilt otherwise, so a query stays on one snapshot while others run in between.

Co-authored-by: audichuang <[email protected]>
2026-11-30 18:32:37 +08:00
Ivan b9e555300f fix(macos): defer moving a full-screen tab out of its group until the app is active (#6997)
Close Project on a tab of a native full-screen group moves the tab into a window, and so a full-screen Space, of its own. While the app is inactive, AppKit's enter-full-screen transition for that Space crashes in SLSWindowServerClientSpaceAddWindowsAndRemoveFromSpaces as soon as the web view draws its next frame, taking every project window with it. Detaching such a tab is now deferred: the tab stays in its group (showing Welcome) and moves to its own Space when the app is next activated. Foreground closes and windowed groups detach immediately as before.

Fixes #6937

Co-authored-by: Pecnikas <[email protected]>
2026-11-30 18:30:57 +08:00
l0ng-ai 7ff223001b fix(fonts): keep Latin text monospaced when the chosen font isn't installed (#7013)
With a fallback font set and a primary family that isn't installed, every glyph came from the fallback. A CJK fallback such as PingFang SC has proportional Latin letters, and the terminal sized its cells for the widest of them, so text came out spread apart. Once the native font catalog shows the family is missing, the bundled JetBrains Mono now stands in for it ahead of the fallback, which still covers the glyphs it lacks. Applies to every monospace stack built from the editor or terminal font settings.

Fixes #6974
2026-11-30 18:25:17 +08:00
37 змінених файлів з 894 додано та 107 видалено

No files matched your search

+2 -1
Переглянути файл
@@ -618,9 +618,10 @@ pub(crate) fn take_debug_server(arguments: &mut Value) -> IdeResult<Option<Debug
/// lldb-dap's ``/usr/lib/swift/libswiftCore.dylib`swift_willThrow`` for a frame without
/// debug info. Opening it would show an error tab; without a path the stop selects the
/// first frame with source instead. Non-file paths (`jdt://`, `<node_internals>`) stay.
/// Rooted rather than absolute: on Windows a `/usr/…` path has a root but no drive.
fn is_pseudo_path(source: Option<&Value>, path: &str) -> bool {
let reference = source.and_then(|s| s.get("sourceReference")).and_then(Value::as_i64).unwrap_or(0);
reference > 0 && Path::new(path).is_absolute() && !Path::new(path).exists()
reference > 0 && Path::new(path).has_root() && !Path::new(path).exists()
}
/// DAP stack frame → [`StackFrame`] (1-based → 0-based).
+57 -15
Переглянути файл
@@ -464,11 +464,16 @@ fn renamed_from(
Ok(None)
}
/// The log index, locked only around reads and writes: Git runs without it, so commit
/// details and one-commit queries need not wait for a long history walk.
fn lock(index: &std::sync::Mutex<crate::log_index::LogIndex>) -> std::sync::MutexGuard<'_, crate::log_index::LogIndex> {
index.lock().unwrap_or_else(|p| p.into_inner())
}
pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResult<Vec<Commit>> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let mut index = r.log_index.lock().unwrap_or_else(|p| p.into_inner());
let result = if q.summary_only {
let mut all = q.clone();
all.skip = 0;
@@ -483,14 +488,19 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
repo.shallow_commits().map_err(gx)?.map(|ids| ids.iter().copied().collect::<Vec<_>>()).unwrap_or_default();
let shallow: HashSet<ObjectId> = shallow_vec.iter().copied().collect();
let key = format!("{}:{generation}:{shallow_vec:?}", serde_json::to_string(&all).map_err(gx)?);
let cached = index.views.get(&key).cloned();
let cached = lock(&r.log_index).views.get(&key).cloned();
let view = if let Some(cached) = cached {
cached
} else {
// Immutable metadata is reused across roots, filters, merges and ref changes.
all.request = q.request;
let rows =
std::sync::Arc::new(crate::log_index::IndexedView::new(log_indexed_rows(r, &all, cancel, &mut index)?));
let rows = std::sync::Arc::new(crate::log_index::IndexedView::new(log_indexed_rows(
r,
&all,
cancel,
&r.log_index,
)?));
let mut index = lock(&r.log_index);
if index.views.len() >= 4 {
index.views.clear();
}
@@ -512,6 +522,7 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
let retain = q.retain_until.as_ref().and_then(|id| find_pos(id)).map(|i| i + 1).unwrap_or(0);
let limit = if q.limit == 0 { usize::MAX } else { (q.limit as usize).max(retain.saturating_sub(start)) };
let total = view.rows.len() as u32;
let mut index = lock(&r.log_index);
let db = index.db().cloned();
let txn = db.as_ref().and_then(|db| db.begin_read().ok());
let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok());
@@ -538,9 +549,9 @@ pub(crate) fn log(r: &Repo, q: &LogQuery, cancel: &CancellationToken) -> IdeResu
}
Ok(result)
} else {
log_indexed(r, q, cancel, &mut index)
log_indexed(r, q, cancel, &r.log_index)
};
index.flush();
lock(&r.log_index).flush();
result
}
@@ -640,7 +651,7 @@ fn log_indexed(
r: &Repo,
q: &LogQuery,
cancel: &CancellationToken,
index: &mut crate::log_index::LogIndex,
shared: &std::sync::Mutex<crate::log_index::LogIndex>,
) -> IdeResult<Vec<Commit>> {
let repo = r.gix()?;
let shallow: HashSet<ObjectId> =
@@ -676,6 +687,8 @@ fn log_indexed(
&& q.since_ms.is_none()
&& q.until_ms.is_none()
{
let mut guard = lock(shared);
let index = &mut *guard;
update_head_reachable(&repo, index, cancel)?;
let id = tips[0];
let record = index.get(&repo, id)?;
@@ -706,7 +719,9 @@ fn log_indexed(
commit.message_truncated = false;
return Ok(vec![commit]);
}
let rows = log_indexed_rows(r, q, cancel, index)?;
let rows = log_indexed_rows(r, q, cancel, shared)?;
let mut guard = lock(shared);
let index = &mut *guard;
let db = index.db().cloned();
let txn = db.as_ref().and_then(|db| db.begin_read().ok());
let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok());
@@ -724,7 +739,7 @@ fn log_indexed_rows(
r: &Repo,
q: &LogQuery,
cancel: &CancellationToken,
index: &mut crate::log_index::LogIndex,
shared: &std::sync::Mutex<crate::log_index::LogIndex>,
) -> IdeResult<Vec<crate::log_index::IndexedRow>> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
@@ -775,7 +790,7 @@ fn log_indexed_rows(
}
}
}
Some(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?)
Some(sort_shared(&repo, ids, q, &shallow, cancel, shared)?)
} else {
None
};
@@ -802,14 +817,17 @@ fn log_indexed_rows(
};
let authors: Vec<_> =
q.author.iter().chain(&q.authors).map(|a| a.trim().to_lowercase()).filter(|a| !a.is_empty()).collect();
update_head_reachable(&repo, index, cancel)?;
let mut range_ids_set = range_ids.as_ref().map(|ids| ids.iter().copied().collect::<HashSet<_>>());
type Walk<'a> = Box<dyn Iterator<Item = IdeResult<ObjectId>> + 'a>;
let walk: Walk<'_> = if let Some(ids) = range_ids {
Box::new(ids.into_iter().map(Ok))
} else if q.summary_only {
let ids = index.graph(&repo, &tips, &shallow, q.first_parent, cancel)?;
Box::new(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?.into_iter().map(Ok))
// One guard for both: a concurrent query with another shallow set resets `nodes`.
let mut guard = lock(shared);
let ids = guard.graph(&repo, &tips, &shallow, q.first_parent, cancel)?;
let sorted = sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &guard.nodes)?;
drop(guard);
Box::new(sorted.into_iter().map(Ok))
} else if repo.is_shallow().unwrap_or(false) || q.request.is_some() {
// The process can be interrupted even during indegree preparation. Git also
// respects shallow boundaries while retaining a topological order.
@@ -866,7 +884,7 @@ fn log_indexed_rows(
LogOrder::Topo | LogOrder::Standard => topo::Sorting::TopoOrder,
LogOrder::Date => topo::Sorting::DateOrder,
};
let topo = topo::Builder::from_iters(&repo.objects, tips, None::<Vec<ObjectId>>)
let topo = topo::Builder::from_iters(&repo.objects, tips.clone(), None::<Vec<ObjectId>>)
.sorting(sorting)
.parents(if q.first_parent { Parents::First } else { Parents::All })
.with_commit_graph(graph)
@@ -876,11 +894,20 @@ fn log_indexed_rows(
};
let walk: Walk<'_> = if q.order == LogOrder::Standard {
let ids = walk.collect::<IdeResult<Vec<_>>>()?;
Box::new(sort_subset(&repo, ids, q.order, q.first_parent, &shallow, cancel, &index.nodes)?.into_iter().map(Ok))
Box::new(sort_shared(&repo, ids, q, &shallow, cancel, shared)?.into_iter().map(Ok))
} else {
walk
};
let text = q.text.as_deref().map(|t| TextFilter::new(r, &scopes, q, t, cancel)).transpose()?.flatten();
let mut guard = lock(shared);
let index = &mut *guard;
// Under the guard that builds the rows: a query run meanwhile (after a branch switch)
// may have moved the shared set to another HEAD.
update_head_reachable(&repo, index, cancel)?;
// A query started before a shallow change may have reset `nodes` to its older set.
if index.shallow != shallow {
index.ensure_nodes(&repo, &tips, &shallow, cancel)?;
}
let db = index.db().cloned();
let txn = db.as_ref().and_then(|db| db.begin_read().ok());
let table = txn.as_ref().and_then(|t| t.open_table(crate::log_index::COMMITS).ok());
@@ -952,6 +979,21 @@ fn log_indexed_rows(
Ok(out)
}
/// Sorts with the shared nodes only when they were built for this query's shallow set.
fn sort_shared(
repo: &gix::Repository,
ids: Vec<ObjectId>,
q: &LogQuery,
shallow: &HashSet<ObjectId>,
cancel: &CancellationToken,
shared: &std::sync::Mutex<crate::log_index::LogIndex>,
) -> IdeResult<Vec<ObjectId>> {
let guard = lock(shared);
let empty = HashMap::new();
let nodes = if &guard.shallow == shallow { &guard.nodes } else { &empty };
sort_subset(repo, ids, q.order, q.first_parent, shallow, cancel, nodes)
}
/// A ready-node stack gives incoming merge parents priority, while child counts
/// prevent an ancestor shared with another branch from moving ahead of its children.
fn sort_subset(
+79
Переглянути файл
@@ -0,0 +1,79 @@
//! A long file history walk must not hold the log index while Git runs: commit details and
//! one-commit queries (inline blame, the blame popup) share that index.
#![cfg(unix)]
use ide_vcs::{LogQuery, Repo};
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::Command;
use std::time::{Duration, Instant};
fn git(dir: &Path, args: &[&str]) -> String {
let out = Command::new("git")
.current_dir(dir)
.args([
"-c",
"init.defaultBranch=main",
"-c",
"user.name=T",
"-c",
"user.email=t@e",
"-c",
"commit.gpgsign=false",
])
.args(args)
.output()
.unwrap();
assert!(out.status.success(), "{args:?}: {}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
#[test]
fn details_and_one_commit_queries_do_not_wait_for_a_file_history_walk() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("repo");
std::fs::create_dir(&dir).unwrap();
git(&dir, &["init", "-q"]);
for i in 0..3 {
std::fs::write(dir.join("file"), format!("{i}")).unwrap();
git(&dir, &["add", "-A"]);
git(&dir, &["commit", "-qm", &format!("c{i}")]);
}
// A git whose path-limited history walks take seconds.
let real = String::from_utf8(Command::new("sh").args(["-c", "command -v git"]).output().unwrap().stdout).unwrap();
let started = tmp.path().join("walk-started");
let wrapper = tmp.path().join("slow-git");
std::fs::write(
&wrapper,
format!(
"#!/bin/sh\ncase \" $* \" in *\" --full-history \"*) : > '{}'; sleep 3;; esac\nexec '{}' \"$@\"\n",
started.display(),
real.trim()
),
)
.unwrap();
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
let repo = Repo::discover(&dir).unwrap().unwrap();
repo.set_execution_allowed(true);
repo.set_git_executable(Some(&wrapper));
std::thread::scope(|scope| {
let walk = scope.spawn(|| {
repo.log(&LogQuery { path: Some("file".into()), follow: true, ..Default::default() }).unwrap().len()
});
let deadline = Instant::now() + Duration::from_secs(20);
while !started.exists() {
assert!(Instant::now() < deadline, "the history walk never started");
std::thread::sleep(Duration::from_millis(20));
}
let asked = Instant::now();
let details = repo.log_details("HEAD").unwrap();
let head = repo.log(&LogQuery { branch: Some("HEAD".into()), limit: 1, ..Default::default() }).unwrap();
let waited = asked.elapsed();
println!("queries waited {waited:?}");
assert_eq!(details.message, "c2");
assert_eq!(head.len(), 1);
assert!(!walk.is_finished(), "the walk ended before the queries ran; the test proves nothing");
assert!(waited < Duration::from_secs(2), "queries waited {waited:?} for the walk");
assert_eq!(walk.join().unwrap(), 3);
});
}
+2
Переглянути файл
@@ -145,6 +145,8 @@ Tab placement, the tab limit and what happens when it is reached, the preview ta
With tabs placed left or right, the tab column is as wide as its longest name, up to a limit. Drag the column's inner edge (or focus it and press `←` / `→`) to change the limit; it applies to every editor group and is remembered.
Double-click a tab, or the empty part of the tab strip, to maximize the editor: all tool windows are hidden, and doing it again brings them back. Double-clicking a preview tab keeps it open as a regular tab instead.
## Split editors
| Action | macOS | Windows / Linux |
+2
Переглянути файл
@@ -143,6 +143,8 @@ description: "多光标与选区、行编辑、剪贴板历史、代码折叠、
标签页放在左侧或右侧时,标签页列的宽度随最长的名称变化,但不超过一个上限。拖动该列靠近编辑器的边缘(或聚焦后按 `←` / `→`)可以调整上限;调整对所有编辑器组生效,并会被记住。
双击标签页或标签页栏的空白处可以最大化编辑器:隐藏所有工具窗口,再双击一次即恢复。双击预览标签页则会把它转为常规标签页。
## 拆分编辑器
| 操作 | macOS | Windows / Linux |
+87
Переглянути файл
@@ -202,6 +202,93 @@ test("File Structure prefers matches inside the caret symbol", async ({ workbenc
await expect(tree.getByRole("treeitem", { name: "load", exact: true })).toHaveAttribute("aria-selected", "false");
});
test("File Structure auto-enables temporary filters without saving them", async ({ workbench: page }) => {
await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate(async () => {
const optionsPath = "/src/features/search/structure/store.ts";
const { useStructureOptions } = await import(/* @vite-ignore */ optionsPath);
useStructureOptions.setState({ showFields: false, showNonPublic: false, showInherited: false, narrowDown: true });
const range = { start: { line: 0, col: 0 }, end: { line: 1, col: 1 } };
const symbol = (name: string, kind: string, visibility?: string) => ({
name,
kind,
visibility,
range,
selection_range: range,
children: [],
});
window.__ipc.handlers.doc_outline = () => [
{
...symbol("Container", "class"),
children: [
symbol("hiddenField", "field"),
symbol("hiddenMethod", "method", "private"),
symbol("visible", "method"),
],
},
];
window.__ipc.handlers.lsp_type_hierarchy = () => [];
const actionsPath = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actionsPath);
await executeAction("navigate.fileStructure");
});
const dialog = page.getByRole("dialog", { name: "File Structure" });
const filter = dialog.getByRole("textbox", { name: "Filter symbols" });
const tree = dialog.getByRole("tree", { name: "Symbols" });
const fields = dialog.getByRole("checkbox", { name: "Show fields" });
const nonPublic = dialog.getByRole("checkbox", { name: "Show non-public" });
const readOptions = () =>
page.evaluate(async () => {
const path = "/src/features/search/structure/store.ts";
const { useStructureOptions } = await import(/* @vite-ignore */ path);
const { showFields, showNonPublic, showInherited } = useStructureOptions.getState();
return { showFields, showNonPublic, showInherited };
});
await expect(fields).not.toBeChecked();
await expect(nonPublic).not.toBeChecked();
await filter.fill("hiddenField");
await expect(fields).toBeChecked();
await expect(nonPublic).not.toBeChecked();
await expect(tree.getByRole("treeitem", { name: "hiddenField", selected: true })).toBeVisible();
expect(await readOptions()).toEqual({ showFields: false, showNonPublic: false, showInherited: false });
await nonPublic.check();
expect(await readOptions()).toEqual({ showFields: false, showNonPublic: true, showInherited: false });
const saved = await page.evaluate(() => localStorage.getItem("openidea.structure.options.v1"));
await filter.press("End");
await filter.press("Backspace");
await expect(filter).toHaveValue("hiddenFiel");
await expect(fields).not.toBeChecked();
await expect(nonPublic).toBeChecked();
await expect(tree.getByRole("treeitem", { name: "hiddenField", exact: true })).toBeHidden();
expect(await readOptions()).toEqual({ showFields: false, showNonPublic: true, showInherited: false });
await filter.fill("hiddenField");
await expect(fields).toBeChecked();
await fields.uncheck();
await expect(fields).not.toBeChecked();
await filter.press("Escape");
await expect(filter).toHaveValue("");
await expect(fields).not.toBeChecked();
await filter.press("Escape");
await expect(dialog).toBeHidden();
expect(await readOptions()).toEqual({ showFields: false, showNonPublic: true, showInherited: false });
expect(await page.evaluate(() => localStorage.getItem("openidea.structure.options.v1"))).toBe(saved);
await page.evaluate(async () => {
const path = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ path);
await executeAction("navigate.fileStructure");
});
await expect(dialog).toBeVisible();
await expect(dialog.getByRole("checkbox", { name: "Show fields" })).not.toBeChecked();
await expect(dialog.getByRole("checkbox", { name: "Show non-public" })).toBeChecked();
expect(await page.evaluate(() => localStorage.getItem("openidea.structure.options.v1"))).toBe(saved);
});
test("F4 jumps to the filtered File Structure symbol", async ({ workbench: page }) => {
await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
+2
Переглянути файл
@@ -26,6 +26,8 @@ impl ApplicationFocus {
pub fn changed(app: &tauri::AppHandle, focused: bool) {
let generation = app.state::<ApplicationFocus>().changed(focused);
if focused {
#[cfg(target_os = "macos")]
crate::window_groups::detach_deferred(app);
return;
}
let app = app.clone();
+10
Переглянути файл
@@ -114,6 +114,16 @@ pub fn sync_tab_group(
})
}
pub fn fullscreen_in_background(window: &WebviewWindow) -> bool {
let target = window.clone();
on_main(window, move || {
let active =
MainThreadMarker::new().is_some_and(|mtm| objc2_app_kit::NSApplication::sharedApplication(mtm).isActive());
!active && native(&target).is_some_and(|w| w.styleMask().contains(objc2_app_kit::NSWindowStyleMask::FullScreen))
})
.unwrap_or(false)
}
/// Takes `window` out of its tab group into a window of its own; in full screen, a Space of its own.
pub fn move_tab_to_new_window(window: &WebviewWindow) -> tauri::Result<()> {
let target = window.clone();
+18
Переглянути файл
@@ -201,9 +201,19 @@ pub fn merge(app: &AppHandle, caller: &str) -> IdeResult<()> {
select(app, caller, caller)
}
#[cfg(target_os = "macos")]
static DEFERRED_DETACH: parking_lot::Mutex<Vec<String>> = parking_lot::Mutex::new(Vec::new());
pub fn detach(app: &AppHandle, caller: &str) -> IdeResult<()> {
let err = |e: tauri::Error| IdeError::internal(e.to_string());
let state = app.state::<WindowsState>();
#[cfg(target_os = "macos")]
if state.groups.lock().group(caller).is_some()
&& app.get_webview_window(caller).is_some_and(|w| crate::macos::fullscreen_in_background(&w))
{
DEFERRED_DETACH.lock().push(caller.to_owned());
return Ok(());
}
let Some(next) = state.groups.lock().detach(caller) else {
changed(app);
return Ok(());
@@ -234,6 +244,14 @@ pub fn detach(app: &AppHandle, caller: &str) -> IdeResult<()> {
Ok(())
}
#[cfg(target_os = "macos")]
pub fn detach_deferred(app: &AppHandle) {
let labels = std::mem::take(&mut *DEFERRED_DETACH.lock());
for label in labels {
let _ = detach(app, &label);
}
}
pub fn destroyed(app: &AppHandle, caller: &str) {
let Some(state) = app.try_state::<WindowsState>() else { return };
let next = state.groups.lock().detach(caller);
+2
Переглянути файл
@@ -399,6 +399,8 @@ function PaneView({ paneId }: { paneId: string }) {
onCloseOthers={(id) => void ctrl.closeOthers(paneId, id)}
onTogglePin={(id) => ctrl.togglePin(paneId, id)}
closeOnShiftClick
// IDEA: a double click on the strip's empty part maximizes the editor, as on a tab.
onBlankDoubleClick={() => void executeAction("toolwindow.hideAll")}
onDoubleClick={(id) => {
// IDEA: a preview tab becomes a regular one; any other tab maximizes the editor.
if (pane.tabs.find((t) => t.id === id)?.preview) ctrl.keepTab(paneId, id);
+16 -5
Переглянути файл
@@ -162,7 +162,7 @@ describe("Agents selection", () => {
vi.mocked(openTask).mockClear();
context("two");
expect(selectedTasks()).toEqual(["one", "two", "three"]);
expect(screen.getByRole("menuitem", { name: "Delete (3)…" })).toBeTruthy();
expect(screen.getByRole("menuitem", { name: /^Delete \(3\)…/ })).toBeTruthy();
expect(openTask).not.toHaveBeenCalled();
});
@@ -298,9 +298,20 @@ describe("Agents docked view", () => {
setup();
expect(screen.queryByRole("button", { name: "Open in Editor" })).toBeNull();
select("two");
expect(openTask).toHaveBeenCalledWith("two");
expect(openTask).toHaveBeenCalledWith("two", { focus: false });
expect(dockTask).not.toHaveBeenCalled();
});
it("keeps focus in the list when a click opens a task, so Delete deletes that task", async () => {
setup();
const tree = screen.getByRole("tree", { name: "Agent tasks" });
tree.focus();
select("two");
expect(openTask).toHaveBeenCalledWith("two", { focus: false });
// The shortcut runs the action without an argument: it takes the list's selection.
await taskActions.find((a) => a.id === "agents.deleteTasks")!.run({ ctx: {}, arg: undefined });
await waitFor(() => expect(deleteTask).toHaveBeenCalledExactlyOnceWith("two", false));
});
});
describe("Agents bulk actions", () => {
@@ -311,7 +322,7 @@ describe("Agents bulk actions", () => {
select("one");
select("three", { shiftKey: true });
context("two");
fireEvent.click(screen.getByRole("menuitem", { name: "Delete (3)…" }));
fireEvent.click(screen.getByRole("menuitem", { name: /^Delete \(3\)…/ }));
await waitFor(() => expect(deleteTask).toHaveBeenCalledTimes(3));
expect(confirmChecked).toHaveBeenCalledTimes(1);
expect(confirmChecked).toHaveBeenCalledWith(
@@ -329,7 +340,7 @@ describe("Agents bulk actions", () => {
select("one");
select("two", { shiftKey: true });
context("four");
fireEvent.click(screen.getByRole("menuitem", { name: "Delete…" }));
fireEvent.click(screen.getByRole("menuitem", { name: /^Delete…/ }));
await waitFor(() => expect(deleteTask).toHaveBeenCalledExactlyOnceWith("four", false));
});
@@ -784,6 +795,6 @@ describe("Agents pinned and grouped tasks", () => {
expect(openTask).not.toHaveBeenCalled();
fireEvent.pointerUp(window, { button: 0, clientX: 10, clientY: 104 });
fireEvent.click(sourceSpan, { button: 0 });
expect(openTask).toHaveBeenCalledWith("two");
expect(openTask).toHaveBeenCalledWith("two", { focus: false });
});
});
+44 -10
Переглянути файл
@@ -52,8 +52,8 @@ import {
openHome,
pinTasks,
refreshExternalSessions,
reorderTask,
reorderTaskGroup,
reorderTasks,
showImportSessions,
useAgents,
} from "./store";
@@ -238,6 +238,8 @@ export function AgentsView() {
searchingRef.current = matches !== null;
}, [matches]);
const cancelDragRef = useRef<(() => void) | undefined>(undefined);
/** Every task the current drag carries, in list order; set when it starts. */
const draggedIdsRef = useRef<string[]>([]);
const [tasksEl, setTasksEl] = useState<HTMLDivElement | null>(null);
const [dropIndicator, setDropIndicator] = useState<DropIndicator | null>(null);
useEffect(() => {
@@ -266,11 +268,18 @@ export function AgentsView() {
const { tasks, organize } = useAgents.getState();
const source = tasks.get(data.payload);
if (!source) return null;
// Dragging a selected task moves the whole selection.
const ids = draggedIdsRef.current.includes(source.id) ? draggedIdsRef.current : [source.id];
const sources = ids.flatMap((id) => {
const task = tasks.get(id);
return task ? [task] : [];
});
const sourceIds = sources.map((t) => t.id);
if (targetKey === PINNED_SECTION) {
return {
indicator: { kind: "section", key: targetKey } as DropIndicator,
apply: () => pinTasks([source.id], true),
apply: () => pinTasks(sourceIds, true),
};
}
if (targetKey.startsWith("ug:")) {
@@ -278,23 +287,33 @@ export function AgentsView() {
if (!organize.groups.some((g) => g.id === groupId)) return null;
return {
indicator: { kind: "section", key: targetKey } as DropIndicator,
apply: () => moveTasksToGroup([source.id], groupId),
apply: () => moveTasksToGroup(sourceIds, groupId),
};
}
if (targetKey.startsWith("g:")) {
if (sectionOfTask(source, organize) === targetKey) return null;
if (statusSection(taskGroupStatus(source)) !== targetKey) return null;
// A status group takes the tasks of its status that are elsewhere.
const movable = sources.filter(
(t) => sectionOfTask(t, organize) !== targetKey && statusSection(taskGroupStatus(t)) === targetKey,
);
if (!movable.length) return null;
return {
indicator: { kind: "section", key: targetKey } as DropIndicator,
apply: () => moveTasksToStatusGroup([source.id]),
apply: () => moveTasksToStatusGroup(movable.map((t) => t.id)),
};
}
if (searchingRef.current) return null;
const target = tasks.get(targetKey);
if (!target || !canReorderTask(source, target, organize)) return null;
if (!target || sourceIds.includes(target.id)) return null;
const movable = sources.filter((t) => canReorderTask(t, target, organize));
if (!movable.length) return null;
return {
indicator: { kind: "row", key: targetKey, position } as DropIndicator,
apply: () => reorderTask(source.id, target.id, position),
apply: () =>
reorderTasks(
movable.map((t) => t.id),
target.id,
position,
),
};
};
const update = () => {
@@ -383,11 +402,26 @@ export function AgentsView() {
setHistoryOpen(false);
void executeAction("agents.openTask", task);
};
// A click or arrow key in the list opens the session but keeps focus in the list, so its
// shortcuts (Delete) still act on the selection; Enter and double-click focus the session.
const previewTask = (task: string) => {
if (inline) showTask(task);
else void executeAction("agents.openTask", { task, focus: false });
};
const dockedTitle = docked ? (tasks.get(docked)?.title ?? docked) : null;
const dragTask = (e: ReactPointerEvent<HTMLElement>, task: string, source: HTMLElement = e.currentTarget) => {
suppressClickRef.current = false;
if (e.button !== 0 || e.ctrlKey || e.metaKey || e.shiftKey) return;
cancelDragRef.current?.();
// A selected row drags the whole selection, in list order.
const current = selectedRef.current;
draggedIdsRef.current =
current.size > 1 && current.has(task)
? roots
.flatMap((n) => (n.kind === "group" ? n.group.tasks : n.kind === "task" ? [n.task] : n.tasks))
.map((t) => t.id)
.filter((id, i, all) => current.has(id) && all.indexOf(id) === i)
: [task];
cancelDragRef.current = startPointerDrag(
e,
source,
@@ -478,7 +512,7 @@ export function AgentsView() {
if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey) return;
if ((e.target as Element).closest("button, input, textarea, [data-tree-toggle]")) return;
const key = (e.target as Element).closest<HTMLElement>("[data-tree-key]")?.dataset.treeKey;
if (key && tasks.has(key)) showTask(key);
if (key && tasks.has(key)) previewTask(key);
}}
onFocus={() => setFocusedTaskList(() => [...selectedRef.current])}
onBlur={(e) => {
@@ -554,7 +588,7 @@ export function AgentsView() {
lead?.kind === "task" &&
sel.has(lead.task.id)
)
showTask(lead.task.id);
previewTask(lead.task.id);
}}
onActivate={(n) => n.kind === "task" && showTask(n.task.id)}
onContextMenu={(n, sel, e) => {
+27 -8
Переглянути файл
@@ -57,6 +57,7 @@ import { withQuote } from "./conversation";
import {
EMPTY_ORGANIZE,
PINNED_SECTION,
canReorderTask,
compactOrder,
customSection,
loadOrganize,
@@ -1184,7 +1185,8 @@ export function useAgentCommands(
return extra.length > 0 ? [...filtered, ...extra] : filtered;
}
export function openTask(task: string) {
/** Opens the task's session; `focus: false` opens it in the editor without taking focus (a click in the task list). */
export function openTask(task: string, options: { focus?: boolean } = {}) {
if (routeToWindow(task)) return;
forgetClosed(task);
if (useAgents.getState().sessionLocation === "toolWindow") {
@@ -1192,13 +1194,13 @@ export function openTask(task: string) {
return;
}
useAgents.setState({ lastTask: task, homeOpen: false, lastComposer: task });
openTaskInEditor(task);
openTaskInEditor(task, options.focus ?? true);
}
function openTaskInEditor(task: string) {
function openTaskInEditor(task: string, focus = true) {
// The title rides along so a restored tab has it before the tasks load.
const title = useAgents.getState().tasks.get(task)?.title;
void editorService().openInput({ kind: SESSION_KIND, key: sessionKey(task), data: { task, title } }, { focus: true });
void editorService().openInput({ kind: SESSION_KIND, key: sessionKey(task), data: { task, title } }, { focus });
}
function showDockedTask(task: string) {
@@ -2189,10 +2191,27 @@ export function moveTasksToStatusGroup(tasks: readonly string[]) {
});
}
/** Places `sourceId` before or after `targetId` (moving it into the target's section when needed). */
export function reorderTask(sourceId: string, targetId: string, position: "before" | "after") {
const tasks = useAgents.getState().tasks.values();
changeOrganize((organize) => reorderTaskInOrganize(organize, tasks, sourceId, targetId, position));
/**
* Places `sourceIds` (in list order) before or after `targetId`, keeping their relative order.
* Tasks that can't go beside the target (another status than its status group) stay where they are.
*/
export function reorderTasks(sourceIds: readonly string[], targetId: string, position: "before" | "after") {
const tasks = [...useAgents.getState().tasks.values()];
changeOrganize((organize) => {
let next = organize;
// Before: each goes right before the target. After: each goes after the one placed last.
let anchor = targetId;
const byId = new Map(tasks.map((t) => [t.id, t]));
for (const id of sourceIds) {
if (id === targetId) continue;
const source = byId.get(id);
const target = byId.get(anchor);
if (!source || !target || !canReorderTask(source, target, next)) continue;
next = reorderTaskInOrganize(next, tasks, id, anchor, position);
if (position === "after") anchor = id;
}
return next;
});
}
/** Reorders a custom group before or after another custom group. */
+7
Переглянути файл
@@ -285,6 +285,11 @@ export const taskActions: Action[] = [
hidden: true,
run: ({ arg }) => {
if (typeof arg === "string") openTask(arg);
// `{ task, focus: false }`: a click in the task list opens the session and keeps focus there.
else if (arg && typeof arg === "object" && typeof (arg as { task?: unknown }).task === "string") {
const { task, focus } = arg as { task: string; focus?: unknown };
openTask(task, { focus: focus !== false });
}
},
},
{
@@ -396,6 +401,8 @@ export const taskActions: Action[] = [
title: "Delete Agent Tasks",
category: "Agents",
hidden: true,
// Without an argument the shortcut deletes the task list's selection.
keyWhen: "agentTaskListFocus",
run: ({ arg }) => confirmDelete(resolveTasks(arg)),
},
{
+34
Переглянути файл
@@ -62,6 +62,7 @@ vi.mock("../find/windowStore", async (orig) => ({
const contributions = await import("@/workbench/contributions");
const { commands, emitLocalIdeEvent } = await import("@/platform/ipc");
const { ContextMenuHost } = await import("@/ui");
const { RecentPopupsOverlay } = await import("../recent/RecentPopups");
const { cycleSwitcher, showRecentPopup, hideRecentPopup, useRecentPopup } = await import("../recent/store");
const { openLocation } = await import("../common/open");
@@ -448,6 +449,39 @@ function clickOption(index: number, modifiers = {}) {
fireEvent.click(row, modifiers);
}
describe("Search Everywhere result actions", () => {
it.each(["keyboard", "right click"] as const)("selects a file in the Project view from the %s menu", async (how) => {
const run = vi.fn();
const project = useProject.getState().project;
useProject.setState({ project: { root: "/p", name: "p", isGit: false } as never });
const dispose = registerAction({
id: "navigate.selectInProjectView",
title: "Select in Project View",
run: ({ arg }) => run(arg),
});
try {
render(
<>
<SearchEverywhereOverlay />
<ContextMenuHost />
</>,
);
act(() => showSearchEverywhere("files", { query: "order" }));
await tick();
if (how === "keyboard") fireEvent.keyDown(screen.getByLabelText("Search query"), { key: "Enter", altKey: true });
else fireEvent.contextMenu(resultOptions()[0]!);
await tick();
fireEvent.click(screen.getByRole("menuitem", { name: /Select in Project View/ }));
await tick();
expect(run).toHaveBeenCalledExactlyOnceWith("/p/src/OrderController.kt");
expect(useSearchEverywhere.getState().open).toBe(false);
} finally {
dispose();
useProject.setState({ project });
}
});
});
describe("Search Everywhere multi-selection", () => {
it("extends, shrinks, crosses the anchor and clamps Shift selection; plain arrows select one", async () => {
const input = await showDuplicateFiles();
+149 -2
Переглянути файл
@@ -1,4 +1,4 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { OutlineItem } from "@/platform/ipc";
@@ -16,10 +16,17 @@ const { FileStructureOverlay, useFileStructurePopup } = await import("../structu
const { useOutline, useStructureOptions } = await import("../structure/store");
const { useTracking } = await import("../common/tracking");
const item = (name: string, kind: OutlineItem["kind"], line: number, children: OutlineItem[] = []): OutlineItem => ({
const item = (
name: string,
kind: OutlineItem["kind"],
line: number,
children: OutlineItem[] = [],
visibility?: OutlineItem["visibility"],
): OutlineItem => ({
name,
detail: null,
kind,
visibility,
range: { start: { line, col: 0 }, end: { line: line + 1, col: 1 } },
selection_range: { start: { line, col: 4 }, end: { line, col: 4 + name.length } },
children,
@@ -61,6 +68,19 @@ function openFunctions(narrowDown: boolean) {
return input;
}
beforeEach(() => {
useStructureOptions.setState({
alphabetical: false,
narrowDown: true,
showFields: true,
showNonPublic: true,
showInherited: false,
sortByVisibility: false,
showOnlyWidgets: false,
});
useOutline.setState({ inheritedSupported: false, inherited: null, flutter: null });
});
afterEach(() => {
act(() => useFileStructurePopup.setState({ open: false }));
useTracking.setState({ caret: null });
@@ -186,6 +206,133 @@ describe("File Structure popup", () => {
expect(useFileStructurePopup.getState().open).toBe(false);
});
describe("temporary filters", () => {
const filteredItems = () => [
item("Container", "class", 0, [
item("hiddenField", "field", 2),
item("hiddenMethod", "method", 4, [], "private"),
item("visible", "method", 6),
]),
];
it("auto-enables only the applicable filter needed for a match, without persisting it", () => {
useStructureOptions.setState({ showFields: false, showNonPublic: false });
const saved = localStorage.getItem("openidea.structure.options.v1");
const input = open(filteredItems());
const fields = screen.getByRole("checkbox", { name: "Show fields" });
const nonPublic = screen.getByRole("checkbox", { name: "Show non-public" });
expect(fields).not.toBeChecked();
expect(nonPublic).not.toBeChecked();
fireEvent.change(input, { target: { value: "hiddenField" } });
expect(fields).toBeChecked();
expect(nonPublic).not.toBeChecked();
expect(screen.getByRole("treeitem", { name: "hiddenField", selected: true })).toBeVisible();
expect(useStructureOptions.getState()).toMatchObject({ showFields: false, showNonPublic: false });
expect(localStorage.getItem("openidea.structure.options.v1")).toBe(saved);
fireEvent.keyDown(input, { key: "Escape" });
expect(fields).not.toBeChecked();
fireEvent.keyDown(input, { key: "Escape" });
expect(useFileStructurePopup.getState().open).toBe(false);
act(() => useFileStructurePopup.setState({ open: true }));
expect(screen.getByLabelText("Filter symbols")).toHaveValue("");
expect(screen.getByRole("checkbox", { name: "Show fields" })).not.toBeChecked();
expect(useStructureOptions.getState().showFields).toBe(false);
});
it("tries unchecked filters one at a time until a match appears, then restores all on Escape", () => {
useStructureOptions.setState({ showFields: false, showNonPublic: false });
const input = open(filteredItems());
const fields = screen.getByRole("checkbox", { name: "Show fields" });
const nonPublic = screen.getByRole("checkbox", { name: "Show non-public" });
fireEvent.change(input, { target: { value: "hiddenMethod" } });
expect(fields).toBeChecked();
expect(nonPublic).toBeChecked();
expect(screen.getByRole("treeitem", { name: "hiddenMethod", selected: true })).toBeVisible();
expect(useStructureOptions.getState()).toMatchObject({ showFields: false, showNonPublic: false });
fireEvent.keyDown(input, { key: "Escape" });
expect(input).toHaveValue("");
expect(fields).not.toBeChecked();
expect(nonPublic).not.toBeChecked();
expect(screen.getByRole("treeitem", { name: "visible" })).toBeVisible();
});
it("does not immediately re-enable a restored filter after backspace", () => {
useStructureOptions.setState({ showFields: false, showNonPublic: false });
const input = open(filteredItems());
const fields = screen.getByRole("checkbox", { name: "Show fields" });
fireEvent.change(input, { target: { value: "hiddenField" } });
expect(fields).toBeChecked();
fireEvent.change(input, { target: { value: "hiddenFiel" } });
expect(fields).not.toBeChecked();
expect(screen.getByText("No symbols")).toBeInTheDocument();
expect(useStructureOptions.getState().showFields).toBe(false);
});
it("does not auto-enable filters when Narrow down on typing is off", () => {
useStructureOptions.setState({ showFields: false, showNonPublic: false });
const input = open(filteredItems());
act(() => useStructureOptions.setState({ narrowDown: false }));
const fields = screen.getByRole("checkbox", { name: "Show fields" });
const nonPublic = screen.getByRole("checkbox", { name: "Show non-public" });
fireEvent.change(input, { target: { value: "hiddenField" } });
expect(fields).not.toBeChecked();
expect(nonPublic).not.toBeChecked();
expect(screen.queryByRole("treeitem", { name: "hiddenField" })).toBeNull();
expect(useStructureOptions.getState()).toMatchObject({ showFields: false, showNonPublic: false });
});
it("restores an auto-enabled filter on backspace without reverting a manual checkbox change", () => {
useStructureOptions.setState({ showFields: false, showNonPublic: false });
const input = open(filteredItems());
const fields = screen.getByRole("checkbox", { name: "Show fields" });
const nonPublic = screen.getByRole("checkbox", { name: "Show non-public" });
fireEvent.change(input, { target: { value: "hiddenField" } });
expect(fields).toBeChecked();
fireEvent.click(nonPublic);
expect(useStructureOptions.getState().showNonPublic).toBe(true);
fireEvent.change(input, { target: { value: "hiddenFielX" } });
expect(fields).toBeChecked(); // Same-length edits do not trigger IDEA's backspace restore.
fireEvent.change(input, { target: { value: "visible" } });
expect(fields).not.toBeChecked();
expect(nonPublic).toBeChecked();
expect(screen.getByRole("treeitem", { name: "visible", selected: true })).toBeVisible();
expect(screen.queryByRole("treeitem", { name: "hiddenField" })).toBeNull();
expect(useStructureOptions.getState()).toMatchObject({ showFields: false, showNonPublic: true });
fireEvent.keyDown(input, { key: "Escape" });
fireEvent.keyDown(input, { key: "Escape" });
act(() => useFileStructurePopup.setState({ open: true }));
expect(screen.getByRole("checkbox", { name: "Show fields" })).not.toBeChecked();
expect(screen.getByRole("checkbox", { name: "Show non-public" })).toBeChecked();
});
it("temporarily enables Show inherited members and restores it when the query gets shorter", () => {
const input = open([item("Container", "class", 0, [item("own", "method", 2)])]);
const inherited = [{ item: item("inheritedNeedle", "method", 40), path: "/lib/Base.kt", owner: "Base" }];
act(() => useOutline.setState({ inheritedSupported: true, inherited: new Map([["0:4", inherited]]) }));
const checkbox = screen.getByRole("checkbox", { name: "Show inherited members" });
expect(checkbox).not.toBeChecked();
fireEvent.change(input, { target: { value: "inheritedNeedle" } });
expect(checkbox).toBeChecked();
expect(screen.getByRole("treeitem", { name: /^inheritedNeedle/, selected: true })).toBeVisible();
expect(useStructureOptions.getState().showInherited).toBe(false);
fireEvent.change(input, { target: { value: "own" } });
expect(checkbox).not.toBeChecked();
expect(screen.getByRole("treeitem", { name: "own", selected: true })).toBeVisible();
expect(screen.queryByRole("treeitem", { name: /^inheritedNeedle/ })).toBeNull();
expect(useStructureOptions.getState().showInherited).toBe(false);
});
});
it("offers Show inherited members only when the server knows type hierarchies", () => {
open();
expect(screen.queryByLabelText("Show inherited members")).toBeNull();
+30
Переглянути файл
@@ -0,0 +1,30 @@
import { afterEach, expect, it } from "vitest";
import { EditorSelection, EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { _setActiveEditor, type TextEditorHandle } from "@/editor/api";
import { editorSelectionText } from "../index";
const views: EditorView[] = [];
const view = (doc: string, from: number, to: number) => {
const v = new EditorView({
state: EditorState.create({ doc, selection: EditorSelection.single(from, to) }),
parent: document.body,
});
views.push(v);
return v;
};
afterEach(() => {
_setActiveEditor(null);
views.splice(0).forEach((v) => v.destroy());
});
it("takes the selection of the focused editor, such as the Find in Files preview, over the active one", () => {
const main = view("val first = 1", 4, 9);
_setActiveEditor({ view: main } as unknown as TextEditorHandle);
expect(editorSelectionText()).toBe("first");
const preview = view("fun second() {}", 4, 10);
preview.contentDOM.focus();
expect(editorSelectionText()).toBe("second");
preview.contentDOM.blur();
expect(editorSelectionText()).toBe("first");
});
+54 -20
Переглянути файл
@@ -34,13 +34,14 @@ import {
selectRow,
selectedRows,
rowSelectionMode,
showContextMenu,
type RowSelection,
type MenuItem,
T,
} from "@/ui";
import { useFileDecoration } from "@/workbench/contributions";
import { highlightTokens, languageForPath, type CodeToken } from "@/editor/lsp/markdown";
import { badgeKind, basename, openInListOrder, openLocation, relDir } from "../common/open";
import { badgeKind, basename, openInListOrder, openLocation, projectRoot, relDir } from "../common/open";
import { parseLocationQuery } from "../common/query";
import { setTextSearchOption, useFindPopup } from "../find/store";
import { CodePreview, type PreviewHighlight } from "../find/parts";
@@ -441,35 +442,67 @@ function SearchEverywhereDialog() {
/** IDEA's ⌥↵ on an action: record a shortcut for it (written to the active keymap). */
const assignShortcut = (id: string) => closeThen(() => void executeAction("settings.assignShortcut", id));
/** Actions of a file, symbol or text result: IDEA's ⌥↵ menu and the row's context menu. */
const resultMenu = (row: NavigationRow): MenuItem[] => {
const copy = (text: string) => void writeClipboardText(text).catch(() => {});
const folder = row.kind === "file" && row.folder;
const root = projectRoot();
const inProject = !!root && (row.path === root || row.path.startsWith(root.endsWith("/") ? root : `${root}/`));
const items: MenuItem[] = [
{ label: "Open", run: () => activate(row) },
{
label: "Open to the Side",
shortcut: formatBinding("Shift+Enter"),
disabled: !!folder,
run: () => activate(row, true),
},
// IDEA's Select in Project View (Select Opened File): shows a result opened in another
// application (.doc in WPS) in the Project view, where its place in the project is visible.
...(inProject
? [
{
label: "Select in Project View",
shortcut: shortcutLabel("navigate.selectInProjectView") ?? undefined,
run: () => closeThen(() => void executeActionFrom("search", "navigate.selectInProjectView", row.path)),
},
]
: []),
{ kind: "separator" },
];
items.push(
{ label: "Copy Path", run: () => copy(nativePath(row.path)) },
{ label: "Copy Path from Project Root", run: () => copy(row.rel) },
...(row.kind === "symbol" ? [{ label: "Copy Name", run: () => copy(row.name) }] : []),
...(row.kind === "file" || row.kind === "text"
? [
{
label: "Find in Directory…",
run: () => closeThen(() => void executeAction("find.inPath", { directory: dirOf(row.path) })),
},
]
: []),
);
return items;
};
const openIntentions = () => {
const row = activeRow;
if (!row || row.kind === "section" || row.kind === "more" || row.kind === "command") return;
if (row.kind === "action") return row.run ? undefined : assignShortcut(row.id);
const anchor = listRef.current?.querySelector('[data-lead="true"]') ?? inputRef.current;
if (!anchor) return;
const copy = (text: string) => void writeClipboardText(text).catch(() => {});
const items: MenuItem[] =
row.kind === "setting"
? [{ label: "Open Settings Page", run: () => activate(row) }]
: [
{ label: "Open", run: () => activate(row) },
{ label: "Open to the Side", shortcut: formatBinding("Shift+Enter"), run: () => activate(row, true) },
{ kind: "separator" },
{ label: "Copy Path", run: () => copy(nativePath(row.path)) },
{ label: "Copy Path from Project Root", run: () => copy(row.rel) },
...(row.kind === "symbol" ? [{ label: "Copy Name", run: () => copy(row.name) }] : []),
...(row.kind === "file" || row.kind === "text"
? [
{
label: "Find in Directory…",
run: () => closeThen(() => void executeAction("find.inPath", { directory: dirOf(row.path) })),
},
]
: []),
];
row.kind === "setting" ? [{ label: "Open Settings Page", run: () => activate(row) }] : resultMenu(row);
setMenu({ anchor, items, placement: "right-start" });
};
const onRowContextMenu = (row: SeRow, index: number, e: MouseEvent) => {
if (row.kind !== "file" && row.kind !== "symbol" && row.kind !== "text") return;
e.preventDefault();
select(index, e);
showContextMenu(e, resultMenu(row));
};
const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
if (isImeKey(e.nativeEvent)) return;
if (tab === "text" && e.altKey && !e.metaKey && !e.ctrlKey && !e.shiftKey) {
@@ -574,6 +607,7 @@ function SearchEverywhereDialog() {
if (preview && previewOf(r) && e.type === "click" && e.detail !== 2) return;
activate(r, e.shiftKey);
}}
onContextMenu={onRowContextMenu}
focusable={false}
rowHeight={rowHeight}
sectionHeight={rowHeight}
+8 -2
Переглянути файл
@@ -3,6 +3,7 @@
* Recent Files / Recent Locations, Find / Replace in Files + the Find tool
* window, the Structure tool window + File Structure popup, and bookmarks.
*/
import { EditorView } from "@codemirror/view";
import { lazyComponent, lazyWhen } from "@/ui";
import { activeEditor, focusedCellEditor, registerEditorContribution } from "@/editor/api";
import { executeAction, registerActions } from "@/platform/actions";
@@ -82,8 +83,13 @@ async function removeMissingBookmarks(removed: readonly string[]) {
}
/** Single-line editor selection, used to prefill search fields. */
function editorSelectionText(): string | null {
const view = activeEditor()?.view;
/**
* The single-line selection a search starts from: the focused editor's (a Find in Files preview,
* a diff pane), else the active editor's, as IDEA reads it from the editor in the action's context.
*/
export function editorSelectionText(): string | null {
const focused = document.activeElement?.closest(".cm-editor");
const view = (focused instanceof HTMLElement ? EditorView.findFromDOM(focused) : null) ?? activeEditor()?.view;
if (!view) return null;
const { from, to } = view.state.selection.main;
if (from === to || to - from > 200) return null;
+97 -14
Переглянути файл
@@ -33,7 +33,16 @@ import {
widgetLetter,
type OutlineNode,
} from "./outline";
import { useCollapsedStructure, useLiveOutline, useOutline, useOutlineNodes, useStructureOptions } from "./store";
import {
getOutlineNodes,
releaseInheritedMembers,
requestInheritedMembers,
useCollapsedStructure,
useLiveOutline,
useOutline,
useOutlineNodes,
useStructureOptions,
} from "./store";
import styles from "./StructureView.module.css";
import { tx } from "@/platform/i18n";
@@ -301,8 +310,30 @@ export function FileStructureOverlay() {
const POPUP_ROW = 22;
type TemporaryFilter = "showFields" | "showNonPublic" | "showInherited";
interface AutoFilter {
key: TemporaryFilter;
queryLength: number;
}
interface PopupFilters {
showFields: boolean;
showNonPublic: boolean;
showInherited: boolean;
}
const TEMPORARY_FILTERS: readonly TemporaryFilter[] = ["showFields", "showNonPublic", "showInherited"];
function effectivePopupFilters(options: PopupFilters, autoFilters: readonly AutoFilter[]): PopupFilters {
const enabled = (key: TemporaryFilter) => autoFilters.some((entry) => entry.key === key);
return {
showFields: options.showFields || enabled("showFields"),
showNonPublic: options.showNonPublic || enabled("showNonPublic"),
showInherited: options.showInherited || enabled("showInherited"),
};
}
function FileStructureDialog() {
useLiveOutline();
useEffect(() => () => releaseInheritedMembers(), []);
const rowHeight = useRowHeight(POPUP_ROW);
const path = useOutline((s) => s.path);
const items = useOutline((s) => s.items);
@@ -313,8 +344,13 @@ function FileStructureDialog() {
const showNonPublic = useStructureOptions((s) => s.showNonPublic);
const showInherited = useStructureOptions((s) => s.showInherited);
const inheritedSupported = useOutline((s) => s.inheritedSupported);
const nodes = useOutlineNodes();
const [query, setQuery] = useState("");
const [autoFilters, setAutoFilters] = useState<AutoFilter[]>([]);
const effectiveOptions = useMemo(
() => effectivePopupFilters({ showFields, showNonPublic, showInherited }, autoFilters),
[showFields, showNonPublic, showInherited, autoFilters],
);
const nodes = useOutlineNodes(false, effectiveOptions);
const [showOptions, setShowOptions] = useState(false);
// IDEA opens the popup fully expanded.
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set());
@@ -351,7 +387,10 @@ function FileStructureDialog() {
else tree.current?.clearSelection();
}, [query, hasQuery, caretKey, filter.preferred, filter.nodes]);
const close = () => useFileStructurePopup.setState({ open: false });
const close = () => {
releaseInheritedMembers();
useFileStructurePopup.setState({ open: false });
};
const choose = (node: OutlineNode | undefined) => {
if (!node || !path) return;
close();
@@ -365,6 +404,53 @@ function FileStructureDialog() {
return next;
});
const availableFilters: Record<TemporaryFilter, boolean> = {
showFields: hasFields(items ?? []),
showNonPublic: hasVisibility(items ?? []),
showInherited: inheritedSupported,
};
const changeQuery = (nextQuery: string) => {
setQuery(nextQuery);
setCollapsed(new Set());
let nextAuto = autoFilters;
if (nextQuery.length < query.length) {
// IDEA restores every auto-click whose query was at least this long, newest first.
nextAuto = autoFilters.filter((entry) => entry.queryLength < nextQuery.length);
if (nextAuto.length !== autoFilters.length) {
if (
autoFilters.some((entry) => entry.key === "showInherited") &&
!nextAuto.some((entry) => entry.key === "showInherited")
)
releaseInheritedMembers();
setAutoFilters(nextAuto);
return;
}
}
if (!nextQuery.trim() || !narrowDown) {
setAutoFilters(nextAuto);
return;
}
const persisted = useStructureOptions.getState();
let options = effectivePopupFilters(persisted, nextAuto);
const hasMatch = () => filterOutline(getOutlineNodes(false, options), nextQuery, narrowDown).best !== null;
if (!hasMatch()) {
for (const key of TEMPORARY_FILTERS) {
if (options[key] || !availableFilters[key]) continue;
nextAuto = [{ key, queryLength: nextQuery.length }, ...nextAuto];
options = effectivePopupFilters(persisted, nextAuto);
if (key === "showInherited") requestInheritedMembers();
if (hasMatch()) break;
}
}
setAutoFilters(nextAuto);
};
const changeFilter = (key: TemporaryFilter, value: boolean) => {
// A manual edit takes ownership of the checkbox; later backspaces must not undo it.
setAutoFilters((entries) => entries.filter((entry) => entry.key !== key));
if (key === "showInherited") releaseInheritedMembers();
useStructureOptions.setState({ [key]: value });
};
const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
const lead = tree.current?.leadKey() ?? null;
const node = lead ? byKey.get(lead) : undefined;
@@ -377,7 +463,7 @@ function FileStructureDialog() {
// The first Esc clears the filter, the next one closes the popup.
if (!query) return;
e.stopPropagation();
setQuery("");
changeQuery("");
break;
case "ArrowDown":
case "ArrowUp": {
@@ -437,22 +523,22 @@ function FileStructureDialog() {
{(hasFields(items ?? []) || !showFields) && (
<Checkbox
label="Show fields"
checked={showFields}
onChange={(v) => useStructureOptions.setState({ showFields: v })}
checked={effectiveOptions.showFields}
onChange={(v) => changeFilter("showFields", v)}
/>
)}
{hasVisibility(items ?? []) && (
<Checkbox
label="Show non-public"
checked={showNonPublic}
onChange={(v) => useStructureOptions.setState({ showNonPublic: v })}
checked={effectiveOptions.showNonPublic}
onChange={(v) => changeFilter("showNonPublic", v)}
/>
)}
{inheritedSupported && (
<Checkbox
label="Show inherited members"
checked={showInherited}
onChange={(v) => useStructureOptions.setState({ showInherited: v })}
checked={effectiveOptions.showInherited}
onChange={(v) => changeFilter("showInherited", v)}
/>
)}
</div>
@@ -496,10 +582,7 @@ function FileStructureDialog() {
aria-label={tx("Filter symbols")}
spellCheck={false}
autoComplete="off"
onChange={(e) => {
setQuery(e.target.value);
setCollapsed(new Set());
}}
onChange={(e) => changeQuery(e.target.value)}
onKeyDown={onKeyDown}
/>
{hasQuery && !narrowDown && !filter.best && filter.nodes.length > 0 && (
+36 -5
Переглянути файл
@@ -47,6 +47,8 @@ let consumers = 0;
let stop: (() => void) | null = null;
let seq = 0;
let flutterSeq = 0;
let reloadOutline: (() => void) | null = null;
let inheritedRequest: { doc: number; path: string } | null = null;
/** A backend document id for `path` while `fn` runs (open editors are reused). */
async function withDoc<T>(path: string, fn: (doc: number) => Promise<T>): Promise<T> {
@@ -99,16 +101,31 @@ async function loadInherited(doc: number, path: string, items: readonly OutlineI
? true
: await probeHierarchy(doc, types);
if (my !== seq) return;
if (!supported || !useStructureOptions.getState().showInherited) {
const requested = inheritedRequest?.doc === doc && inheritedRequest.path === path;
if (!supported || !(useStructureOptions.getState().showInherited || requested)) {
if (requested) inheritedRequest = null;
useOutline.setState({ inheritedSupported: supported, inherited: null });
return;
}
useOutline.setState({ inheritedSupported: true });
const deps = inheritedDeps(path, doc, language === "python");
const entries = await Promise.all(
types.map(async (t) => [typeKey(t), await inheritedMembers(path, t, deps).catch(() => [])] as const),
);
if (my === seq)
useOutline.setState({ inheritedSupported: true, inherited: new Map(entries.filter(([, m]) => m.length)) });
if (my === seq) useOutline.setState({ inherited: new Map(entries.filter(([, m]) => m.length)) });
}
/** Loads inherited members for a temporary popup filter without changing persisted options. */
export function requestInheritedMembers() {
const { doc, path, inherited } = useOutline.getState();
if (doc === null || path === null) return;
inheritedRequest = { doc, path };
if (inherited === null) reloadOutline?.();
}
/** Ends a popup's temporary inherited-member request when its filter is restored or it closes. */
export function releaseInheritedMembers() {
inheritedRequest = null;
}
async function loadFlutter(doc: number, language: string) {
@@ -153,6 +170,7 @@ function start(): () => void {
if (!ctx) {
seq++;
flutterSeq++;
inheritedRequest = null;
useOutline.setState({
path: null,
doc: null,
@@ -167,6 +185,7 @@ function start(): () => void {
}
void load(ctx.doc, ctx.path, ctx.language);
};
reloadOutline = reloadNow;
reloadNow();
const unsubActive = useEditorRegistry.subscribe((s, prev) => {
if (s.active?.ctx.doc !== prev.active?.ctx.doc || s.active?.ctx.path !== prev.active?.ctx.path) reloadNow();
@@ -188,6 +207,8 @@ function start(): () => void {
return () => {
clearTimeout(timer);
flutterSeq++;
if (reloadOutline === reloadNow) reloadOutline = null;
inheritedRequest = null;
unsubFlutter();
unsubActive();
unsubInherited();
@@ -268,6 +289,8 @@ const outlinePreferences = (s: StructureOptions) => ({
showOnlyWidgets: s.showOnlyWidgets,
});
type OutlinePreferences = ReturnType<typeof outlinePreferences>;
function outlineNodes(
items: OutlineState["items"],
flutter: OutlineState["flutter"],
@@ -285,12 +308,20 @@ function outlineNodes(
return flutter && options.showOnlyWidgets ? onlyWidgets(nodes) : nodes;
}
export function useOutlineNodes(widgets = false) {
/** Snapshot builder for query-event transitions, which cannot call hooks. */
export function getOutlineNodes(widgets = false, overrides?: Partial<OutlinePreferences>) {
const { items, flutter, inheritedSupported, inherited } = useOutline.getState();
const options = { ...outlinePreferences(useStructureOptions.getState()), ...overrides };
return outlineNodes(items, widgets ? flutter : null, inheritedSupported ? inherited : null, options);
}
export function useOutlineNodes(widgets = false, overrides?: Partial<OutlinePreferences>) {
const items = useOutline((s) => s.items);
const flutter = useOutline((s) => (widgets ? s.flutter : null));
const inherited = useOutline((s) => (s.inheritedSupported ? s.inherited : null));
const options = useStructureOptions(useShallow(outlinePreferences));
return useMemo(() => outlineNodes(items, flutter, inherited, options), [items, flutter, inherited, options]);
const effective = useMemo(() => (overrides ? { ...options, ...overrides } : options), [options, overrides]);
return useMemo(() => outlineNodes(items, flutter, inherited, effective), [items, flutter, inherited, effective]);
}
function collapseStructure() {
+23
Переглянути файл
@@ -101,6 +101,29 @@ describe("resolveMonoFont", () => {
});
});
describe("a chosen family that isn't installed", () => {
afterEach(() => {
vi.resetModules();
});
it("puts the bundled face before the fallback, so Latin text doesn't take the fallback's proportional letters", async () => {
const fonts = await import("./fonts");
// Before the native catalog loads nothing is known to be missing.
expect(fonts.monoFontFamily("Fira Code", "PingFang SC", BASE)).toBe(`"Fira Code", "PingFang SC", ${BASE}`);
fonts.noteInstalledFonts(["PingFang SC", "Menlo"]);
expect(fonts.monoFontFamily("Fira Code", "PingFang SC", BASE)).toBe(
`"Fira Code", "JetBrains Mono", "JetBrains Mono Variable", "PingFang SC", ${BASE}`,
);
// Installed, bundled and generic families keep the fallback right after them; so does no fallback.
expect(fonts.monoFontFamily("menlo", "PingFang SC", BASE)).toBe(`"menlo", "PingFang SC", ${BASE}`);
expect(fonts.monoFontFamily("Inter", "PingFang SC", BASE)).toBe(
`"Inter", "Inter Variable", "PingFang SC", ${BASE}`,
);
expect(fonts.monoFontFamily("monospace", "PingFang SC", BASE)).toBe(`"monospace", "PingFang SC", ${BASE}`);
expect(fonts.monoFontFamily("Fira Code", "", BASE)).toBe(`"Fira Code", ${BASE}`);
});
});
describe("discovered Nerd Font fallbacks (#3723)", () => {
afterEach(() => {
vi.resetModules();
+20 -2
Переглянути файл
@@ -98,12 +98,15 @@ async function loadUserFont(name: string, alias: string): Promise<void> {
* face is named alone unless the native catalog lists an installed JetBrains Mono.
*/
let monoInstalled: boolean | null = null;
/** Lower-cased installed family names from the native catalog, once it has loaded. */
let installedFamilies: ReadonlySet<string> | null = null;
const bundledMonoOnly = () => guessOs() === "linux" && monoInstalled !== true;
const BUNDLED_MONO_STACK = '"JetBrains Mono Variable", ui-monospace, monospace';
/** Records whether the system has JetBrains Mono installed (`installed`: the native catalog, not the bundled list). */
export function noteInstalledFonts(installed: readonly string[], root?: HTMLElement): void {
monoInstalled = installed.some((name) => name.trim().toLowerCase() === BUNDLED_MONO_FAMILY.toLowerCase());
installedFamilies = new Set(installed.map((name) => name.trim().toLowerCase()));
monoInstalled = installedFamilies.has(BUNDLED_MONO_FAMILY.toLowerCase());
installMonoStack(root);
}
@@ -256,7 +259,22 @@ export function monoFontFamily(family: string | undefined, fallback = "", base =
const name = familyName(family ?? "");
const fb = familyName(fallback);
const head = familyFaces(name || BUNDLED_MONO_FAMILY);
return [...head, ...(fb ? familyFaces(fb) : []), base].join(", ");
// A chosen family that isn't installed leaves every glyph to the fallback, often a CJK face
// whose Latin letters are proportional: a grid measures its cells by the widest of them and
// the text comes out spread apart. The bundled face stands in for the missing one, and the
// fallback still covers what that lacks.
const standIn = fb && name && familyMissing(name) ? familyFaces(BUNDLED_MONO_FAMILY) : [];
return [...head, ...standIn, ...(fb ? familyFaces(fb) : []), base].join(", ");
}
const GENERIC_FAMILIES =
/^(?:monospace|ui-monospace|sans-serif|serif|system-ui|ui-sans-serif|ui-serif|cursive|fantasy)$/i;
/** Whether the native catalog has loaded and doesn't list `name` (bundled and generic families always count as present). */
function familyMissing(name: string): boolean {
if (!installedFamilies) return false;
const key = name.toLowerCase();
return !installedFamilies.has(key) && !BUNDLED_FACES.has(key) && !GENERIC_FAMILIES.test(name);
}
/** Tools › Terminal › Font, shared by the terminal and the Run console. */
+1
Переглянути файл
@@ -495,6 +495,7 @@ export const intellijMacos: Record<string, string[]> = {
"agents.sendToAgent": [],
// Agents task list (when it has focus)
"agents.archiveTasks": ["Meta+Shift+E"],
"agents.deleteTasks": ["Delete", "Meta+Backspace"],
// Database tool window (when the tree has focus; `db.openConsole` anywhere).
"db.openConsole": ["Meta+Shift+L"],
"db.newDataSource": [],
+1
Переглянути файл
@@ -493,6 +493,7 @@ export const intellijWindows: Record<string, string[]> = {
"agents.sendToAgent": [],
// Agents task list (when it has focus)
"agents.archiveTasks": ["Ctrl+Shift+E"],
"agents.deleteTasks": ["Delete"],
// Database tool window (when the tree has focus; `db.openConsole` anywhere).
"db.openConsole": ["Ctrl+Shift+Q"],
"db.newDataSource": [],
+1
Переглянути файл
@@ -528,6 +528,7 @@ export const vscodeMacos: Record<string, string[]> = {
"agents.sendToAgent": [],
// Agents task list (when it has focus)
"agents.archiveTasks": ["Meta+Shift+E"],
"agents.deleteTasks": ["Meta+Backspace"],
// Python Console: VS Code's Shift+Enter would shadow typing in Python files, so unbound.
"python.console.executeSelection": [],
// Search fields (find bar, Find in Files): last, so they win over editor keys while one is focused.
+1
Переглянути файл
@@ -45,6 +45,7 @@ export const vscodeWindows: Record<string, string[]> = {
"project.rename": ["F2"],
"project.delete": ["Delete"],
"db.drop": ["Delete"],
"agents.deleteTasks": ["Delete"],
"project.copyAbsolutePath": ["Alt+Shift+C"],
"project.open": [],
"project.openInRightSplit": ["Ctrl+Enter"],
+1
Переглянути файл
@@ -3740,6 +3740,7 @@
"Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.",
"Hot reload on save failed: {0}": "Hot reload on save failed: {0}",
"Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?",
"Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?",
"New Tab": "New Tab",
"New tab in current window": "New tab in current window",
"Show Only Widgets": "Show Only Widgets",
+1
Переглянути файл
@@ -9762,6 +9762,7 @@
"Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "Сохранение файла Dart во время запущенной сессии отладки Flutter перезагружает приложение, если в файле нет ошибок.",
"Hot reload on save failed: {0}": "Ошибка горячей перезагрузки при сохранении: {0}",
"Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Проекты можно открывать в новом окне, вместо текущего проекта, присоединять к уже открытым проектам или открывать как новую вкладку в этом окне.\nКак открыть «{name}»?",
"Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Проекты можно открывать в новом окне, вместо текущего проекта или как новую вкладку в этом окне.\nКак открыть «{name}»?",
"Show Only Widgets": "Показывать только виджеты",
"Update failed": "Не удалось выполнить обновление",
"Updating branches": "Обновление веток",
+1
Переглянути файл
@@ -2668,6 +2668,7 @@
"Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "Çalışan Flutter hata ayıklama oturumunda Dart dosyası kaydedildiğinde, dosyada hata yoksa uygulama yeniden yüklenir.",
"Hot reload on save failed: {0}": "Kaydetmede sıcak yeniden yükleme başarısız: {0}",
"Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projeler yeni pencerede açılabilir, geçerli projenin yerini alabilir, açık projelere bağlanabilir veya bu pencerede yeni sekmede açılabilir.\n\"{name}\" nasıl açılsın?",
"Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "Projeler yeni pencerede açılabilir, geçerli projenin yerini alabilir veya bu pencerede yeni sekmede açılabilir.\n\"{name}\" nasıl açılsın?",
"New Tab": "Yeni sekme",
"New tab in current window": "Geçerli pencerede yeni sekme",
"Show Only Widgets": "Yalnızca Bileşenleri Göster",
+1
Переглянути файл
@@ -9195,6 +9195,7 @@
"Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "儲存正在執行的 Flutter 偵錯工作階段裡的 Dart 檔案時重新載入應用,檔案有錯誤時跳過。",
"Hot reload on save failed: {0}": "儲存時熱過載失敗:{0}",
"Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "專案可以在新視窗中開啟、取代目前專案、附加到已開啟的專案,或以新分頁在目前視窗中開啟。\n要如何開啟「{name}」?",
"Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "專案可以在新視窗中開啟、取代目前專案,或以新分頁在目前視窗中開啟。\n要如何開啟「{name}」?",
"Show Only Widgets": "僅顯示 Widget",
"Update failed": "更新失敗",
"Updating branches": "正在更新分支",
+1
Переглянути файл
@@ -10315,6 +10315,7 @@
"Saving a Dart file of a running Flutter debug session reloads the app, unless the file has errors.": "保存正在运行的 Flutter 调试会话里的 Dart 文件时重新加载应用,文件有错误时跳过。",
"Hot reload on save failed: {0}": "保存时热重载失败:{0}",
"Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "项目可以在新窗口中打开、替换当前项目、附加到已打开的项目,或以新标签页在当前窗口中打开。\n要如何打开“{name}”?",
"Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open \"{name}\"?": "项目可以在新窗口中打开、替换当前项目,或以新标签页在当前窗口中打开。\n要如何打开“{name}”?",
"Show Only Widgets": "仅显示 Widget",
"Update failed": "更新失败",
"Updating branches": "正在更新分支",
+10
Переглянути файл
@@ -103,6 +103,16 @@ describe("Tabs interactions", () => {
expect(onClose).toHaveBeenCalledWith("b");
});
it("double click on the empty strip calls onBlankDoubleClick, not on a tab", () => {
const onBlank = vi.fn();
const { container } = render(<Tabs items={items} activeId="a" onSelect={() => {}} onBlankDoubleClick={onBlank} />);
fireEvent.doubleClick(screen.getByRole("tab", { name: "A" }));
expect(onBlank).not.toHaveBeenCalled();
fireEvent.doubleClick(screen.getByRole("tablist"));
fireEvent.doubleClick(container.firstElementChild!);
expect(onBlank).toHaveBeenCalledTimes(2);
});
it("Shift+left-click closes an editor tab without selecting it", () => {
const onClose = vi.fn();
const onSelect = vi.fn();
+15 -1
Переглянути файл
@@ -136,6 +136,8 @@ export interface TabsProps {
/** Shift+left-click a tab closes it (editor tabs; plain clicks still select). */
closeOnShiftClick?: boolean;
onDoubleClick?: (id: string) => void;
/** Double click on the empty part of the strip (not on a tab or button), e.g. to maximize the editor. */
onBlankDoubleClick?: () => void;
onContextMenu?: (id: string, e: MouseEvent) => void;
/** `editor`: 30px with separators (editor tabs); `compact`: 28px plain (popups, tool window sub-tabs). */
variant?: "editor" | "compact";
@@ -176,6 +178,7 @@ export function Tabs({
onTogglePin,
closeOnShiftClick,
onDoubleClick,
onBlankDoubleClick,
onContextMenu,
variant = "editor",
trailing,
@@ -397,7 +400,18 @@ export function Tabs({
);
return (
<div className={stripClass} ref={stripRef}>
<div
className={stripClass}
ref={stripRef}
onDoubleClick={
onBlankDoubleClick
? (e) => {
// Only the strip's own background counts: tabs, buttons and trailing content handle their own clicks.
if (e.target === e.currentTarget || e.target === scrollRef.current) onBlankDoubleClick();
}
: undefined
}
>
{vertical && trailing && <div className={styles.trailing}>{trailing}</div>}
<div
ref={scrollRef}
+11 -1
Переглянути файл
@@ -749,7 +749,17 @@ export function Tree<T>(props: TreeProps<T>) {
endSearch();
if (e.shiftKey) selectIndex(i, "range");
else if (e.metaKey || e.ctrlKey) selectIndex(i, "toggle");
else selectIndex(i);
else if (multiSelect && selected.size > 1 && selected.has(rows[i]!.key)) {
// Pressing a row of a multi-selection keeps the selection so a drag carries all of it;
// a release without moving (a plain click) narrows it to the row.
const x0 = e.clientX;
const y0 = e.clientY;
const up = (u: globalThis.MouseEvent) => {
window.removeEventListener("mouseup", up, true);
if (Math.abs(u.clientX - x0) < 4 && Math.abs(u.clientY - y0) < 4) selectIndex(i);
};
window.addEventListener("mouseup", up, true);
} else selectIndex(i);
};
const leadRow = leadIndex >= 0 ? rows[leadIndex] : undefined;
+25 -5
Переглянути файл
@@ -7,9 +7,11 @@ import { ask } from "./messages";
import { commands } from "@/platform/ipc";
const windowOpenRemote = vi.fn();
const windowGroupJoin = vi.fn();
const remoteWindow = vi.hoisted(() => ({ value: false }));
vi.mock("./messages", () => ({ ask: vi.fn() }));
vi.mock("@/platform/remote", () => ({
isRemoteWindow: () => false,
isRemoteWindow: () => remoteWindow.value,
connectRemote: vi.fn(),
}));
vi.mock("@/platform/ipc", () => ({
@@ -18,10 +20,12 @@ vi.mock("@/platform/ipc", () => ({
commands: {
settingsSet: vi.fn(async () => ({ general: { openProjectIn: "attach" } })),
windowOpenRemote: (...a: unknown[]) => windowOpenRemote(...a),
windowGroupJoin: (...a: unknown[]) => windowGroupJoin(...a),
},
}));
beforeEach(() => {
vi.clearAllMocks();
remoteWindow.value = false;
useProject.setState({
project: { root: "/a", name: "A", settings: {}, trusted: true, isGit: false },
settings: {},
@@ -40,14 +44,20 @@ it("offers attach for this open without remembering it", async () => {
expect(await chooseProjectWindow("C")).toBe(button);
expect(ask).toHaveBeenCalledTimes(2);
});
it("does not attach without a project or when opening a remote project", async () => {
it("offers a new tab but no attach for a remote project or from a remote window", async () => {
useProject.setState({
settings: { general: { openProjectIn: "attach" } } as never,
});
vi.mocked(ask).mockResolvedValue({ button: "cancel", checked: false });
expect(await chooseProjectWindow("remote", false)).toBeNull();
expect(vi.mocked(ask).mock.calls[0]![0].buttons.map((b) => b.id)).toEqual(["cancel", "new", "same"]);
useProject.setState({ project: null });
expect(vi.mocked(ask).mock.calls[0]![0].buttons.map((b) => b.id)).toEqual(["cancel", "tab", "new", "same"]);
remoteWindow.value = true;
expect(await chooseProjectWindow("B")).toBeNull();
expect(vi.mocked(ask).mock.calls[1]![0].buttons.map((b) => b.id)).toEqual(["cancel", "tab", "new", "same"]);
useProject.setState({ project: null, lightEdit: true });
expect(await chooseProjectWindow("B")).toBeNull();
expect(vi.mocked(ask).mock.calls[2]![0].buttons.map((b) => b.id)).toEqual(["cancel", "new", "same"]);
useProject.setState({ project: null, lightEdit: false });
expect(await chooseProjectWindow("B")).toBe("same");
});
@@ -65,7 +75,7 @@ it("opens a project tab by policy, or a new window when this one can't take one"
useProject.setState({ settings: { general: { openProjectIn: "tab" } } } as never);
expect(openPolicy()).toBe("tab");
expect(await chooseProjectWindow("B")).toBe("tab");
expect(await chooseProjectWindow("remote", false)).toBe("new");
expect(await chooseProjectWindow("remote", false)).toBe("tab");
useProject.setState({ project: null, lightEdit: true });
expect(await chooseProjectWindow("B")).toBe("new");
expect(ask).not.toHaveBeenCalled();
@@ -91,6 +101,16 @@ describe("a recent project opened with a modifier key", () => {
usePlatform.setState({ os });
});
it("opens a remote project as a project tab of this window", async () => {
windowOpenRemote.mockResolvedValueOnce({ kind: "current" }).mockResolvedValueOnce({ kind: "opened", label: "w2" });
const here = vi.fn(async () => {});
useProject.setState({ settings: { general: { openProjectIn: "tab" } } as never });
expect(await openRemoteProject(target, "/home/me/app", here)).toBe(true);
expect(windowOpenRemote).toHaveBeenLastCalledWith(target, "/home/me/app", true);
expect(windowGroupJoin).toHaveBeenCalledWith("w2");
expect(here).not.toHaveBeenCalled();
});
it("opens a remote project in that window without asking", async () => {
windowOpenRemote.mockResolvedValue({ kind: "opened" });
const here = vi.fn(async () => {});
+18 -16
Переглянути файл
@@ -40,26 +40,26 @@ export async function chooseProjectWindow(
): Promise<"new" | "same" | "attach" | "tab" | null> {
const { project, lightEdit } = useProject.getState();
if (!project && !lightEdit) return "same";
// Both ways of keeping this window's project: a workspace folder, or a project tab of this window.
const canAdd = allowAttach && !!project && !isRemoteWindow();
// Attach adds a local folder to this local window's workspace; a project tab is a window of its
// own joined to this one's group, so it takes remote projects and remote windows too.
const canTab = !!project;
const canAttach = allowAttach && canTab && !isRemoteWindow();
const mode = openPolicy();
// A project tab needs this window's project beside it; without one, a new window is the closest.
if (mode === "tab") return canAdd ? "tab" : "new";
if (mode === "tab") return canTab ? "tab" : "new";
if (mode !== "ask") return mode;
const r = await ask({
title: t("app.window.askTitle"),
width: canAdd ? 640 : undefined,
body: canAdd
width: canAttach ? 640 : undefined,
body: canAttach
? tx`Projects can be opened in a new window, replace the current project, be attached to the already opened projects, or open as a new tab of this window.\nHow would you like to open "${name}"?`
: t("app.window.askBody", { name }),
: canTab
? tx`Projects can be opened in a new window, replace the current project, or open as a new tab of this window.\nHow would you like to open "${name}"?`
: t("app.window.askBody", { name }),
buttons: [
{ id: "cancel", label: t("common.cancel") },
...(canAdd
? [
{ id: "attach", label: t("app.window.askAttach") },
{ id: "tab", label: tx`New Tab` },
]
: []),
...(canAttach ? [{ id: "attach", label: t("app.window.askAttach") }] : []),
...(canTab ? [{ id: "tab", label: tx`New Tab` }] : []),
{ id: "new", label: t("app.window.askNew") },
{ id: "same", label: t("app.window.askThis"), primary: true },
],
@@ -81,8 +81,8 @@ export async function chooseProjectWindow(
/**
* Opens folder `path` of `target` (an SSH host or a WSL distribution): focuses the
* window that has it, else opens it in a new window or (`here`) this one per
* "Open project in", or where `override` says. `false`: cancelled.
* window that has it, else opens it in a new window, a project tab of this window or
* (`here`) this one per "Open project in", or where `override` says. `false`: cancelled.
*/
export async function openRemoteProject(
target: RemoteTarget,
@@ -93,8 +93,10 @@ export async function openRemoteProject(
if ((await call(commands.windowOpenRemote(target, path, false))).kind === "focused") return true;
const mode = override ?? (await chooseProjectWindow(path.replace(/\/+$/, "").split("/").pop() || path, false));
if (!mode) return false;
if (mode === "new") {
await call(commands.windowOpenRemote(target, path, true));
if (mode === "new" || mode === "tab") {
const outcome = await call(commands.windowOpenRemote(target, path, true));
// As a local project tab: the window holding the project, new or focused, joins this one's group.
if (mode === "tab" && outcome.kind !== "current") await call(commands.windowGroupJoin(outcome.label));
return true;
}
// The remote host's project doesn't take this window's untitled buffers.