diff --git a/e2e/commitAddSelection.spec.ts b/e2e/commitAddSelection.spec.ts index 3116ad9b6e..cd2bf71bf7 100644 --- a/e2e/commitAddSelection.spec.ts +++ b/e2e/commitAddSelection.spec.ts @@ -37,6 +37,79 @@ async function openUnversionedFiles(page: Page, groupByRepo: boolean) { return page.getByRole("tree", { name: "Changes", exact: true }); } +async function openCommitDialogAllUnversioned(page: Page) { + await openFromTree(page, "build.gradle.kts"); + await stubDesktop(page); + await page.evaluate( + async ({ root, paths }) => { + const project = "/src/platform/project.ts"; + const { useProject } = await import(project); + useProject.setState((s: { settings: Record | null }) => { + const settings = s.settings ?? {}; + const vcs = (settings.vcs ?? {}) as Record; + return { + settings: { + ...settings, + vcs: { ...vcs, commit: { ...(vcs.commit as Record | undefined), nonModal: false } }, + }, + }; + }); + const vcsModule = "/src/features/vcs/store.ts"; + const commitModule = "/src/features/vcs/commitStore.ts"; + const { useVcs, refreshNow } = await import(vcsModule); + const { useCommit } = await import(commitModule); + useCommit.setState({ groupByDir: true, groupByRepo: false, showUnversionedSeparately: true }); + const branch = { head: "main", headCommit: "1111111", operation: null }; + const h = window.__ipc.handlers; + h.vcs_branch_info = () => ({ ...branch, upstream: null, ahead: 0, behind: 0 }); + h.vcs_roots = () => [{ ...branch, root }]; + h.vcs_status = () => + paths.map((path) => ({ + path, + relPath: path.slice(root.length + 1), + staged: null, + unstaged: "untracked", + renamedFrom: null, + })); + h.vcs_stage = () => null; + useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false }); + await refreshNow(); + }, + { root, paths }, + ); + await page.keyboard.press("Meta+k"); + return page.getByRole("dialog", { name: "Commit Changes", exact: true }); +} + +test("Add to VCS keyboard shortcut stages the selected folder in the Commit Changes dialog", async ({ + workbench: page, +}) => { + const dialog = await openCommitDialogAllUnversioned(page); + const tree = dialog.getByRole("tree", { name: "Changes", exact: true }); + await tree + .getByRole("treeitem", { name: /Unversioned Files/ }) + .locator("[data-tree-toggle]") + .click(); + await tree.getByText("alpha", { exact: true }).click(); + await page.keyboard.press("Meta+Alt+a"); + await expect.poll(() => ipcCalls(page, "vcs_stage")).toEqual([{ paths: [paths[0]] }]); +}); + +test("Add to VCS in the Commit dialog ignores a leftover Local Changes selection", async ({ workbench: page }) => { + const dialog = await openCommitDialogAllUnversioned(page); + // Leave a selection in the shared store, as the Git window's Local Changes tab does; + // the dialog's tree starts empty, so the shortcut must not stage it. + await page.evaluate(async (path) => { + const commitModule = "/src/features/vcs/commitStore.ts"; + const { useCommit } = await import(commitModule); + useCommit.setState({ selection: [path], selectionKeys: ["leftover"] }); + }, paths[0]!); + await expect(dialog).toBeVisible(); + await page.keyboard.press("Meta+Alt+a"); + await expect(page.getByRole("status").filter({ hasText: "Nothing to add" })).toBeVisible(); + expect(await ipcCalls(page, "vcs_stage")).toEqual([]); +}); + for (const grouping of ["repositories", "folders"] as const) { test(`Add to VCS includes both selected ${grouping}`, async ({ workbench: page }) => { const tree = await openUnversionedFiles(page, grouping === "repositories"); diff --git a/src/features/vcs/CommitView.tsx b/src/features/vcs/CommitView.tsx index b8b959a3bb..375a69a256 100644 --- a/src/features/vcs/CommitView.tsx +++ b/src/features/vcs/CommitView.tsx @@ -107,6 +107,7 @@ import { import { SHOW_THREE_SIDE_DIFF } from "./stagingVersions"; import { addToChangelist, commitFiles } from "./changelistsUi"; import { acceptConflictSide, canRevertResolved } from "./conflictsUi"; +import { setCommitDialogSelection } from "./commitDialogSelection"; import { messageHistory, pendingFixup, @@ -823,6 +824,14 @@ export function ChangesTree({ mode, amended }: { mode: "commit" | "local" | "dia const [selected, setSelected] = useState>(() => new Set()); const treeRef = useRef(null); const viewRef = useRef(null); + // The modal dialog's tree publishes its own selection; the shared store may hold + // the Git window's Local Changes selection instead. Mounted = empty, unmounted = null. + const dialogMode = mode === "dialog"; + useLayoutEffect(() => { + if (!dialogMode) return; + setCommitDialogSelection({ paths: [], keys: [] }); + return () => setCommitDialogSelection(null); + }, [dialogMode]); const repos = useVcs((s) => s.roots); const heads = useVcs((s) => s.heads); @@ -1153,12 +1162,14 @@ export function ChangesTree({ mode, amended }: { mode: "commit" | "local" | "dia onSelectionChange={(sel) => { setSelected(sel); const nodes = [...sel].map((k) => byKey.get(k)).filter((n): n is ChangeNode => !!n); + const paths = filesOf(nodes.filter((n) => n.group !== "ignored")).map((f) => f.path); useCommit.setState({ - selection: filesOf(nodes.filter((n) => n.group !== "ignored")).map((f) => f.path), + selection: paths, selectionKeys: [...sel], unstagedSelection: unstagedSelection(nodes).map((file) => file.path), selectedList: nodes.find((n) => n.changelist)?.changelist ?? null, }); + if (dialogMode) setCommitDialogSelection({ paths, keys: [...sel] }); followSelection(nodes); }} onActivate={(n) => openNode(n, roots, mode === "dialog")} diff --git a/src/features/vcs/__tests__/addToVcsAction.test.ts b/src/features/vcs/__tests__/addToVcsAction.test.ts index 552c26e9a3..f23cc91116 100644 --- a/src/features/vcs/__tests__/addToVcsAction.test.ts +++ b/src/features/vcs/__tests__/addToVcsAction.test.ts @@ -30,7 +30,10 @@ vi.mock("../diffDialog", () => ({ openDiffDialog: vi.fn() })); vi.mock("../DiffWindow", () => ({ showDiffWindow: vi.fn() })); import { getAction } from "@/platform/actions"; +import { clearContext, setContext } from "@/platform/context"; import { registerVcsActions } from "../actions"; +import { setCommitDialogSelection } from "../commitDialogSelection"; +import { useCommit } from "../commitStore"; import { useVcs } from "../store"; const fs = (relPath: string, unstaged: FileStatus["unstaged"]): FileStatus => ({ @@ -86,6 +89,46 @@ describe("Add to VCS", () => { }); }); +describe("Add to VCS from the modal Commit dialog", () => { + beforeEach(() => { + setContext("activeToolWindow", "project"); + useCommit.setState({ selection: [], selectionKeys: [] }); + document.body.innerHTML = '
'; + (document.querySelector('[data-changes-tree="dialog"]') as HTMLElement).focus(); + setCommitDialogSelection({ paths: ["/repo/dir/new.ts"], keys: ["unversioned:dir:dir"] }); + }); + + afterEach(() => { + setCommitDialogSelection(null); + document.body.innerHTML = ""; + clearContext("activeToolWindow"); + }); + + it("stages the dialog tree's own selection while that tree has focus", async () => { + await addToVcs().run({ arg: undefined, ctx: { vcsAvailable: true, projectViewFocus: false } }); + expect(stage).toHaveBeenCalledWith(["/repo/dir/new.ts"]); + }); + + it("does not fall back to the shared store or the Project view on an empty dialog selection", async () => { + setCommitDialogSelection({ paths: [], keys: [] }); + useCommit.setState({ selection: ["/repo/dir/new.ts"], selectionKeys: ["leftover"] }); + project.paths = ["/repo/dir/new.ts"]; + await addToVcs().run({ arg: undefined, ctx: { vcsAvailable: true, projectViewFocus: true } }); + expect(stage).not.toHaveBeenCalled(); + expect(notify).toHaveBeenCalledWith( + expect.objectContaining({ title: "Nothing to add: the files are already under version control" }), + ); + }); + + it("ignores the dialog selection once focus leaves its changes tree", async () => { + const message = document.createElement("textarea"); + document.body.append(message); + message.focus(); + await addToVcs().run({ arg: undefined, ctx: { vcsAvailable: true } }); + expect(stage).not.toHaveBeenCalled(); + }); +}); + describe("Add to .gitignore", () => { it("ignores the Project view's selection while it has focus, and not otherwise", async () => { project.paths = ["/repo/dir/new.ts"]; diff --git a/src/features/vcs/__tests__/rollbackAction.test.ts b/src/features/vcs/__tests__/rollbackAction.test.ts index 8fdb6d9ec8..2d4d51700c 100644 --- a/src/features/vcs/__tests__/rollbackAction.test.ts +++ b/src/features/vcs/__tests__/rollbackAction.test.ts @@ -29,6 +29,7 @@ vi.mock("../changeOps", async (orig) => { }); const { registerVcsActions } = await import("../actions"); +const { setCommitDialogSelection } = await import("../commitDialogSelection"); const { useVcs } = await import("../store"); const { useCommit } = await import("../commitStore"); @@ -53,10 +54,17 @@ const status = [ afterEach(() => { vi.clearAllMocks(); toolWindow = null; + setCommitDialogSelection(null); + document.body.innerHTML = ""; useVcs.setState({ status: [], root: null, roots: [] }); useCommit.setState({ selection: [], checks: new Map() }); }); +function focusDialogTree() { + document.body.innerHTML = '
'; + (document.querySelector('[data-changes-tree="dialog"]') as HTMLElement).focus(); +} + describe("vcs.rollback targets", () => { it("rolls back the checked changes when the selection holds unversioned files", async () => { const unregister = registerVcsActions(); @@ -130,6 +138,48 @@ describe("vcs.rollback targets", () => { } }); + it("rolls back the Commit dialog tree's own selection while it has focus", async () => { + const unregister = registerVcsActions(); + try { + useVcs.setState({ status, root: "/r", roots: ["/r"] }); + setCommitDialogSelection({ paths: ["/r/src/main.tsx"], keys: ["k"] }); + focusDialogTree(); + await getAction("vcs.rollback")!.run({ arg: undefined, ctx: { vcsAvailable: true } }); + expect(mocks.showDialog).toHaveBeenCalledWith([status[1]]); + } finally { + unregister(); + } + }); + + it("does nothing on an empty dialog selection instead of falling back to the checked changes", async () => { + const unregister = registerVcsActions(); + try { + useVcs.setState({ status, root: "/r", roots: ["/r"] }); + setCommitDialogSelection({ paths: [], keys: [] }); + focusDialogTree(); + await getAction("vcs.rollback")!.run({ arg: undefined, ctx: { vcsAvailable: true } }); + expect(mocks.showDialog).not.toHaveBeenCalled(); + } finally { + unregister(); + } + }); + + it("ignores the dialog selection once focus leaves its changes tree", async () => { + const unregister = registerVcsActions(); + try { + useVcs.setState({ status, root: "/r", roots: ["/r"] }); + setCommitDialogSelection({ paths: ["/r/src/main.tsx"], keys: ["k"] }); + focusDialogTree(); + const message = document.createElement("textarea"); + document.body.append(message); + message.focus(); + await getAction("vcs.rollback")!.run({ arg: undefined, ctx: { vcsAvailable: true } }); + expect(mocks.showDialog).toHaveBeenCalledWith([status[0], status[1]]); + } finally { + unregister(); + } + }); + it("opens Rollback for an explicitly selected submodule entry", async () => { const unregister = registerVcsActions(); try { diff --git a/src/features/vcs/actions.tsx b/src/features/vcs/actions.tsx index 947228d1e7..9cb232a188 100644 --- a/src/features/vcs/actions.tsx +++ b/src/features/vcs/actions.tsx @@ -54,6 +54,7 @@ import { showUnstashDialog, } from "./changeOps"; import { setAmend, showsIgnoredFiles, toggleIgnoredFiles, useCommit } from "./commitStore"; +import { commitDialogTreeSelection } from "./commitDialogSelection"; import { amendPreviewNode } from "./amendPreview"; import { SELECT_AMEND_TARGET, type EarlierAmend } from "./amendTargets"; import { TOGGLE_IGNORED_FILES } from "./ignoredFiles"; @@ -229,6 +230,8 @@ function showDiffTargets(tree: readonly ChangeNode[], paths: readonly string[], function changedPaths(arg: unknown): string[] { const explicit = argPaths(arg); if (explicit?.length) return explicit; + const dialog = commitDialogTreeSelection(); + if (dialog) return dialog.paths; const sel = useCommit.getState().selection; return commitWindowFocused() ? sel : []; } @@ -264,7 +267,8 @@ function gutterTarget(arg: unknown, flag: "staged" | "unstaged"): GutterChangeTa /** Files the current context refers to: argument, commit view selection, or the active file. */ function contextPaths(arg: unknown): string[] { const changed = changedPaths(arg); - if (changed.length) return changed; + // The Commit dialog tree's selection is final, even when it is empty. + if (changed.length || commitDialogTreeSelection()) return changed; const active = maybeEditorService()?.activePath(); return active ? [active] : []; } @@ -277,6 +281,8 @@ function contextPaths(arg: unknown): string[] { function selectedPaths(arg: unknown): string[] { const changed = changedPaths(arg); if (changed.length) return changed; + // The Commit dialog tree's selection is final, even when it is empty. + if (commitDialogTreeSelection()) return []; if (commitWindowFocused() && useCommit.getState().selectionKeys.some((key) => key.startsWith("amend:"))) return []; if (commitWindowFocused() && stagingAreaOn() && showsIgnoredFiles(useVcs.getState().root ?? "")) { const { selectionKeys } = useCommit.getState(); @@ -730,6 +736,16 @@ export function registerVcsActions(): () => void { if (!explicit?.length && ed?.view.hasFocus) { if (rollbackSelectedLines(ed.view, ed.ctx.path) || stagingAreaOn()) return; } + // The Commit dialog's tree, while it owns the focus, targets its own selection; + // an empty selection is final and does not fall back to the checked changes. + const dialog = commitDialogTreeSelection(); + if (dialog && !explicit?.length) { + if (dialog.paths.length) { + const files = rollbackCandidates(dialog.paths); + if (files.length) showRollbackDialog(files); + } + return; + } // The Commit window's subject is its tree selection; when the selection holds // nothing rollbackable (unversioned files, stale paths), the checked changes are // instead — as IDEA's toolbar Rollback acts on the checked changes there. diff --git a/src/features/vcs/commitDialogSelection.ts b/src/features/vcs/commitDialogSelection.ts new file mode 100644 index 0000000000..7d0a5d6959 --- /dev/null +++ b/src/features/vcs/commitDialogSelection.ts @@ -0,0 +1,27 @@ +/** The Commit dialog's own changes-tree selection, used only while that tree has keyboard focus. */ +export interface CommitDialogSelection { + paths: string[]; + keys: string[]; +} + +let published: CommitDialogSelection | null = null; + +/** The dialog's ChangesTree publishes its selection here; `null` once it unmounts. */ +export function setCommitDialogSelection(selection: CommitDialogSelection | null) { + published = selection; +} + +/** + * The dialog tree's selection while it owns the keyboard focus, else `null`. + * + * The modal Commit dialog shares `useCommit.selection` with the Git window's Local + * Changes tab, so that store can hold a selection the dialog's tree does not show. + * Selection-based actions therefore read this snapshot instead, and only while the + * focus is inside the dialog's changes tree. + */ +export function commitDialogTreeSelection(): CommitDialogSelection | null { + if (published === null) return null; + const active = typeof document !== "undefined" ? document.activeElement : null; + if (!(active instanceof Element) || !active.closest('[data-changes-tree="dialog"]')) return null; + return published; +}