fix(vcs): align the worktrees panel (#4937)

- Place the actions on the left of the Worktrees tree in both the dialog and the Git tool window.
- Show the checkout name above its branch and path, with the same UI font size for the checkout name and branch. Current, locked, and prunable worktrees have status icons. The tree supports searching by either checkout name or branch.
This commit is contained in:
l0ng-ai
2026-11-21 10:40:52 +08:00
committed by GitHub
parent 1a470e2a23
commit f0a412f3e2
5 changed files with 275 additions and 102 deletions
+67
View File
@@ -0,0 +1,67 @@
import { expect, stubDesktop, test } from "./fixtures";
test("Worktrees places actions beside the tree and shows the folder above its branch", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1100, height: 700 });
await stubDesktop(page);
await page.evaluate(async () => {
const root = "/dev/acme-api";
const service = `${root}/service`;
const worktree = (path: string, branch: string | null, main = false, locked = false) => ({
path,
branch,
head: "a1234567e312",
main,
locked,
prunable: false,
});
window.__ipc.handlers.vcs_worktrees = ({ repo }) =>
repo === service
? [worktree(service, "release", true), worktree("/dev/service-snapshot", null)]
: [worktree(root, "main", true), worktree("/dev/review-worktree", "feature/review", false, true)];
const store = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ store);
useVcs.setState({ root, roots: [root, service], repo: root, available: true });
const context = "/src/platform/context.ts";
const { setContext } = await import(/* @vite-ignore */ context);
setContext("vcsAvailable", true);
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction("vcs.worktrees");
});
const dialog = page.getByRole("dialog", { name: "Worktrees", exact: true });
const toolbar = dialog.getByRole("toolbar", { name: "Worktrees", exact: true });
const tree = dialog.getByRole("tree", { name: "Worktrees", exact: true });
await expect(tree.getByText("feature/review", { exact: true })).toBeVisible();
const barBox = (await toolbar.boundingBox())!;
const treeBox = (await tree.boundingBox())!;
expect(barBox.x + barBox.width).toBeLessThanOrEqual(treeBox.x);
const row = tree.getByRole("treeitem", { name: /review-worktree.*feature\/review/ });
const name = row.getByText("review-worktree", { exact: true });
const branch = row.getByText("feature/review", { exact: true });
const nameBox = (await name.boundingBox())!;
const branchBox = (await branch.boundingBox())!;
expect(nameBox.y + nameBox.height).toBeLessThanOrEqual(branchBox.y);
await expect(name).toHaveCSS("font-size", await branch.evaluate((el) => getComputedStyle(el).fontSize));
await expect(row.getByRole("img", { name: "locked", exact: true })).toBeVisible();
await expect(tree.getByRole("treeitem", { name: /service-snapshot.*a1234567/ })).toBeVisible();
await tree.focus();
await tree.press("End");
await tree.press("r");
await tree.press("e");
await tree.press("v");
await expect(row).toHaveAttribute("aria-selected", "true");
await tree.press("Escape");
await expect(row.getByText("/dev/review-worktree", { exact: true })).toBeVisible();
await dialog.getByRole("button", { name: "Close", exact: true }).last().click();
await page.getByRole("toolbar", { name: "Tool windows" }).getByRole("button", { name: "Git", exact: true }).click();
await page.getByRole("tab", { name: "Worktrees", exact: true }).click();
const panel = page.getByRole("tabpanel", { name: "Worktrees", exact: true });
const dockedTree = panel.getByRole("tree", { name: "Worktrees", exact: true });
await expect(dockedTree.getByRole("treeitem", { name: /review-worktree.*feature\/review/ })).toBeVisible();
const dockedBarBox = (await panel.getByRole("toolbar", { name: "Worktrees" }).boundingBox())!;
const dockedTreeBox = (await dockedTree.boundingBox())!;
expect(dockedBarBox.x + dockedBarBox.width).toBeLessThanOrEqual(dockedTreeBox.x);
});
+90
View File
@@ -0,0 +1,90 @@
.panel {
display: flex;
flex-direction: column;
min-width: 0;
min-height: 0;
}
.body {
display: flex;
flex: 1;
gap: var(--space-1);
min-width: 0;
min-height: 0;
font-size: var(--fs-ui);
}
.toolbar {
display: flex;
flex: none;
flex-direction: column;
align-items: center;
gap: var(--space-0-5);
padding-inline-end: var(--space-1);
border-inline-end: 1px solid var(--border);
}
.tree {
flex: 1;
min-width: 0;
min-height: 0;
}
.dialogTree {
height: 340px;
}
.icon {
flex: none;
color: var(--fg-muted);
}
.leading {
align-self: flex-start;
margin-block-start: var(--space-1);
}
.details {
display: flex;
flex: 1;
flex-direction: column;
justify-content: center;
gap: var(--space-0-5);
min-width: 0;
line-height: 1.25;
}
.line,
.secondary {
display: flex;
align-items: center;
gap: var(--space-1);
min-width: 0;
}
.line > svg,
.secondary > svg {
flex: none;
}
.secondary {
color: var(--fg-secondary);
}
.path {
flex: 1 1 0;
margin-inline-start: var(--space-1);
color: var(--fg-muted);
font-size: var(--fs-small);
}
.truncated {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.main {
font-weight: 600;
}
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
const { list, move, remove, open, confirm, windowOpenRemote } = vi.hoisted(() => ({
list: vi.fn(),
@@ -43,6 +43,9 @@ const wsl = { kind: "wsl", distro: "Ubuntu" } as const;
const ok = <T,>(data: T) => ({ status: "ok" as const, data });
const fail = (message: string) => ({ status: "error", error: { kind: "invalidInput", message, detail: null } });
const rowAt = async (path: string) =>
within((await screen.findByText(path)).closest<HTMLElement>('[role="treeitem"]')!);
beforeEach(() => {
useProject.setState({ project: { root: "/work/app-feature" } as never });
list.mockReset().mockResolvedValue(ok(worktrees));
@@ -55,15 +58,15 @@ beforeEach(() => {
it("marks the linked project root current when its main worktree is also listed", async () => {
render(<WorktreesPanel />);
expect(await screen.findByText("current /work/app-feature")).toBeInTheDocument();
expect(screen.getByText("main /work/app")).toBeInTheDocument();
expect((await rowAt("/work/app-feature")).getByRole("img", { name: "current" })).toBeInTheDocument();
expect((await rowAt("/work/app")).queryByRole("img", { name: "current" })).toBeNull();
});
it("marks both opened roots current while grouping their repository once", async () => {
useVcs.setState({ roots: ["/work/app-feature", "/work/app"] });
render(<WorktreesPanel />);
expect(await screen.findByText("current /work/app-feature")).toBeInTheDocument();
expect(screen.getByText("current /work/app")).toBeInTheDocument();
expect((await rowAt("/work/app-feature")).getByRole("img", { name: "current" })).toBeInTheDocument();
expect((await rowAt("/work/app")).getByRole("img", { name: "current" })).toBeInTheDocument();
expect(screen.getAllByRole("treeitem")).toHaveLength(3);
});
-25
View File
@@ -720,31 +720,6 @@
align-items: center;
gap: var(--space-0-5);
}
/* Worktrees dialog: the tree needs a height of its own inside the auto-sized body. */
.worktreeListDialog {
height: 340px;
min-height: 0;
}
/* Worktrees tree rows: the worktree name keeps its width, the path is what gets cut short. */
.worktreeIcon {
flex: none;
margin-right: 2px;
color: var(--fg-muted);
}
.worktreeLabel {
flex: none;
max-width: 45%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.worktreeDetail {
min-width: 0;
margin-left: 4px;
overflow: hidden;
text-overflow: ellipsis;
color: var(--fg-muted);
}
.comparisonDialog > [data-dialog-body] {
display: flex;
+110 -72
View File
@@ -23,11 +23,13 @@ import {
type SelectProps,
type MenuItem,
} from "@/ui";
import { useRowHeight } from "@/ui/density";
import { sortLocal, sortRemote } from "./branches";
import { conflictActions, openConflictsInstead, validateBranchName } from "./branchOps";
import { cleanUpBranchNameOnTyping } from "@/platform/gitRefName";
import { confirmDialog, openDialog } from "./dialogs";
import { errorMessage, runOp, runRemote, saveAll } from "./ops";
import { baseName } from "./model";
import { currentRepo, loadBranches, refreshNow, repoName, useVcs } from "./store";
import {
groupWorktrees,
@@ -39,6 +41,7 @@ import {
import styles from "./common.module.css";
import remoteStyles from "./GitRemotes.module.css";
import commandStyles from "./GitCommandDialog.module.css";
import worktreeStyles from "./Worktrees.module.css";
import { tx } from "@/platform/i18n";
import { useProject } from "@/platform/project";
@@ -788,16 +791,15 @@ function WorktreesDialog({ onClose }: { onClose: () => void }) {
interface WorktreeNode {
key: string;
label: string;
worktree?: Worktree;
worktree?: { entry: Worktree; branch: string };
children?: WorktreeNode[];
}
/**
* The worktrees of every repository of the project as one tree, styled like the Log's
* Branches pane, with New / Remove / Open: the Worktrees dialog's content and the Git
* tool window's Worktrees tab. `listClassName` replaces the dialog's default height.
* The worktrees of every project repository, shown in the dialog and in the Git tool window.
*/
export function WorktreesPanel({ className, listClassName }: { className?: string; listClassName?: string }) {
const rowHeight = useRowHeight(40);
const projectRoot = useProject((s) => s.project?.root);
const repo = useVcs((s) => s.repo);
const repos = useVcs((s) => s.roots);
@@ -833,8 +835,8 @@ export function WorktreesPanel({ className, listClassName }: { className?: strin
label: repoName(group.root),
children: group.worktrees.map((w): WorktreeNode => ({
key: `w:${w.path}`,
label: w.branch ?? (w.head ? w.head.slice(0, 8) : tx("(bare)")),
worktree: w,
label: baseName(w.path.replaceAll("\\", "/")) || w.path,
worktree: { entry: w, branch: w.branch ?? (w.head ? w.head.slice(0, 8) : tx("(bare)")) },
})),
})),
[groups],
@@ -846,18 +848,6 @@ export function WorktreesPanel({ className, listClassName }: { className?: strin
const containsProject = !!current && worktreeContainsProject(current.path, projectRoot);
const selectedKeys = useMemo(() => new Set(selected ? [selected] : []), [selected]);
const isCurrent = (path: string) => repos.some((root) => isCurrentWorktree(path, root));
const icon = (node: WorktreeNode) =>
node.worktree ? (isCurrent(node.worktree.path) ? "current-branch" : "branch") : "folder";
const detail = (node: WorktreeNode) => {
const w = node.worktree;
if (!w) return "";
const current = isCurrent(w.path);
// "main" only when the main worktree is not the one this window works in.
const flags = [
current ? tx("current") : w.main ? "main" : w.locked ? tx("locked") : w.prunable ? tx("prunable") : "",
].filter(Boolean);
return [...flags, w.path].join(" ");
};
const mutate = async (task: () => Promise<unknown>, selection: string | null) => {
if (projectRoot !== useProject.getState().project?.root) return;
@@ -926,62 +916,110 @@ export function WorktreesPanel({ className, listClassName }: { className?: strin
};
return (
<div className={className}>
<div className={styles.manageBar} role="toolbar" aria-label={tx("Worktrees")}>
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => void reload()} />
<IconButton
icon="plus"
title="New Worktree…"
size="small"
onClick={() => showNewWorktree(() => void reload(), currentGroup?.root ?? repo ?? repos[0])}
/>
<IconButton
icon="minus"
title={containsProject ? "Cannot remove a worktree containing the open project." : "Remove Worktree"}
aria-label="Remove Worktree"
size="small"
disabled={!current || current.main || containsProject}
onClick={() => void remove()}
/>
<IconButton
icon="export"
title={containsProject ? "Cannot move a worktree containing the open project." : "Move Worktree…"}
aria-label="Move Worktree…"
size="small"
disabled={!current || current.main || containsProject}
onClick={() => void move()}
/>
<IconButton
icon="folder"
title="Open in New Window"
size="small"
disabled={!current}
onClick={() => current && void openWorktree(current.path)}
<div className={clsx(worktreeStyles.panel, className)}>
<div className={worktreeStyles.body}>
<div className={worktreeStyles.toolbar} role="toolbar" aria-label={tx("Worktrees")} aria-orientation="vertical">
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => void reload()} />
<IconButton
icon="plus"
title="New Worktree…"
size="small"
onClick={() => showNewWorktree(() => void reload(), currentGroup?.root ?? repo ?? repos[0])}
/>
<IconButton
icon="minus"
title={containsProject ? "Cannot remove a worktree containing the open project." : "Remove Worktree"}
aria-label="Remove Worktree"
size="small"
disabled={!current || current.main || containsProject}
onClick={() => void remove()}
/>
<IconButton
icon="export"
title={containsProject ? "Cannot move a worktree containing the open project." : "Move Worktree…"}
aria-label="Move Worktree…"
size="small"
disabled={!current || current.main || containsProject}
onClick={() => void move()}
/>
<IconButton
icon="folder"
title="Open in New Window"
size="small"
disabled={!current}
onClick={() => current && void openWorktree(current.path)}
/>
</div>
<Tree<WorktreeNode>
// A new set of repositories starts with every section expanded.
key={tree.map((n) => n.key).join("|")}
roots={tree}
getKey={(n) => n.key}
getLabel={(n) => (n.worktree ? `${n.label} ${n.worktree.branch}` : n.label)}
getChildren={(n) => n.children}
isExpandable={(n) => !!n.children}
renderNode={(node, { matches }) => {
if (!node.worktree) {
return (
<>
<Icon name="folder" size={16} className={worktreeStyles.icon} />
<HighlightedText
className={worktreeStyles.truncated}
text={node.label}
indices={matches}
tone="accent"
/>
</>
);
}
const { entry, branch } = node.worktree;
const current = isCurrent(entry.path);
const branchStart = node.label.length + 1;
return (
<>
<Icon
name={current ? "check" : "folder"}
size={16}
label={current ? tx("current") : undefined}
className={clsx(worktreeStyles.icon, worktreeStyles.leading)}
/>
<div className={worktreeStyles.details}>
<span className={worktreeStyles.line}>
<HighlightedText
className={clsx(worktreeStyles.truncated, entry.main && worktreeStyles.main)}
text={node.label}
indices={matches?.filter((i) => i < node.label.length)}
tone="accent"
/>
{entry.locked && <Icon name="lock" size={12} label={tx("locked")} />}
{entry.prunable && <Icon name="warning" size={12} label={tx("prunable")} />}
</span>
<span className={worktreeStyles.secondary}>
<Icon name="branch" size={12} />
<HighlightedText
className={worktreeStyles.truncated}
text={branch}
indices={matches?.filter((i) => i >= branchStart).map((i) => i - branchStart)}
tone="accent"
/>
<span className={clsx(worktreeStyles.path, worktreeStyles.truncated)} title={entry.path}>
{entry.path}
</span>
</span>
</div>
</>
);
}}
defaultExpanded={tree.map((n) => n.key)}
selected={selectedKeys}
multiSelect={false}
onSelectionChange={(selection) => setSelected([...selection][0] ?? null)}
onActivate={(n) => n.worktree && void openWorktree(n.worktree.entry.path)}
className={clsx(worktreeStyles.tree, listClassName ?? worktreeStyles.dialogTree)}
rowHeight={rowHeight}
aria-label="Worktrees"
/>
</div>
<Tree<WorktreeNode>
// A new set of repositories starts with every section expanded.
key={tree.map((n) => n.key).join("|")}
roots={tree}
getKey={(n) => n.key}
getLabel={(n) => n.label}
getChildren={(n) => n.children}
isExpandable={(n) => !!n.children}
renderNode={(node, state) => (
<>
<Icon name={icon(node)} size={16} className={styles.worktreeIcon} />
<HighlightedText className={styles.worktreeLabel} text={node.label} indices={state.matches} tone="accent" />
{node.worktree && <span className={styles.worktreeDetail}>{detail(node)}</span>}
</>
)}
defaultExpanded={tree.map((n) => n.key)}
selected={selectedKeys}
multiSelect={false}
onSelectionChange={(selection) => setSelected([...selection][0] ?? null)}
onActivate={(n) => n.worktree && void openWorktree(n.worktree.path)}
className={listClassName ?? styles.worktreeListDialog}
aria-label="Worktrees"
/>
{groups.map(
(group) =>
group.error && (