From 6bf7bc8c2ba8806af14187c148970a2a4845deb8 Mon Sep 17 00:00:00 2001 From: faysou Date: Fri, 20 Nov 2026 22:18:36 +0000 Subject: [PATCH] fix(vcs): apply Directory Mappings changes to all selected roots (#4908) Directory Mappings now supports multi-row selection with Cmd/Ctrl and Shift. Minus moves the selected Git roots to an Unregistered roots section instead of only removing manually added ones, and plus registers the selected unregistered roots again in one step. Applying a removal refreshes Git status and branches: removing the selected repository switches to the remaining one, and removing the last repository clears the previous Git state and decorations. Co-authored-by: faysou <893862+faysou@users.noreply.github.com> Co-authored-by: faysou <893862+faysou@users.noreply.github.com> --- e2e/settings.spec.ts | 48 ++++- .../settings/pages/Workflow.module.css | 10 + src/features/settings/pages/vcs.tsx | 203 ++++++++++++------ src/features/vcs/store.switch.test.ts | 71 +++++- src/features/vcs/store.ts | 22 +- src/platform/locales/text/en.json | 1 + src/platform/locales/text/zh.json | 1 + 7 files changed, 282 insertions(+), 74 deletions(-) diff --git a/e2e/settings.spec.ts b/e2e/settings.spec.ts index e3e54cd4c..1dc548e0d 100644 --- a/e2e/settings.spec.ts +++ b/e2e/settings.spec.ts @@ -120,15 +120,53 @@ test("Directory Mappings keeps the controls and headers visible while scrolling name: "VCS of integrations/finance-and-order-reconciliation/ledger-adapter-32", exact: true, }); - await vcs.click(); - await page.getByRole("option", { name: "", exact: true }).click(); - await expect(vcs).toHaveText(""); + await name.click(); + const remove = toolbar.getByRole("button", { name: "Remove", exact: true }); + await expect(remove).toBeEnabled(); + await remove.click(); + const unregistered = table.getByRole("rowgroup", { name: "Unregistered roots" }); + await expect(unregistered.getByRole("row").last()).toContainText("ledger-adapter-32"); + await expect(repo).toHaveAttribute("aria-selected", "true"); + await expect(repo.getByRole("cell", { name: "Git", exact: true })).toBeVisible(); + await expect(remove).toBeDisabled(); - await toolbar.getByRole("button", { name: "Add", exact: true }).click(); + const add = toolbar.getByRole("button", { name: "Add", exact: true }); + await add.click(); + await expect(vcs).toHaveText("Git"); + await expect(unregistered).toHaveCount(0); + await expect(table.getByText("billing-audit-adapter", { exact: true })).toHaveCount(0); + + const ledger = (n: number) => table.getByText(`ledger-adapter-${n}`, { exact: true }); + const selectedNames = () => table.locator("tr[aria-selected=true] td:first-child").allTextContents(); + await ledger(29).click(); + await ledger(31).click({ modifiers: ["Meta"] }); + expect(await selectedNames()).toEqual([ + "integrations/finance-and-order-reconciliation/ledger-adapter-29", + "integrations/finance-and-order-reconciliation/ledger-adapter-31", + ]); + await ledger(29).click(); + await ledger(31).click({ modifiers: ["Shift"] }); + await expect(table.locator("tr[aria-selected=true]")).toHaveCount(3); + expect(await page.evaluate(() => window.getSelection()?.toString())).toBe(""); + await remove.click(); + await expect(unregistered.getByRole("row")).toHaveCount(4); + await expect(unregistered.locator("tr[aria-selected=true]")).toHaveCount(3); + await expect(unregistered.getByText("ledger-adapter-29", { exact: true })).toBeVisible(); + await expect(unregistered.getByText("ledger-adapter-30", { exact: true })).toBeVisible(); + await expect(unregistered.getByText("ledger-adapter-31", { exact: true })).toBeVisible(); + await ledger(32).click({ modifiers: ["Meta"] }); + await expect(remove).toBeDisabled(); + await expect(add).toBeDisabled(); + await ledger(32).click({ modifiers: ["Meta"] }); + await add.click(); + await expect(unregistered).toHaveCount(0); + await expect(table.locator("tr[aria-selected=true]")).toHaveCount(3); + + await add.click(); const added = table.getByRole("row").filter({ hasText: "billing-audit-adapter" }); await expect(added.getByText("billing-audit-adapter", { exact: true })).toBeInViewport({ ratio: 1 }); await expect(added).toHaveAttribute("aria-selected", "true"); - await toolbar.getByRole("button", { name: "Remove", exact: true }).click(); + await remove.click(); await expect(added).toHaveCount(0); await settings.getByRole("button", { name: "Cancel", exact: true }).click(); diff --git a/src/features/settings/pages/Workflow.module.css b/src/features/settings/pages/Workflow.module.css index cb739462f..1954e3878 100644 --- a/src/features/settings/pages/Workflow.module.css +++ b/src/features/settings/pages/Workflow.module.css @@ -180,6 +180,8 @@ min-height: 0; overflow: auto; scroll-padding-top: var(--h-list-row); + -webkit-user-select: none; + user-select: none; } .mappingRows th { position: sticky; @@ -192,6 +194,14 @@ .mappingVcsColumn { width: 112px; } +.unregisteredMappings { + color: var(--fg-subtle); + background: var(--bg-control-hover); +} +.unregisteredMappings .mappingGroupHeader { + color: var(--fg-muted); + font-weight: 600; +} .mappingRows .mappingSelect { width: 100%; padding-inline-start: 0; diff --git a/src/features/settings/pages/vcs.tsx b/src/features/settings/pages/vcs.tsx index c48e13cc9..106ff474c 100644 --- a/src/features/settings/pages/vcs.tsx +++ b/src/features/settings/pages/vcs.tsx @@ -4,13 +4,13 @@ * Behaviour lives in the vcs feature, which reads `vcs.*` through * `platform/workflowSettings`. */ -import { useCallback, useEffect, useId, useMemo, useState } from "react"; +import { useCallback, useEffect, useId, useMemo, useState, type MouseEvent } from "react"; import clsx from "clsx"; -import { call, commands, isTauri } from "@/platform/ipc"; +import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc"; import { useProject } from "@/platform/project"; -import { WORKFLOW_LIMITS, type IssueLinkValid } from "@/platform/workflowSettings"; +import { WORKFLOW_LIMITS, type IssueLinkValid, type VcsSettingsValid } from "@/platform/workflowSettings"; import { showInFileManagerLabel } from "@/platform/fileManager"; -import { Button, Icon, IconButton, Input, Select, type SelectOption, T } from "@/ui"; +import { Button, Icon, IconButton, Input, rowSelectionMode, Select, selectRow, type SelectOption, T } from "@/ui"; import { choosePath } from "@/platform/choosePath"; import { Row, SettingSelect } from "../components/Form"; import { useSetting } from "../components/context"; @@ -62,10 +62,13 @@ function mappingPath(root: string, key: string): string { function MappingsTable() { const project = useProject((s) => s.project); const root = project?.root ?? null; - const [excluded, setExcluded] = useSetting("vcs.mappings.excluded", "project"); - const [added, setAdded] = useSetting("vcs.mappings.added", "project"); + const [{ excluded, added }, setMappings] = useSetting("vcs.mappings", "project"); const [detected, setDetected] = useState(null); - const [selected, setSelected] = useState(null); + const [registered, setRegistered] = useState([]); + const [selection, setSelection] = useState<{ keys: ReadonlySet; anchor: string | null }>(() => ({ + keys: new Set(), + anchor: null, + })); useEffect(() => { if (!root || !isTauri()) return; let live = true; @@ -73,45 +76,82 @@ function MappingsTable() { (roots) => live && setDetected(roots), () => live && setDetected([]), ); + const refreshRegistered = () => + call(commands.vcsRoots()).then( + (roots) => live && setRegistered(roots.map((repo) => repo.root)), + () => live && setRegistered([]), + ); + void refreshRegistered(); + const off = onIdeEvent("vcsChanged", (event) => { + if (event.root === root) void refreshRegistered(); + }); return () => { live = false; + off(); }; }, [root]); const rows = useMemo(() => { if (!root) return []; - const keys = new Set([...(detected ?? []).map((p) => mappingKey(root, p)), ...added]); - if (!keys.size) keys.add("."); + const detectedKeys = new Set((detected ?? []).map((path) => mappingKey(root, path))); + const registeredKeys = new Set(registered.map((path) => mappingKey(root, path))); + const keys = new Set([...detectedKeys, ...added, ...excluded]); + if (!keys.size && detected === null && project?.isGit) keys.add("."); return [...keys] .sort((a, b) => (a === "." ? -1 : b === "." ? 1 : a.localeCompare(b))) .map((key) => ({ key, path: mappingPath(root, key), - manual: added.includes(key), - vcs: (excluded.includes(key) || (!project?.isGit && key === "." && !detected?.length && !added.length) - ? "none" - : "git") as VcsChoice, + detected: detectedKeys.has(key), + knownRoot: detectedKeys.has(key) || registeredKeys.has(key), + unregistered: excluded.includes(key), })); - }, [root, detected, added, excluded, project?.isGit]); + }, [root, detected, registered, added, excluded, project?.isGit]); + + const activeRows = rows.filter((row) => !row.unregistered); + const unregisteredRows = rows.filter((row) => row.unregistered); + const displayedRows = [...activeRows, ...unregisteredRows]; + const selected = displayedRows.filter((row) => selection.keys.has(row.key)); + const selectedUnregistered = selected.filter((row) => row.unregistered); + const canAdd = !selectedUnregistered.length || selectedUnregistered.length === selected.length; + const canRemove = selected.length > 0 && !selectedUnregistered.length; const setVcs = (key: string, vcs: VcsChoice) => - setExcluded(vcs === "none" ? [...excluded.filter((k) => k !== key), key] : excluded.filter((k) => k !== key)); + setMappings({ + added, + excluded: vcs === "none" ? [...new Set([...excluded, key])] : excluded.filter((k) => k !== key), + }); + const register = (mappings: readonly { key: string; detected: boolean }[]) => { + const keys = new Set(mappings.map((row) => row.key)); + setMappings({ + added: [...new Set([...added, ...mappings.filter((row) => !row.detected).map((row) => row.key)])], + excluded: excluded.filter((entry) => !keys.has(entry)), + }); + }; const add = async () => { - if (!root) return; + if (!root || !canAdd) return; + if (selectedUnregistered.length) { + register(selectedUnregistered); + return; + } const picked = await choosePath({ directory: true, title: "Select Repository Root", defaultPath: root }); if (!picked) return; const key = mappingKey(root, picked); - if (excluded.includes(key)) setExcluded(excluded.filter((k) => k !== key)); - if (!rows.some((r) => r.key === key)) setAdded([...added, key]); - setSelected(key); + register([{ key, detected: rows.some((row) => row.key === key && row.detected) }]); + setSelection({ keys: new Set([key]), anchor: key }); }; - const removable = rows.find((r) => r.key === selected && r.manual); const remove = () => { - if (!removable) return; - setAdded(added.filter((k) => k !== removable.key)); - setExcluded(excluded.filter((k) => k !== removable.key)); - setSelected(null); + if (!canRemove) return; + const moved = selected.filter((row) => row.knownRoot).map((row) => row.key); + setMappings({ + added: added.filter((key) => !selection.keys.has(key)), + excluded: [...excluded, ...moved], + }); + setSelection({ + keys: new Set(moved), + anchor: selection.anchor && moved.includes(selection.anchor) ? selection.anchor : (moved[0] ?? null), + }); }; const revealRow = useCallback((row: HTMLTableRowElement | null) => { row?.scrollIntoView({ block: "nearest" }); @@ -121,8 +161,8 @@ function MappingsTable() {
{root && (
- void add()} /> - + void add()} /> +
)}
@@ -142,53 +182,92 @@ function MappingsTable() { - {!root ? ( + {root ? ( + activeRows.map(renderRow) + ) : ( No project is open - ) : ( - rows.map((row) => { - const directory = mappingKey(root.replaceAll("\\", "/"), row.path.replaceAll("\\", "/")); - const name = directory === "." ? tx("") : directory; - const leaf = name.lastIndexOf("/") + 1; - return ( - setSelected(row.key)} - > - - - - - {leaf > 0 && {name.slice(0, leaf)}} - {name.slice(leaf)} - - - - - setVcs(row.key, v)} + /> + )} + + + ); + } + + function selectMapping(event: MouseEvent, row: (typeof rows)[number]) { + if (!event.currentTarget.contains(event.target as Node)) return; + const mode = rowSelectionMode(event); + setSelection(({ keys, anchor }) => { + if (mode === "toggle" && keys.size === 1 && keys.has(row.key)) { + return { keys: new Set(), anchor: null }; + } + const index = displayedRows.indexOf(row); + const anchorIndex = displayedRows.findIndex((entry) => entry.key === anchor); + const next = selectRow( + displayedRows, + { keys, lead: anchorIndex, anchor: anchorIndex }, + index, + anchorIndex < 0 ? "single" : mode, + ); + return { + keys: next.keys ?? new Set([row.key]), + anchor: displayedRows[next.anchor]?.key ?? null, + }; + }); + } } // --------------------------------------------------------------------------- diff --git a/src/features/vcs/store.switch.test.ts b/src/features/vcs/store.switch.test.ts index 72ad8f01e..5d800afee 100644 --- a/src/features/vcs/store.switch.test.ts +++ b/src/features/vcs/store.switch.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { BranchInfo, FileStatus, ProjectInfo, VcsRoot } from "@/bindings"; +import type { Branch, BranchInfo, FileStatus, ProjectInfo, VcsRoot } from "@/bindings"; import { commands, isTauri } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { deferred } from "@/test/deferred"; @@ -205,4 +205,73 @@ describe("VCS status ownership", () => { expect(appeared).toHaveBeenCalledExactlyOnceWith([conflicted]); expect(cleared).not.toHaveBeenCalled(); }); + + it("clears the previous Git state when Directory Mappings removes the last repository", async () => { + useProject.setState({ project: git }); + await refreshNow(); + expect(getFileDecoration(modified.path)?.color).toBe("var(--vcs-modified)"); + + vi.mocked(commands.vcsRoots).mockResolvedValue(ok([])); + vi.mocked(commands.vcsStatus).mockRejectedValue(new Error("project is not a git repository")); + vi.mocked(commands.vcsBranchInfo).mockRejectedValue(new Error("repository was removed")); + await refreshNow(); + + expect(useVcs.getState()).toMatchObject({ + root: git.root, + available: false, + roots: [], + repo: null, + status: [], + branch: null, + branches: [], + heads: {}, + operations: {}, + error: null, + }); + expect(getFileDecoration(modified.path)).toBeUndefined(); + }); + + it("refreshes branch lists and status when Directory Mappings removes the selected repository", async () => { + useProject.setState({ project: git }); + await refreshNow(); + useVcs.setState({ branchesLoaded: true }); + const remaining = "/a/remaining"; + const remainingBranch: Branch = { + name: "main", + remote: false, + current: true, + upstream: null, + ahead: 0, + behind: 0, + lastCommitMs: 0, + commit: "def1234", + }; + const remainingStatus = { ...modified, path: remaining + "/src/edited.ts" }; + vi.mocked(commands.vcsRoots).mockResolvedValue( + ok([{ root: remaining, head: "main", headCommit: "def1234", operation: null }]), + ); + vi.mocked(commands.vcsStatus).mockResolvedValue(ok([remainingStatus])); + vi.mocked(commands.vcsBranchInfo).mockImplementation(async (repo) => { + if (repo === git.root) throw new Error("repository was removed"); + return ok({ ...branch, head: "main", headCommit: "def1234", operation: null }); + }); + const listBranches = vi.spyOn(commands, "vcsBranches").mockImplementation(async (repo) => { + if (repo === git.root) throw new Error("repository was removed"); + return ok([remainingBranch]); + }); + + await refreshNow(); + await vi.waitFor(() => + expect(useVcs.getState()).toMatchObject({ + available: true, + roots: [remaining], + repo: remaining, + status: [remainingStatus], + branches: [remainingBranch], + }), + ); + expect(listBranches).toHaveBeenLastCalledWith(remaining); + expect(getFileDecoration(modified.path)).toBeUndefined(); + expect(getFileDecoration(remainingStatus.path)?.color).toBe("var(--vcs-modified)"); + }); }); diff --git a/src/features/vcs/store.ts b/src/features/vcs/store.ts index afba340f3..69ac2e2d9 100644 --- a/src/features/vcs/store.ts +++ b/src/features/vcs/store.ts @@ -239,18 +239,28 @@ export function refreshNow(): Promise { ); const [vcsRoots, status, selected] = await Promise.all([ call(commands.vcsRoots()), - call(commands.vcsStatus()), + call(commands.vcsStatus()).then( + (files) => ({ files }), + (error: unknown) => ({ error }), + ), scoped, ]); if (generation !== projectGeneration) return; const roots = vcsRoots.map((r) => r.root); - if ("error" in selected) { - // The selected repository is gone (removed since the last scan): fall back to the primary one. - if (!s.repo || roots.includes(s.repo)) throw selected.error; - useVcs.setState({ roots, repo: null, branchesLoaded: false, stashesLoaded: false }); + if (!roots.length) { + useVcs.setState({ ...initial, root: s.root, version: s.version }); + setContext("vcsAvailable", false); + setFileDecorations("vcs", new Map()); + return; + } + if ("error" in status) throw status.error; + if (s.repo && !roots.includes(s.repo)) { + // Keep the loaded flags so the retry also reads the new repository's branch and stash lists. + useVcs.setState({ repo: roots[0]!, branch: null, branches: [], stashes: [] }); void refreshNow(); return; } + if ("error" in selected) throw selected.error; const [branch, branches, stashes] = selected.values; const operations = Object.fromEntries(vcsRoots.filter((r) => r.operation).map((r) => [r.root, r.operation!])); // `null` (before the first refresh) is the primary repository, listed first. @@ -260,7 +270,7 @@ export function refreshNow(): Promise { useVcs.setState({ operations, heads }); const sameRoots = roots.join("\n") === s.roots.join("\n"); if (repo !== s.repo || !sameRoots) useVcs.setState({ roots: sameRoots ? s.roots : roots, repo }); - applyStatus(status, branch); + applyStatus(status.files, branch); useVcs.setState({ branches, stashes, error: null }); // Branch info and branches above are of another repository: load the selected one's. if (repo !== shown || (s.repo && repo !== s.repo)) { diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 0b9759fbe..b6172683b 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2646,6 +2646,7 @@ "Detect changes with the Git command line": "Detect changes with the Git command line", "Slower, but matches git status where encryption or file protection software makes files look modified.": "Slower, but matches git status where encryption or file protection software makes files look modified.", "Directory mappings actions": "Directory mappings actions", + "Unregistered roots": "Unregistered roots", "Select Repository Root": "Select Repository Root", "VCS of {name}": "VCS of {name}", "Remember size for each tool window": "Remember size for each tool window", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index fa8f37113..ae449cdff 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -1333,6 +1333,7 @@ "Directory (relative to project root)": "目录(相对于项目根目录)", "Enter a directory to search": "请输入要搜索的目录", "Directory Mappings": "目录映射", + "Unregistered roots": "未注册的根目录", "Directory mappings": "目录映射", "Directory of the current file": "当前文件所在的目录", "Directory of the current file relative to the project": "当前文件所在目录相对于项目的路径",