feat(vcs): checkable directory tree in the Shelve, Unshelve and Create Patch dialogs (#3778)

The files of the Shelve, Unshelve and Create Patch dialogs were a flat list. They are now a tree under the repository node, grouped by directory with file counts; a directory's checkbox checks or clears every file below it and shows a dash when only some are included. Unshelve lists the shelved files too and applies only the checked ones.

Co-authored-by: PLZY <41029728+PLZY@users.noreply.github.com>
This commit is contained in:
zhangdagou
2026-11-17 00:58:14 +08:00
committed by GitHub
co-authored by PLZY
parent 122d7f3d0f
commit d3d799b8fe
5 changed files with 251 additions and 42 deletions
@@ -0,0 +1,59 @@
import { afterEach, beforeEach, expect, it } from "vitest";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { useState } from "react";
import type { FileStatus } from "@/bindings";
import { FileChecklist } from "../shelf";
import { useVcs } from "../store";
const file = (rel: string): FileStatus => ({
path: `/repo/${rel}`,
relPath: rel,
staged: null,
unstaged: "modified",
renamedFrom: null,
});
const files = [
file("src/chat/web/ChatApiController.java"),
file("src/chat/web/ChatController.java"),
file("src/chat/config/AiConfig.java"),
file("pom.xml"),
];
function Harness() {
const [selected, setSelected] = useState<ReadonlySet<string>>(() => new Set(files.map((f) => f.path)));
return <FileChecklist files={files} selected={selected} onChange={setSelected} label="Files to shelve" />;
}
const box = (name: string) => screen.getByRole("checkbox", { name: `Include ${name}` });
beforeEach(() => useVcs.setState({ root: "/repo" }));
afterEach(cleanup);
it("groups the files by directory, merging single-child chains and counting files", () => {
render(<Harness />);
expect(screen.getByRole("tree", { name: "Files to shelve" })).toBeTruthy();
expect(screen.getByText("repo")).toBeTruthy();
expect(screen.getByText("4 files")).toBeTruthy();
expect(screen.getByText("src/chat")).toBeTruthy();
expect(screen.getByText("3 files")).toBeTruthy();
expect(screen.getByText("web")).toBeTruthy();
expect(screen.getByText("2 files")).toBeTruthy();
expect(box("pom.xml")).toBeChecked();
});
it("checks or clears a directory's files at once and shows a partly included one as mixed", () => {
render(<Harness />);
fireEvent.click(box("ChatController.java"));
expect(box("ChatController.java")).not.toBeChecked();
expect(box("web")).toHaveAttribute("aria-checked", "mixed");
expect(box("src/chat")).toHaveAttribute("aria-checked", "mixed");
expect(box("repo")).toHaveAttribute("aria-checked", "mixed");
fireEvent.click(box("web"));
expect(box("ChatController.java")).toBeChecked();
expect(box("web")).toHaveAttribute("aria-checked", "true");
fireEvent.click(box("src/chat"));
for (const name of ["ChatApiController.java", "ChatController.java", "AiConfig.java"])
expect(box(name)).not.toBeChecked();
expect(box("pom.xml")).toBeChecked();
});
+25 -2
View File
@@ -3,7 +3,14 @@ import { act, fireEvent, render, screen, waitFor, cleanup } from "@testing-libra
import { afterEach } from "vitest";
import type { ShelvedChangeList } from "@/bindings";
const mocks = vi.hoisted(() => ({ openDiff: vi.fn(), execute: vi.fn(), ipc: vi.fn(), patch: vi.fn(), probe: vi.fn() }));
const mocks = vi.hoisted(() => ({
openDiff: vi.fn(),
execute: vi.fn(),
ipc: vi.fn(),
patch: vi.fn(),
probe: vi.fn(),
unshelve: vi.fn(),
}));
vi.mock("../diffInput", async (original) => ({
...(await original<typeof import("../diffInput")>()),
openDiff: mocks.openDiff,
@@ -22,7 +29,7 @@ vi.mock("@/platform/ipc", async (original) => ({
vcsShelfDiff: () => Promise.resolve(null),
fsProbe: mocks.probe,
vcsShelfPatch: mocks.patch,
vcsUnshelve: () => Promise.resolve(null),
vcsUnshelve: mocks.unshelve,
},
}));
import { ShelfPanel, copyShelfPatch, shelfDiffs, shelfTarget, showShelfDiff, unshelve, useShelf } from "../shelf";
@@ -166,6 +173,22 @@ describe("shelf scope and diffs", () => {
fireEvent.click(screen.getByRole("button", { name: "Unshelve" }));
await waitFor(() => expect(useChangelists.getState().state.files).toEqual({ [expected]: "target" }));
});
it("unshelves only the files left checked, one by one", async () => {
useChangelists.setState({
loaded: false,
state: { lists: [{ id: "target", name: "Target", comment: "" }], active: "target", files: {} },
});
mocks.ipc.mockReset().mockResolvedValue({ applied: [], conflicts: [] });
render(<VcsDialogHost />);
act(() => unshelve(entry));
expect(screen.getByRole("tree", { name: "Files to unshelve" })).toBeTruthy();
expect(screen.getAllByText("Added")).toHaveLength(2);
fireEvent.click(screen.getByRole("checkbox", { name: "Include b.txt" }));
expect(screen.getByRole("checkbox", { name: "Include repo" })).toHaveAttribute("aria-checked", "mixed");
fireEvent.click(screen.getByRole("button", { name: "Unshelve" }));
await waitFor(() => expect(mocks.unshelve).toHaveBeenCalledTimes(2));
expect(mocks.unshelve.mock.calls.map((c) => c[2])).toEqual(["a.txt", "binary.dat"]);
});
it("copies only the selected file patch through the scoped patch command", async () => {
const previous = Object.getOwnPropertyDescriptor(navigator, "clipboard");
const writeText = vi.fn().mockResolvedValue(undefined);
+17
View File
@@ -78,6 +78,23 @@
overflow: hidden;
text-overflow: ellipsis;
}
/* Checkable changes tree in the Shelve / Create Patch dialogs. */
.fileTree {
display: flex;
height: 260px;
margin: 0 14px;
border: 1px solid var(--border);
border-radius: var(--radius-small);
}
.fileTreeView {
flex: 1;
min-width: 0;
}
.fileTreeRow {
composes: fileRow;
flex: 1;
padding: 0;
}
.grow {
flex: 1;
}
+149 -40
View File
@@ -6,7 +6,7 @@
import { writeClipboardText } from "@/platform/clipboard";
import { useEffect, useMemo, useState, type MouseEvent } from "react";
import { create } from "zustand";
import type { ApplyOutcome, FileStatus, ShelvedChangeList, ShelfDiffFile } from "@/bindings";
import type { ApplyOutcome, ChangedFile, FileStatus, ShelvedChangeList, ShelfDiffFile } from "@/bindings";
import { setContext } from "@/platform/context";
import { shortcutLabel } from "@/platform/keymap";
import { openDiff, openVcsDiff, withChain, type DiffData } from "./diffInput";
@@ -17,11 +17,22 @@ import { workflowSettings } from "@/platform/workflowSettings";
import { Checkbox, Dialog, Icon, IconButton, Input, Select, Tree, fileIconName, showContextMenu, T } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { groupOf } from "./changes";
import { buildFileTree, dirKeys, type FileTreeNode } from "./fileTree";
import { activeList, listOf, moveFiles, relOf, updateChangelists, useChangelists } from "./changelists";
import { useCommit } from "./commitStore";
import { showLocalChanges } from "./commitUi";
import { confirmDialog, openDialog, promptText } from "./dialogs";
import { KIND_COLOR, baseName, dirName, effectiveKind, fileCount, formatTime, relTo, stripSlash } from "./model";
import {
KIND_COLOR,
KIND_LABEL,
baseName,
dirName,
effectiveKind,
fileCount,
formatTime,
relTo,
stripSlash,
} from "./model";
import { errorMessage, logConsole, runOp, saveAll } from "./ops";
import { conflictedFiles, currentRepo, refreshNow, useVcs } from "./store";
import { repositoryPath } from "./repositoryPaths";
@@ -88,7 +99,93 @@ export function shelveChanges(paths?: readonly string[]) {
openDialog((close) => <ShelveDialog files={files} initialName={name} onClose={close} />);
}
/** A checkable list of changed files (Shelve, Create Patch). */
/** Files of `node` and everything below it. */
function filesBelow<F>(node: FileTreeNode<F>, out: F[] = []): F[] {
if (node.file) out.push(node.file);
for (const child of node.children) filesBelow(child, out);
return out;
}
/**
* A checkable tree of changed files under the repository's node, grouped by directory (Shelve,
* Unshelve, Create Patch), as IDEA's changes tree: a directory's box checks or clears every file
* below it and shows a dash when only some are included.
*/
function ChangeChecklist<F>({
files,
keyOf,
relPath,
colorOf,
detailOf,
rootName,
selected,
onChange,
label,
}: {
files: readonly F[];
keyOf: (f: F) => string;
relPath: (f: F) => string;
colorOf: (f: F) => string | undefined;
/** Muted text after a file name, e.g. its change kind. */
detailOf?: (f: F) => string;
rootName: string;
selected: ReadonlySet<string>;
onChange: (next: Set<string>) => void;
label: string;
}) {
const tree: FileTreeNode<F>[] = [
{ key: "r:", name: rootName, file: null, children: buildFileTree(files, relPath), count: files.length },
];
const [expanded, setExpanded] = useState<ReadonlySet<string> | null>(null);
const toggle = (node: FileTreeNode<F>) => {
const below = filesBelow(node);
const include = !below.every((f) => selected.has(keyOf(f)));
const next = new Set(selected);
for (const f of below) {
if (include) next.add(keyOf(f));
else next.delete(keyOf(f));
}
onChange(next);
};
return (
<div className={styles.fileTree}>
<Tree<FileTreeNode<F>>
roots={tree}
getKey={(n) => n.key}
getLabel={(n) => n.name}
getChildren={(n) => (n.file ? undefined : n.children)}
isExpandable={(n) => !n.file}
expanded={expanded ?? new Set(dirKeys(tree))}
onExpandedChange={setExpanded}
onActivate={toggle}
aria-label={label}
className={styles.fileTreeView}
renderNode={(n) => {
const below = filesBelow(n);
const on = below.filter((f) => selected.has(keyOf(f))).length;
return (
<span className={styles.fileTreeRow}>
<Checkbox
tabIndex={-1}
aria-label={tx`Include ${n.name}`}
checked={on > 0 && on === below.length}
indeterminate={on > 0 && on < below.length}
onChange={() => toggle(n)}
/>
<Icon name={n.file ? fileIconName(n.name, relPath(n.file)) : "folder"} size={14} />
<span className={styles.fileName} style={{ color: n.file ? colorOf(n.file) : undefined }}>
{n.name}
</span>
<span className={styles.fileDir}>{n.file ? (detailOf?.(n.file) ?? "") : fileCount(n.count)}</span>
</span>
);
}}
/>
</div>
);
}
/** The checkable tree of working tree changes (Shelve, Create Patch). */
export function FileChecklist({
files,
selected,
@@ -102,33 +199,18 @@ export function FileChecklist({
}) {
const root = useVcs((s) => s.root) ?? "";
return (
<div className={styles.fileList} role="group" aria-label={label}>
{files.map((f) => {
const kind = effectiveKind(f) ?? "modified";
return (
<div key={f.path} className={styles.fileRow}>
<Checkbox
aria-label={tx`Include ${baseName(f.path)}`}
checked={selected.has(f.path)}
onChange={(v) => {
const n = new Set(selected);
if (v) n.add(f.path);
else n.delete(f.path);
onChange(n);
}}
/>
<Icon name={fileIconName(baseName(f.path), f.path)} size={14} />
<span className={styles.fileName} style={{ color: KIND_COLOR[kind] }}>
{baseName(stripSlash(f.path))}
</span>
<span className={styles.fileDir}>{dirName(relTo(root, stripSlash(f.path)))}</span>
</div>
);
})}
</div>
<ChangeChecklist
files={files}
keyOf={(f) => f.path}
relPath={(f) => relTo(root, stripSlash(f.path))}
colorOf={(f) => KIND_COLOR[effectiveKind(f) ?? "modified"]}
rootName={baseName(root)}
selected={selected}
onChange={onChange}
label={label}
/>
);
}
function ShelveDialog({
files,
initialName,
@@ -210,21 +292,39 @@ export function unshelve(entry: ShelvedChangeList, path?: string) {
openDialog((close) => <UnshelveDialog entry={entry} path={path} onClose={close} />);
}
/** Applies the shelved `paths` of `entry`: in one go when that is all of it, else file by file. */
async function unshelveFiles(entry: ShelvedChangeList, paths: readonly string[], remove: boolean) {
if (paths.length === entry.files.length) return call(commands.vcsUnshelve(entry.id, remove, null));
const outcome: ApplyOutcome = { applied: [], conflicts: [] };
for (const path of paths) {
const one = await call(commands.vcsUnshelve(entry.id, remove, path));
outcome.applied.push(...one.applied);
outcome.conflicts.push(...one.conflicts);
}
return outcome;
}
function UnshelveDialog({ entry, path, onClose }: { entry: ShelvedChangeList; path?: string; onClose: () => void }) {
const lists = useChangelists((s) => s.state);
const [target, setTarget] = useState(lists.active);
const [remove, setRemove] = useState(() => workflowSettings().vcs.shelf.removeApplied);
const repo = shelfRepository(entry);
const files = useMemo<ChangedFile[]>(() => {
if (path === undefined) return entry.files;
const own = entry.files.filter((f) => f.path === path);
return own.length ? own : [{ path, kind: "modified", oldPath: null }];
}, [entry, path]);
const [selected, setSelected] = useState<ReadonlySet<string>>(() => new Set(files.map((f) => f.path)));
const projectRoot = useVcs((s) => s.root);
const root = repo ?? projectRoot ?? "";
const run = async () => {
const chosen = files.filter((f) => selected.has(f.path)).map((f) => f.path);
if (!chosen.length) return;
onClose();
await saveAll();
const outcome = await runOp(
tx`Unshelve “${entry.name}”`,
() => call(commands.vcsUnshelve(entry.id, remove, path ?? null)),
{
refresh: false,
},
);
const outcome = await runOp(tx`Unshelve “${entry.name}”`, () => unshelveFiles(entry, chosen, remove), {
refresh: false,
});
if (!outcome) return;
await refreshNow();
const rels = [...outcome.applied, ...outcome.conflicts].map((p) => relOf(repositoryPath(repo, p)));
@@ -237,15 +337,24 @@ function UnshelveDialog({ entry, path, onClose }: { entry: ShelvedChangeList; pa
open
title="Unshelve Changes"
onClose={onClose}
width={480}
width={560}
buttons={[
{ label: "Unshelve", role: "default", autoFocus: true, onClick: () => void run() },
{ label: "Unshelve", role: "default", autoFocus: true, disabled: !selected.size, onClick: () => void run() },
{ label: "Cancel", role: "cancel" },
]}
>
<div className={styles.section}>
{path ?? entry.name} · {fileCount(path ? 1 : entry.files.length)}
</div>
<div className={styles.section}>{entry.name}</div>
<ChangeChecklist
files={files}
keyOf={(f) => f.path}
relPath={(f) => f.path}
colorOf={(f) => KIND_COLOR[f.kind === "untracked" ? "added" : f.kind]}
detailOf={(f) => tx(KIND_LABEL[f.kind === "untracked" ? "added" : f.kind])}
rootName={baseName(root)}
selected={selected}
onChange={setSelected}
label="Files to unshelve"
/>
<div className={styles.form}>
<label className={styles.fieldLabel}>
<T>Changelist:</T>
+1
View File
@@ -1365,6 +1365,7 @@
"Files to include": "要包括的文件",
"Files to roll back": "要回滚的文件",
"Files to shelve": "要搁置的文件",
"Files to unshelve": "要取消搁置的文件",
"Files will be reverted to the state of the selected commit, but local changes will be kept intact.": "文件将还原到所选提交的状态,但本地更改将保持不变。",
"Files will be reverted to the state of the selected commit. Warning: any local changes will be lost.": "文件将还原到所选提交的状态。警告:所有本地更改都将丢失。",
"Files won't change, differences will be staged for commit.": "文件不会更改,差异将被暂存以供提交。",