diff --git a/src/features/vcs/__tests__/fileChecklist.test.tsx b/src/features/vcs/__tests__/fileChecklist.test.tsx new file mode 100644 index 000000000..aa6c7a098 --- /dev/null +++ b/src/features/vcs/__tests__/fileChecklist.test.tsx @@ -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>(() => new Set(files.map((f) => f.path))); + return ; +} + +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(); + 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(); + 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(); +}); diff --git a/src/features/vcs/__tests__/shelf.test.tsx b/src/features/vcs/__tests__/shelf.test.tsx index 330a749b5..ca2fc60df 100644 --- a/src/features/vcs/__tests__/shelf.test.tsx +++ b/src/features/vcs/__tests__/shelf.test.tsx @@ -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()), 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(); + 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); diff --git a/src/features/vcs/common.module.css b/src/features/vcs/common.module.css index fe4287eaf..781d47f9a 100644 --- a/src/features/vcs/common.module.css +++ b/src/features/vcs/common.module.css @@ -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; } diff --git a/src/features/vcs/shelf.tsx b/src/features/vcs/shelf.tsx index a47dbc2f0..b7661520c 100644 --- a/src/features/vcs/shelf.tsx +++ b/src/features/vcs/shelf.tsx @@ -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) => ); } -/** A checkable list of changed files (Shelve, Create Patch). */ +/** Files of `node` and everything below it. */ +function filesBelow(node: FileTreeNode, 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({ + 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; + onChange: (next: Set) => void; + label: string; +}) { + const tree: FileTreeNode[] = [ + { key: "r:", name: rootName, file: null, children: buildFileTree(files, relPath), count: files.length }, + ]; + const [expanded, setExpanded] = useState | null>(null); + const toggle = (node: FileTreeNode) => { + 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 ( +
+ > + 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 ( + + 0 && on === below.length} + indeterminate={on > 0 && on < below.length} + onChange={() => toggle(n)} + /> + + + {n.name} + + {n.file ? (detailOf?.(n.file) ?? "") : fileCount(n.count)} + + ); + }} + /> +
+ ); +} + +/** 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 ( -
- {files.map((f) => { - const kind = effectiveKind(f) ?? "modified"; - return ( -
- { - const n = new Set(selected); - if (v) n.add(f.path); - else n.delete(f.path); - onChange(n); - }} - /> - - - {baseName(stripSlash(f.path))} - - {dirName(relTo(root, stripSlash(f.path)))} -
- ); - })} -
+ 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) => ); } +/** 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(() => { + 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>(() => 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" }, ]} > -
- {path ?? entry.name} · {fileCount(path ? 1 : entry.files.length)} -
+
{entry.name}
+ 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" + />