дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 09:11:10 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
4304d10021 | ||
|
|
e2b1a2d732 | ||
|
|
db5a306450 | ||
|
|
bad9429e79 | ||
|
|
c942374f8a | ||
|
|
611b27b974 | ||
|
|
71f948cc9f | ||
|
|
79a750362a | ||
|
|
f1c0d098ad | ||
|
|
d9c1a9ff22 | ||
|
|
e86011fc87 | ||
|
|
f80dd0aa49 | ||
|
|
832c397e0b | ||
|
|
0f91aac0d4 | ||
|
|
d4b2ade24d | ||
|
|
4b7870ba2a |
No files matched your search
@@ -325,6 +325,20 @@ pub fn migrate(data: &Path, local: &Path) {
|
||||
if cfg!(target_os = "windows") && data != local {
|
||||
migrate_entries(data, local);
|
||||
}
|
||||
if cfg!(target_os = "windows") {
|
||||
relative_tool_shims(&local.join("tools"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrappers written before they named their tool relative to themselves hold its absolute
|
||||
/// path, which cmd.exe can't find through a non-ASCII user directory (#3338).
|
||||
fn relative_tool_shims(tools: &Path) {
|
||||
let Ok(entries) = fs::read_dir(tools) else { return };
|
||||
for dir in entries.flatten().map(|e| e.path()).filter(|p| p.is_dir()) {
|
||||
if let Err(error) = relocate_shims(&dir, &dir) {
|
||||
tracing::warn!(%error, ?dir, "cannot make the tool's wrappers relative");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn migrate_entries(data: &Path, local: &Path) {
|
||||
@@ -651,6 +665,22 @@ mod tests {
|
||||
fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_tool_wrappers_become_relative() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let tools = tmp.path().join("tools");
|
||||
let tool = tools.join("taplo");
|
||||
fs::create_dir_all(tool.join("bin")).unwrap();
|
||||
let shim = tool.join("bin/taplo.cmd");
|
||||
fs::write(&shim, format!("@echo off\r\n\"{}\\taplo.exe\" %*\r\n", tool.display())).unwrap();
|
||||
// A wrapper the user re-saved in another encoding is left alone.
|
||||
fs::create_dir_all(tools.join("other/bin")).unwrap();
|
||||
fs::write(tools.join("other/bin/x.cmd"), b"@echo off\r\n\"C:\\\xd5\xc5\" %*\r\n").unwrap();
|
||||
relative_tool_shims(&tools);
|
||||
assert_eq!(fs::read_to_string(&shim).unwrap(), "@echo off\r\n\"%~dp0..\\taplo.exe\" %*\r\n");
|
||||
relative_tool_shims(&tmp.path().join("missing"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrappers_accept_mixed_separators_without_rewriting_neighbor_paths() {
|
||||
let text = "@echo off\r\n\"C:\\old\\tools/demo\\payload.exe\" \"C:\\old\\tools/demo-other\\x\" %*\r\n";
|
||||
|
||||
@@ -207,3 +207,22 @@ async fn change_commit_branch_stash_and_merge_a_conflict() {
|
||||
assert!(f.status().await.is_empty());
|
||||
assert_eq!(std::fs::read_to_string(&lib_path).unwrap(), resolved);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn checkout_reports_a_branch_held_by_another_worktree() {
|
||||
let f = Flow::new("rust-app").await;
|
||||
let linked = f._tmp.path().join("linked");
|
||||
git(&f.root, &["worktree", "add", "-q", "-b", "topic", linked.to_str().unwrap()]);
|
||||
|
||||
let outcome = ops::vcs::vcs_checkout(&f.host, WINDOW, None, "topic".into(), false, None).await.unwrap();
|
||||
assert_eq!(
|
||||
outcome,
|
||||
ide_vcs::CheckoutOutcome::CheckedOutInWorktree {
|
||||
branch: "topic".into(),
|
||||
path: dunce::canonicalize(&linked).unwrap()
|
||||
}
|
||||
);
|
||||
// Nothing changed: the project is still on main.
|
||||
let branches = ops::vcs::vcs_branches(&f.host, WINDOW, None).await.unwrap();
|
||||
assert!(branches.iter().any(|b| b.name == "main" && b.current), "{branches:?}");
|
||||
}
|
||||
@@ -331,8 +331,8 @@ pub fn env_wrapper(bin_dir: &Path, command: &str, target: &Path, env: &[(&str, &
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let link = bin_dir.join(format!("{command}.cmd"));
|
||||
let vars: String = env.iter().map(|(k, v)| format!("set \"{k}={}\"\r\n", v.display())).collect();
|
||||
fs::write(&link, format!("@echo off\r\nsetlocal\r\n{vars}\"{}\" %*\r\n", target.display()))?;
|
||||
let vars: String = env.iter().map(|(k, v)| format!("set \"{k}={}\"\r\n", cmd_path(bin_dir, v))).collect();
|
||||
fs::write(&link, format!("@echo off\r\nsetlocal\r\n{vars}\"{}\" %*\r\n", cmd_path(bin_dir, target)))?;
|
||||
Ok(link)
|
||||
}
|
||||
}
|
||||
@@ -357,11 +357,25 @@ pub fn link_executable(bin_dir: &Path, command: &str, target: &Path) -> IdeResul
|
||||
{
|
||||
let link = bin_dir.join(format!("{command}.cmd"));
|
||||
let runner = if target.extension().is_some_and(|e| e == "js") { "node " } else { "" };
|
||||
fs::write(&link, format!("@echo off\r\n{runner}\"{}\" %*\r\n", target.display()))?;
|
||||
fs::write(&link, format!("@echo off\r\n{runner}\"{}\" %*\r\n", cmd_path(bin_dir, target)))?;
|
||||
Ok(link)
|
||||
}
|
||||
}
|
||||
|
||||
/// `path` as a `.cmd` shim in `bin_dir` names it: relative to the shim (`%~dp0..\…`) when it
|
||||
/// is in the tool's own directory. cmd.exe reads a batch file in the console's code page, so
|
||||
/// an absolute path through a non-ASCII user directory, written as UTF-8, isn't found (#3338).
|
||||
#[cfg_attr(unix, allow(dead_code))]
|
||||
fn cmd_path(bin_dir: &Path, path: &Path) -> String {
|
||||
match bin_dir.parent().and_then(|tool| path.strip_prefix(tool).ok()) {
|
||||
Some(rest) => {
|
||||
let rest: Vec<_> = rest.components().map(|c| c.as_os_str().to_string_lossy()).collect();
|
||||
format!("%~dp0..\\{}", rest.join("\\"))
|
||||
}
|
||||
None => path.display().to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -743,6 +757,17 @@ mod tests {
|
||||
assert!(found.ends_with("server/com.microsoft.java.debug.plugin-0.53.2.jar"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_shims_name_the_tool_relative_to_themselves() {
|
||||
let tool = Path::new("/Users/张三/AppData/Local/ai.l0ng.openidea/tools/taplo");
|
||||
let bin = tool.join("bin");
|
||||
assert_eq!(cmd_path(&bin, &tool.join("taplo.exe")), "%~dp0..\\taplo.exe");
|
||||
assert_eq!(cmd_path(&bin, &tool.join("gems/bin/solargraph")), "%~dp0..\\gems\\bin\\solargraph");
|
||||
// Outside the tool's directory (a system SDK) stays absolute.
|
||||
let sdk = Path::new("/usr/local/share/dotnet");
|
||||
assert_eq!(cmd_path(&bin, sdk), sdk.display().to_string());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn wrapper_runs_target() {
|
||||
|
||||
@@ -496,6 +496,9 @@ pub struct CheckoutOptions {
|
||||
/// Required when checking out a remote branch whose local namesake is ahead of it.
|
||||
#[serde(default)]
|
||||
pub diverged: Option<DivergedLocal>,
|
||||
/// Check the branch out even though another worktree has it checked out.
|
||||
#[serde(default)]
|
||||
pub ignore_other_worktrees: bool,
|
||||
}
|
||||
|
||||
/// Result of [`Repo::checkout_with`]; the non-`Done` variants other than `Conflicts`
|
||||
@@ -522,6 +525,12 @@ pub enum CheckoutOutcome {
|
||||
Conflicts {
|
||||
files: Vec<String>,
|
||||
},
|
||||
/// Git refused: `branch` is checked out in the linked worktree at `path`. Nothing
|
||||
/// changed; the branch can be worked on there.
|
||||
CheckedOutInWorktree {
|
||||
branch: String,
|
||||
path: PathBuf,
|
||||
},
|
||||
}
|
||||
|
||||
/// HEAD before and after a history rewrite, for its Undo.
|
||||
|
||||
@@ -765,6 +765,18 @@ fn overwritten_untracked(stderr: &str) -> Option<Vec<String>> {
|
||||
listed_files(stderr, "untracked working tree files would be")
|
||||
}
|
||||
|
||||
/// The branch git refused to check out or update because another worktree has it, from
|
||||
/// its error message: a switch says `'<branch>' is already used by worktree at '<path>'`,
|
||||
/// a forced update says `cannot force update the branch '<branch>' used by worktree at
|
||||
/// '<path>'`; git before 2.42 says `'<branch>' is already checked out at '<path>'`.
|
||||
fn branch_of_other_worktree(stderr: &str) -> Option<(String, String)> {
|
||||
const MARKERS: [&str; 3] =
|
||||
["' is already used by worktree at '", "' used by worktree at '", "' is already checked out at '"];
|
||||
let (before, path) = stderr.lines().find_map(|l| MARKERS.iter().find_map(|m| l.split_once(m)))?;
|
||||
let branch = before.rsplit('\'').next()?.to_string();
|
||||
Some((branch, path.strip_suffix('\'').unwrap_or(path).to_string()))
|
||||
}
|
||||
|
||||
fn listed_files(stderr: &str, header: &str) -> Option<Vec<String>> {
|
||||
let mut lines = stderr.lines().skip_while(|l| !l.contains(header));
|
||||
lines.next()?;
|
||||
@@ -805,12 +817,18 @@ pub(crate) fn checkout_with(
|
||||
if options.mode == CheckoutMode::Force {
|
||||
args.push("--discard-changes".into());
|
||||
}
|
||||
if options.ignore_other_worktrees {
|
||||
args.push("--ignore-other-worktrees".into());
|
||||
}
|
||||
let argv: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
let out = cli::run_raw(r.root(), &argv, None)?;
|
||||
if out.code == Some(0) {
|
||||
return Ok(CheckoutOutcome::Done);
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
if let Some((branch, path)) = branch_of_other_worktree(&stderr) {
|
||||
return Ok(CheckoutOutcome::CheckedOutInWorktree { branch, path: path.into() });
|
||||
}
|
||||
if let Some(files) = overwritten_untracked(&stderr) {
|
||||
return Ok(CheckoutOutcome::UntrackedFiles { files });
|
||||
}
|
||||
@@ -893,7 +911,14 @@ pub(crate) fn create_branch(
|
||||
args.extend(["--", name]);
|
||||
}
|
||||
args.extend(start);
|
||||
run(r.root(), &args, None).map(|_| ())
|
||||
let out = cli::run_raw(r.root(), &args, None)?;
|
||||
if out.code == Some(0) {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some((branch, path)) = branch_of_other_worktree(&String::from_utf8_lossy(&out.stderr)) {
|
||||
return Err(IdeError::invalid(format!("branch '{branch}' is already checked out in worktree at '{path}'")));
|
||||
}
|
||||
Err(cli::failure(&args, &out.stderr, &out.stdout, out.code))
|
||||
}
|
||||
|
||||
/// Whether `start` is a remote-tracking branch with another name than the new branch
|
||||
@@ -1479,7 +1504,22 @@ fn decode_diff(bytes: &[u8], encoding: TextEncoding) -> String {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::append_revision;
|
||||
use super::{append_revision, branch_of_other_worktree};
|
||||
|
||||
#[test]
|
||||
fn the_worktree_holding_a_branch_is_read_from_each_git_wording() {
|
||||
let held = |b: &str, p: &str| Some((b.to_string(), p.to_string()));
|
||||
assert_eq!(
|
||||
branch_of_other_worktree("fatal: 'topic' is already used by worktree at '/w/t'\n"),
|
||||
held("topic", "/w/t")
|
||||
);
|
||||
assert_eq!(
|
||||
branch_of_other_worktree("fatal: cannot force update the branch 'topic' used by worktree at '/w/t'"),
|
||||
held("topic", "/w/t")
|
||||
);
|
||||
assert_eq!(branch_of_other_worktree("fatal: 'a/b' is already checked out at '/w/t'"), held("a/b", "/w/t"));
|
||||
assert_eq!(branch_of_other_worktree("fatal: invalid reference: x"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_revision_is_appended_once_keeping_the_list() {
|
||||
|
||||
@@ -1070,7 +1070,7 @@ fn smart_and_force_checkout_with_local_changes_in_the_way() {
|
||||
fx.commit_all("other edit");
|
||||
fx.git(&["checkout", "-q", "main"]);
|
||||
let repo = fx.repo();
|
||||
let opts = |mode| CheckoutOptions { mode, diverged: None };
|
||||
let opts = |mode| CheckoutOptions { mode, ..Default::default() };
|
||||
|
||||
// A non-conflicting local edit to a file the switch rewrites.
|
||||
fx.write("f.txt", "1\n2\n3\n4\nlocal\n");
|
||||
@@ -1110,6 +1110,50 @@ fn smart_and_force_checkout_with_local_changes_in_the_way() {
|
||||
assert_eq!(fx.read("untouched.txt"), "new\n", "untracked files survive");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkout_of_a_branch_held_by_another_worktree_reports_it_and_changes_nothing() {
|
||||
let fx = Fixture::new();
|
||||
fx.write("f.txt", "1\n");
|
||||
fx.commit_all("base");
|
||||
let linked = fx._tmp.path().join("linked");
|
||||
fx.git(&["worktree", "add", "-q", "-b", "topic", linked.to_str().unwrap()]);
|
||||
let repo = fx.repo();
|
||||
let none = CheckoutOptions::default();
|
||||
let linked_path = std::fs::canonicalize(&linked).unwrap();
|
||||
|
||||
// From the main worktree, the branch the linked worktree has checked out.
|
||||
let outcome = repo.checkout_with("topic", false, &none).unwrap();
|
||||
assert_eq!(outcome, CheckoutOutcome::CheckedOutInWorktree { branch: "topic".into(), path: linked_path.clone() });
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"), "nothing changed");
|
||||
|
||||
// With local changes in the way too: reported before any Smart Checkout stash.
|
||||
fx.write("f.txt", "changed\n");
|
||||
let smart = CheckoutOptions { mode: CheckoutMode::Smart, ..Default::default() };
|
||||
let outcome = repo.checkout_with("topic", false, &smart).unwrap();
|
||||
assert_eq!(outcome, CheckoutOutcome::CheckedOutInWorktree { branch: "topic".into(), path: linked_path.clone() });
|
||||
assert_eq!(fx.read("f.txt"), "changed\n", "local changes untouched");
|
||||
assert!(repo.stashes().unwrap().is_empty());
|
||||
fx.git(&["reset", "-q", "--hard"]);
|
||||
|
||||
// The same refusal from the linked worktree, for the main worktree's branch.
|
||||
let linked_repo = Repo::discover(&linked).unwrap().unwrap();
|
||||
linked_repo.set_execution_allowed(true);
|
||||
let outcome = linked_repo.checkout_with("main", false, &none).unwrap();
|
||||
let main_path = std::fs::canonicalize(&fx.dir).unwrap();
|
||||
assert_eq!(outcome, CheckoutOutcome::CheckedOutInWorktree { branch: "main".into(), path: main_path });
|
||||
assert_eq!(linked_repo.branch_info().unwrap().head.as_deref(), Some("topic"));
|
||||
|
||||
// Overwriting such a branch (New Branch with Checkout) names the worktree, not raw stderr.
|
||||
let error = repo.create_branch_with_overwrite("topic", Some("main"), true, true).unwrap_err();
|
||||
assert!(error.message.contains("branch 'topic' is already checked out in worktree"), "{error}");
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
|
||||
|
||||
// Checkout Anyway: both worktrees then have the branch.
|
||||
let anyway = CheckoutOptions { ignore_other_worktrees: true, ..Default::default() };
|
||||
assert_eq!(repo.checkout_with("topic", false, &anyway).unwrap(), CheckoutOutcome::Done);
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("topic"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkout_remote_branch_with_existing_local_namesake() {
|
||||
let (fx, bare) = with_remote();
|
||||
@@ -1939,7 +1983,7 @@ fn smart_checkout_keeps_staged_changes_staged() {
|
||||
fx.write("f.txt", "1\n2\n3\n4\nlocal\n");
|
||||
fx.write("s.txt", "staged\n");
|
||||
fx.git(&["add", "s.txt"]);
|
||||
let opts = CheckoutOptions { mode: CheckoutMode::Smart, diverged: None };
|
||||
let opts = CheckoutOptions { mode: CheckoutMode::Smart, ..Default::default() };
|
||||
assert_eq!(repo.checkout_with("other", false, &opts).unwrap(), CheckoutOutcome::Done);
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("other"));
|
||||
assert_eq!(fx.read("f.txt"), "1\nother\n3\n4\nlocal\n");
|
||||
@@ -1960,7 +2004,7 @@ fn checkout_reports_untracked_files_it_would_overwrite() {
|
||||
fx.write("dir/new.txt", "mine\n");
|
||||
let repo = fx.repo();
|
||||
for mode in [CheckoutMode::Normal, CheckoutMode::Smart] {
|
||||
let opts = CheckoutOptions { mode, diverged: None };
|
||||
let opts = CheckoutOptions { mode, ..Default::default() };
|
||||
let outcome = repo.checkout_with("other", false, &opts).unwrap();
|
||||
assert_eq!(outcome, CheckoutOutcome::UntrackedFiles { files: vec!["dir/new.txt".into()] });
|
||||
assert_eq!(repo.branch_info().unwrap().head.as_deref(), Some("main"));
|
||||
|
||||
@@ -372,20 +372,25 @@ test("keeps chat history readable and selections free of timestamps and status l
|
||||
expect(narrow.reply).toBeLessThanOrEqual((narrow.width - narrow.padding) * 0.96);
|
||||
});
|
||||
|
||||
test("fits conversation stream, composer, question card and user bubbles to window width when enabled", async ({
|
||||
test("fits conversation stream, composer, question card and off-screen rows live from Settings without restarting", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1800, height: 1000 });
|
||||
await page.setViewportSize({ width: 1800, height: 900 });
|
||||
await openReply(page, "Initial reply");
|
||||
await page.evaluate(async (task) => {
|
||||
const storePath = "/src/features/agents/store.ts";
|
||||
const store = await import(storePath);
|
||||
const filler = Array.from({ length: 8 }, (_, i) => ({
|
||||
type: "agent" as const,
|
||||
text: `Earlier paragraph ${i + 1}: ` + "wrapped words across the column ".repeat(35),
|
||||
}));
|
||||
store.useAgents.setState({
|
||||
tasks: new Map([[task.id, { ...task, status: "needsInput" as const }]]),
|
||||
entries: new Map([
|
||||
[
|
||||
task.id,
|
||||
[
|
||||
...filler,
|
||||
{
|
||||
type: "user",
|
||||
text: "Long prompt ".repeat(40),
|
||||
@@ -419,11 +424,15 @@ test("fits conversation stream, composer, question card and user bubbles to wind
|
||||
|
||||
const stream = page.locator("[class*='_stream_']:visible");
|
||||
await expect(page.getByRole("form", { name: "Choose layout" })).toBeVisible();
|
||||
await expect(stream.locator("[data-measured]").first()).toBeAttached();
|
||||
|
||||
const measure = () =>
|
||||
stream.evaluate((root) => {
|
||||
const conversation = root.closest<HTMLElement>("[class*='_conversation_']")!;
|
||||
const column = root.querySelector<HTMLElement>("[class*='_agentMessage_']")!.getBoundingClientRect();
|
||||
const rows = [...root.querySelectorAll<HTMLElement>("[class*='_conversationRow_']")];
|
||||
const column = [...root.querySelectorAll<HTMLElement>("[class*='_agentMessage_']")]
|
||||
.at(-1)!
|
||||
.getBoundingClientRect();
|
||||
const bubble = root.querySelector<HTMLElement>("[class*='_user_']")!.getBoundingClientRect();
|
||||
const composer = conversation.querySelector<HTMLElement>("[class*='_composerArea_']")!.getBoundingClientRect();
|
||||
const question = conversation.querySelector<HTMLElement>("[class*='_questionCard_']")!.getBoundingClientRect();
|
||||
@@ -436,6 +445,8 @@ test("fits conversation stream, composer, question card and user bubbles to wind
|
||||
bubbleWidth: bubble.width,
|
||||
composerWidth: composer.width,
|
||||
questionWidth: question.width,
|
||||
offscreenRowHeight: rows[0]!.getBoundingClientRect().height,
|
||||
scrollHeight: root.scrollHeight,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -446,14 +457,18 @@ test("fits conversation stream, composer, question card and user bubbles to wind
|
||||
expect(Math.abs(capped.composerWidth - 924)).toBeLessThan(1);
|
||||
expect(Math.abs(capped.questionWidth - 900)).toBeLessThan(1);
|
||||
|
||||
// Toggle on through Settings › Agents › Chat › Apply and verify live re-layout including off-screen rows.
|
||||
await page.evaluate(async () => {
|
||||
const projectPath = "/src/platform/project.ts";
|
||||
const { useProject } = await import(projectPath);
|
||||
const settings = useProject.getState().settings;
|
||||
useProject.setState({
|
||||
settings: { ...settings, agents: { ...settings?.agents, fitWindowWidth: true } } as never,
|
||||
});
|
||||
const actionsPath = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(actionsPath);
|
||||
await executeAction("file.settings", "agents.chat");
|
||||
});
|
||||
const dialog = page.getByRole("dialog", { name: "Settings" });
|
||||
const toggle = dialog.getByRole("checkbox", { name: "Fit conversation to the window width" });
|
||||
await expect(toggle).not.toBeChecked();
|
||||
await toggle.click();
|
||||
await dialog.getByRole("button", { name: "Apply", exact: true }).click();
|
||||
await expect(stream.locator("[data-measured]").first()).toBeAttached();
|
||||
|
||||
const fitted = await measure();
|
||||
expect(Math.abs(fitted.columnWidth - fitted.streamInnerWidth)).toBeLessThan(1);
|
||||
@@ -461,6 +476,18 @@ test("fits conversation stream, composer, question card and user bubbles to wind
|
||||
expect(Math.abs(fitted.bubbleWidth - fitted.streamInnerWidth * 0.8)).toBeLessThan(1);
|
||||
expect(Math.abs(fitted.composerWidth - fitted.conversationWidth)).toBeLessThan(1);
|
||||
expect(Math.abs(fitted.questionWidth - fitted.streamInnerWidth)).toBeLessThan(1);
|
||||
expect(fitted.offscreenRowHeight).toBeLessThan(capped.offscreenRowHeight);
|
||||
expect(fitted.scrollHeight).toBeLessThan(capped.scrollHeight);
|
||||
|
||||
// Toggle back off and click OK: dialog closes and conversation returns to the 900px column live.
|
||||
await toggle.click();
|
||||
await dialog.getByRole("button", { name: "OK", exact: true }).click();
|
||||
await expect(dialog).toBeHidden();
|
||||
await expect(stream.locator("[data-measured]").first()).toBeAttached();
|
||||
|
||||
const restored = await measure();
|
||||
expect(Math.abs(restored.columnWidth - 900)).toBeLessThan(1);
|
||||
expect(Math.abs(restored.offscreenRowHeight - capped.offscreenRowHeight)).toBeLessThan(1);
|
||||
});
|
||||
|
||||
test("keeps hover actions reachable when the pointer leaves the message body", async ({ page, context }) => {
|
||||
@@ -668,3 +695,69 @@ test("draws a diagram without reaching the hosts its configuration names", async
|
||||
);
|
||||
expect(asked).toEqual(["/after"]);
|
||||
});
|
||||
|
||||
test("Find in Conversation skips user-select:none summaries and closed <details> until stepped into", async ({
|
||||
page,
|
||||
}) => {
|
||||
await openReply(page, "Confirmed—PR is merged.");
|
||||
await page.evaluate(async (task) => {
|
||||
const path = "/src/features/agents/store.ts";
|
||||
const store = await import(path);
|
||||
store.useAgents.setState({
|
||||
entries: new Map([
|
||||
[
|
||||
task.id,
|
||||
[
|
||||
{
|
||||
type: "thought",
|
||||
text: "**Confirming Active Watch Shell**\n\nCheck background shell before rebasing.",
|
||||
},
|
||||
{
|
||||
type: "tool",
|
||||
id: "t1",
|
||||
title: "stop_bash",
|
||||
kind: "other",
|
||||
status: "completed",
|
||||
locations: [],
|
||||
output: "<command with id: 60 had already stopped>",
|
||||
diffs: [],
|
||||
},
|
||||
{ type: "agent", text: "Confirmed—PR is merged." },
|
||||
],
|
||||
],
|
||||
]),
|
||||
});
|
||||
store.openTaskInEditorLocation(task.id);
|
||||
}, TASK);
|
||||
|
||||
const stream = page.locator("[class*='_stream_']:visible");
|
||||
const runSummary = stream.locator("details[class*='_processRun_'] > summary");
|
||||
await runSummary.click();
|
||||
await expect(stream.getByText("stop_bash")).toBeVisible();
|
||||
|
||||
await stream.focus();
|
||||
await page.keyboard.press("Meta+f");
|
||||
const findBox = page.getByLabel("Find in Conversation");
|
||||
await findBox.fill("confirm");
|
||||
|
||||
// 2 matches total (1 inside collapsed thought body, 1 in visible reply); unselectable <summary> is excluded.
|
||||
await expect(page.locator("[class*='_findCount_']")).toHaveText("1/2");
|
||||
const initialHighlights = await page.evaluate(() => ({
|
||||
find: [...(CSS.highlights.get("agent-find") ?? [])].map((r) => (r as Range).startContainer.textContent),
|
||||
current: [...(CSS.highlights.get("agent-find-current") ?? [])].map((r) => (r as Range).startContainer.textContent),
|
||||
}));
|
||||
expect(initialHighlights.find).toEqual(["Confirmed—PR is merged."]);
|
||||
expect(initialHighlights.current).toEqual([]);
|
||||
|
||||
// Stepping to match 2/2 opens the collapsed thought <details> and highlights it.
|
||||
await findBox.press("Enter");
|
||||
await expect(page.locator("[class*='_findCount_']")).toHaveText("2/2");
|
||||
await findBox.press("Enter");
|
||||
await expect(page.locator("[class*='_findCount_']")).toHaveText("1/2");
|
||||
const expandedHighlights = await page.evaluate(() => ({
|
||||
thoughtOpen: document.querySelector<HTMLDetailsElement>("details[class*='_thought_']")?.open,
|
||||
findCount: CSS.highlights.get("agent-find")?.size ?? 0,
|
||||
currentCount: CSS.highlights.get("agent-find-current")?.size ?? 0,
|
||||
}));
|
||||
expect(expandedHighlights).toEqual({ thoughtOpen: true, findCount: 2, currentCount: 1 });
|
||||
});
|
||||
@@ -98,6 +98,58 @@ test("completion lists the server's items and inserts the chosen one", async ({
|
||||
expect((await ipcCalls(page, "lsp_completion")).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("typing closes an open documentation tooltip", async ({ workbench: page }) => {
|
||||
const editor = await openSample(page);
|
||||
await page.evaluate(() => {
|
||||
const item = (label: string) => ({
|
||||
label,
|
||||
labelDetail: "()",
|
||||
detail: "Unit",
|
||||
kind: "method",
|
||||
documentation: { kind: "markdown", value: `Docs for **${label}**.` },
|
||||
sortText: null,
|
||||
filterText: null,
|
||||
preselect: false,
|
||||
deprecated: false,
|
||||
insertText: `${label}()`,
|
||||
isSnippet: false,
|
||||
replaceRange: null,
|
||||
replaceRangeTab: null,
|
||||
additionalEdits: [],
|
||||
commitCharacters: [],
|
||||
command: null,
|
||||
data: null,
|
||||
server: 1,
|
||||
});
|
||||
window.__ipc.handlers.lsp_completion = () => ({
|
||||
isIncomplete: false,
|
||||
items: [item("service"), item("serviceName"), item("setUp")],
|
||||
});
|
||||
window.__ipc.handlers.lsp_hover = () => ({
|
||||
contents: { kind: "markdown", value: "Docs for **service**." },
|
||||
range: null,
|
||||
});
|
||||
});
|
||||
const geometry = await editor.locator(".cm-content").evaluate(async (content) => {
|
||||
const viewModule = "/node_modules/.vite/deps/@codemirror_view.js";
|
||||
const { EditorView } = await import(/* @vite-ignore */ viewModule);
|
||||
const view = EditorView.findFromDOM(content as HTMLElement)!;
|
||||
const find = view.state.doc.toString().indexOf("find");
|
||||
if (find < 0 || !view.coordsAtPos(find)) throw new Error('the fixture has no visible "find"');
|
||||
const word = view.coordsAtPos(find)!;
|
||||
view.dispatch({ selection: { anchor: find + 5 } });
|
||||
view.focus();
|
||||
return { wordX: word.left + 2, wordY: (word.top + word.bottom) / 2 };
|
||||
});
|
||||
await page.mouse.move(geometry.wordX, geometry.wordY);
|
||||
const tooltip = page.locator(".cm-tooltip-hover");
|
||||
await expect(tooltip).toBeVisible();
|
||||
await page.keyboard.type("se");
|
||||
const popup = page.locator(".cm-tooltip-autocomplete");
|
||||
await expect(popup.getByText("service", { exact: true })).toBeVisible();
|
||||
await expect(tooltip).toHaveCount(0);
|
||||
});
|
||||
|
||||
for (const key of ["Enter", "Tab"]) {
|
||||
for (const prefix of ["", "v"]) {
|
||||
test(`${key} leaves the caret after a field snippet at root.${prefix}`, async ({ workbench: page }, info) => {
|
||||
|
||||
@@ -174,12 +174,36 @@ test("⌘R replaces every match in the file", async ({ workbench: page }) => {
|
||||
await expect(editor.locator(".cm-line", { hasText: "OrderDto" })).toHaveCount(2);
|
||||
});
|
||||
|
||||
test("Markdown preview highlights ⌘F matches and selected word occurrences", async ({ workbench: page }) => {
|
||||
test("Markdown preview highlights ⌘F matches, selected words and scales diagrams with font zoom", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.evaluate(async () => {
|
||||
const svg =
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 96" width="320" height="96"><!-- svg-source:excalidraw --><rect width="320" height="96"/></svg>';
|
||||
const url = `data:image/svg+xml;base64,${btoa(svg)}`;
|
||||
const routeModule = "/src/platform/tauriCore.ts";
|
||||
const { setInvokeRoute } = await import(/* @vite-ignore */ routeModule);
|
||||
setInvokeRoute((cmd: string) => (cmd === "fs_read_image" ? Promise.resolve(url) : null));
|
||||
});
|
||||
|
||||
const editor = await openFromTree(page, "README.md");
|
||||
const content = editor.locator(".cm-content");
|
||||
await content.click();
|
||||
await page.keyboard.press("Meta+a");
|
||||
await page.keyboard.insertText("# Order Service\n\nManage **Order** items and `Order` status.\n");
|
||||
await page.keyboard.insertText(
|
||||
[
|
||||
"# Order Service",
|
||||
"",
|
||||
"Manage **Order** items and `Order` status.",
|
||||
"",
|
||||
"```mermaid",
|
||||
"flowchart LR",
|
||||
" A --> B",
|
||||
"```",
|
||||
"",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
const preview = page.getByRole("document", { name: "Markdown preview" });
|
||||
await expect(preview).toContainText("Manage Order items");
|
||||
@@ -209,6 +233,44 @@ test("Markdown preview highlights ⌘F matches and selected word occurrences", a
|
||||
})),
|
||||
)
|
||||
.toEqual({ current: ["Order"], other: ["Order", "Order"] });
|
||||
|
||||
const mermaidSvg = preview.locator(".mermaid-output svg");
|
||||
const excalidrawImg = preview.locator('img[alt="Diagram"]');
|
||||
await expect(mermaidSvg).toBeVisible();
|
||||
await expect(excalidrawImg).toHaveAttribute("src", /^data:image\/svg\+xml/);
|
||||
|
||||
const widths = async () => ({
|
||||
mermaid: (await mermaidSvg.boundingBox())!.width,
|
||||
excalidraw: (await excalidrawImg.boundingBox())!.width,
|
||||
});
|
||||
const base = await widths();
|
||||
expect(base.mermaid).toBeGreaterThan(50);
|
||||
expect(base.excalidraw).toBeCloseTo(320, 0);
|
||||
|
||||
const runAction = (id: string, times = 1) =>
|
||||
page.evaluate(
|
||||
async ({ id, times }) => {
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
for (let i = 0; i < times; i++) await executeAction(id);
|
||||
},
|
||||
{ id, times },
|
||||
);
|
||||
|
||||
await runAction("editor.increaseFontSize", 4);
|
||||
const zoomedIn = await widths();
|
||||
expect(zoomedIn.mermaid / base.mermaid).toBeCloseTo(17 / 13, 2);
|
||||
expect(zoomedIn.excalidraw / base.excalidraw).toBeCloseTo(17 / 13, 2);
|
||||
|
||||
await runAction("editor.decreaseFontSize", 6);
|
||||
const zoomedOut = await widths();
|
||||
expect(zoomedOut.mermaid / base.mermaid).toBeCloseTo(11 / 13, 2);
|
||||
expect(zoomedOut.excalidraw / base.excalidraw).toBeCloseTo(11 / 13, 2);
|
||||
|
||||
await runAction("editor.resetFontSize");
|
||||
const reset = await widths();
|
||||
expect(reset.mermaid).toBeCloseTo(base.mermaid, 1);
|
||||
expect(reset.excalidraw).toBeCloseTo(base.excalidraw, 1);
|
||||
});
|
||||
|
||||
test("the bookmark gutter takes no width until the file has a bookmark", async ({ workbench: page }) => {
|
||||
|
||||
+10
-1
@@ -708,6 +708,8 @@ export const commands = {
|
||||
mode?: CheckoutMode,
|
||||
/** Required when checking out a remote branch whose local namesake is ahead of it. */
|
||||
diverged?: DivergedLocal | null,
|
||||
/** Check the branch out even though another worktree has it checked out. */
|
||||
ignoreOtherWorktrees?: boolean,
|
||||
} | null) => typedError<CheckoutOutcome, IdeError>(__TAURI_INVOKE("vcs_checkout", { repo, branch, create, options })),
|
||||
vcsDeleteBranch: (repo: string | null, branch: string) => typedError<DeletedBranch, IdeError>(__TAURI_INVOKE("vcs_delete_branch", { repo, branch })),
|
||||
/** "Restore" of the branch-deleted notification. */
|
||||
@@ -2980,6 +2982,8 @@ export type CheckoutOptions = {
|
||||
mode?: CheckoutMode,
|
||||
/** Required when checking out a remote branch whose local namesake is ahead of it. */
|
||||
diverged?: DivergedLocal | null,
|
||||
/** Check the branch out even though another worktree has it checked out. */
|
||||
ignoreOtherWorktrees?: boolean,
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -2997,7 +3001,12 @@ export type CheckoutOutcome = { kind: "done" } |
|
||||
* Switched, but restoring the local changes (Smart Checkout) or the rebase stopped
|
||||
* on conflicts in these files.
|
||||
*/
|
||||
{ kind: "conflicts"; files: string[] };
|
||||
{ kind: "conflicts"; files: string[] } |
|
||||
/**
|
||||
* Git refused: `branch` is checked out in the linked worktree at `path`. Nothing
|
||||
* changed; the branch can be worked on there.
|
||||
*/
|
||||
{ kind: "checkedOutInWorktree"; branch: string; path: string };
|
||||
|
||||
export type ChoiceOption = {
|
||||
value: string,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorState, StateEffect, type Extension } from "@codemirror/state";
|
||||
import { EditorView, runScopeHandlers } from "@codemirror/view";
|
||||
import type { CompletionItem } from "@/bindings";
|
||||
import type { EditorDocContext } from "@/editor/api";
|
||||
import { remoteChange, type EditorDocContext } from "@/editor/api";
|
||||
import { lspDoc } from "./lsp";
|
||||
import { insertTab, tabOut, tabOutOfScope } from "@/editor/core/cm/smartKeys";
|
||||
import {
|
||||
@@ -294,6 +294,32 @@ describe("applying completions", () => {
|
||||
await vi.waitFor(() => expect(view.state.selection.main.head).toBe(17));
|
||||
});
|
||||
|
||||
it("leaves an item its server inserts to the server, and puts the caret after what it inserted", async () => {
|
||||
const executed: string[] = [];
|
||||
setInvokeRoute((cmd) => {
|
||||
executed.push(cmd);
|
||||
return Promise.resolve(null);
|
||||
});
|
||||
try {
|
||||
const { view, req } = setup("p.ref|\n", "", [completionExtension()]);
|
||||
view.dispatch({ effects: StateEffect.appendConfig.of(lspDoc.of({ doc: 1 } as EditorDocContext)) });
|
||||
// kotlin-lsp: an empty text, inserted by `jetbrains.kotlin.completion.apply` as a workspace edit.
|
||||
const command = { title: "Apply Completion", command: "jetbrains.kotlin.completion.apply", arguments: ["1"] };
|
||||
const kotlin = item({ label: "refreshName", labelDetail: "()", insertText: "", command });
|
||||
applyLspCompletion(view, makeCompletion(kotlin, req), 5, 5, "insert");
|
||||
expect(view.state.doc.toString()).toBe("p.ref\n");
|
||||
await vi.waitFor(() => expect(executed).toContain("lsp_execute_command"));
|
||||
view.dispatch({ changes: { from: 5, insert: "reshName()" }, annotations: remoteChange.of(true) });
|
||||
expect(view.state.doc.toString()).toBe("p.refreshName()\n");
|
||||
expect(view.state.selection.main.head).toBe(15);
|
||||
// Later edits from elsewhere leave the caret alone.
|
||||
view.dispatch({ changes: { from: 15, insert: " " }, annotations: remoteChange.of(true) });
|
||||
expect(view.state.selection.main.head).toBe(15);
|
||||
} finally {
|
||||
setInvokeRoute(null);
|
||||
}
|
||||
});
|
||||
|
||||
it("does not register a scope when jumping outside closing brackets is off", () => {
|
||||
const { view, req } = setup("service.cr|");
|
||||
applyLspCompletion(view, makeCompletion(item(), req), 8, 10, "insert");
|
||||
@@ -532,6 +558,7 @@ describe("insert parentheses", () => {
|
||||
expect(callParens(item({ kind: "field" }), line("a.cr"), 2, 4)).toBeNull();
|
||||
expect(callParens(item({ isSnippet: true }), line("a.cr"), 2, 4)).toBeNull();
|
||||
expect(callParens(item({ insertText: "create()" }), line("a.cr"), 2, 4)).toBeNull();
|
||||
expect(callParens(item({ insertText: "" }), line("a.cr"), 4, 4)).toBeNull();
|
||||
});
|
||||
|
||||
it("skips calls that already have parentheses and imports", () => {
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
type CompletionResult,
|
||||
type CompletionSource,
|
||||
} from "@codemirror/autocomplete";
|
||||
import { EditorSelection, Prec, type Text } from "@codemirror/state";
|
||||
import { EditorSelection, EditorState, Prec, StateEffect, StateField, type Text } from "@codemirror/state";
|
||||
import { EditorView, ViewPlugin, keymap, type ViewUpdate } from "@codemirror/view";
|
||||
import {
|
||||
call,
|
||||
@@ -58,6 +58,7 @@ import { tx } from "@/platform/i18n";
|
||||
import { showHint } from "./hint";
|
||||
import { inplaceRenameActive } from "./inplaceRename";
|
||||
import { languageSemantics } from "./semantic";
|
||||
import { remoteChange } from "@/editor/api";
|
||||
|
||||
interface RequestContext {
|
||||
doc: number;
|
||||
@@ -297,7 +298,9 @@ export function callParens(
|
||||
start: number,
|
||||
end: number,
|
||||
): "inside" | "after" | null {
|
||||
if (item.isSnippet || !item.kind || !CALLABLE.has(item.kind) || /[(<[{]/.test(item.insertText)) return null;
|
||||
// An empty text is inserted by the item's server command (kotlin-lsp), parentheses included.
|
||||
if (item.isSnippet || !item.kind || !CALLABLE.has(item.kind) || !item.insertText || /[(<[{]/.test(item.insertText))
|
||||
return null;
|
||||
const next = line.text.charAt(end - line.from);
|
||||
if (next && /[(\p{L}\p{N}_$'"`]/u.test(next)) return null;
|
||||
if (IMPORT_LINE.test(line.text.slice(0, start - line.from))) return null;
|
||||
@@ -322,6 +325,33 @@ async function applyLateEdits(view: EditorView, c: LspCompletion, insertedAt: nu
|
||||
view.dispatch({ changes: edits, userEvent: "input.complete" });
|
||||
}
|
||||
|
||||
/** Where the caret was when an item its server inserts was picked, until that edit lands (`null`: none). */
|
||||
const awaitServerInsert = StateEffect.define<number | null>();
|
||||
const serverInsertAt = StateField.define<number | null>({
|
||||
create: () => null,
|
||||
update(at, tr) {
|
||||
for (const e of tr.effects) if (e.is(awaitServerInsert)) return e.value;
|
||||
// The edit landed, or the caret moved on before it did.
|
||||
if (at === null || tr.annotation(remoteChange) || tr.selection) return null;
|
||||
return tr.changes.mapPos(at, -1);
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* The server's edit inserts the item at the caret: the caret goes after it, as after any other
|
||||
* completion (a remote insertion at the caret would otherwise leave it in front).
|
||||
*/
|
||||
const caretAfterServerInsert = EditorState.transactionFilter.of((tr) => {
|
||||
const at = tr.startState.field(serverInsertAt, false);
|
||||
const caret = tr.startState.selection.main;
|
||||
if (at == null || !tr.docChanged || !tr.annotation(remoteChange) || !caret.empty || caret.head !== at) return tr;
|
||||
let inserted = false;
|
||||
tr.changes.iterChangedRanges((fromA, toA) => {
|
||||
if (fromA <= at && toA >= at) inserted = true;
|
||||
});
|
||||
return inserted ? [tr, { selection: EditorSelection.cursor(tr.changes.mapPos(at, 1)), sequential: true }] : tr;
|
||||
});
|
||||
|
||||
/** Client-side commands handled by the editor itself (VS Code ids servers commonly send). */
|
||||
const CLIENT_COMMANDS = new Set(["editor.action.triggerParameterHints", "editor.action.triggerSuggest"]);
|
||||
|
||||
@@ -329,18 +359,30 @@ function runCommand(view: EditorView, item: CompletionItem) {
|
||||
const command = item.command;
|
||||
if (!command?.command) return;
|
||||
const cmd = command.command;
|
||||
// kotlin-lsp inserts the item itself (`jetbrains.kotlin.completion.apply`): nothing went in here.
|
||||
const serverInserted = !item.insertText && !CLIENT_COMMANDS.has(cmd) && !cmd.startsWith("editor.");
|
||||
if (serverInserted) view.dispatch({ effects: awaitServerInsert.of(view.state.selection.main.head) });
|
||||
if (cmd === "editor.action.triggerParameterHints") setTimeout(() => triggerSignatureHelp(view), 0);
|
||||
else if (cmd === "editor.action.triggerSuggest") setTimeout(() => startCompletion(view), 0);
|
||||
else if (!CLIENT_COMMANDS.has(cmd) && !cmd.startsWith("editor.")) {
|
||||
const doc = docOf(view);
|
||||
// Server commands (auto-import, postfix…); resulting edits come back as workspace/applyEdit.
|
||||
if (doc)
|
||||
void lspRequest(() => commands.lspExecuteCommand(doc.doc, command)).catch((e: unknown) =>
|
||||
reportLspError(view, e, false),
|
||||
);
|
||||
void lspRequest(() => commands.lspExecuteCommand(doc.doc, command))
|
||||
.catch((e: unknown) => reportLspError(view, e, false))
|
||||
.finally(() => {
|
||||
// The edit arrives before the command's answer; allow for the document update.
|
||||
if (serverInserted)
|
||||
setTimeout(() => {
|
||||
if (view.dom.isConnected && view.state.field(serverInsertAt, false) != null)
|
||||
view.dispatch({ effects: awaitServerInsert.of(null) });
|
||||
}, SERVER_INSERT_WAIT_MS);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const SERVER_INSERT_WAIT_MS = 1000;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Source
|
||||
|
||||
@@ -828,6 +870,8 @@ export function completionExtension() {
|
||||
}),
|
||||
completionFooter,
|
||||
lookupTracker,
|
||||
serverInsertAt,
|
||||
caretAfterServerInsert,
|
||||
Prec.highest(
|
||||
keymap.of([
|
||||
// macOS: ⌃N / ⌃P are line down / up in text, so they move through the lookup as ↓ / ↑ do.
|
||||
|
||||
@@ -216,7 +216,10 @@ const hoverYieldsToNavigation = ViewPlugin.fromClass(
|
||||
|
||||
export function hoverExtension(): Extension {
|
||||
return [
|
||||
hoverTooltip(hoverSource, { hoverTime: Math.max(100, editorPrefs().codeEditing.quickDocDelay) }),
|
||||
hoverTooltip(hoverSource, {
|
||||
hoverTime: Math.max(100, editorPrefs().codeEditing.quickDocDelay),
|
||||
hideOnChange: true,
|
||||
}),
|
||||
hoverYieldsToNavigation,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -81,7 +81,7 @@ import {
|
||||
} from "./composerModel";
|
||||
import { ConfigPickers } from "./ConfigPickers";
|
||||
import { useEffortFocus } from "./effortFocus";
|
||||
import { findRanges, formatDuration, formatSentAt } from "./conversation";
|
||||
import { findRanges, formatDuration, formatSentAt, isFindRangeShown } from "./conversation";
|
||||
import { ImagePreview, imageSrc } from "./ImagePreview";
|
||||
import { useAgentSettings } from "./agentSettings";
|
||||
import { foldedTurns, summarizeWork, workParts, type FoldedTurn, type WorkSummary } from "./timeline";
|
||||
@@ -594,10 +594,15 @@ function SubagentBar({
|
||||
* doesn't jump (WebKit has no scroll anchoring). A new width lays them out again once it
|
||||
* settles; Find in Conversation (`enabled` false) needs every row laid out.
|
||||
*/
|
||||
function useOffscreenRows(ref: RefObject<HTMLElement | null>, visible: boolean, enabled: boolean) {
|
||||
// The width the marked rows were laid out at.
|
||||
const width = useRef(0);
|
||||
useEffect(() => {
|
||||
function useOffscreenRows(
|
||||
ref: RefObject<HTMLElement | null>,
|
||||
visible: boolean,
|
||||
enabled: boolean,
|
||||
fitWindowWidth: boolean,
|
||||
) {
|
||||
// The container width and column mode the marked rows were laid out at.
|
||||
const measured = useRef<{ width: number; fitWindowWidth: boolean } | null>(null);
|
||||
useLayoutEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
const unmark = () => {
|
||||
@@ -605,10 +610,26 @@ function useOffscreenRows(ref: RefObject<HTMLElement | null>, visible: boolean,
|
||||
row.removeAttribute("data-measured");
|
||||
}
|
||||
};
|
||||
if (!enabled) return unmark();
|
||||
if (!enabled) {
|
||||
measured.current = null;
|
||||
unmark();
|
||||
return;
|
||||
}
|
||||
if (!visible) return;
|
||||
if (measured.current?.width === el.clientWidth && measured.current.fitWindowWidth === fitWindowWidth) return;
|
||||
measured.current = { width: el.clientWidth, fitWindowWidth };
|
||||
unmark();
|
||||
}, [ref, visible, enabled, fitWindowWidth]);
|
||||
useEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el || !enabled || !visible) return;
|
||||
let frame = 0;
|
||||
let timer: number | undefined;
|
||||
const unmark = () => {
|
||||
for (const row of el.querySelectorAll(`:scope > .${styles.conversationRow}[data-measured]`)) {
|
||||
row.removeAttribute("data-measured");
|
||||
}
|
||||
};
|
||||
const mark = () => {
|
||||
cancelAnimationFrame(frame);
|
||||
// The next frame lays the new rows out (and remembers their size); mark them after it.
|
||||
@@ -621,8 +642,8 @@ function useOffscreenRows(ref: RefObject<HTMLElement | null>, visible: boolean,
|
||||
});
|
||||
};
|
||||
const remeasure = () => {
|
||||
if (el.clientWidth === width.current) return;
|
||||
width.current = el.clientWidth;
|
||||
if (measured.current?.width === el.clientWidth && measured.current.fitWindowWidth === fitWindowWidth) return;
|
||||
measured.current = { width: el.clientWidth, fitWindowWidth };
|
||||
unmark();
|
||||
};
|
||||
remeasure();
|
||||
@@ -643,7 +664,7 @@ function useOffscreenRows(ref: RefObject<HTMLElement | null>, visible: boolean,
|
||||
rows.disconnect();
|
||||
resize.disconnect();
|
||||
};
|
||||
}, [ref, visible, enabled]);
|
||||
}, [ref, visible, enabled, fitWindowWidth]);
|
||||
}
|
||||
|
||||
interface StreamProps {
|
||||
@@ -765,7 +786,8 @@ function Stream({ loadError, task, entries, subagent, onOpenSubagent, finding, f
|
||||
}, [start]);
|
||||
// Hidden behind another tab, it has no layout to scroll; shown again, it follows the end again.
|
||||
const visible = useEditorShown();
|
||||
useOffscreenRows(ref, visible, !finding);
|
||||
const { foldTurns, toolCalls, fitWindowWidth } = useAgentSettings();
|
||||
useOffscreenRows(ref, visible, !finding, fitWindowWidth);
|
||||
/** A diagram that drew after the last streamed chunk grows the conversation: keep following. */
|
||||
const onDiagramDrawn = useCallback(() => {
|
||||
const el = ref.current;
|
||||
@@ -874,7 +896,6 @@ function Stream({ loadError, task, entries, subagent, onOpenSubagent, finding, f
|
||||
const busy = subagent ? subagentWorking(subagent.status) : isBusy(task.status);
|
||||
const lastIndex = entries ? entries.length - 1 : -1;
|
||||
// Keep the row stable when earlier history is prepended; its author can move with the work.
|
||||
const { foldTurns, toolCalls } = useAgentSettings();
|
||||
const rows = useMemo(() => {
|
||||
if (!entries) return [];
|
||||
const rows = conversationRows(entries, start, toolCalls === "grouped");
|
||||
@@ -1121,14 +1142,9 @@ interface RangeSet {
|
||||
clear(): void;
|
||||
add(range: Range): void;
|
||||
}
|
||||
const highlights = (globalThis as { CSS?: { highlights?: Map<string, RangeSet> } }).CSS?.highlights;
|
||||
const HighlightCtor = (globalThis as { Highlight?: new () => RangeSet }).Highlight;
|
||||
|
||||
/**
|
||||
* Sets the ranges of highlight `name`. One registered highlight per name, changed in
|
||||
* place: WebKit doesn't repaint where a replaced highlight object was.
|
||||
*/
|
||||
function setHighlight(name: string, ranges: Range[]) {
|
||||
const highlights = (globalThis as { CSS?: { highlights?: Map<string, RangeSet> } }).CSS?.highlights;
|
||||
const HighlightCtor = (globalThis as { Highlight?: new () => RangeSet }).Highlight;
|
||||
if (!highlights || !HighlightCtor) return;
|
||||
let set = highlights.get(name);
|
||||
if (!set) {
|
||||
@@ -1204,12 +1220,15 @@ function FindBar({
|
||||
return () => stream?.removeEventListener("toggle", toggled, true);
|
||||
}, [streamRef]);
|
||||
useEffect(() => {
|
||||
// Only rendered matches: WebKit paints those in collapsed <details> over the text next to them.
|
||||
const visible = (r: Range) => r.getClientRects().length > 0;
|
||||
const stream = streamRef.current;
|
||||
if (!stream) return;
|
||||
// Only rendered selectable matches outside closed <details>: WebKit paints unrendered
|
||||
// or user-select:none ranges in CSS.highlights over the next selectable row instead.
|
||||
const visible = (r: Range) => isFindRangeShown(r, stream);
|
||||
const current = index >= 0 ? ranges[index]! : null;
|
||||
setHighlight("agent-find", ranges.filter(visible));
|
||||
setHighlight("agent-find-current", current && visible(current) ? [current] : []);
|
||||
}, [ranges, index, shown]);
|
||||
}, [ranges, index, shown, streamRef]);
|
||||
useEffect(
|
||||
() => () => {
|
||||
setHighlight("agent-find", []);
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { fileHref, findAll, findRanges, formatDuration, pathLink, quoteText, withQuote } from "./conversation";
|
||||
import {
|
||||
fileHref,
|
||||
findAll,
|
||||
findRanges,
|
||||
formatDuration,
|
||||
isFindRangeShown,
|
||||
pathLink,
|
||||
quoteText,
|
||||
withQuote,
|
||||
} from "./conversation";
|
||||
|
||||
describe("quoting", () => {
|
||||
it("quotes each line and leaves a line to type on", () => {
|
||||
@@ -84,4 +93,28 @@ describe("finding", () => {
|
||||
expect(findRanges(root, "one").map((r) => r.toString())).toEqual(["one", "one"]);
|
||||
expect(findRanges(root, "TWO")).toHaveLength(1);
|
||||
});
|
||||
it("skips user-select:none chrome, buttons, svgs and mermaid source, and hides ranges in closed <details>", () => {
|
||||
const root = document.createElement("div");
|
||||
root.innerHTML = [
|
||||
'<details><summary style="user-select: none">Confirming summary</summary><div>hidden confirm body</div></details>',
|
||||
"<details><summary>stop_bash confirm</summary><pre>tool confirm output</pre></details>",
|
||||
"<button>confirm button</button>",
|
||||
"<svg><text>confirm svg</text></svg>",
|
||||
'<div data-mermaid-state="ok"><pre><code>graph TD; confirm</code></pre></div>',
|
||||
"<p>Visible confirm</p>",
|
||||
].join("");
|
||||
const ranges = findRanges(root, "confirm");
|
||||
expect(ranges.map((r) => r.startContainer.parentElement?.tagName)).toEqual(["DIV", "SUMMARY", "PRE", "P"]);
|
||||
|
||||
// Simulate WebKit's content-visibility: hidden on closed <details>, where getClientRects() stays non-empty.
|
||||
for (const r of ranges) r.getClientRects = () => [new DOMRect(0, 0, 10, 10)] as unknown as DOMRectList;
|
||||
expect(ranges.filter((r) => isFindRangeShown(r, root)).map((r) => r.startContainer.parentElement?.tagName)).toEqual(
|
||||
["SUMMARY", "P"],
|
||||
);
|
||||
|
||||
for (const d of root.querySelectorAll("details")) d.open = true;
|
||||
expect(ranges.filter((r) => isFindRangeShown(r, root)).map((r) => r.startContainer.parentElement?.tagName)).toEqual(
|
||||
["DIV", "SUMMARY", "PRE", "P"],
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -93,11 +93,36 @@ export function findAll(text: string, query: string): number[] {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** DOM ranges of `query` in the text under `root` (matches within one text node). */
|
||||
const SKIP_FIND_TAGS = new Set(["STYLE", "SCRIPT", "NOSCRIPT", "SVG", "BUTTON"]);
|
||||
|
||||
function isUnselectable(el: Element): boolean {
|
||||
const style = getComputedStyle(el);
|
||||
return style.userSelect === "none" || style.webkitUserSelect === "none";
|
||||
}
|
||||
|
||||
/**
|
||||
* DOM ranges of `query` in the selectable text under `root` (matches within one text node).
|
||||
* Skips `user-select: none` chrome (`.thought summary`, `.processSummary`, `.messageTime`,
|
||||
* `.role`…): WebKit's `CSS.highlights` skips unselectable text renderers and paints the
|
||||
* highlight over the next selectable text node instead.
|
||||
*/
|
||||
export function findRanges(root: Node, query: string): Range[] {
|
||||
const out: Range[] = [];
|
||||
if (!query) return out;
|
||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
||||
const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, {
|
||||
acceptNode(node) {
|
||||
if (node.nodeType === Node.ELEMENT_NODE) {
|
||||
const el = node as Element;
|
||||
const tag = el.tagName.toUpperCase();
|
||||
if (SKIP_FIND_TAGS.has(tag)) return NodeFilter.FILTER_REJECT;
|
||||
if (tag === "PRE" && el.parentElement?.getAttribute("data-mermaid-state") === "ok")
|
||||
return NodeFilter.FILTER_REJECT;
|
||||
if (isUnselectable(el)) return NodeFilter.FILTER_REJECT;
|
||||
return NodeFilter.FILTER_SKIP;
|
||||
}
|
||||
return NodeFilter.FILTER_ACCEPT;
|
||||
},
|
||||
});
|
||||
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
||||
for (const at of findAll(node.textContent ?? "", query)) {
|
||||
const range = document.createRange();
|
||||
@@ -108,3 +133,20 @@ export function findRanges(root: Node, query: string): Range[] {
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when `range` is rendered on screen and not inside a collapsed `<details>` or
|
||||
* `user-select: none` subtree. WebKit hides closed `<details>` bodies with
|
||||
* `content-visibility: hidden` (where `getClientRects()` stays non-empty once opened)
|
||||
* and forwards unrendered or unselectable `CSS.highlights` ranges onto adjacent rows.
|
||||
*/
|
||||
export function isFindRangeShown(range: Range, root: Node): boolean {
|
||||
for (let el = range.startContainer.parentElement; el && el !== root; el = el.parentElement) {
|
||||
if (isUnselectable(el)) return false;
|
||||
if (el instanceof HTMLDetailsElement && !el.open) {
|
||||
const summary = el.querySelector(":scope > summary");
|
||||
if (!summary?.contains(range.startContainer)) return false;
|
||||
}
|
||||
}
|
||||
return range.getClientRects().length > 0;
|
||||
}
|
||||
@@ -540,20 +540,60 @@ describe("opened runs", () => {
|
||||
});
|
||||
|
||||
describe("folded content", () => {
|
||||
it("is rendered for Find in Conversation, so its text is found", async () => {
|
||||
backend.entries.set("A", [
|
||||
tool("one", { output: "needle in a tool output" }),
|
||||
tool("two"),
|
||||
{ type: "agent", text: "Answer A" },
|
||||
]);
|
||||
useAgents.setState({ entries: new Map(backend.entries) });
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
const summary = await screen.findByText("Read 2 files");
|
||||
expect(screen.queryByText("needle in a tool output")).toBeNull();
|
||||
fireEvent.focus(summary);
|
||||
act(() => focusedSession()!.openFind());
|
||||
expect(await screen.findByText("needle in a tool output")).toBeInTheDocument();
|
||||
expect(summary.closest("details")!.open).toBe(false);
|
||||
it("is rendered for Find in Conversation without painting closed <details> highlights until stepped into", async () => {
|
||||
const rectSpy = vi
|
||||
.spyOn(Range.prototype, "getClientRects")
|
||||
.mockImplementation(() => [new DOMRect(0, 0, 20, 12)] as unknown as DOMRectList);
|
||||
const prevCss = (globalThis as { CSS?: unknown }).CSS;
|
||||
const prevHighlight = (globalThis as { Highlight?: unknown }).Highlight;
|
||||
const highlights = new Map<string, Set<Range>>();
|
||||
if (typeof prevHighlight === "undefined") {
|
||||
(globalThis as { Highlight?: unknown }).Highlight = Set;
|
||||
}
|
||||
if (!(prevCss as { highlights?: unknown } | undefined)?.highlights) {
|
||||
(globalThis as { CSS?: unknown }).CSS = {
|
||||
...(typeof prevCss === "object" && prevCss ? prevCss : {}),
|
||||
highlights,
|
||||
};
|
||||
}
|
||||
try {
|
||||
backend.entries.set("A", [
|
||||
{ type: "thought", text: "Reviewing Changes\n\nConfirm the branch state before rebasing." },
|
||||
tool("one", { title: "stop_bash", output: "stopped" }),
|
||||
{ type: "agent", text: "Confirmed—PR is merged." },
|
||||
]);
|
||||
useAgents.setState({ entries: new Map(backend.entries) });
|
||||
render(<SessionEditor input={input("A")} />);
|
||||
const runSummary = await screen.findByText("Read 1 file");
|
||||
const runDetails = runSummary.closest("details")!;
|
||||
runDetails.open = true;
|
||||
fireEvent(runDetails, new Event("toggle"));
|
||||
|
||||
const thoughtDetails = (await screen.findByText("Reviewing Changes")).closest("details")!;
|
||||
expect(thoughtDetails.open).toBe(false);
|
||||
|
||||
fireEvent.focus(runSummary);
|
||||
act(() => focusedSession()!.openFind());
|
||||
const findBox = await screen.findByLabelText("Find in Conversation");
|
||||
fireEvent.change(findBox, { target: { value: "confirm" } });
|
||||
|
||||
const registry = (globalThis as unknown as { CSS: { highlights: Map<string, Set<Range>> } }).CSS.highlights;
|
||||
await waitFor(() => expect(screen.getByText("1/2")).toBeInTheDocument());
|
||||
await waitFor(() => expect([...(registry.get("agent-find") ?? [])]).toHaveLength(1));
|
||||
expect([...(registry.get("agent-find") ?? [])][0]!.startContainer.textContent).toContain("Confirmed");
|
||||
expect([...(registry.get("agent-find-current") ?? [])]).toHaveLength(0);
|
||||
|
||||
fireEvent.keyDown(findBox, { key: "Enter" });
|
||||
fireEvent.keyDown(findBox, { key: "Enter" });
|
||||
fireEvent(thoughtDetails, new Event("toggle"));
|
||||
expect(thoughtDetails.open).toBe(true);
|
||||
await waitFor(() => expect([...(registry.get("agent-find") ?? [])]).toHaveLength(2));
|
||||
expect([...(registry.get("agent-find-current") ?? [])]).toHaveLength(1);
|
||||
} finally {
|
||||
rectSpy.mockRestore();
|
||||
(globalThis as { CSS?: unknown }).CSS = prevCss;
|
||||
(globalThis as { Highlight?: unknown }).Highlight = prevHighlight;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1817,30 +1857,57 @@ describe("meters in the task header", () => {
|
||||
expect(screen.getByText("$0.42")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("toggles fitWidth on the session root from settings.agents.fitWindowWidth", () => {
|
||||
const { container } = render(<SessionEditor input={input("A")} />);
|
||||
const root = container.querySelector(`.${styles.session}`)!;
|
||||
expect(root).not.toHaveClass(styles.fitWidth!);
|
||||
act(() =>
|
||||
useProject.setState({
|
||||
settings: {
|
||||
agents: {
|
||||
fitWindowWidth: true,
|
||||
},
|
||||
} as never,
|
||||
}),
|
||||
);
|
||||
expect(root).toHaveClass(styles.fitWidth!);
|
||||
act(() =>
|
||||
useProject.setState({
|
||||
settings: {
|
||||
agents: {
|
||||
fitWindowWidth: false,
|
||||
},
|
||||
} as never,
|
||||
}),
|
||||
);
|
||||
expect(root).not.toHaveClass(styles.fitWidth!);
|
||||
it("toggles fitWidth on the session root and remeasures off-screen rows from settings.agents.fitWindowWidth", async () => {
|
||||
const frames: FrameRequestCallback[] = [];
|
||||
const raf = vi.spyOn(window, "requestAnimationFrame").mockImplementation((cb) => {
|
||||
frames.push(cb);
|
||||
return frames.length;
|
||||
});
|
||||
const flushFrames = () => {
|
||||
for (let pass = 0; pass < 2; pass++) {
|
||||
for (const cb of frames.splice(0)) cb(performance.now());
|
||||
}
|
||||
};
|
||||
try {
|
||||
const { container } = render(<SessionEditor input={input("A")} />);
|
||||
await screen.findByText("Answer A");
|
||||
const root = container.querySelector(`.${styles.session}`)!;
|
||||
const row = container.querySelector(`.${styles.conversationRow}`)!;
|
||||
act(flushFrames);
|
||||
expect(root).not.toHaveClass(styles.fitWidth!);
|
||||
expect(row).toHaveAttribute("data-measured");
|
||||
|
||||
act(() =>
|
||||
useProject.setState({
|
||||
settings: {
|
||||
agents: {
|
||||
fitWindowWidth: true,
|
||||
},
|
||||
} as never,
|
||||
}),
|
||||
);
|
||||
expect(root).toHaveClass(styles.fitWidth!);
|
||||
// Cleared synchronously before paint so content-visibility doesn't keep the 900px intrinsic height.
|
||||
expect(row).not.toHaveAttribute("data-measured");
|
||||
act(flushFrames);
|
||||
expect(row).toHaveAttribute("data-measured");
|
||||
|
||||
act(() =>
|
||||
useProject.setState({
|
||||
settings: {
|
||||
agents: {
|
||||
fitWindowWidth: false,
|
||||
},
|
||||
} as never,
|
||||
}),
|
||||
);
|
||||
expect(root).not.toHaveClass(styles.fitWidth!);
|
||||
expect(row).not.toHaveAttribute("data-measured");
|
||||
act(flushFrames);
|
||||
expect(row).toHaveAttribute("data-measured");
|
||||
} finally {
|
||||
raf.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("hides the status-bar Terminal button in the local checkout and opens the worktree's terminal otherwise", async () => {
|
||||
|
||||
@@ -303,6 +303,6 @@ describe("closing the hierarchy tab", () => {
|
||||
useHierarchy.setState({ root: { name: "Number", path: "/p/Number.java", line: 0, col: 0 } as never });
|
||||
closeHierarchy();
|
||||
expect(useHierarchy.getState().root).toBeNull();
|
||||
expect(hide).toHaveBeenCalledWith("hierarchy");
|
||||
expect(hide).toHaveBeenCalledWith("hierarchy", { removeFromStripe: true });
|
||||
});
|
||||
});
|
||||
@@ -92,10 +92,10 @@ export function resetHierarchy() {
|
||||
}));
|
||||
}
|
||||
|
||||
/** Closes the hierarchy's content tab; with no content left the tool window hides. */
|
||||
/** Closes the hierarchy's content tab; with no content left the tool window and its stripe button go. */
|
||||
export function closeHierarchy() {
|
||||
resetHierarchy();
|
||||
toolWindowService().hide("hierarchy");
|
||||
toolWindowService().hide("hierarchy", { removeFromStripe: true });
|
||||
}
|
||||
|
||||
/** The empty-result line of the hierarchy tree. */
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const show = vi.fn();
|
||||
const hide = vi.fn();
|
||||
vi.mock("@/workbench/contributions", async (orig) => ({
|
||||
...(await orig<typeof import("@/workbench/contributions")>()),
|
||||
toolWindowService: () => ({ show }),
|
||||
toolWindowService: () => ({ show, hide }),
|
||||
}));
|
||||
/** The editor at the caret (`null`: a search from outside an editor). */
|
||||
let caretView: import("@codemirror/view").EditorView | null = null;
|
||||
@@ -35,8 +36,16 @@ vi.mock("@tauri-apps/api/core", async (orig) => ({
|
||||
|
||||
const { registerDocumentIndexSync } = await import("@/workbench/contributions");
|
||||
|
||||
const { activeUsageSearch, findUsages, openUsageTab, pinUsageTab, resetUsages, showUsageResults, useUsages } =
|
||||
await import("./usages");
|
||||
const {
|
||||
activeUsageSearch,
|
||||
closeUsageTab,
|
||||
findUsages,
|
||||
openUsageTab,
|
||||
pinUsageTab,
|
||||
resetUsages,
|
||||
showUsageResults,
|
||||
useUsages,
|
||||
} = await import("./usages");
|
||||
|
||||
describe("showUsageResults", () => {
|
||||
it("shows given usages in the Find Usages tool window", async () => {
|
||||
@@ -221,4 +230,16 @@ describe("usage tabs", () => {
|
||||
openUsageTab(search(104));
|
||||
expect(useUsages.getState().tabs.map((t) => t.id)).toEqual([102, 104]);
|
||||
});
|
||||
|
||||
it("take the tool window and its stripe button away with the last one", () => {
|
||||
resetUsages();
|
||||
hide.mockClear();
|
||||
openUsageTab(search(201));
|
||||
pinUsageTab(201, true);
|
||||
openUsageTab(search(202));
|
||||
closeUsageTab(201);
|
||||
expect(hide).not.toHaveBeenCalled();
|
||||
closeUsageTab(202);
|
||||
expect(hide).toHaveBeenCalledWith("usages", { removeFromStripe: true });
|
||||
});
|
||||
});
|
||||
@@ -168,6 +168,14 @@ export function closeUsageTab(id: number) {
|
||||
const active = s.active === id ? (tabs[Math.min(i, tabs.length - 1)]?.id ?? null) : s.active;
|
||||
return { tabs, active };
|
||||
});
|
||||
// As in IDEA, the tool window and its stripe button go away with its last tab.
|
||||
if (!useUsages.getState().tabs.length) {
|
||||
try {
|
||||
toolWindowService().hide("usages", { removeFromStripe: true });
|
||||
} catch {
|
||||
// Workbench not ready (tests).
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Rerun of the selected tab (⌘R in the Find Usages tool window). */
|
||||
|
||||
@@ -15,5 +15,5 @@ it("hides the Debug tool window once its last session tab is closed", async () =
|
||||
expect(await closeSessionTab(1)).toBe(true);
|
||||
expect(hide).not.toHaveBeenCalled();
|
||||
expect(await closeSessionTab(2)).toBe(true);
|
||||
expect(hide).toHaveBeenCalledWith("debug");
|
||||
expect(hide).toHaveBeenCalledWith("debug", { removeFromStripe: true });
|
||||
});
|
||||
@@ -880,10 +880,10 @@ export async function closeSessionTab(id: DebugSessionId): Promise<boolean> {
|
||||
await stopSession(s.id);
|
||||
}
|
||||
removeSession(s.id);
|
||||
// As in IDEA, the tool window goes away with its last tab.
|
||||
// As in IDEA, the tool window and its stripe button go away with its last tab.
|
||||
if (!Object.keys(useDebug.getState().sessions).length) {
|
||||
try {
|
||||
toolWindowService().hide("debug");
|
||||
toolWindowService().hide("debug", { removeFromStripe: true });
|
||||
} catch {
|
||||
// Workbench not ready (tests).
|
||||
}
|
||||
|
||||
@@ -303,7 +303,8 @@ function currentTab(
|
||||
export async function closeRunTab(id: string, traces: readonly StackTraceTab[]) {
|
||||
if (traces.some((t) => t.id === id)) closeStackTrace(id);
|
||||
else if (!(await closeSessionTab(id))) return;
|
||||
if (!useRun.getState().sessions.length && !useStackTraces.getState().tabs.length) toolWindowService().hide("run");
|
||||
if (!useRun.getState().sessions.length && !useStackTraces.getState().tabs.length)
|
||||
toolWindowService().hide("run", { removeFromStripe: true });
|
||||
}
|
||||
|
||||
/** Session (and stack trace) tabs in the tool window header. */
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";
|
||||
import { useState } from "react";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { ContextMenuHost } from "@/ui";
|
||||
import { occurrenceNavigator } from "@/workbench/contributions";
|
||||
import { TestResults } from "./testing";
|
||||
import { TestTreeView } from "./TestTreeView";
|
||||
import { testTree } from "./testTree";
|
||||
|
||||
const nav = vi.hoisted(() => ({ openTarget: vi.fn(async () => {}) }));
|
||||
vi.mock("./navigate", () => nav);
|
||||
@@ -112,3 +116,173 @@ describe("TestTreeView", () => {
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("Previous / Next Failed Test", () => {
|
||||
beforeEach(() => localStorage.clear());
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
/** Two suites with failures in a nested suite and between passing tests. */
|
||||
function nested(failures = true) {
|
||||
const r = new TestResults();
|
||||
const bad = failures ? "failed" : "passed";
|
||||
r.apply([
|
||||
{ type: "result", path: ["ApiTest", "lists()"], status: "passed" },
|
||||
{ type: "result", path: ["ApiTest", "Auth", "rejects()"], status: bad },
|
||||
{ type: "result", path: ["ApiTest", "Auth", "accepts()"], status: "passed" },
|
||||
{ type: "result", path: ["DbTest", "reads()"], status: bad },
|
||||
{ type: "result", path: ["DbTest", "skips()"], status: "skipped" },
|
||||
{ type: "result", path: ["DbTest", "writes()"], status: bad },
|
||||
{ type: "location", path: ["DbTest", "writes()"], location: { path: "DbTest.java", line: 20, resolve: "name" } },
|
||||
]);
|
||||
r.finish(failures ? 1 : 0);
|
||||
return r;
|
||||
}
|
||||
|
||||
function Nested({ results }: { results: TestResults }) {
|
||||
const [selected, setSelected] = useState<string | null>(null);
|
||||
return (
|
||||
<TestTreeView results={results} version={1} cwd="/p" selected={selected} onSelect={setSelected} running={false} />
|
||||
);
|
||||
}
|
||||
|
||||
const go = (dir: 1 | -1, focus = false) => {
|
||||
let step: ReturnType<NonNullable<ReturnType<typeof occurrenceNavigator>>["go"]> = null;
|
||||
act(() => {
|
||||
step = occurrenceNavigator("run")!.go(dir, focus);
|
||||
});
|
||||
return step as { key: string; index: number; total: number } | null;
|
||||
};
|
||||
const selectedName = () => screen.getByRole("treeitem", { selected: true }).textContent;
|
||||
const prev = () => screen.getByRole("button", { name: "Previous Failed Test" });
|
||||
const next = () => screen.getByRole("button", { name: "Next Failed Test" });
|
||||
|
||||
it("steps through the failed tests in tree order and stops at both ends", () => {
|
||||
render(<Nested results={nested()} />);
|
||||
expect(prev()).toBeEnabled();
|
||||
expect(next()).toBeEnabled();
|
||||
expect(go(1)).toMatchObject({ index: 1, total: 3 });
|
||||
expect(selectedName()).toContain("rejects()");
|
||||
expect(go(1)).toMatchObject({ index: 2, total: 3 });
|
||||
expect(selectedName()).toContain("reads()");
|
||||
expect(go(1)).toMatchObject({ index: 3, total: 3 });
|
||||
expect(selectedName()).toContain("writes()");
|
||||
// IDEA doesn't wrap: Next is unavailable on the last failure, and the selection stays.
|
||||
expect(next()).toBeDisabled();
|
||||
expect(prev()).toBeEnabled();
|
||||
expect(go(1)).toBeNull();
|
||||
expect(selectedName()).toContain("writes()");
|
||||
expect(go(-1)).toMatchObject({ index: 2 });
|
||||
expect(go(-1)).toMatchObject({ index: 1 });
|
||||
expect(prev()).toBeDisabled();
|
||||
expect(go(-1)).toBeNull();
|
||||
expect(selectedName()).toContain("rejects()");
|
||||
});
|
||||
|
||||
it("expands the collapsed suites of the failure it selects", () => {
|
||||
render(<Nested results={nested()} />);
|
||||
const suite = screen.getByText("ApiTest").closest('[role="treeitem"]')!;
|
||||
fireEvent.mouseDown(suite.querySelector("[data-tree-toggle]")!, { button: 0 });
|
||||
expect(screen.queryByText("rejects()")).toBeNull();
|
||||
go(1);
|
||||
expect(selectedName()).toContain("rejects()");
|
||||
});
|
||||
|
||||
it("opens the failure's source, focusing the editor only when asked", () => {
|
||||
render(<Nested results={nested()} />);
|
||||
go(-1);
|
||||
expect(nav.openTarget).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ path: "DbTest.java", line: 20 }),
|
||||
"/p",
|
||||
false,
|
||||
);
|
||||
go(-1, true);
|
||||
// reads() has no location: nothing to open.
|
||||
expect(nav.openTarget).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("is unavailable when no test failed", () => {
|
||||
render(<Nested results={nested(false)} />);
|
||||
expect(prev()).toBeDisabled();
|
||||
expect(next()).toBeDisabled();
|
||||
expect(go(1)).toBeNull();
|
||||
expect(go(-1)).toBeNull();
|
||||
});
|
||||
|
||||
it("runs Previous / Next Occurrence, so ⌘⌥↑ / ⌘⌥↓ do the same", () => {
|
||||
render(<Nested results={nested()} />);
|
||||
fireEvent.click(next());
|
||||
expect(actions.executeAction).toHaveBeenCalledWith("navigate.nextOccurrence", undefined);
|
||||
fireEvent.click(prev());
|
||||
expect(actions.executeAction).toHaveBeenCalledWith("navigate.prevOccurrence", undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Expand All / Collapse All", () => {
|
||||
beforeEach(() => localStorage.clear());
|
||||
afterEach(() => vi.clearAllMocks());
|
||||
|
||||
function nested() {
|
||||
const r = new TestResults();
|
||||
r.apply([
|
||||
{ type: "result", path: ["ApiTest", "Auth", "Tokens", "refreshes()"], status: "failed" },
|
||||
{ type: "result", path: ["ApiTest", "Users", "lists()"], status: "passed" },
|
||||
{ type: "result", path: ["DbTest", "Pool", "reuses()"], status: "passed" },
|
||||
]);
|
||||
r.finish(1);
|
||||
return r;
|
||||
}
|
||||
|
||||
const view = (results: TestResults) => (
|
||||
<TestTreeView results={results} version={1} cwd="/p" selected={null} onSelect={() => {}} running={false} />
|
||||
);
|
||||
const rows = () => screen.queryAllByRole("treeitem").map((r) => r.textContent?.replace(/\d+ ms$/, ""));
|
||||
|
||||
it("opens every suite, including those of hidden passed tests, and folds back to the top-level suites", () => {
|
||||
localStorage.setItem("openidea.run.testFilters", JSON.stringify({ showPassed: true }));
|
||||
render(view(nested()));
|
||||
// By default only the top level and the suites with failures are open.
|
||||
expect(rows()).toEqual(["ApiTest", "Auth", "Tokens", "refreshes()", "Users", "DbTest", "Pool"]);
|
||||
act(() => testTree.expandAll!());
|
||||
expect(rows()).toEqual([
|
||||
"ApiTest",
|
||||
"Auth",
|
||||
"Tokens",
|
||||
"refreshes()",
|
||||
"Users",
|
||||
"lists()",
|
||||
"DbTest",
|
||||
"Pool",
|
||||
"reuses()",
|
||||
]);
|
||||
act(() => testTree.collapseAll!());
|
||||
expect(rows()).toEqual(["ApiTest", "DbTest"]);
|
||||
// Expanded state survives a filter change.
|
||||
act(() => testTree.expandAll!());
|
||||
fireEvent.click(screen.getByRole("button", { name: "Show Passed" }));
|
||||
expect(rows()).toEqual(["ApiTest", "Auth", "Tokens", "refreshes()"]);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Show Passed" }));
|
||||
expect(rows()).toContain("reuses()");
|
||||
});
|
||||
|
||||
it("the buttons run the actions, and are unavailable without suites", () => {
|
||||
const dispose = registerActions([
|
||||
{ id: "run.expandAllTests", title: "Expand All", run: () => {} },
|
||||
{ id: "run.collapseAllTests", title: "Collapse All", run: () => {} },
|
||||
]);
|
||||
onTestFinished(dispose);
|
||||
const { unmount } = render(view(nested()));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Expand All" }));
|
||||
expect(actions.executeAction).toHaveBeenCalledWith("run.expandAllTests", undefined);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Collapse All" }));
|
||||
expect(actions.executeAction).toHaveBeenCalledWith("run.collapseAllTests", undefined);
|
||||
unmount();
|
||||
expect(testTree.expandAll).toBeNull();
|
||||
|
||||
const flat = new TestResults();
|
||||
flat.apply([{ type: "result", path: ["main_test"], status: "failed" }]);
|
||||
flat.finish(1);
|
||||
render(view(flat));
|
||||
expect(screen.getByRole("button", { name: "Expand All" })).toBeDisabled();
|
||||
expect(screen.getByRole("button", { name: "Collapse All" })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,22 @@
|
||||
import { useMemo, useState, type MouseEvent } from "react";
|
||||
import { useEffect, useMemo, useRef, useState, type MouseEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { Icon, IconButton, showContextMenu, useContextMenuStore, Spinner, Tree, type MenuItem } from "@/ui";
|
||||
import {
|
||||
findOccurrence,
|
||||
Icon,
|
||||
IconButton,
|
||||
showContextMenu,
|
||||
useContextMenuStore,
|
||||
Spinner,
|
||||
Tree,
|
||||
type MenuItem,
|
||||
type TreeHandle,
|
||||
} from "@/ui";
|
||||
import { useOccurrenceNavigator } from "@/workbench/contributions";
|
||||
import { openTarget } from "./navigate";
|
||||
import { nodeStatus, type TestNode, type TestResults, type TestStatus } from "./testing";
|
||||
import { parseComparison } from "./testing/comparison";
|
||||
import { TEST_TREE_FOCUS, testTree } from "./testTree";
|
||||
import styles from "./Run.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
@@ -84,6 +96,24 @@ export function StatusIcon({ status }: { status: TestStatus | null }) {
|
||||
}
|
||||
}
|
||||
|
||||
const isFailedTest = (n: TestNode) => n.children.length === 0 && nodeStatus(n) === "failed";
|
||||
|
||||
const treeModel = {
|
||||
getKey: (n: TestNode) => n.id,
|
||||
getChildren: (n: TestNode) => n.children,
|
||||
isExpandable: (n: TestNode) => n.children.length > 0,
|
||||
isOccurrence: isFailedTest,
|
||||
};
|
||||
|
||||
function suiteIds(nodes: readonly TestNode[], out: Set<string> = new Set()): Set<string> {
|
||||
for (const n of nodes) {
|
||||
if (n.children.length === 0) continue;
|
||||
out.add(n.id);
|
||||
suiteIds(n.children, out);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function filterTree(nodes: readonly TestNode[], keep: (n: TestNode) => boolean): TestNode[] {
|
||||
const out: TestNode[] = [];
|
||||
for (const n of nodes) {
|
||||
@@ -129,6 +159,7 @@ export function TestTreeView({
|
||||
});
|
||||
const [expanded, setExpanded] = useState<Set<string> | null>(null);
|
||||
const [selection, setSelection] = useState<Set<string>>(new Set());
|
||||
const tree = useRef<TreeHandle>(null);
|
||||
const selectedKeys = useMemo(
|
||||
() => (selected === null ? new Set<string>() : selection.has(selected) ? selection : new Set([selected])),
|
||||
[selected, selection],
|
||||
@@ -209,6 +240,28 @@ export function TestTreeView({
|
||||
return set;
|
||||
}, [expanded, roots]);
|
||||
|
||||
// Collapse All leaves the top-level suites in view, as IDEA's test tree does.
|
||||
useEffect(() => {
|
||||
testTree.expandAll = () => setExpanded(suiteIds(results.roots));
|
||||
testTree.collapseAll = () => setExpanded(new Set());
|
||||
return () => {
|
||||
testTree.expandAll = null;
|
||||
testTree.collapseAll = null;
|
||||
};
|
||||
});
|
||||
const hasSuites = roots.some((n) => n.children.length > 0);
|
||||
|
||||
// Previous / Next Failed Test (⌘⌥↑ / ⌘⌥↓): like IDEA, stops at the first / last failure instead of wrapping.
|
||||
useOccurrenceNavigator("run", (dir, focus) => {
|
||||
const step = tree.current?.selectOccurrence(dir);
|
||||
if (!step) return null;
|
||||
const n = step.node as TestNode;
|
||||
if (n.location) void openTarget(n.location, cwd, focus);
|
||||
return step;
|
||||
});
|
||||
const hasPrevFailed = findOccurrence(roots, selected, -1, treeModel) !== null;
|
||||
const hasNextFailed = findOccurrence(roots, selected, 1, treeModel) !== null;
|
||||
|
||||
const status = running ? "running" : counts.failed > 0 ? "failed" : counts.total > 0 ? "passed" : null;
|
||||
const duration = results.summary.durationMs;
|
||||
|
||||
@@ -240,15 +293,42 @@ export function TestTreeView({
|
||||
pressed={showIgnored}
|
||||
onClick={() => toggle("showIgnored")}
|
||||
/>
|
||||
<IconButton icon="expand-all" action="run.expandAllTests" size="small" iconSize={16} disabled={!hasSuites} />
|
||||
<IconButton
|
||||
icon="collapse-all"
|
||||
action="run.collapseAllTests"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
disabled={!hasSuites}
|
||||
/>
|
||||
<IconButton
|
||||
icon="arrow-up"
|
||||
action="navigate.prevOccurrence"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title="Previous Failed Test"
|
||||
disabled={!hasPrevFailed}
|
||||
/>
|
||||
<IconButton
|
||||
icon="arrow-down"
|
||||
action="navigate.nextOccurrence"
|
||||
size="small"
|
||||
iconSize={16}
|
||||
title="Next Failed Test"
|
||||
disabled={!hasNextFailed}
|
||||
/>
|
||||
</div>
|
||||
<Tree<TestNode>
|
||||
aria-label="Test results"
|
||||
className={styles.testTree}
|
||||
handleRef={tree}
|
||||
focusContext={TEST_TREE_FOCUS}
|
||||
roots={roots}
|
||||
getKey={(n) => n.id}
|
||||
getLabel={(n) => n.name}
|
||||
getChildren={(n) => (n.children.length ? n.children : undefined)}
|
||||
isExpandable={(n) => n.children.length > 0}
|
||||
isOccurrence={isFailedTest}
|
||||
expanded={effectiveExpanded}
|
||||
onExpandedChange={(next) => setExpanded(next)}
|
||||
selected={selectedKeys}
|
||||
|
||||
@@ -24,5 +24,5 @@ it("hides the Run tool window once its last tab is closed", async () => {
|
||||
await closeRunTab("t", useStackTraces.getState().tabs);
|
||||
expect(hide).not.toHaveBeenCalled();
|
||||
await closeRunTab("b", useStackTraces.getState().tabs);
|
||||
expect(hide).toHaveBeenCalledWith("run");
|
||||
expect(hide).toHaveBeenCalledWith("run", { removeFromStripe: true });
|
||||
});
|
||||
@@ -218,3 +218,48 @@ describe("Debug entry", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Run with Fuzzing", () => {
|
||||
const goTest: RunConfig = {
|
||||
...npmTest,
|
||||
id: "go:test",
|
||||
name: "go test ./...",
|
||||
kind: "go",
|
||||
command: "go",
|
||||
args: ["test", "./..."],
|
||||
debugAdapter: "delve",
|
||||
};
|
||||
const text = "package parse\nfunc TestParse(t *testing.T) {}\nfunc FuzzParse(f *testing.F) {\n}\n";
|
||||
const path = `${ROOT}/parse/parse_test.go`;
|
||||
const target = (line: number, name: string): RunTarget => ({ line, kind: "test", name, path: [name] });
|
||||
const itemLabels = (items: MenuItem[]) => items.map((i) => ("label" in i ? (i.label ?? "") : "---"));
|
||||
|
||||
beforeEach(() => {
|
||||
useProject.setState({ project: { name: "app", root: ROOT, trusted: true, isGit: false, settings: {} } as never });
|
||||
useRun.setState({ configs: [goTest], loaded: true });
|
||||
});
|
||||
afterEach(() => {
|
||||
useProject.setState({ project: null });
|
||||
useRun.setState({ configs: [], loaded: false });
|
||||
});
|
||||
|
||||
it("the gutter offers it on a Fuzz function, after Run and Debug", () => {
|
||||
expect(itemLabels(targetMenuItems(target(2, "FuzzParse"), path, text))).toEqual([
|
||||
"Run 'FuzzParse in parse'",
|
||||
"Debug 'FuzzParse in parse'",
|
||||
"Run 'FuzzParse in parse' with Fuzzing",
|
||||
"---",
|
||||
"Modify Run Configuration…",
|
||||
]);
|
||||
expect(itemLabels(targetMenuItems(target(1, "TestParse"), path, text)).some((l) => /Fuzzing/.test(l))).toBe(false);
|
||||
});
|
||||
|
||||
it("the editor menu offers it under More Run/Debug at a Fuzz function only", () => {
|
||||
const at = (line: number) => labels(contextMenuItems("editor", { paths: [path], text, line }));
|
||||
expect(at(2)).toContain("Run 'FuzzParse in parse' with Fuzzing");
|
||||
expect(at(1).some((l) => /Fuzzing/.test(l))).toBe(false);
|
||||
expect(
|
||||
labels(contextMenuItems("projectView", { paths: [path], dirs: [false] })).some((l) => /Fuzzing/.test(l)),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
produceContextChoices,
|
||||
produceDirectory,
|
||||
produceFile,
|
||||
produceFuzz,
|
||||
scriptLanguage,
|
||||
type ContextInput,
|
||||
type Produced,
|
||||
@@ -293,6 +294,21 @@ export function executorItems(config: RunConfig | null | undefined, name: string
|
||||
}));
|
||||
}
|
||||
|
||||
/** "Run '<FuzzXxx>' with Fuzzing" at a Go fuzz target: `go test -fuzz` until it is stopped or fails. */
|
||||
export function fuzzItems(input: ContextInput, context: ContextArg): MenuItem[] {
|
||||
const p = produceFuzz(input, OPTIMISTIC);
|
||||
return p ? [{ label: tx`Run '${p.name}' with Fuzzing`, icon: "run", run: () => void fuzzContext(context) }] : [];
|
||||
}
|
||||
|
||||
async function fuzzContext(arg: ContextArg): Promise<void> {
|
||||
await ensureConfigs();
|
||||
const input = await withArgContent(arg);
|
||||
if (!input) return;
|
||||
await loadGoModules(input.root, useRun.getState().configs);
|
||||
const p = produceFuzz({ ...input, configs: useRun.getState().configs, goModule: goModulePath }, OPTIMISTIC);
|
||||
if (p) await launchProduced(p, false);
|
||||
}
|
||||
|
||||
export interface ContextArg {
|
||||
path: string;
|
||||
line?: number;
|
||||
@@ -394,6 +410,7 @@ export function contextMenuItems(menu: ContextMenuId, ctx: MenuGroupContext): Me
|
||||
label: "More Run/Debug",
|
||||
submenu: [
|
||||
...executorItems(p.config, p.name, arg),
|
||||
...fuzzItems(input, arg),
|
||||
{ kind: "action", action: "run.modifyContext", arg, label: "Modify Run Configuration…", icon: "edit" },
|
||||
],
|
||||
},
|
||||
|
||||
@@ -99,6 +99,7 @@ import {
|
||||
isLive,
|
||||
} from "./store";
|
||||
import { rerunFailedConfigs } from "./testing/rerun";
|
||||
import { TEST_TREE_FOCUS, testTree } from "./testTree";
|
||||
import { startAgentRun, trimAgentArchive, type AgentRunRequest } from "./agentRuns";
|
||||
import { compoundTargets, selectedTarget } from "./sessionTargets";
|
||||
import { tx } from "@/platform/i18n";
|
||||
@@ -638,6 +639,24 @@ export function activate(): () => void {
|
||||
});
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "run.expandAllTests",
|
||||
title: "Expand All",
|
||||
category: "Run",
|
||||
icon: "expand-all",
|
||||
when: "projectOpen && activeToolWindow == 'run'",
|
||||
keyWhen: TEST_TREE_FOCUS,
|
||||
run: () => testTree.expandAll?.(),
|
||||
},
|
||||
{
|
||||
id: "run.collapseAllTests",
|
||||
title: "Collapse All",
|
||||
category: "Run",
|
||||
icon: "collapse-all",
|
||||
when: "projectOpen && activeToolWindow == 'run'",
|
||||
keyWhen: TEST_TREE_FOCUS,
|
||||
run: () => testTree.collapseAll?.(),
|
||||
},
|
||||
{
|
||||
id: "run.reloadConfigs",
|
||||
title: "Reload Run Configurations",
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
produceContextChoices,
|
||||
produceDirectory,
|
||||
produceFile,
|
||||
produceFuzz,
|
||||
shebang,
|
||||
shellWord,
|
||||
fileTargets,
|
||||
@@ -1137,6 +1138,57 @@ describe("Go test names (GoLand)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Go Run with Fuzzing (GoLand)", () => {
|
||||
const GO = [
|
||||
cfg({ id: "go:test", kind: "go", command: "go", args: ["test", "./..."], isTest: true, debugAdapter: "delve" }),
|
||||
];
|
||||
const src = [
|
||||
"package parse", // 0
|
||||
'import "testing"',
|
||||
"func TestParse(t *testing.T) {}", // 2
|
||||
"func BenchmarkParse(b *testing.B) {}",
|
||||
"func ExampleParse() {}",
|
||||
"func FuzzParse(f *testing.F) {", // 5
|
||||
'\tf.Add("x")',
|
||||
"\tf.Fuzz(func(t *testing.T, s string) {", // 7
|
||||
"\t})",
|
||||
"}",
|
||||
"func helper() {}", // 10
|
||||
].join("\n");
|
||||
const modules = (dir: string) => (dir === ROOT ? "example.com/fixture" : undefined);
|
||||
const at = (line: number | undefined, path = `${ROOT}/internal/parse/parse_test.go`, content = src) =>
|
||||
produceFuzz({ path, root: ROOT, configs: GO, content, line, goModule: modules }, ALL);
|
||||
|
||||
it("the Fuzz function at the caret, its body included, fuzzes its package", () => {
|
||||
for (const line of [5, 7]) {
|
||||
const p = at(line)!;
|
||||
expect(p.name).toBe("FuzzParse in example.com/fixture/internal/parse");
|
||||
expect(p.config).toMatchObject({
|
||||
args: ["test", "./internal/parse", "-run", "^FuzzParse$", "-fuzz", "^FuzzParse$"],
|
||||
name: "FuzzParse in example.com/fixture/internal/parse (fuzzing)",
|
||||
isTest: true,
|
||||
});
|
||||
}
|
||||
expect(at(5, `${ROOT}/parse_test.go`)!.config!.args).toEqual([
|
||||
"test",
|
||||
".",
|
||||
"-run",
|
||||
"^FuzzParse$",
|
||||
"-fuzz",
|
||||
"^FuzzParse$",
|
||||
]);
|
||||
});
|
||||
|
||||
it("nothing for tests, benchmarks, examples, other code or the file", () => {
|
||||
for (const line of [0, 2, 3, 4, 10, undefined]) expect(at(line)).toBeNull();
|
||||
// Not a test file: `go test` doesn't build its Fuzz functions as fuzz targets.
|
||||
expect(at(5, `${ROOT}/internal/parse/parse.go`)).toBeNull();
|
||||
// `Fuzzer` is not a fuzz target name; a Fuzz function needs a *testing.F.
|
||||
const misnamed = "package p\nfunc Fuzzer(f *testing.F) {}\nfunc FuzzT(t *testing.T) {}";
|
||||
for (const line of [1, 2]) expect(at(line, undefined, misnamed)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("CMake file context", () => {
|
||||
const configure = cfg({
|
||||
id: "cmake:build:configure",
|
||||
|
||||
@@ -31,7 +31,7 @@ import { djangoLabel, djangoTestsOf, hasDjangoTests } from "./djangoTypes";
|
||||
import { firstTopLevelType, scanJvmTargets, simpleClassName } from "./jvmTargets";
|
||||
import { isWindows } from "./jvmTypes";
|
||||
import { inheritedRunTargets } from "./inheritedMain";
|
||||
import { detectRunTargets, targetConfig, targetLanguage, zigTargets, type RunTarget } from "./targets";
|
||||
import { detectRunTargets, goFuzzConfig, targetConfig, targetLanguage, zigTargets, type RunTarget } from "./targets";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
export interface LocatedTool {
|
||||
@@ -1164,6 +1164,17 @@ export function produceContext(input: ContextInput, env: ToolEnv): Produced | nu
|
||||
return produceFile(input, env);
|
||||
}
|
||||
|
||||
/** GoLand's "Run '<name>' with Fuzzing": the `Fuzz` function at the caret, run with `go test -fuzz`. */
|
||||
export function produceFuzz(input: ContextInput, env: ToolEnv): Produced | null {
|
||||
input = scopedInput(input);
|
||||
if (input.content === undefined || input.line === undefined || !/_test\.go$/.test(input.path)) return null;
|
||||
const targets = fileTargets(input, input.content.slice(0, 400_000));
|
||||
const inner = innermostTarget(input.content, targets, input.line);
|
||||
const produced = inner && elementProduction(input, env, inner);
|
||||
const config = inner && produced?.config && goFuzzConfig(produced.config, inner);
|
||||
return produced && config ? { ...produced, config } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every configuration that can run the context, when several test
|
||||
* configurations match it equally well (`npm run test` and `npm run test:unit`):
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
canDebugProduced,
|
||||
choiceItems,
|
||||
executeContext,
|
||||
fuzzItems,
|
||||
launchProduced,
|
||||
modifyContext,
|
||||
produceResolved,
|
||||
@@ -123,6 +124,7 @@ export function targetMenuItems(target: RunTarget, path: string, content: string
|
||||
...runExecutors()
|
||||
.filter((e) => !!p?.config && e.supports(p.config))
|
||||
.map((e) => ({ label: e.label(name), icon: e.icon, run: () => void executeContext(e.id, context) })),
|
||||
...fuzzItems(input, context),
|
||||
{ kind: "separator" },
|
||||
{ label: "Modify Run Configuration…", icon: "edit", run: () => void modifyContext(context) },
|
||||
];
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { detectRunTargets, jsNamePattern, targetConfig } from "./targets";
|
||||
import { detectRunTargets, goFuzzConfig, jsNamePattern, targetConfig, type RunTarget } from "./targets";
|
||||
|
||||
const cfg = (over: Partial<RunConfig> & { id: string; kind: string }): RunConfig => ({
|
||||
name: over.id,
|
||||
@@ -239,6 +239,99 @@ describe("Go test targets", () => {
|
||||
"-test.short",
|
||||
]);
|
||||
});
|
||||
describe("Run with Fuzzing", () => {
|
||||
const text = [
|
||||
"package parse",
|
||||
"func TestParse(t *testing.T) {}",
|
||||
"func BenchmarkParse(b *testing.B) {}",
|
||||
"func FuzzParse(f *testing.F) {",
|
||||
' f.Add("x")',
|
||||
" f.Fuzz(func(t *testing.T, s string) {})",
|
||||
"}",
|
||||
"func ExampleParse() {}",
|
||||
].join("\n");
|
||||
const base = cfg({ id: "go:test", kind: "go", args: ["test", "-tags", "demo", "./...", "-args", "-test.short"] });
|
||||
const fuzzOf = (rel: string, name: string, configs = [base]) => {
|
||||
const target = detectRunTargets(text, rel).find((t) => t.name === name)!;
|
||||
const config = targetConfig(target, rel, configs, text)!;
|
||||
return goFuzzConfig(config, target);
|
||||
};
|
||||
|
||||
it("adds -fuzz with the -run pattern of a Fuzz function", () => {
|
||||
const config = fuzzOf("parse/parse_test.go", "FuzzParse")!;
|
||||
expect(config.args).toEqual([
|
||||
"test",
|
||||
"-tags",
|
||||
"demo",
|
||||
"./parse",
|
||||
"-run",
|
||||
"^FuzzParse$",
|
||||
"-fuzz",
|
||||
"^FuzzParse$",
|
||||
"-args",
|
||||
"-test.short",
|
||||
]);
|
||||
// A temporary configuration of its own, beside the plain run of the fuzz target.
|
||||
expect(config.id).not.toBe(
|
||||
targetConfig(detectRunTargets(text, "parse/parse_test.go")[2]!, "parse/parse_test.go", [base], text)!.id,
|
||||
);
|
||||
expect(config.name).toBe("FuzzParse (fuzzing)");
|
||||
});
|
||||
|
||||
it("runs a fuzz target at the module root and in nested package directories", () => {
|
||||
expect(fuzzOf("parse_test.go", "FuzzParse")!.args.slice(3, 4)).toEqual(["."]);
|
||||
expect(fuzzOf("internal/text/parse/parse_test.go", "FuzzParse")!.args.slice(3, 4)).toEqual([
|
||||
"./internal/text/parse",
|
||||
]);
|
||||
});
|
||||
|
||||
it("is offered for Fuzz functions only", () => {
|
||||
for (const name of ["TestParse", "BenchmarkParse", "ExampleParse"])
|
||||
expect(fuzzOf("parse/parse_test.go", name)).toBeNull();
|
||||
const npm = cfg({ id: "npm:test", kind: "npm", command: "npm", args: ["run", "test"] });
|
||||
const js: RunTarget = { line: 0, kind: "test", name: "Fuzz it", path: ["Fuzz it"] };
|
||||
expect(goFuzzConfig(targetConfig(js, "src/a.test.ts", [npm])!, js)).toBeNull();
|
||||
});
|
||||
|
||||
it("escapes the name and replaces a saved selection", () => {
|
||||
const saved = cfg({
|
||||
id: "go:saved",
|
||||
kind: "go",
|
||||
args: ["test", "-fuzz=Old", "-run", "Old", "-bench", ".", "./parse", "-fuzztime", "30s"],
|
||||
});
|
||||
const target: RunTarget = { line: 0, kind: "test", name: "Fuzz.Δ+", path: ["Fuzz.Δ+"] };
|
||||
expect(goFuzzConfig(saved, target)!.args).toEqual([
|
||||
"test",
|
||||
"-fuzztime",
|
||||
"30s",
|
||||
"./parse",
|
||||
"-run",
|
||||
"^Fuzz\\.Δ\\+$",
|
||||
"-fuzz",
|
||||
"^Fuzz\\.Δ\\+$",
|
||||
]);
|
||||
});
|
||||
|
||||
it("needs exactly one package: -fuzz cannot match across packages", () => {
|
||||
const target: RunTarget = { line: 0, kind: "test", name: "FuzzParse", path: ["FuzzParse"] };
|
||||
const go = (args: string[]) => cfg({ id: "go:x", kind: "go", args });
|
||||
expect(goFuzzConfig(go(["test", "./..."]), target)).toBeNull();
|
||||
expect(goFuzzConfig(go(["test", "./a", "./b"]), target)).toBeNull();
|
||||
expect(goFuzzConfig(go(["run", "."]), target)).toBeNull();
|
||||
expect(goFuzzConfig(go(["test", "./a"]), target)).not.toBeNull();
|
||||
});
|
||||
|
||||
it("keeps a Go Test configuration's form in step", () => {
|
||||
const typed = cfg({
|
||||
id: "go:typed",
|
||||
kind: "go",
|
||||
args: ["test", "-tags", "demo", "."],
|
||||
params: { goKind: "test", scope: "package", target: ".", toolArgs: "-tags demo" },
|
||||
});
|
||||
const config = fuzzOf("parse/parse_test.go", "FuzzParse", [typed])!;
|
||||
expect(config.params).toMatchObject({ pattern: "^FuzzParse$", toolArgs: "-tags demo -fuzz '^FuzzParse$'" });
|
||||
});
|
||||
});
|
||||
it("uses the module and overrides a saved filter before binary arguments", () => {
|
||||
const base = cfg({
|
||||
id: "go:typed",
|
||||
|
||||
@@ -415,6 +415,29 @@ function withLast(args: string[], f: (last: string) => string): string[] {
|
||||
return args.length ? [...args.slice(0, -1), f(args[args.length - 1]!)] : args;
|
||||
}
|
||||
|
||||
/**
|
||||
* GoLand's "Run with Fuzzing" of a `Fuzz` function: its `go test` configuration with
|
||||
* `-fuzz` added. Null for other targets, and when the configuration doesn't test one
|
||||
* package (`go test -fuzz` refuses several).
|
||||
*/
|
||||
export function goFuzzConfig(config: RunConfig, target: RunTarget): RunConfig | null {
|
||||
if (target.kind !== "test" || target.path.length !== 1 || !/^Fuzz/.test(target.name)) return null;
|
||||
if (config.kind !== "go" || config.args[0] !== "test") return null;
|
||||
const parts = goTestParts(config.args);
|
||||
if (parts.targets.length !== 1 || /(^|\/)\.\.\.$/.test(parts.targets[0]!)) return null;
|
||||
const pattern = `^${escapeRegExp(target.name)}$`;
|
||||
const flags = withoutGoSelection(parts.flags);
|
||||
return {
|
||||
...config,
|
||||
id: `${config.id}:fuzz`,
|
||||
name: `${config.name} (fuzzing)`,
|
||||
args: ["test", ...flags, ...parts.targets, "-run", pattern, "-fuzz", pattern, ...withoutGoSelection(parts.program)],
|
||||
...(config.params?.goKind
|
||||
? { params: { ...config.params, pattern, toolArgs: formatArgs([...flags, "-fuzz", pattern]) } }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** Run configuration for one target, or null when the project has no matching runner. */
|
||||
export function targetConfig(
|
||||
target: RunTarget,
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
/** Context key: the test results tree has focus. */
|
||||
export const TEST_TREE_FOCUS = "testTreeFocus";
|
||||
|
||||
/** Set while a test results tree is shown: Expand All / Collapse All act on it. */
|
||||
export const testTree: { expandAll: (() => void) | null; collapseAll: (() => void) | null } = {
|
||||
expandAll: null,
|
||||
collapseAll: null,
|
||||
};
|
||||
@@ -1,8 +1,10 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { provideToolWindowService, type ToolWindowService } from "@/workbench/contributions";
|
||||
import type { FileMatches, SearchQuery } from "@/platform/ipc";
|
||||
import { buildFindTree } from "../find/FindToolWindow";
|
||||
import type { FindDeps } from "../find/session";
|
||||
import {
|
||||
closeFindTab,
|
||||
disposeFindWindow,
|
||||
openEditorResults,
|
||||
openInFindWindow,
|
||||
@@ -38,6 +40,18 @@ const file = (rel: string): FileMatches => ({
|
||||
afterEach(disposeFindWindow);
|
||||
|
||||
describe("Find tool window tabs", () => {
|
||||
it("take the tool window and its stripe button away with the last one", () => {
|
||||
const hide = vi.fn();
|
||||
provideToolWindowService({ show: vi.fn(), hide } as unknown as ToolWindowService);
|
||||
const a = openInFindWindow(q("a"), "a", { deps });
|
||||
pinFindTab(a, true);
|
||||
const b = openInFindWindow(q("b"), "b", { deps });
|
||||
closeFindTab(a);
|
||||
expect(hide).not.toHaveBeenCalled();
|
||||
closeFindTab(b);
|
||||
expect(hide).toHaveBeenCalledWith("find", { removeFromStripe: true });
|
||||
});
|
||||
|
||||
it("reuses the selected tab unless it is pinned", () => {
|
||||
const a = openInFindWindow(q("a"), "a", { deps });
|
||||
const b = openInFindWindow(q("b"), "b", { deps });
|
||||
|
||||
@@ -134,6 +134,8 @@ export function closeFindTab(id: number) {
|
||||
const active = s.active === id ? (tabs[Math.min(i, tabs.length - 1)]?.id ?? null) : s.active;
|
||||
return { tabs, active };
|
||||
});
|
||||
// As in IDEA, the tool window and its stripe button go away with its last tab.
|
||||
if (!useFindWindow.getState().tabs.length) maybeToolWindowService()?.hide("find", { removeFromStripe: true });
|
||||
}
|
||||
|
||||
export function disposeFindWindow() {
|
||||
|
||||
@@ -71,6 +71,7 @@ import {
|
||||
setCommitDiffPreview,
|
||||
setDiffPreview,
|
||||
setGroupByDir,
|
||||
setGroupByRepo,
|
||||
setGroupByStaging,
|
||||
useCommit,
|
||||
type CommitTab,
|
||||
@@ -567,6 +568,7 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
|
||||
const root = useVcs((s) => s.root) ?? "";
|
||||
const groupByDir = useCommit((s) => s.groupByDir);
|
||||
const groupByStaging = useCommit((s) => s.groupByStaging);
|
||||
const groupByRepo = useCommit((s) => s.groupByRepo);
|
||||
const diffPreview = useCommit((s) => s.diffPreview);
|
||||
const commitDiffPreview = useCommit((s) => s.commitDiffPreview);
|
||||
const doubleClickOpensDiff = useWorkflowSettings((s) => s.vcs.commit.doubleClickOpensDiff);
|
||||
@@ -584,8 +586,8 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
|
||||
const heads = useVcs((s) => s.heads);
|
||||
const projectRoots = useEffectiveRoots();
|
||||
const roots = useMemo(
|
||||
() => buildChangeTree(status, root, groupByDir, lists, repos, groupByStaging, heads),
|
||||
[status, root, groupByDir, lists, repos, groupByStaging, heads],
|
||||
() => buildChangeTree(status, root, groupByDir, lists, repos, groupByStaging, heads, groupByRepo),
|
||||
[status, root, groupByDir, lists, repos, groupByStaging, heads, groupByRepo],
|
||||
);
|
||||
const [byKey, parents] = useMemo(() => {
|
||||
const m = new Map<string, ChangeNode>();
|
||||
@@ -703,6 +705,10 @@ export function ChangesTree({ mode }: { mode: "commit" | "local" | "dialog" }) {
|
||||
showContextMenu(bottomLeft(viewRef.current), [
|
||||
{ kind: "header", label: "Group By" },
|
||||
{ label: "Directory", checked: groupByDir, run: () => setGroupByDir(!groupByDir) },
|
||||
// IDEA offers it once the project has several repositories.
|
||||
...(repos.length > 1
|
||||
? [{ label: "Repository", checked: groupByRepo, run: () => setGroupByRepo(!groupByRepo) }]
|
||||
: []),
|
||||
{ label: "Staging State", checked: groupByStaging, run: () => setGroupByStaging(!groupByStaging) },
|
||||
...(mode === "local"
|
||||
? [
|
||||
|
||||
@@ -10,12 +10,23 @@ const mocks = vi.hoisted(() => ({
|
||||
restoreBranch: vi.fn(),
|
||||
branches: vi.fn(),
|
||||
rename: vi.fn(),
|
||||
ask: vi.fn(),
|
||||
checkout: vi.fn(),
|
||||
executeAction: vi.fn(),
|
||||
}));
|
||||
vi.mock("../dialogs", async (original) => ({
|
||||
...(await original<typeof import("../dialogs")>()),
|
||||
promptText: mocks.prompt,
|
||||
confirmDialog: mocks.confirm,
|
||||
}));
|
||||
vi.mock("@/workbench/messages", async (original) => ({
|
||||
...(await original<typeof import("@/workbench/messages")>()),
|
||||
ask: mocks.ask,
|
||||
}));
|
||||
vi.mock("@/platform/actions", async (original) => ({
|
||||
...(await original<typeof import("@/platform/actions")>()),
|
||||
executeAction: mocks.executeAction,
|
||||
}));
|
||||
vi.mock("@/workbench/contributions", () => ({ notifications: () => ({ notify: mocks.notify, expire: vi.fn() }) }));
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const real = await original<typeof import("@/platform/ipc")>();
|
||||
@@ -29,10 +40,11 @@ vi.mock("@/platform/ipc", async (original) => {
|
||||
vcsRestoreBranch: mocks.restoreBranch,
|
||||
vcsBranches: mocks.branches,
|
||||
vcsRenameBranch: mocks.rename,
|
||||
vcsCheckout: mocks.checkout,
|
||||
},
|
||||
};
|
||||
});
|
||||
import { deleteBranch, deleteBranches, newBranch, newBranchInRepos, renameBranch } from "../branchOps";
|
||||
import { checkoutBranch, deleteBranch, deleteBranches, newBranch, newBranchInRepos, renameBranch } from "../branchOps";
|
||||
import { useVcs } from "../store";
|
||||
import { useProject } from "@/platform/project";
|
||||
|
||||
@@ -175,6 +187,38 @@ it("deletes a worktree holding the branch before deleting it", async () => {
|
||||
expect(mocks.deleteBranch).toHaveBeenCalledWith("/p/front", "feature/wt");
|
||||
});
|
||||
|
||||
it("offers to open the worktree that has the branch checked out", async () => {
|
||||
mocks.checkout.mockResolvedValue(ok({ kind: "checkedOutInWorktree", branch: "feature/wt", path: "/p/front-wt" }));
|
||||
mocks.ask.mockResolvedValue({ button: "open" });
|
||||
await checkoutBranch("feature/wt");
|
||||
expect(mocks.checkout).toHaveBeenCalledWith("/p/front", "feature/wt", false, { mode: "normal", diverged: null });
|
||||
expect(mocks.ask.mock.calls[0]?.[0].title).toBe("Worktree Conflict");
|
||||
expect(mocks.ask.mock.calls[0]?.[0].body).toContain("already checked out in a worktree at:\n/p/front-wt");
|
||||
expect(mocks.executeAction).toHaveBeenCalledWith("file.openProjectPath", "/p/front-wt");
|
||||
expect(mocks.checkout).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("checks the branch out anyway when asked, alongside the other worktree", async () => {
|
||||
mocks.checkout
|
||||
.mockResolvedValueOnce(ok({ kind: "checkedOutInWorktree", branch: "feature/wt", path: "/p/front-wt" }))
|
||||
.mockResolvedValueOnce(ok({ kind: "done" }));
|
||||
mocks.ask.mockResolvedValue({ button: "anyway" });
|
||||
await checkoutBranch("feature/wt");
|
||||
expect(mocks.checkout).toHaveBeenLastCalledWith("/p/front", "feature/wt", false, {
|
||||
mode: "normal",
|
||||
diverged: null,
|
||||
ignoreOtherWorktrees: true,
|
||||
});
|
||||
expect(mocks.executeAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not open the worktree when the checkout offer is declined", async () => {
|
||||
mocks.checkout.mockResolvedValue(ok({ kind: "checkedOutInWorktree", branch: "feature/wt", path: "/p/front-wt" }));
|
||||
mocks.ask.mockResolvedValue({ button: "cancel" });
|
||||
await checkoutBranch("feature/wt");
|
||||
expect(mocks.executeAction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps the branch when the worktree question is turned down", async () => {
|
||||
mocks.worktrees.mockResolvedValue(ok([worktree("/p/front-feature-wt", "feature/wt")]));
|
||||
mocks.confirm.mockResolvedValue(false);
|
||||
|
||||
@@ -229,6 +229,97 @@ describe("several repositories", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Group By › Repository off", () => {
|
||||
const at = (path: string, unstaged: FileStatus["unstaged"] = "modified", staged: FileStatus["staged"] = null) => ({
|
||||
path,
|
||||
relPath: path.split("/").slice(3).join("/"),
|
||||
staged,
|
||||
unstaged,
|
||||
renamedFrom: null,
|
||||
});
|
||||
// Two repositories holding the same repository-relative path.
|
||||
const repos = ["/w/api", "/w/sdk"];
|
||||
const twins = [at("/w/api/src/config.ts"), at("/w/sdk/src/config.ts"), at("/w/sdk/src/client.ts")];
|
||||
const keys = (nodes: readonly ChangeNode[]): string[] => nodes.flatMap((n) => [n.key, ...keys(n.children ?? [])]);
|
||||
const files = (nodes: readonly ChangeNode[]) =>
|
||||
changeFileNodes(nodes).map((n) => `${n.label} ${n.path} ${n.detail || "-"}`);
|
||||
|
||||
it("lists the files of all repositories together, told apart by their directory", () => {
|
||||
const tree = buildChangeTree(twins, "/w", false, undefined, repos, false, {}, false);
|
||||
expect(shape(tree)).toEqual(["Changes", " client.ts", " config.ts", " config.ts"]);
|
||||
expect(files(tree)).toEqual([
|
||||
"client.ts /w/sdk/src/client.ts sdk/src",
|
||||
"config.ts /w/api/src/config.ts api/src",
|
||||
"config.ts /w/sdk/src/config.ts sdk/src",
|
||||
]);
|
||||
const all = keys(tree);
|
||||
expect(new Set(all).size).toBe(all.length);
|
||||
});
|
||||
|
||||
it("keeps directory grouping, with each repository's directories apart", () => {
|
||||
const tree = buildChangeTree(twins, "/w", true, undefined, repos, false, {}, false);
|
||||
expect(shape(tree)).toEqual([
|
||||
"Changes",
|
||||
" api/src",
|
||||
" config.ts",
|
||||
" sdk/src",
|
||||
" client.ts",
|
||||
" config.ts",
|
||||
]);
|
||||
expect(tree[0]!.children!.map((n) => [n.path, n.files.length])).toEqual([
|
||||
["/w/api/src", 1],
|
||||
["/w/sdk/src", 2],
|
||||
]);
|
||||
const all = keys(tree);
|
||||
expect(new Set(all).size).toBe(all.length);
|
||||
});
|
||||
|
||||
it("shows a repository outside the project by its absolute directory", () => {
|
||||
const outside = [at("/w/README.md"), at("/x/lib/src/Lib.kt")];
|
||||
const flat = buildChangeTree(outside, "/w", false, undefined, ["/w", "/x/lib"], false, {}, false);
|
||||
expect(files(flat)).toEqual(["Lib.kt /x/lib/src/Lib.kt /x/lib/src", "README.md /w/README.md -"]);
|
||||
const dirs = buildChangeTree(outside, "/w", true, undefined, ["/w", "/x/lib"], false, {}, false);
|
||||
expect(shape(dirs)).toEqual(["Changes", " /x/lib/src", " Lib.kt", " README.md"]);
|
||||
expect(dirs[0]!.children![0]!.path).toBe("/x/lib/src");
|
||||
});
|
||||
|
||||
it("applies to every group, staging groups and change lists included", () => {
|
||||
const mixed = [...twins, at("/w/api/new.txt", "untracked"), at("/w/sdk/src/both.ts", "modified", "modified")];
|
||||
const noRepoNodes = (tree: ChangeNode[]) =>
|
||||
tree.every((g) => g.children!.every((n) => n.type === "file" && !repos.includes(n.path!)));
|
||||
expect(noRepoNodes(buildChangeTree(mixed, "/w", false, undefined, repos, false, {}, false))).toBe(true);
|
||||
expect(noRepoNodes(buildChangeTree(mixed, "/w", false, undefined, repos, true, {}, false))).toBe(true);
|
||||
const lists = { active: "default", lists: [{ id: "default", name: "Changes", comment: "" }], files: {} };
|
||||
const listed = buildChangeTree(mixed, "/w", false, lists as never, repos, false, {}, false);
|
||||
expect(noRepoNodes(listed)).toBe(true);
|
||||
expect(changeFileNodes(listed).every((n) => n.changelist === "default" || n.group === "unversioned")).toBe(true);
|
||||
});
|
||||
|
||||
it("checks and commits files of every repository from the one flat group", () => {
|
||||
const [changes] = buildChangeTree(twins, "/w", false, undefined, repos, false, {}, false);
|
||||
expect(aggregateCheck(changes!.files, new Map())).toMatchObject({ checked: true, on: 3 });
|
||||
const checks = new Map<string, CheckState>([["/w/api/src/config.ts", "none"]]);
|
||||
expect(aggregateCheck(changes!.files, checks)).toMatchObject({ checked: false, indeterminate: true, on: 2 });
|
||||
const plan = planCommit(twins, checks);
|
||||
expect(plan.included.map((f) => f.path)).toEqual(["/w/sdk/src/config.ts", "/w/sdk/src/client.ts"]);
|
||||
expect(commitRepos(planCommit(twins, new Map()).included, repos, "/w/api")).toEqual(["/w/sdk", "/w/api"]);
|
||||
});
|
||||
|
||||
it("is on by default: a repository level as before", () => {
|
||||
expect(buildChangeTree(twins, "/w", true, undefined, repos, false, {})).toEqual(
|
||||
buildChangeTree(twins, "/w", true, undefined, repos, false, {}, true),
|
||||
);
|
||||
expect(shape(buildChangeTree(twins, "/w", false, undefined, repos))).toEqual([
|
||||
"Changes",
|
||||
" api",
|
||||
" config.ts",
|
||||
" sdk",
|
||||
" client.ts",
|
||||
" config.ts",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ignore targets", () => {
|
||||
const group = (roots: ChangeNode[], id: string) => roots.find((n) => n.group === id)!;
|
||||
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return { ...real, call: vi.fn() };
|
||||
});
|
||||
|
||||
vi.mock("../DiffEditor", () => ({ DiffEditor: () => <div /> }));
|
||||
|
||||
import { ChangesTree } from "../CommitView";
|
||||
import { setGroupByRepo, useCommit } from "../commitStore";
|
||||
import { useVcs } from "../store";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { useContextMenuStore, type MenuItem } from "@/ui/Menu";
|
||||
|
||||
const change = (path: string) => ({
|
||||
path,
|
||||
relPath: path.split("/").slice(3).join("/"),
|
||||
staged: null,
|
||||
unstaged: "modified" as const,
|
||||
renamedFrom: null,
|
||||
});
|
||||
|
||||
/** The Group By items of the View Options menu: label → checked. */
|
||||
function groupByItems(): Record<string, boolean> {
|
||||
act(() => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "View Options" }));
|
||||
});
|
||||
const items = useContextMenuStore.getState().menu!.items as Array<MenuItem & { label?: string; checked?: boolean }>;
|
||||
act(() => useContextMenuStore.setState({ menu: null }));
|
||||
const end = items.findIndex((i) => i.kind === "separator");
|
||||
return Object.fromEntries(
|
||||
items
|
||||
.slice(0, end < 0 ? undefined : end)
|
||||
.filter((i) => i.kind !== "header" && i.label)
|
||||
.map((i) => [i.label!, !!i.checked]),
|
||||
);
|
||||
}
|
||||
|
||||
function runItem(label: string) {
|
||||
act(() => {
|
||||
fireEvent.click(screen.getByRole("button", { name: "View Options" }));
|
||||
});
|
||||
const item = useContextMenuStore.getState().menu!.items.find((i) => "label" in i && i.label === label) as {
|
||||
run: () => void;
|
||||
};
|
||||
act(() => {
|
||||
item.run();
|
||||
useContextMenuStore.setState({ menu: null });
|
||||
});
|
||||
}
|
||||
|
||||
describe("Group By › Repository in the changes tree", () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
useCommit.setState({
|
||||
groupByDir: false,
|
||||
groupByStaging: false,
|
||||
groupByRepo: true,
|
||||
checks: new Map(),
|
||||
selection: [],
|
||||
});
|
||||
useProject.setState({
|
||||
project: { name: "p", root: "/p", trusted: true, isGit: true, settings: {} } as never,
|
||||
settings: {} as never,
|
||||
});
|
||||
useVcs.setState({
|
||||
root: "/p",
|
||||
repo: "/p",
|
||||
roots: ["/p", "/p/orders"],
|
||||
status: [change("/p/src/App.kt"), change("/p/orders/src/App.kt")],
|
||||
heads: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("is offered, checked, with several repositories", () => {
|
||||
render(<ChangesTree mode="commit" />);
|
||||
expect(groupByItems()).toEqual({ Directory: false, Repository: true, "Staging State": false });
|
||||
});
|
||||
|
||||
it("is not offered with one repository", () => {
|
||||
useVcs.setState({ roots: ["/p"], status: [change("/p/src/App.kt")] });
|
||||
render(<ChangesTree mode="commit" />);
|
||||
expect(groupByItems()).toEqual({ Directory: false, "Staging State": false });
|
||||
});
|
||||
|
||||
it("unchecked, lists both repositories' files together and remembers the choice", () => {
|
||||
render(<ChangesTree mode="commit" />);
|
||||
expect(screen.getByText("orders")).toBeTruthy();
|
||||
runItem("Repository");
|
||||
expect(useCommit.getState().groupByRepo).toBe(false);
|
||||
expect(localStorage.getItem("openidea.vcs.groupByRepo")).toBe("false");
|
||||
expect(screen.queryByText("orders")).toBeNull();
|
||||
expect(screen.getAllByText("App.kt")).toHaveLength(2);
|
||||
expect(screen.getByText("orders/src")).toBeTruthy();
|
||||
expect(groupByItems().Repository).toBe(false);
|
||||
// Each file keeps its own checkbox.
|
||||
const boxes = screen.getAllByRole("checkbox", { name: "Include App.kt in commit" });
|
||||
expect(boxes).toHaveLength(2);
|
||||
act(() => {
|
||||
fireEvent.mouseDown(boxes[0]!);
|
||||
});
|
||||
expect([...useCommit.getState().checks]).toEqual([["/p/orders/src/App.kt", "none"]]);
|
||||
runItem("Repository");
|
||||
expect(localStorage.getItem("openidea.vcs.groupByRepo")).toBe("true");
|
||||
expect(screen.getByText("orders")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Group By › Repository persistence", () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it("starts on when nothing is stored", async () => {
|
||||
const { useCommit: fresh } = await import("../commitStore");
|
||||
expect(fresh.getState().groupByRepo).toBe(true);
|
||||
});
|
||||
|
||||
it("starts with the stored choice", async () => {
|
||||
setGroupByRepo(false);
|
||||
const { useCommit: fresh } = await import("../commitStore");
|
||||
expect(fresh.getState().groupByRepo).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
pushes: [] as Array<{ repo: string | null; message: string | null; paths: string[] | null }>,
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
const ok = (data: unknown) => Promise.resolve({ status: "ok" as const, data });
|
||||
return {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
vcsBranchInfo: (repo: string | null) =>
|
||||
ok({
|
||||
head: repo === "/p/b" ? "dev" : "main",
|
||||
headCommit: "c1",
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
operation: null,
|
||||
}),
|
||||
vcsStashPush: (
|
||||
repo: string | null,
|
||||
message: string | null,
|
||||
_untracked: boolean,
|
||||
_keepIndex: boolean,
|
||||
paths: string[] | null,
|
||||
) => {
|
||||
mocks.pushes.push({ repo, message, paths });
|
||||
return ok(null);
|
||||
},
|
||||
vcsStashes: () => ok([]),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
import { VcsDialogHost } from "../dialogs";
|
||||
import { stashChanges } from "../changeOps";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.pushes = [];
|
||||
useVcs.setState({
|
||||
root: "/p",
|
||||
roots: ["/p/a", "/p/b"],
|
||||
repo: "/p/a",
|
||||
branch: { head: "main", headCommit: "c1", upstream: null, ahead: 0, behind: 0, operation: null },
|
||||
available: false,
|
||||
});
|
||||
});
|
||||
|
||||
const pick = async (combo: string, option: string) => {
|
||||
fireEvent.click(screen.getByRole("button", { name: combo }));
|
||||
fireEvent.click(await screen.findByRole("option", { name: option }));
|
||||
};
|
||||
|
||||
it("offers no repository choice when the project has one repository", async () => {
|
||||
useVcs.setState({ roots: ["/p"], repo: null });
|
||||
render(<VcsDialogHost />);
|
||||
let done!: Promise<void>;
|
||||
act(() => {
|
||||
done = stashChanges();
|
||||
});
|
||||
expect(await screen.findByText("Current branch: main")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Repository" })).toBeNull();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Create Stash" }));
|
||||
await done;
|
||||
expect(mocks.pushes).toEqual([{ repo: null, message: null, paths: null }]);
|
||||
});
|
||||
|
||||
it("stashes the repository picked in the dialog and shows its branch", async () => {
|
||||
render(<VcsDialogHost />);
|
||||
let done!: Promise<void>;
|
||||
act(() => {
|
||||
done = stashChanges();
|
||||
});
|
||||
expect(await screen.findByText("Current branch: main")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Repository" })).toHaveTextContent("a");
|
||||
|
||||
fireEvent.change(screen.getByRole("textbox", { name: "Message" }), { target: { value: "wip b" } });
|
||||
await pick("Repository", "b");
|
||||
expect(await screen.findByText("Current branch: dev")).toBeInTheDocument();
|
||||
expect(screen.queryByText("Current branch: main")).toBeNull();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Create Stash" }));
|
||||
await done;
|
||||
expect(mocks.pushes).toEqual([{ repo: "/p/b", message: "wip b", paths: null }]);
|
||||
});
|
||||
|
||||
it("starts on the repository it was given and can switch back", async () => {
|
||||
render(<VcsDialogHost />);
|
||||
let done!: Promise<void>;
|
||||
act(() => {
|
||||
done = stashChanges([], "/p/b");
|
||||
});
|
||||
expect(await screen.findByText("Current branch: dev")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Repository" })).toHaveTextContent("b");
|
||||
|
||||
await pick("Repository", "a");
|
||||
expect(await screen.findByText("Current branch: main")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Create Stash" }));
|
||||
await done;
|
||||
expect(mocks.pushes).toEqual([{ repo: "/p/a", message: null, paths: null }]);
|
||||
});
|
||||
|
||||
it("offers no repository choice when stashing selected files, which pick their own repositories", async () => {
|
||||
render(<VcsDialogHost />);
|
||||
let done!: Promise<void>;
|
||||
act(() => {
|
||||
done = stashChanges(["/p/a/x.ts", "/p/b/y.ts"]);
|
||||
});
|
||||
expect(await screen.findByText("Current branch: main")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Repository" })).toBeNull();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Create Stash" }));
|
||||
await done;
|
||||
expect(mocks.pushes).toEqual([{ repo: "/p/a", message: null, paths: ["/p/a/x.ts", "/p/b/y.ts"] }]);
|
||||
});
|
||||
|
||||
it("stashes nothing when cancelled after picking another repository", async () => {
|
||||
render(<VcsDialogHost />);
|
||||
let done!: Promise<void>;
|
||||
act(() => {
|
||||
done = stashChanges();
|
||||
});
|
||||
await pick("Repository", "b");
|
||||
expect(await screen.findByText("Current branch: dev")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
||||
await done;
|
||||
await waitFor(() => expect(screen.queryByRole("button", { name: "Repository" })).toBeNull());
|
||||
expect(mocks.pushes).toEqual([]);
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
created: [] as Array<{ repo: string | null; name: string; commit: string; message: string | null; force: boolean }>,
|
||||
tags: {} as Record<string, Promise<string[]> | string[]>,
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
const ok = (data: unknown) => Promise.resolve({ status: "ok" as const, data });
|
||||
return {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
vcsTags: async (repo: string | null) => ({ status: "ok" as const, data: await (mocks.tags[repo ?? ""] ?? []) }),
|
||||
vcsCreateTag: (repo: string | null, name: string, commit: string, message: string | null, force: boolean) => {
|
||||
mocks.created.push({ repo, name, commit, message, force });
|
||||
return ok(null);
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
import { VcsDialogHost } from "../dialogs";
|
||||
import { showTagDialog } from "../operations";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.created = [];
|
||||
mocks.tags = { "/p/a": ["v1.0"], "/p/b": ["v2.0"], "/p": ["v1.0"] };
|
||||
useVcs.setState({
|
||||
root: "/p",
|
||||
roots: ["/p/a", "/p/b"],
|
||||
repo: "/p/a",
|
||||
branch: { head: "main", headCommit: "c1", upstream: null, ahead: 0, behind: 0, operation: null },
|
||||
available: false,
|
||||
});
|
||||
});
|
||||
|
||||
const pick = async (combo: string, option: string) => {
|
||||
fireEvent.click(screen.getByRole("button", { name: combo }));
|
||||
fireEvent.click(await screen.findByRole("option", { name: option }));
|
||||
};
|
||||
|
||||
const typeName = (value: string) => fireEvent.change(screen.getByLabelText("Tag name:"), { target: { value } });
|
||||
|
||||
it("offers no repository choice when the project has one repository", async () => {
|
||||
useVcs.setState({ roots: ["/p"], repo: null });
|
||||
mocks.tags = { "": ["v1.0"] };
|
||||
render(<VcsDialogHost />);
|
||||
await act(() => showTagDialog());
|
||||
expect(await screen.findByText("Tag")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Repository" })).toBeNull();
|
||||
|
||||
typeName("v1.0");
|
||||
expect(await screen.findByText("Tag 'v1.0' already exists")).toBeInTheDocument();
|
||||
typeName("v1.1");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Create Tag" }));
|
||||
await waitFor(() => expect(mocks.created).toHaveLength(1));
|
||||
expect(mocks.created[0]).toMatchObject({ repo: null, name: "v1.1", commit: "HEAD" });
|
||||
});
|
||||
|
||||
it("creates the tag in the repository picked in the dialog", async () => {
|
||||
render(<VcsDialogHost />);
|
||||
await act(() => showTagDialog());
|
||||
expect(screen.getByRole("button", { name: "Repository" })).toHaveTextContent("a");
|
||||
|
||||
await pick("Repository", "b");
|
||||
expect(screen.getByRole("button", { name: "Repository" })).toHaveTextContent("b");
|
||||
typeName("v3.0");
|
||||
fireEvent.change(screen.getByLabelText("Message:"), { target: { value: "Release" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Create Tag" }));
|
||||
await waitFor(() => expect(mocks.created).toHaveLength(1));
|
||||
expect(mocks.created[0]).toEqual({ repo: "/p/b", name: "v3.0", commit: "HEAD", message: "Release", force: false });
|
||||
});
|
||||
|
||||
it("checks the name against the tags of the picked repository", async () => {
|
||||
render(<VcsDialogHost />);
|
||||
await act(() => showTagDialog());
|
||||
|
||||
typeName("v1.0");
|
||||
expect(await screen.findByText("Tag 'v1.0' already exists")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Create Tag" })).toBeDisabled();
|
||||
|
||||
// v1.0 exists only in a: the name is free in b, and b's own v2.0 is taken.
|
||||
await pick("Repository", "b");
|
||||
await waitFor(() => expect(screen.queryByText("Tag 'v1.0' already exists")).toBeNull());
|
||||
expect(screen.getByRole("button", { name: "Create Tag" })).toBeEnabled();
|
||||
typeName("v2.0");
|
||||
expect(await screen.findByText("Tag 'v2.0' already exists")).toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
|
||||
expect(mocks.created).toEqual([]);
|
||||
});
|
||||
|
||||
it("ignores the tags of a repository that is no longer picked", async () => {
|
||||
let resolveA: (tags: string[]) => void = () => undefined;
|
||||
mocks.tags["/p/a"] = new Promise<string[]>((resolve) => (resolveA = resolve));
|
||||
render(<VcsDialogHost />);
|
||||
await act(() => showTagDialog());
|
||||
|
||||
await pick("Repository", "b");
|
||||
typeName("v1.0");
|
||||
// a's tags arrive after b was picked: they must not mark v1.0 as taken in b.
|
||||
await act(async () => resolveA(["v1.0"]));
|
||||
expect(screen.queryByText("Tag 'v1.0' already exists")).toBeNull();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Create Tag" }));
|
||||
await waitFor(() => expect(mocks.created).toHaveLength(1));
|
||||
expect(mocks.created[0]).toMatchObject({ repo: "/p/b", name: "v1.0" });
|
||||
});
|
||||
@@ -0,0 +1,152 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import type { Stash } from "@/bindings";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
stashes: new Map<string | null, Stash[]>(),
|
||||
drops: [] as Array<{ repo: string | null; index: number }>,
|
||||
diffs: [] as Array<{ repo: string | null; from: string; to: string }>,
|
||||
applies: [] as Array<{ repo: string | null; index: number }>,
|
||||
confirm: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
const ok = (data: unknown) => Promise.resolve({ status: "ok" as const, data });
|
||||
return {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
vcsStashes: (repo: string | null) => ok(mocks.stashes.get(repo) ?? []),
|
||||
vcsStashDrop: (repo: string | null, index: number) => {
|
||||
mocks.drops.push({ repo, index });
|
||||
const list = mocks.stashes.get(repo) ?? [];
|
||||
mocks.stashes.set(
|
||||
repo,
|
||||
list.filter((s) => s.index !== index).map((s) => (s.index > index ? { ...s, index: s.index - 1 } : s)),
|
||||
);
|
||||
return ok(null);
|
||||
},
|
||||
vcsStashApply: (repo: string | null, index: number) => {
|
||||
mocks.applies.push({ repo, index });
|
||||
return ok(null);
|
||||
},
|
||||
vcsDiffRevisions: (repo: string | null, from: string, to: string) => {
|
||||
mocks.diffs.push({ repo, from, to });
|
||||
return ok([{ path: "src/a.ts", kind: "modified", oldPath: null }]);
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../dialogs", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("../dialogs")>()),
|
||||
confirmDialog: mocks.confirm,
|
||||
}));
|
||||
|
||||
import { VcsDialogHost } from "../dialogs";
|
||||
import { showUnstashDialog } from "../changeOps";
|
||||
import { useVcs } from "../store";
|
||||
|
||||
const stash = (index: number, message: string): Stash => ({ index, message, timeMs: null });
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.stashes = new Map([
|
||||
["/p/a", [stash(0, "On main: a0")]],
|
||||
["/p/b", [stash(0, "On dev: first"), stash(1, "On dev: second"), stash(2, "On dev: third")]],
|
||||
]);
|
||||
mocks.drops = [];
|
||||
mocks.diffs = [];
|
||||
mocks.applies = [];
|
||||
mocks.confirm.mockReset().mockResolvedValue(true);
|
||||
useVcs.setState({ root: "/p", roots: ["/p/a", "/p/b"], repo: "/p/a", available: false });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Dialogs live in a module store: close what a test left open.
|
||||
for (let open = screen.queryAllByRole("dialog"); open.length; open = screen.queryAllByRole("dialog")) {
|
||||
const before = open.length;
|
||||
fireEvent.keyDown(open[open.length - 1]!, { key: "Escape" });
|
||||
if (screen.queryAllByRole("dialog").length === before) break;
|
||||
}
|
||||
});
|
||||
|
||||
const radio = (name: string) => screen.getByRole("radio", { name: new RegExp(name.replace(/[{}@]/g, "\\$&")) });
|
||||
|
||||
it("disables Show Changes and Drop Stash when there is no stash", async () => {
|
||||
mocks.stashes.set("/p/a", []);
|
||||
render(<VcsDialogHost />);
|
||||
act(() => showUnstashDialog(0, "/p/a"));
|
||||
expect(await screen.findByText("No stashes")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Show Changes" })).toBeDisabled();
|
||||
expect(screen.getByRole("button", { name: "Drop Stash" })).toBeDisabled();
|
||||
});
|
||||
|
||||
it("views the changes of the selected stash in the dialog's repository", async () => {
|
||||
render(<VcsDialogHost />);
|
||||
act(() => showUnstashDialog(0, "/p/b"));
|
||||
await screen.findByText("stash@{0}: On dev: first");
|
||||
fireEvent.click(radio("stash@{1}"));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Show Changes" }));
|
||||
|
||||
await waitFor(() => expect(mocks.diffs).toEqual([{ repo: "/p/b", from: "stash@{1}^", to: "stash@{1}" }]));
|
||||
expect(await screen.findByText(/Changes between stash@\{1\}\^ and stash@\{1\}/)).toBeInTheDocument();
|
||||
// The Unstash dialog stays open behind the changes, nothing applied or dropped.
|
||||
expect(screen.getByText("stash@{2}: On dev: third")).toBeInTheDocument();
|
||||
expect(mocks.applies).toEqual([]);
|
||||
expect(mocks.drops).toEqual([]);
|
||||
});
|
||||
|
||||
it("drops the selected stash after confirming, refreshes the list and selects the next one", async () => {
|
||||
render(<VcsDialogHost />);
|
||||
act(() => showUnstashDialog(0, "/p/b"));
|
||||
await screen.findByText("stash@{0}: On dev: first");
|
||||
fireEvent.click(radio("stash@{1}"));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Drop Stash" }));
|
||||
|
||||
await waitFor(() => expect(mocks.drops).toEqual([{ repo: "/p/b", index: 1 }]));
|
||||
expect(mocks.confirm).toHaveBeenCalledWith(expect.objectContaining({ title: "Drop Stash", danger: true }));
|
||||
await waitFor(() => expect(screen.queryByText("stash@{1}: On dev: second")).toBeNull());
|
||||
// The older stash moved up into the dropped one's place and is selected.
|
||||
expect(screen.getByText("stash@{1}: On dev: third")).toBeInTheDocument();
|
||||
expect(radio("stash@{1}")).toBeChecked();
|
||||
expect(radio("stash@{0}")).not.toBeChecked();
|
||||
|
||||
// The dialog stays open and acts on the refreshed list.
|
||||
fireEvent.click(screen.getByRole("button", { name: "Apply Stash" }));
|
||||
await waitFor(() => expect(mocks.applies).toEqual([{ repo: "/p/b", index: 1 }]));
|
||||
});
|
||||
|
||||
it("selects the new last stash after dropping the last one, and disables both when none is left", async () => {
|
||||
mocks.stashes.set("/p/b", [stash(0, "On dev: first"), stash(1, "On dev: second")]);
|
||||
render(<VcsDialogHost />);
|
||||
act(() => showUnstashDialog(1, "/p/b"));
|
||||
await screen.findByText("stash@{1}: On dev: second");
|
||||
expect(radio("stash@{1}")).toBeChecked();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Drop Stash" }));
|
||||
await waitFor(() => expect(screen.queryByText("stash@{1}: On dev: second")).toBeNull());
|
||||
expect(radio("stash@{0}")).toBeChecked();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Drop Stash" }));
|
||||
expect(await screen.findByText("No stashes")).toBeInTheDocument();
|
||||
expect(mocks.drops).toEqual([
|
||||
{ repo: "/p/b", index: 1 },
|
||||
{ repo: "/p/b", index: 0 },
|
||||
]);
|
||||
expect(screen.getByRole("button", { name: "Show Changes" })).toBeDisabled();
|
||||
expect(screen.getByRole("button", { name: "Drop Stash" })).toBeDisabled();
|
||||
expect(screen.getByRole("button", { name: "Apply Stash" })).toBeDisabled();
|
||||
});
|
||||
|
||||
it("keeps the stash when the drop is not confirmed", async () => {
|
||||
mocks.confirm.mockResolvedValue(false);
|
||||
render(<VcsDialogHost />);
|
||||
act(() => showUnstashDialog(0, "/p/a"));
|
||||
await screen.findByText("stash@{0}: On main: a0");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Drop Stash" }));
|
||||
await waitFor(() => expect(mocks.confirm).toHaveBeenCalledTimes(1));
|
||||
expect(mocks.drops).toEqual([]);
|
||||
expect(screen.getByText("stash@{0}: On main: a0")).toBeInTheDocument();
|
||||
expect(radio("stash@{0}")).toBeChecked();
|
||||
});
|
||||
@@ -431,6 +431,8 @@ export function registerVcsActions(): () => void {
|
||||
useChangelists.getState().state,
|
||||
state.roots,
|
||||
useCommit.getState().groupByStaging,
|
||||
undefined,
|
||||
useCommit.getState().groupByRepo,
|
||||
);
|
||||
// The modal interface has one front diff window (#1863): a file with its group
|
||||
// as the F7 chain, or several selected files as the chain.
|
||||
|
||||
@@ -132,6 +132,24 @@ async function performCheckout(
|
||||
options = { ...options, diverged: r.button };
|
||||
continue;
|
||||
}
|
||||
case "checkedOutInWorktree": {
|
||||
const { branch, path } = outcome;
|
||||
const r = await ask({
|
||||
title: "Worktree Conflict",
|
||||
body: tx`Branch '${branch}' is already checked out in a worktree at:\n${path}`,
|
||||
buttons: [
|
||||
{ id: "anyway", label: "Checkout Anyway", primary: true },
|
||||
{ id: "open", label: "Open Existing Worktree" },
|
||||
{ id: "cancel", label: "Cancel" },
|
||||
],
|
||||
});
|
||||
if (r.button === "anyway") {
|
||||
options = { ...options, ignoreOtherWorktrees: true };
|
||||
continue;
|
||||
}
|
||||
if (r.button === "open") await executeAction("file.openProjectPath", path);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { FileStatus, Stash } from "@/bindings";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { Checkbox, Dialog, Icon, Input, T, fileIconName } from "@/ui";
|
||||
import { Checkbox, Dialog, Icon, IconButton, Input, T, fileIconName } from "@/ui";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { groupOf, remainingOverrides, renamedFromPath } from "./changes";
|
||||
import { runCommitChecks } from "./commitChecks";
|
||||
@@ -11,8 +11,10 @@ import { forgetAmendDraft, keepMessageAfterCommit, rememberMessage, useCommit }
|
||||
import { workflowSettings } from "@/platform/workflowSettings";
|
||||
import { notifyFileOperation } from "@/platform/fileOps";
|
||||
import { confirmDialog, openDialog } from "./dialogs";
|
||||
import { RepoPicker, useBranchInfo } from "./gitMenuDialogs";
|
||||
import { KIND_COLOR, baseName, dirName, effectiveKind, relTo, stripSlash } from "./model";
|
||||
import { logConsole, runOp, saveAll } from "./ops";
|
||||
import { showCompareRevisions } from "./operations";
|
||||
import { currentRepo, loadStashes, refreshNow, useVcs } from "./store";
|
||||
import styles from "./common.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
@@ -304,11 +306,16 @@ export async function addToVcs(paths: readonly string[]) {
|
||||
);
|
||||
}
|
||||
|
||||
/** Stash Changes dialog: message, Keep index (staged changes stay), include untracked files. */
|
||||
/**
|
||||
* Stash Changes dialog: message, Keep index (staged changes stay), include untracked files.
|
||||
* `repo`: the repository it starts on; selected `paths` stash in the repositories holding them.
|
||||
*/
|
||||
export function stashChanges(paths: readonly string[] = [], repo = currentRepo()): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
const close = openDialog(() => (
|
||||
<StashDialog
|
||||
initialRepo={repo}
|
||||
pickRepo={!paths.length}
|
||||
onDone={async (r) => {
|
||||
close();
|
||||
if (r) {
|
||||
@@ -318,7 +325,7 @@ export function stashChanges(paths: readonly string[] = [], repo = currentRepo()
|
||||
() =>
|
||||
call(
|
||||
commands.vcsStashPush(
|
||||
repo,
|
||||
r.repo,
|
||||
r.message || null,
|
||||
r.includeUntracked,
|
||||
r.keepIndex,
|
||||
@@ -337,15 +344,20 @@ export function stashChanges(paths: readonly string[] = [], repo = currentRepo()
|
||||
}
|
||||
|
||||
function StashDialog({
|
||||
initialRepo,
|
||||
pickRepo,
|
||||
onDone,
|
||||
}: {
|
||||
onDone: (r: { message: string; keepIndex: boolean; includeUntracked: boolean } | null) => void;
|
||||
initialRepo: string | null;
|
||||
pickRepo: boolean;
|
||||
onDone: (r: { repo: string | null; message: string; keepIndex: boolean; includeUntracked: boolean } | null) => void;
|
||||
}) {
|
||||
const [repo, setRepo] = useState(initialRepo);
|
||||
const [message, setMessage] = useState("");
|
||||
const [keepIndex, setKeepIndex] = useState(false);
|
||||
const [includeUntracked, setIncludeUntracked] = useState(false);
|
||||
const branch = useVcs((s) => s.branch?.head ?? null);
|
||||
const submit = () => onDone({ message: message.trim(), keepIndex, includeUntracked });
|
||||
const branch = useBranchInfo(repo)?.head ?? null;
|
||||
const submit = () => onDone({ repo, message: message.trim(), keepIndex, includeUntracked });
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
@@ -364,6 +376,7 @@ function StashDialog({
|
||||
submit();
|
||||
}}
|
||||
>
|
||||
{pickRepo && <RepoPicker repo={repo} onChange={setRepo} />}
|
||||
{branch && <div className={styles.hint}>{tx`Current branch: ${branch}`}</div>}
|
||||
<label className={styles.fieldLabel}>
|
||||
<T>Message:</T>
|
||||
@@ -415,13 +428,14 @@ export function applyStash(index: number, pop: boolean, repo = currentRepo()) {
|
||||
return unstash({ index, pop, reinstateIndex: false, branch: null }, repo);
|
||||
}
|
||||
|
||||
/** Unstash Changes dialog: pick a stash; Pop, Reinstate index, or As new branch. */
|
||||
/** Unstash Changes dialog: pick a stash; Pop, Reinstate index, or As new branch; view or drop it. */
|
||||
export function showUnstashDialog(index = 0, repo = currentRepo()) {
|
||||
openDialog((close) => <UnstashDialog initial={index} repo={repo} onClose={close} />);
|
||||
}
|
||||
|
||||
function UnstashDialog({ initial, repo, onClose }: { initial: number; repo: string | null; onClose: () => void }) {
|
||||
const [stashes, setStashes] = useState<Stash[]>([]);
|
||||
const [tick, setTick] = useState(0);
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
void call(commands.vcsStashes(repo))
|
||||
@@ -430,13 +444,24 @@ function UnstashDialog({ initial, repo, onClose }: { initial: number; repo: stri
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [repo]);
|
||||
}, [repo, tick]);
|
||||
const [index, setIndex] = useState(initial);
|
||||
const [pop, setPop] = useState(false);
|
||||
const [reinstateIndex, setReinstateIndex] = useState(false);
|
||||
const [branch, setBranch] = useState("");
|
||||
const asBranch = branch.trim();
|
||||
const chosen = stashes.find((s) => s.index === index) ?? stashes[0];
|
||||
const view = () => {
|
||||
if (!chosen) return;
|
||||
const ref = `stash@{${chosen.index}}`;
|
||||
showCompareRevisions(`${ref}^`, ref, `${ref}^`, ref, repo);
|
||||
};
|
||||
const drop = async () => {
|
||||
if (!chosen || !(await dropStash(chosen.index, chosen.message, repo))) return;
|
||||
// The older stashes move up: the next one takes the dropped one's index, else the new last one.
|
||||
setIndex(Math.max(0, Math.min(chosen.index, stashes.length - 2)));
|
||||
setTick((n) => n + 1);
|
||||
};
|
||||
const submit = () => {
|
||||
if (!chosen) return;
|
||||
onClose();
|
||||
@@ -465,6 +490,10 @@ function UnstashDialog({ initial, repo, onClose }: { initial: number; repo: stri
|
||||
submit();
|
||||
}}
|
||||
>
|
||||
<div className={styles.manageBar} role="toolbar" aria-label={tx("Stashes")}>
|
||||
<IconButton icon="diff" title="Show Changes" size="small" disabled={!chosen} onClick={view} />
|
||||
<IconButton icon="trash" title="Drop Stash" size="small" disabled={!chosen} onClick={() => void drop()} />
|
||||
</div>
|
||||
<div className={styles.choiceList} role="radiogroup" aria-label={tx("Stashes")}>
|
||||
{stashes.length === 0 && (
|
||||
<div className={styles.hint}>
|
||||
@@ -496,7 +525,8 @@ function UnstashDialog({ initial, repo, onClose }: { initial: number; repo: stri
|
||||
);
|
||||
}
|
||||
|
||||
export async function dropStash(index: number, message: string, repo = currentRepo()) {
|
||||
/** Drops the stash once confirmed; whether it was confirmed. */
|
||||
export async function dropStash(index: number, message: string, repo = currentRepo()): Promise<boolean> {
|
||||
const ok = await confirmDialog({
|
||||
title: "Drop Stash",
|
||||
message: message
|
||||
@@ -505,9 +535,10 @@ export async function dropStash(index: number, message: string, repo = currentRe
|
||||
okLabel: "Drop",
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
if (!ok) return false;
|
||||
await runOp(tx`Drop ${`stash@{${index}}`}`, () => call(commands.vcsStashDrop(repo, index)), {
|
||||
success: tx`Dropped ${`stash@{${index}}`}`,
|
||||
});
|
||||
void loadStashes().catch((e) => logConsole("err", String(e)));
|
||||
return true;
|
||||
}
|
||||
@@ -122,6 +122,8 @@ function fileNode(fs: FileStatus, root: string, group: GroupId, flat: boolean, s
|
||||
interface Trie {
|
||||
dirs: Map<string, Trie>;
|
||||
files: FileStatus[];
|
||||
/** Absolute path of the directory. */
|
||||
path?: string;
|
||||
}
|
||||
|
||||
function dirNodes(trie: Trie, prefix: string, root: string, group: GroupId, scope: string = group): ChangeNode[] {
|
||||
@@ -147,7 +149,7 @@ function dirNodes(trie: Trie, prefix: string, root: string, group: GroupId, scop
|
||||
group,
|
||||
children,
|
||||
files,
|
||||
path: `${root}/${rel}`,
|
||||
path: node.path!,
|
||||
});
|
||||
}
|
||||
const files = [...trie.files].sort((a, b) => baseName(a.path).localeCompare(baseName(b.path)));
|
||||
@@ -165,13 +167,18 @@ function childNodes(files: readonly FileStatus[], root: string, group: GroupId,
|
||||
if (groupByDir) {
|
||||
const trie: Trie = { dirs: new Map(), files: [] };
|
||||
for (const f of files) {
|
||||
const rel = relTo(root, stripSlash(f.path));
|
||||
const path = stripSlash(f.path);
|
||||
const rel = relTo(root, path);
|
||||
const parts = rel.split("/");
|
||||
parts.pop();
|
||||
// Outside the root (a repository elsewhere, not grouped by repository): from its absolute path.
|
||||
if (rel === path && parts[0] === "" && parts.length > 1) parts.splice(0, 2, `/${parts[1]}`);
|
||||
let t = trie;
|
||||
let at = rel === path ? "" : `${root}/`;
|
||||
for (const p of parts) {
|
||||
at += t === trie ? p : `/${p}`;
|
||||
let next = t.dirs.get(p);
|
||||
if (!next) t.dirs.set(p, (next = { dirs: new Map(), files: [] }));
|
||||
if (!next) t.dirs.set(p, (next = { dirs: new Map(), files: [], path: at }));
|
||||
t = next;
|
||||
}
|
||||
t.files.push(f);
|
||||
@@ -236,8 +243,8 @@ function tagList(nodes: ChangeNode[], id: string): ChangeNode[] {
|
||||
* children. With change lists, "Changes" is split into one group per list
|
||||
* (`ChangelistState.files` keys are project-relative paths). With several
|
||||
* repositories (`repos`), each group's files are grouped by repository first, with
|
||||
* each repository's branch (`heads`) beside its name. With `byStaging`, "Changes"
|
||||
* becomes "Staged Changes" and "Unstaged Changes" instead.
|
||||
* each repository's branch (`heads`) beside its name, unless `byRepo` is off. With
|
||||
* `byStaging`, "Changes" becomes "Staged Changes" and "Unstaged Changes" instead.
|
||||
*/
|
||||
export function buildChangeTree(
|
||||
status: readonly FileStatus[],
|
||||
@@ -247,7 +254,9 @@ export function buildChangeTree(
|
||||
repos: readonly string[] = [],
|
||||
byStaging = false,
|
||||
heads: Readonly<Record<string, RepoHead>> = {},
|
||||
byRepo = true,
|
||||
): ChangeNode[] {
|
||||
const repoRoots = byRepo ? repos : [];
|
||||
const byGroup = new Map<GroupId, FileStatus[]>();
|
||||
for (const fs of status) {
|
||||
const g = groupOf(fs);
|
||||
@@ -267,7 +276,7 @@ export function buildChangeTree(
|
||||
];
|
||||
for (const [side, own] of sides) {
|
||||
if (!own.length) continue;
|
||||
const children = repoNodes(own, root, side, groupByDir, side, repos, heads);
|
||||
const children = repoNodes(own, root, side, groupByDir, side, repoRoots, heads);
|
||||
roots.push({
|
||||
key: `group:${side}`,
|
||||
type: "group",
|
||||
@@ -295,7 +304,7 @@ export function buildChangeTree(
|
||||
type: "group",
|
||||
label: l.name,
|
||||
group: g,
|
||||
children: tagList(repoNodes(own, root, g, groupByDir, scope, repos, heads), l.id),
|
||||
children: tagList(repoNodes(own, root, g, groupByDir, scope, repoRoots, heads), l.id),
|
||||
files: own,
|
||||
changelist: l.id,
|
||||
active: l.id === lists.active,
|
||||
@@ -305,7 +314,7 @@ export function buildChangeTree(
|
||||
continue;
|
||||
}
|
||||
if (!files.length) continue;
|
||||
const children = repoNodes(files, root, g, groupByDir, g, repos, heads);
|
||||
const children = repoNodes(files, root, g, groupByDir, g, repoRoots, heads);
|
||||
roots.push({ key: `group:${g}`, type: "group", label: GROUP_LABEL[g], group: g, children, files });
|
||||
}
|
||||
return roots;
|
||||
|
||||
@@ -17,6 +17,8 @@ interface CommitState {
|
||||
groupByDir: boolean;
|
||||
/** Group the changes into Staged / Unstaged instead of one "Changes" group. */
|
||||
groupByStaging: boolean;
|
||||
/** With several repositories, a node per repository above their files. */
|
||||
groupByRepo: boolean;
|
||||
/** Whether the Git window's Local Changes tab previews the selection's diff. */
|
||||
diffPreview: boolean;
|
||||
/** Whether the Commit tool window previews the selection's diff beside the changes (#1599). */
|
||||
@@ -54,6 +56,7 @@ export const useCommit = create<CommitState>(() => ({
|
||||
runHooks: true,
|
||||
groupByDir: readBool("openidea.vcs.groupByDir", false),
|
||||
groupByStaging: readBool("openidea.vcs.groupByStaging", false),
|
||||
groupByRepo: readBool("openidea.vcs.groupByRepo", true),
|
||||
diffPreview: readBool("openidea.vcs.diffPreview", true),
|
||||
commitDiffPreview: readBool("openidea.vcs.commitDiffPreview", false),
|
||||
checks: new Map(),
|
||||
@@ -104,6 +107,15 @@ export function setGroupByStaging(v: boolean) {
|
||||
}
|
||||
}
|
||||
|
||||
export function setGroupByRepo(v: boolean) {
|
||||
useCommit.setState({ groupByRepo: v });
|
||||
try {
|
||||
localStorage.setItem("openidea.vcs.groupByRepo", String(v));
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
export function setDiffPreview(v: boolean) {
|
||||
useCommit.setState({ diffPreview: v });
|
||||
try {
|
||||
|
||||
@@ -135,7 +135,7 @@ export function showPullDialog(repo?: string | null) {
|
||||
}
|
||||
|
||||
/** IDEA's Git Root choice: shown only when the project holds several repositories. */
|
||||
function RepoPicker({ repo, onChange }: { repo: string | null; onChange: (root: string) => void }) {
|
||||
export function RepoPicker({ repo, onChange }: { repo: string | null; onChange: (root: string) => void }) {
|
||||
const [roots] = useState(() => useVcs.getState().roots);
|
||||
if (roots.length < 2) return null;
|
||||
return (
|
||||
@@ -149,7 +149,7 @@ function RepoPicker({ repo, onChange }: { repo: string | null; onChange: (root:
|
||||
}
|
||||
|
||||
/** The repository's branch info: the store's for the selected repository, else read from git. */
|
||||
function useBranchInfo(repo: string | null) {
|
||||
export function useBranchInfo(repo: string | null) {
|
||||
const [initial] = useState(() => ({ repo: currentRepo(), info: useVcs.getState().branch }));
|
||||
const [loaded, setLoaded] = useState<{ repo: string | null; info: BranchInfo | null } | null>(null);
|
||||
useEffect(() => {
|
||||
|
||||
@@ -27,6 +27,7 @@ import { buildFileTree, type FileTreeNode } from "./fileTree";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { displayPath } from "./compareData";
|
||||
import { repositoryPath } from "./repositoryPaths";
|
||||
import { RepoPicker } from "./gitMenuDialogs";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Operation in progress
|
||||
@@ -437,15 +438,27 @@ export function showTagDialog() {
|
||||
}
|
||||
|
||||
function TagDialog({ onClose }: { onClose: () => void }) {
|
||||
const [repo] = useState(currentRepo);
|
||||
const [repo, setRepo] = useState(currentRepo);
|
||||
const [name, setName] = useState("");
|
||||
const [commit, setCommit] = useState("HEAD");
|
||||
const [message, setMessage] = useState("");
|
||||
const [force, setForce] = useState(false);
|
||||
const [existing, setExisting] = useState<string[]>([]);
|
||||
useEffect(() => {
|
||||
void call(commands.vcsTags(repo)).then(setExisting, () => undefined);
|
||||
}, []);
|
||||
let live = true;
|
||||
void call(commands.vcsTags(repo)).then(
|
||||
(tags) => live && setExisting(tags),
|
||||
() => undefined,
|
||||
);
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, [repo]);
|
||||
const chooseRepo = (root: string) => {
|
||||
if (root === repo) return;
|
||||
setRepo(root);
|
||||
setExisting([]);
|
||||
};
|
||||
const error = validateTagName(name, force ? [] : existing);
|
||||
const run = async () => {
|
||||
if (error) return;
|
||||
@@ -470,6 +483,7 @@ function TagDialog({ onClose }: { onClose: () => void }) {
|
||||
]}
|
||||
>
|
||||
<div className={styles.form}>
|
||||
<RepoPicker repo={repo} onChange={chooseRepo} />
|
||||
<label className={styles.fieldLabel} htmlFor="openidea-tag-name">
|
||||
<T>Tag name:</T>
|
||||
</label>
|
||||
@@ -518,21 +532,21 @@ export function showCompareVersions(older: Commit, newer: Commit) {
|
||||
showComparison({ rev: older.id, label: short(older.id) }, { rev: newer.id, label: short(newer.id) });
|
||||
}
|
||||
|
||||
/** Files that differ between two revisions (e.g. two branches from Compare with Current). */
|
||||
export function showCompareRevisions(from: string, to: string, fromLabel = from, toLabel = to) {
|
||||
showComparison({ rev: from, label: fromLabel }, { rev: to, label: toLabel });
|
||||
/** Files that differ between two revisions (e.g. two branches from Compare with Current) of `repo`. */
|
||||
export function showCompareRevisions(from: string, to: string, fromLabel = from, toLabel = to, repo = currentRepo()) {
|
||||
showComparison({ rev: from, label: fromLabel }, { rev: to, label: toLabel }, undefined, repo);
|
||||
}
|
||||
|
||||
export function showPathComparison(paths: string[], rev: string, repositories: string[] | null) {
|
||||
showComparison({ rev, label: rev }, null, { paths, repositories });
|
||||
}
|
||||
|
||||
function showComparison(from: Revision, to: Revision | null, scope?: ScopedComparison) {
|
||||
function showComparison(from: Revision, to: Revision | null, scope?: ScopedComparison, repo = currentRepo()) {
|
||||
if (!isTauri()) {
|
||||
openDialog((close) => <ChangesBetweenDialog from={from} to={to} scope={scope} onClose={close} />);
|
||||
openDialog((close) => <ChangesBetweenDialog from={from} to={to} scope={scope} repo={repo} onClose={close} />);
|
||||
return;
|
||||
}
|
||||
const comparison = { from, to, scope: scope ?? null, repo: currentRepo() };
|
||||
const comparison = { from, to, scope: scope ?? null, repo };
|
||||
void call(commands.windowOpenComparison(comparison, windowBackgroundHex())).catch((error) =>
|
||||
notifications().notify({ level: "error", title: "Could not open comparison", body: String(error) }),
|
||||
);
|
||||
@@ -596,6 +610,7 @@ export function ChangesBetweenDialog({
|
||||
from,
|
||||
to,
|
||||
scope,
|
||||
repo: givenRepo,
|
||||
onClose,
|
||||
native = false,
|
||||
onCaption,
|
||||
@@ -607,6 +622,8 @@ export function ChangesBetweenDialog({
|
||||
from: Revision;
|
||||
to: Revision | null;
|
||||
scope?: ScopedComparison;
|
||||
/** The repository compared (the selected one when omitted). */
|
||||
repo?: string | null;
|
||||
onClose: () => void;
|
||||
/** Content of the comparison window rather than a dialog: its caption goes to `onCaption`. */
|
||||
native?: boolean;
|
||||
@@ -619,8 +636,8 @@ export function ChangesBetweenDialog({
|
||||
/** Files only, each diff opening in the editor (the Compare tool window's narrow sidebar). */
|
||||
listOnly?: boolean;
|
||||
}) {
|
||||
const [root] = useState(currentRepoRoot);
|
||||
const [repo] = useState(currentRepo);
|
||||
const [repo] = useState(() => (givenRepo === undefined ? currentRepo() : givenRepo));
|
||||
const [root] = useState(() => repo ?? currentRepoRoot());
|
||||
const [files, setFiles] = useState<ComparisonFile[] | null>(null);
|
||||
const [result, setResult] = useState<CompareResult | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
@@ -130,7 +130,11 @@
|
||||
margin: 1.5em 0;
|
||||
}
|
||||
.preview :global(img) {
|
||||
max-width: 100%;
|
||||
max-width: calc(100% * var(--markdown-zoom-scale, 1));
|
||||
}
|
||||
.preview :global(img[data-natural-width]) {
|
||||
width: calc(min(var(--image-width), 100%) * var(--markdown-zoom-scale, 1));
|
||||
height: auto;
|
||||
}
|
||||
.preview :global(ul.contains-task-list) {
|
||||
list-style: none;
|
||||
@@ -155,10 +159,18 @@
|
||||
display: none;
|
||||
}
|
||||
.preview :global(.mermaid-output) {
|
||||
overflow: hidden;
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
text-align: center;
|
||||
}
|
||||
.preview :global(.mermaid-output svg[data-natural-width]) {
|
||||
display: block;
|
||||
margin: 0 auto;
|
||||
width: calc(min(var(--diagram-width), 100%) * var(--markdown-zoom-scale, 1));
|
||||
height: auto;
|
||||
}
|
||||
.preview :global(.mermaid-output[data-zoomed="true"]) {
|
||||
overflow: hidden;
|
||||
cursor: grab;
|
||||
touch-action: none;
|
||||
user-select: none;
|
||||
|
||||
@@ -51,6 +51,7 @@ import {
|
||||
resolveLink,
|
||||
slugify,
|
||||
} from "./render";
|
||||
import { applyImageZoomWidth, svgDataUrlSize } from "./svgSize";
|
||||
import styles from "./Markdown.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
@@ -110,6 +111,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
const text = useLiveMarkdown((s) => s[path]?.text);
|
||||
const fontZoom = useLiveMarkdown((s) => s[path]?.fontZoom ?? 0);
|
||||
const fontSize = useMarkdownPreviewFontSize();
|
||||
const zoomScale = Number((Math.max(4, fontSize + fontZoom) / fontSize).toFixed(4));
|
||||
const topLine = useLiveMarkdown((s) => s[path]?.topLine ?? 0);
|
||||
const scrollSeq = useLiveMarkdown((s) => s[path]?.scrollSeq ?? 0);
|
||||
const caretLine = useLiveMarkdown((s) => s[path]?.caretLine ?? 0);
|
||||
@@ -161,10 +163,32 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
const root = ref.current;
|
||||
if (!root) return;
|
||||
let live = true;
|
||||
root.querySelectorAll<HTMLImageElement>("img[data-src]").forEach((img) => {
|
||||
const bindImageUrl = (img: HTMLImageElement, url: string, asyncLoad: boolean) => {
|
||||
const svgSize = svgDataUrlSize(url);
|
||||
if (svgSize && applyImageZoomWidth(img, svgSize) && asyncLoad) {
|
||||
setDiagramsDrawn((n) => n + 1);
|
||||
}
|
||||
img.onload = () => {
|
||||
if (!live) return;
|
||||
if (!img.hasAttribute("data-natural-width") && img.naturalWidth > 0 && img.naturalHeight > 0) {
|
||||
if (applyImageZoomWidth(img, { w: img.naturalWidth, h: img.naturalHeight })) {
|
||||
setDiagramsDrawn((n) => n + 1);
|
||||
}
|
||||
} else if (asyncLoad) {
|
||||
setDiagramsDrawn((n) => n + 1);
|
||||
}
|
||||
};
|
||||
img.src = url;
|
||||
if (!img.hasAttribute("data-natural-width") && img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) {
|
||||
applyImageZoomWidth(img, { w: img.naturalWidth, h: img.naturalHeight });
|
||||
}
|
||||
};
|
||||
const imgs = [...root.querySelectorAll<HTMLImageElement>("img[data-src]")];
|
||||
imgs.forEach((img) => {
|
||||
applyImageZoomWidth(img);
|
||||
const src = img.dataset.src ?? "";
|
||||
if (/^data:image\//i.test(src)) {
|
||||
img.src = src;
|
||||
bindImageUrl(img, src, false);
|
||||
return;
|
||||
}
|
||||
const target = resolveLink(path, src);
|
||||
@@ -174,7 +198,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
return;
|
||||
}
|
||||
imageUrl(target.path).then(
|
||||
(url) => live && (img.src = url),
|
||||
(url) => live && bindImageUrl(img, url, true),
|
||||
() => live && img.classList.add(styles.blocked!),
|
||||
);
|
||||
});
|
||||
@@ -187,6 +211,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
});
|
||||
return () => {
|
||||
live = false;
|
||||
for (const img of imgs) img.onload = null;
|
||||
};
|
||||
}, [html, path]);
|
||||
|
||||
@@ -195,7 +220,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
const root = ref.current;
|
||||
if (!root || !sync) return;
|
||||
root.scrollTop = topLine <= 0 ? 0 : previewOffsetForLine(blocksOf(root), topLine, root.scrollHeight);
|
||||
}, [html, topLine, scrollSeq, sync, diagramsDrawn]);
|
||||
}, [html, topLine, scrollSeq, sync, diagramsDrawn, fontZoom, fontSize]);
|
||||
|
||||
// The preview's own scroll offset: tab switches and mode toggles unmount the
|
||||
// preview, so Preview Only would otherwise start over at the top. Writes made
|
||||
@@ -376,6 +401,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
{
|
||||
"--markdown-preview-font-size": `${fontSize}px`,
|
||||
"--markdown-font-zoom": `${fontZoom}px`,
|
||||
"--markdown-zoom-scale": String(zoomScale),
|
||||
} as CSSProperties
|
||||
}
|
||||
tabIndex={-1}
|
||||
|
||||
@@ -396,6 +396,15 @@ describe("mermaid in the markdown preview", () => {
|
||||
expect(root.querySelector("[data-mermaid]")?.getAttribute("data-mermaid-state")).toBe("pending");
|
||||
});
|
||||
|
||||
it("records a diagram's natural width so preview font zoom scales it without clamping", async () => {
|
||||
const svg = await renderedSvg(
|
||||
'<svg id="openidea-mermaid-1" width="100%" style="max-width: 540px;" viewBox="0 0 540 320"><text>flow</text></svg>',
|
||||
);
|
||||
expect(svg.hasAttribute("data-natural-width")).toBe(true);
|
||||
expect(svg.style.getPropertyValue("--diagram-width")).toBe("540px");
|
||||
expect(svg.style.maxWidth).toBe("calc(min(var(--diagram-width), 100%) * var(--markdown-zoom-scale, 1))");
|
||||
});
|
||||
|
||||
it("puts full-screen and download tools on a drawn diagram", async () => {
|
||||
const root = preview(SEQ);
|
||||
await renderMermaidIn(root).done;
|
||||
|
||||
@@ -11,6 +11,7 @@ import { attachPanZoom } from "../panZoom";
|
||||
import { attachDiagramTools, TOOLS_ATTR } from "./mermaidTools";
|
||||
import { localSvg } from "./localSvg";
|
||||
import { reid } from "./svgIds";
|
||||
import { svgElementSize } from "./svgSize";
|
||||
|
||||
export const MERMAID_SELECTOR = "[data-mermaid]";
|
||||
const OUTPUT_CLASS = "mermaid-output";
|
||||
@@ -250,7 +251,15 @@ function show(block: HTMLElement, result: Result | null, stale?: Node) {
|
||||
if (block.getAttribute(RENDERED_ATTR) === "ok") {
|
||||
attachPanZoom(out);
|
||||
const svg = out.querySelector("svg");
|
||||
if (svg) attachDiagramTools(block, svg);
|
||||
if (svg) {
|
||||
const size = svgElementSize(svg);
|
||||
if (size) {
|
||||
svg.dataset.naturalWidth = "";
|
||||
svg.style.setProperty("--diagram-width", `${Number(size.w.toFixed(2))}px`);
|
||||
svg.style.maxWidth = "calc(min(var(--diagram-width), 100%) * var(--markdown-zoom-scale, 1))";
|
||||
}
|
||||
attachDiagramTools(block, svg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import { openLayer, trapTab } from "@/ui/popupState";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { attachPanZoom } from "../panZoom";
|
||||
import { reid } from "./svgIds";
|
||||
import { svgElementSize } from "./svgSize";
|
||||
import styles from "./MermaidTools.module.css";
|
||||
|
||||
/** Marks the tool strip, so a redrawing block replaces it rather than stacking one. */
|
||||
@@ -161,11 +162,8 @@ function fittedCopy(svg: SVGSVGElement, availW: number, availH: number): SVGSVGE
|
||||
}
|
||||
|
||||
function naturalSize(svg: SVGSVGElement): { w: number; h: number } {
|
||||
const box = (svg as SVGSVGElement & { viewBox?: SVGAnimatedRect }).viewBox?.baseVal;
|
||||
if (box && box.width > 0 && box.height > 0) return { w: box.width, h: box.height };
|
||||
const width = Number(svg.getAttribute("width"));
|
||||
const height = Number(svg.getAttribute("height"));
|
||||
if (width > 0 && height > 0) return { w: width, h: height };
|
||||
const declared = svgElementSize(svg);
|
||||
if (declared) return declared;
|
||||
const rect = svg.getBoundingClientRect();
|
||||
return { w: rect.width > 0 ? rect.width : 800, h: rect.height > 0 ? rect.height : 600 };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Intrinsic CSS pixel dimensions of SVGs and Markdown preview images, so
|
||||
* diagrams and embedded `.svg` / raster assets scale with `--markdown-zoom-scale`.
|
||||
*/
|
||||
|
||||
const UNIT_PX: Record<string, number> = {
|
||||
"": 1,
|
||||
px: 1,
|
||||
pt: 96 / 72,
|
||||
pc: 16,
|
||||
in: 96,
|
||||
cm: 96 / 2.54,
|
||||
mm: 96 / 25.4,
|
||||
};
|
||||
|
||||
/** Parses an absolute SVG/HTML length into CSS pixels (ignoring `%`, `em`, etc.). */
|
||||
export function parseLengthPx(raw: string | null | undefined): number | null {
|
||||
if (!raw) return null;
|
||||
const m = /^\s*(\d+(?:\.\d+)?|\.\d+)\s*([a-z%]*)\s*$/i.exec(raw);
|
||||
if (!m) return null;
|
||||
const factor = UNIT_PX[m[2]!.toLowerCase()];
|
||||
if (!factor) return null;
|
||||
const n = Number(m[1]) * factor;
|
||||
return Number.isFinite(n) && n > 0 ? n : null;
|
||||
}
|
||||
|
||||
function parsePercent(raw: string | null | undefined): number | null {
|
||||
if (!raw) return null;
|
||||
const m = /^\s*(\d+(?:\.\d+)?|\.\d+)%\s*$/.exec(raw);
|
||||
if (!m) return null;
|
||||
const n = Number(m[1]);
|
||||
return Number.isFinite(n) && n > 0 ? n : null;
|
||||
}
|
||||
|
||||
/** Parses `viewBox="minX minY width height"` into `{ w, h }`. */
|
||||
export function parseViewBoxSize(raw: string | null | undefined): { w: number; h: number } | null {
|
||||
if (!raw) return null;
|
||||
const parts = raw
|
||||
.trim()
|
||||
.split(/[\s,]+/)
|
||||
.map(Number);
|
||||
if (parts.length !== 4) return null;
|
||||
const w = parts[2]!;
|
||||
const h = parts[3]!;
|
||||
return Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0 ? { w, h } : null;
|
||||
}
|
||||
|
||||
function resolveSvgDims(
|
||||
style: string | null | undefined,
|
||||
widthAttr: string | null | undefined,
|
||||
heightAttr: string | null | undefined,
|
||||
viewBoxAttr: string | null | undefined,
|
||||
): { w: number; h: number } | null {
|
||||
const vb = parseViewBoxSize(viewBoxAttr);
|
||||
const storedW = parseLengthPx(/(?:^|;)\s*--diagram-width\s*:\s*([^;]+)/i.exec(style ?? "")?.[1]);
|
||||
const inlineMaxW = parseLengthPx(/(?:^|;)\s*max-width\s*:\s*([^;]+)/i.exec(style ?? "")?.[1]);
|
||||
const attrW = parseLengthPx(widthAttr);
|
||||
const attrH = parseLengthPx(heightAttr);
|
||||
|
||||
const w = storedW ?? inlineMaxW ?? attrW ?? (attrH && vb ? (attrH * vb.w) / vb.h : (vb?.w ?? null));
|
||||
if (!w) return null;
|
||||
const h = attrH ?? (vb ? (w * vb.h) / vb.w : w * 0.75);
|
||||
return { w, h };
|
||||
}
|
||||
|
||||
/** Intrinsic CSS pixel size of an in-DOM `<svg>`, when declared on the element. */
|
||||
export function svgElementSize(svg: SVGSVGElement): { w: number; h: number } | null {
|
||||
const fromAttrs = resolveSvgDims(
|
||||
svg.getAttribute("style"),
|
||||
svg.getAttribute("width"),
|
||||
svg.getAttribute("height"),
|
||||
svg.getAttribute("viewBox"),
|
||||
);
|
||||
if (fromAttrs) return fromAttrs;
|
||||
const box = (svg as SVGSVGElement & { viewBox?: SVGAnimatedRect }).viewBox?.baseVal;
|
||||
if (box && box.width > 0 && box.height > 0) return { w: box.width, h: box.height };
|
||||
return null;
|
||||
}
|
||||
|
||||
function readAttr(tag: string, name: string): string | null {
|
||||
const re = new RegExp(`(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i");
|
||||
const m = re.exec(tag);
|
||||
return m ? (m[1] ?? m[2] ?? m[3] ?? null) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Intrinsic CSS pixel size of a `data:image/svg+xml` URL from its `<svg>` header.
|
||||
* Decodes only the leading chunk so large `.excalidraw.svg` scenes stay cheap.
|
||||
*/
|
||||
export function svgDataUrlSize(url: string): { w: number; h: number } | null {
|
||||
const comma = url.indexOf(",");
|
||||
if (comma < 0) return null;
|
||||
const header = url.slice(0, comma);
|
||||
if (!/^data:image\/svg\+xml\b/i.test(header)) return null;
|
||||
const payload = url.slice(comma + 1, comma + 1 + 16384);
|
||||
let head: string;
|
||||
try {
|
||||
if (/;base64\b/i.test(header)) {
|
||||
const clean = payload.replace(/\s+/g, "");
|
||||
const aligned = clean.slice(0, clean.length - (clean.length % 4));
|
||||
head = atob(aligned);
|
||||
} else {
|
||||
const safe = payload.replace(/%[0-9a-f]?$/i, "");
|
||||
head = decodeURIComponent(safe);
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const withoutComments = head.replace(/<!--[\s\S]*?-->/g, "");
|
||||
const open = /<svg\b((?:"[^"]*"|'[^']*'|[^'">])*)>/i.exec(withoutComments);
|
||||
if (!open) return null;
|
||||
const attrs = open[1]!;
|
||||
return resolveSvgDims(
|
||||
readAttr(attrs, "style"),
|
||||
readAttr(attrs, "width"),
|
||||
readAttr(attrs, "height"),
|
||||
readAttr(attrs, "viewBox"),
|
||||
);
|
||||
}
|
||||
|
||||
const formatPx = (n: number) => `${Number(n.toFixed(2))}px`;
|
||||
|
||||
/**
|
||||
* Sets an `<img>`'s 1× base width so CSS scales it by `--markdown-zoom-scale`,
|
||||
* respecting explicit HTML `width` / `height` attributes when present.
|
||||
*/
|
||||
export function applyImageZoomWidth(img: HTMLImageElement, intrinsic?: { w: number; h: number } | null): boolean {
|
||||
const rawWidth = img.getAttribute("width");
|
||||
const pct = parsePercent(rawWidth);
|
||||
if (pct !== null) {
|
||||
img.style.width = `calc(${pct}% * var(--markdown-zoom-scale, 1))`;
|
||||
img.style.height = "auto";
|
||||
return true;
|
||||
}
|
||||
const attrW = parseLengthPx(rawWidth);
|
||||
if (attrW !== null) {
|
||||
img.style.setProperty("--image-width", formatPx(attrW));
|
||||
img.dataset.naturalWidth = "";
|
||||
return true;
|
||||
}
|
||||
if (!intrinsic || intrinsic.w <= 0 || intrinsic.h <= 0) return false;
|
||||
const attrH = parseLengthPx(img.getAttribute("height"));
|
||||
const baseW = attrH !== null ? (attrH * intrinsic.w) / intrinsic.h : intrinsic.w;
|
||||
img.style.setProperty("--image-width", formatPx(baseW));
|
||||
img.dataset.naturalWidth = "";
|
||||
return true;
|
||||
}
|
||||
@@ -101,14 +101,102 @@ describe("editor font size actions", () => {
|
||||
);
|
||||
const preview = screen.getByRole("document", { name: "Markdown preview" });
|
||||
expect(preview.style.getPropertyValue("--markdown-font-zoom")).toBe("0px");
|
||||
expect(preview.style.getPropertyValue("--markdown-zoom-scale")).toBe("1");
|
||||
|
||||
await act(() => executeAction("editor.increaseFontSize"));
|
||||
await act(() => executeAction("editor.increaseFontSize"));
|
||||
expect(preview.style.getPropertyValue("--markdown-font-zoom")).toBe("2px");
|
||||
expect(preview.style.getPropertyValue("--markdown-zoom-scale")).toBe("1.1538");
|
||||
|
||||
await act(() => executeAction("editor.decreaseFontSize"));
|
||||
await act(() => executeAction("editor.decreaseFontSize"));
|
||||
await act(() => executeAction("editor.decreaseFontSize"));
|
||||
expect(preview.style.getPropertyValue("--markdown-font-zoom")).toBe("-1px");
|
||||
expect(preview.style.getPropertyValue("--markdown-zoom-scale")).toBe("0.9231");
|
||||
|
||||
await act(() => executeAction("editor.resetFontSize"));
|
||||
expect(zoom(md)).toBe(0);
|
||||
expect(preview.style.getPropertyValue("--markdown-font-zoom")).toBe("0px");
|
||||
expect(preview.style.getPropertyValue("--markdown-zoom-scale")).toBe("1");
|
||||
});
|
||||
|
||||
it("sizes embedded excalidraw.svg, graph SVGs and raster images so they scale with font zoom", async () => {
|
||||
const excalidrawSvg =
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 940" width="1280" height="940"><!-- svg-source:excalidraw --></svg>';
|
||||
const excalidrawUrl = `data:image/svg+xml;base64,${btoa(excalidrawSvg)}`;
|
||||
const graphvizUrl = `data:image/svg+xml;utf8,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="300pt" height="150pt" viewBox="0 0 300 150"></svg>')}`;
|
||||
const wordmarkUrl = `data:image/svg+xml;base64,${btoa('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 280 56"></svg>')}`;
|
||||
const pngUrl = "data:image/png;base64,iVBORw0KGgo=";
|
||||
|
||||
const ipc = await import("@/platform/ipc");
|
||||
const fsReadImage = vi.spyOn(ipc.commands, "fsReadImage").mockImplementation(async (p: string) => {
|
||||
if (p.endsWith("architecture.excalidraw.svg")) return { status: "ok", data: excalidrawUrl };
|
||||
if (p.endsWith("wordmark.svg")) return { status: "ok", data: wordmarkUrl };
|
||||
if (p.endsWith("shot.png")) return { status: "ok", data: pngUrl };
|
||||
return { status: "error", error: { kind: "notFound", message: p } } as never;
|
||||
});
|
||||
|
||||
try {
|
||||
const doc = [
|
||||
"",
|
||||
"",
|
||||
``,
|
||||
"",
|
||||
'<img src="./wordmark.svg" alt="Wordmark" height="56">',
|
||||
"",
|
||||
'<img src="./wordmark.svg" alt="Icon" width="80">',
|
||||
"",
|
||||
"",
|
||||
].join("\n");
|
||||
const live = editorContributions().find((c) => c.id === "viewers.markdownLive")!;
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({ doc, extensions: [fontZoom, live.extensions(mdCtx)] }),
|
||||
});
|
||||
const handle = { view, ctx: mdCtx };
|
||||
_addEditor(handle);
|
||||
disposers.push(() => _removeEditor(handle));
|
||||
views.push(view);
|
||||
activate(view);
|
||||
|
||||
act(() => useMarkdownModes.setState((s) => ({ byPath: { ...s.byPath, [mdCtx.path]: "preview" } })));
|
||||
render(
|
||||
<MarkdownEditor path={mdCtx.path} tabId="t">
|
||||
<div />
|
||||
</MarkdownEditor>,
|
||||
);
|
||||
const preview = screen.getByRole("document", { name: "Markdown preview" });
|
||||
await vi.waitFor(() => {
|
||||
const arch = preview.querySelector<HTMLImageElement>('img[alt="Architecture"]');
|
||||
expect(arch?.getAttribute("src")).toBe(excalidrawUrl);
|
||||
});
|
||||
|
||||
const arch = preview.querySelector<HTMLImageElement>('img[alt="Architecture"]')!;
|
||||
expect(arch.hasAttribute("data-natural-width")).toBe(true);
|
||||
expect(arch.style.getPropertyValue("--image-width")).toBe("1280px");
|
||||
|
||||
const graph = preview.querySelector<HTMLImageElement>('img[alt="Graph"]')!;
|
||||
expect(graph.hasAttribute("data-natural-width")).toBe(true);
|
||||
expect(graph.style.getPropertyValue("--image-width")).toBe("400px");
|
||||
|
||||
const wordmark = preview.querySelector<HTMLImageElement>('img[alt="Wordmark"]')!;
|
||||
expect(wordmark.hasAttribute("data-natural-width")).toBe(true);
|
||||
expect(wordmark.style.getPropertyValue("--image-width")).toBe("280px");
|
||||
|
||||
const icon = preview.querySelector<HTMLImageElement>('img[alt="Icon"]')!;
|
||||
expect(icon.hasAttribute("data-natural-width")).toBe(true);
|
||||
expect(icon.style.getPropertyValue("--image-width")).toBe("80px");
|
||||
|
||||
const shot = preview.querySelector<HTMLImageElement>('img[alt="Shot"]')!;
|
||||
Object.defineProperty(shot, "naturalWidth", { value: 960, configurable: true });
|
||||
Object.defineProperty(shot, "naturalHeight", { value: 600, configurable: true });
|
||||
act(() => {
|
||||
shot.dispatchEvent(new Event("load"));
|
||||
});
|
||||
expect(shot.hasAttribute("data-natural-width")).toBe(true);
|
||||
expect(shot.style.getPropertyValue("--image-width")).toBe("960px");
|
||||
} finally {
|
||||
fsReadImage.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("scales a configured editor font size", () => {
|
||||
|
||||
@@ -50,6 +50,11 @@ export function attachPanZoom(viewport: HTMLElement, options: PanZoomOptions = {
|
||||
(e) => {
|
||||
if (!(e.metaKey || e.ctrlKey) || !e.deltaY) return;
|
||||
e.preventDefault();
|
||||
if (view.z === origin.z && (viewport.scrollLeft || viewport.scrollTop)) {
|
||||
view = { ...view, x: view.x - viewport.scrollLeft, y: view.y - viewport.scrollTop };
|
||||
viewport.scrollLeft = 0;
|
||||
viewport.scrollTop = 0;
|
||||
}
|
||||
const rect = viewport.getBoundingClientRect();
|
||||
// One wheel notch (~100 px, 3 lines or a page) zooms about 15%; a trackpad
|
||||
// sends small pixel deltas, so zooming follows the gesture continuously.
|
||||
|
||||
@@ -94,6 +94,18 @@ export const CLIENT_SETTINGS_KEYS = [
|
||||
"vcs.commit.nonModal",
|
||||
"vcs.commit.doubleClickOpensDiff",
|
||||
"vcs.commit.showRightMargin",
|
||||
"agents.showContextUsage",
|
||||
"agents.showWorkTime",
|
||||
"agents.showUsageLimits",
|
||||
"agents.showCost",
|
||||
"agents.foldTurns",
|
||||
"agents.smoothText",
|
||||
"agents.fitWindowWidth",
|
||||
"agents.thinking",
|
||||
"agents.toolCalls",
|
||||
"agents.expandToolOutput",
|
||||
"agents.sendWith",
|
||||
"agents.whileRunning",
|
||||
] as const;
|
||||
|
||||
export function isClientSetting(key: string): boolean {
|
||||
|
||||
@@ -20,6 +20,7 @@ export const eclipseMacos: Record<string, string[]> = {
|
||||
"editor.closeAllTabs": ["Meta+Shift+W"],
|
||||
"analyze.inspectFile": [],
|
||||
"project.collapseAll": ["Meta+Shift+NumpadDivide"],
|
||||
"run.collapseAllTests": ["Meta+Shift+NumpadDivide"],
|
||||
"code.foldAll": ["Meta+Shift+NumpadDivide"],
|
||||
"code.fold": ["Meta+NumpadSubtract"],
|
||||
"code.commentBlock": ["Shift+Meta+/"],
|
||||
@@ -39,6 +40,7 @@ export const eclipseMacos: Record<string, string[]> = {
|
||||
"code.shrinkSelection": ["Shift+Ctrl+Down"],
|
||||
"debug.evaluate": ["Meta+U"],
|
||||
"project.expandAll": ["Meta+Shift+NumpadMultiply"],
|
||||
"run.expandAllTests": ["Meta+Shift+NumpadMultiply"],
|
||||
"code.unfoldAll": ["Meta+NumpadMultiply"],
|
||||
"code.unfold": ["Meta+NumpadAdd"],
|
||||
"code.expandAllToLevel1": [],
|
||||
|
||||
@@ -20,6 +20,7 @@ export const eclipseWindows: Record<string, string[]> = {
|
||||
"editor.closeAllTabs": ["Shift+Ctrl+F4", "Shift+Ctrl+W"],
|
||||
"analyze.inspectFile": [],
|
||||
"project.collapseAll": ["Ctrl+Shift+NumpadDivide"],
|
||||
"run.collapseAllTests": ["Ctrl+Shift+NumpadDivide"],
|
||||
"code.foldAll": ["Ctrl+Shift+NumpadDivide"],
|
||||
"code.fold": ["Ctrl+NumpadSubtract"],
|
||||
"code.commentBlock": ["Shift+Ctrl+/"],
|
||||
@@ -41,6 +42,7 @@ export const eclipseWindows: Record<string, string[]> = {
|
||||
"code.shrinkSelection": ["Shift+Alt+Down"],
|
||||
"debug.evaluate": ["Ctrl+U"],
|
||||
"project.expandAll": ["Ctrl+Shift+NumpadMultiply"],
|
||||
"run.expandAllTests": ["Ctrl+Shift+NumpadMultiply"],
|
||||
"code.unfoldAll": ["Ctrl+NumpadMultiply"],
|
||||
"code.unfold": ["Ctrl+NumpadAdd"],
|
||||
"code.expandAllToLevel1": [],
|
||||
|
||||
@@ -53,7 +53,8 @@ const shared = [
|
||||
["code.optimizeImports", "project.optimizeImports"],
|
||||
["code.deleteLine", "db.duplicateSource", "project.compareWith", "vcs.showDiff", "vcs.log.changes.showDiff"],
|
||||
["code.moveStatementDown", "find.field.recentSearches", "find.popup.recentSearches"],
|
||||
["code.foldAll", "project.collapseAll"],
|
||||
["code.foldAll", "project.collapseAll", "run.collapseAllTests"],
|
||||
["project.expandAll", "run.expandAllTests"],
|
||||
["refactor.rename", "project.rename", "db.rename", "vcs.changelist.edit", "vcs.log.editMessage", "vcs.shelf.rename"],
|
||||
["refactor.changeSignature", "db.modifyTable"],
|
||||
["refactor.move", "project.move"],
|
||||
|
||||
@@ -35,6 +35,8 @@ describe("IDEA keymap parity", () => {
|
||||
["project.reloadFromDisk", ["Meta+Alt+Y"], ["Ctrl+Alt+Y"]],
|
||||
["project.expandAll", ["Meta+="], ["Ctrl+="]],
|
||||
["project.collapseAll", ["Meta+-"], ["Ctrl+-"]],
|
||||
["run.expandAllTests", ["Meta+="], ["Ctrl+="]],
|
||||
["run.collapseAllTests", ["Meta+-"], ["Ctrl+-"]],
|
||||
["navigate.searchText", ["Meta+Alt+Shift+E"], ["Ctrl+Alt+Shift+E"]],
|
||||
["window.next", ["Meta+Alt+`"], ["Ctrl+Alt+]"]],
|
||||
["window.previous", ["Meta+Alt+Shift+`"], ["Ctrl+Alt+["]],
|
||||
@@ -101,6 +103,8 @@ describe("IDEA keymap parity", () => {
|
||||
order(km, "file.reloadFromDisk", "project.reloadFromDisk");
|
||||
order(km, "code.unfold", "project.expandAll");
|
||||
order(km, "code.fold", "project.collapseAll");
|
||||
order(km, "code.unfold", "run.expandAllTests");
|
||||
order(km, "code.fold", "run.collapseAllTests");
|
||||
order(km, "navigate.nextError", "vcs.changelist.edit");
|
||||
order(km, "debug.setValue", "vcs.changelist.edit");
|
||||
order(km, "find.replaceInFile", "find.rerun");
|
||||
|
||||
@@ -218,6 +218,9 @@ export const intellijMacos: Record<string, string[]> = {
|
||||
"project.reloadFromDisk": ["Meta+Alt+Y"],
|
||||
"project.expandAll": ["Meta+="],
|
||||
"project.collapseAll": ["Meta+-"],
|
||||
// In the test results tree (keyWhen).
|
||||
"run.expandAllTests": ["Meta+="],
|
||||
"run.collapseAllTests": ["Meta+-"],
|
||||
|
||||
// Tool windows
|
||||
"toolwindow.project": ["Meta+1"],
|
||||
|
||||
@@ -219,6 +219,9 @@ export const intellijWindows: Record<string, string[]> = {
|
||||
"project.reloadFromDisk": ["Ctrl+Alt+Y"],
|
||||
"project.expandAll": ["Ctrl+="],
|
||||
"project.collapseAll": ["Ctrl+-"],
|
||||
// In the test results tree (keyWhen).
|
||||
"run.expandAllTests": ["Ctrl+="],
|
||||
"run.collapseAllTests": ["Ctrl+-"],
|
||||
|
||||
// Tool windows
|
||||
"toolwindow.project": ["Alt+1"],
|
||||
|
||||
@@ -228,6 +228,8 @@ export const vscodeMacos: Record<string, string[]> = {
|
||||
"project.reloadFromDisk": [],
|
||||
"project.expandAll": [],
|
||||
"project.collapseAll": [],
|
||||
"run.expandAllTests": [],
|
||||
"run.collapseAllTests": [],
|
||||
"project.findUsages": ["Alt+Shift+F12"],
|
||||
"project.reformatCode": ["Alt+Shift+F"],
|
||||
"project.optimizeImports": ["Alt+Shift+O"],
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
{
|
||||
"Worktree Conflict": "Worktree Conflict",
|
||||
"Branch '{branch}' is already checked out in a worktree at:\n{path}": "Branch '{branch}' is already checked out in a worktree at:\n{path}",
|
||||
"Checkout Anyway": "Checkout Anyway",
|
||||
"Open Existing Worktree": "Open Existing Worktree",
|
||||
"Favorites": "Favorites",
|
||||
"Add": "Add",
|
||||
"Cancel": "Cancel",
|
||||
@@ -1778,5 +1782,9 @@
|
||||
"Class '{name}' does not implement abstract method '{method}'": "Class '{name}' does not implement abstract method '{method}'",
|
||||
"Redundant override of '{name}'": "Redundant override of '{name}'",
|
||||
"All Configurations": "All Configurations",
|
||||
"'{name}' keeps running without the debugger: {message}": "'{name}' keeps running without the debugger: {message}"
|
||||
"'{name}' keeps running without the debugger: {message}": "'{name}' keeps running without the debugger: {message}",
|
||||
"Show Changes": "Show Changes",
|
||||
"Previous Failed Test": "Previous Failed Test",
|
||||
"Next Failed Test": "Next Failed Test",
|
||||
"Run '{name}' with Fuzzing": "Run '{name}' with Fuzzing"
|
||||
}
|
||||
@@ -1,4 +1,8 @@
|
||||
{
|
||||
"Worktree Conflict": "工作树冲突",
|
||||
"Branch '{branch}' is already checked out in a worktree at:\n{path}": "分支 '{branch}' 已在以下位置的工作树中签出:\n{path}",
|
||||
"Checkout Anyway": "仍然签出",
|
||||
"Open Existing Worktree": "打开现有工作树",
|
||||
"Favorites": "收藏夹",
|
||||
"Fix ESLint Problems": "修复 ESLint 问题",
|
||||
"No ESLint problems to fix": "没有可修复的 ESLint 问题",
|
||||
@@ -8179,5 +8183,9 @@
|
||||
"End Process {label}": "结束进程 {label}",
|
||||
"Diff too large: a side is over {max} MiB": "差异过大:有一侧超过 {max} MiB",
|
||||
"All Configurations": "所有配置",
|
||||
"'{name}' keeps running without the debugger: {message}": "'{name}' 继续运行,但未附加调试器:{message}"
|
||||
"'{name}' keeps running without the debugger: {message}": "'{name}' 继续运行,但未附加调试器:{message}",
|
||||
"Show Changes": "显示更改",
|
||||
"Previous Failed Test": "上一个失败的测试",
|
||||
"Next Failed Test": "下一个失败的测试",
|
||||
"Run '{name}' with Fuzzing": "使用模糊测试运行 '{name}'"
|
||||
}
|
||||
@@ -24,6 +24,7 @@ const local = {
|
||||
appearance: { theme: "dark" },
|
||||
editor: { fontSize: 19, tabSize: 8 },
|
||||
terminal: { fontSize: 18, shellPath: "/local" },
|
||||
agents: { fitWindowWidth: true, newTaskApprovals: "ask" },
|
||||
};
|
||||
const remote = {
|
||||
keymap: "intellij-linux",
|
||||
@@ -32,6 +33,7 @@ const remote = {
|
||||
appearance: { theme: "light" },
|
||||
editor: { fontSize: 13, tabSize: 2 },
|
||||
terminal: { fontSize: 13, shellPath: "/remote" },
|
||||
agents: { fitWindowWidth: false, newTaskApprovals: "bypass", mcpServers: { docs: { command: "npx" } } },
|
||||
};
|
||||
const served = new Set(["settings_get", "settings_set", "project_current"]);
|
||||
let invoke: ReturnType<typeof vi.fn>;
|
||||
@@ -142,6 +144,9 @@ describe("remote client settings", () => {
|
||||
"terminal.env",
|
||||
"tools.node",
|
||||
"languages.python.interpreter",
|
||||
"agents.newTaskApprovals",
|
||||
"agents.defaults",
|
||||
"agents.mcpServers",
|
||||
"keymapExtra",
|
||||
])("preserves routing for host setting %s", (key) => {
|
||||
expect(remoteRouting("settings_set", { scope: "project", key }, served)).toBe("remote");
|
||||
@@ -222,6 +227,7 @@ describe("remote client settings", () => {
|
||||
...local,
|
||||
editor: { fontSize: 19, tabSize: 2 },
|
||||
terminal: { fontSize: 18, shellPath: "/remote" },
|
||||
agents: { fitWindowWidth: true, newTaskApprovals: "bypass", mcpServers: { docs: { command: "npx" } } },
|
||||
});
|
||||
expect(invoke).toHaveBeenCalledWith("settings_get_global", {}, undefined);
|
||||
});
|
||||
|
||||
@@ -709,7 +709,11 @@ export interface EditorCloseSession {
|
||||
|
||||
export interface ToolWindowService {
|
||||
show(id: string, focus?: boolean): void;
|
||||
hide(id: string): void;
|
||||
/**
|
||||
* `removeFromStripe`: a window whose content is its tabs (Find, Run, Hierarchy…) lost its last
|
||||
* one: its stripe button goes too, until new content opens it again (IDEA).
|
||||
*/
|
||||
hide(id: string, options?: { removeFromStripe?: boolean }): void;
|
||||
toggle(id: string): void;
|
||||
isVisible(id: string): boolean;
|
||||
}
|
||||
|
||||
@@ -476,6 +476,19 @@ describe("stripe buttons", () => {
|
||||
resetToolWindowPlacements();
|
||||
expect(buttons()).toEqual({});
|
||||
});
|
||||
|
||||
it("drops the button of a window that lost its last tab until new content opens it", () => {
|
||||
disposers.push(registerToolWindow(find));
|
||||
showToolWindow("find");
|
||||
toolWindowServiceImpl.hide("find");
|
||||
expect(hasStripeButton(find, buttons())).toBe(true);
|
||||
showToolWindow("find");
|
||||
toolWindowServiceImpl.hide("find", { removeFromStripe: true });
|
||||
expect(isToolWindowVisible("find")).toBe(false);
|
||||
expect(hasStripeButton(find, buttons())).toBe(false);
|
||||
showToolWindow("find");
|
||||
expect(hasStripeButton(find, buttons())).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("view modes", () => {
|
||||
|
||||
@@ -742,7 +742,7 @@ function isFocusWithinToolWindow(id: string): boolean {
|
||||
|
||||
export const toolWindowServiceImpl: ToolWindowService = {
|
||||
show: (id, focus) => showToolWindow(id, focus),
|
||||
hide: hideToolWindow,
|
||||
hide: (id, options) => (options?.removeFromStripe ? removeFromStripe(id) : hideToolWindow(id)),
|
||||
toggle: toggleToolWindow,
|
||||
isVisible: isToolWindowVisible,
|
||||
};
|
||||
|
||||
Reference in new issue
Заблокувати користувача