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>
This commit is contained in:
faysou
2026-11-21 06:18:36 +08:00
committed by GitHub
co-authored by faysou
parent 34dfc166db
commit 6bf7bc8c2b
7 changed files with 282 additions and 74 deletions
+43 -5
View File
@@ -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: "<none>", exact: true }).click();
await expect(vcs).toHaveText("<none>");
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();
@@ -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;
+141 -62
View File
@@ -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<string[]>("vcs.mappings.excluded", "project");
const [added, setAdded] = useSetting<string[]>("vcs.mappings.added", "project");
const [{ excluded, added }, setMappings] = useSetting<VcsSettingsValid["mappings"]>("vcs.mappings", "project");
const [detected, setDetected] = useState<string[] | null>(null);
const [selected, setSelected] = useState<string | null>(null);
const [registered, setRegistered] = useState<string[]>([]);
const [selection, setSelection] = useState<{ keys: ReadonlySet<string>; 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() {
<div className={clsx(styles.tableBox, styles.mappingsTable)}>
{root && (
<div className={styles.toolbar} role="toolbar" aria-label={tx("Directory mappings actions")}>
<IconButton icon="plus" title="Add" size="small" onClick={() => void add()} />
<IconButton icon="minus" title="Remove" size="small" disabled={!removable} onClick={remove} />
<IconButton icon="plus" title="Add" size="small" disabled={!canAdd} onClick={() => void add()} />
<IconButton icon="minus" title="Remove" size="small" disabled={!canRemove} onClick={remove} />
</div>
)}
<div className={styles.mappingRows}>
@@ -142,53 +182,92 @@ function MappingsTable() {
</tr>
</thead>
<tbody>
{!root ? (
{root ? (
activeRows.map(renderRow)
) : (
<tr>
<td colSpan={2} className={styles.empty}>
<T>No project is open</T>
</td>
</tr>
) : (
rows.map((row) => {
const directory = mappingKey(root.replaceAll("\\", "/"), row.path.replaceAll("\\", "/"));
const name = directory === "." ? tx("<Project>") : directory;
const leaf = name.lastIndexOf("/") + 1;
return (
<tr
key={row.key}
ref={selected === row.key ? revealRow : undefined}
aria-selected={selected === row.key}
className={clsx(selected === row.key && styles.selectedRow)}
onMouseDown={() => setSelected(row.key)}
>
<td title={row.path}>
<span className={styles.mappingDirectory}>
<Icon name="folder" size={16} className={styles.mappingIcon} />
<span className={styles.mappingPath}>
{leaf > 0 && <span className={styles.mappingParent}>{name.slice(0, leaf)}</span>}
<span className={styles.mappingName}>{name.slice(leaf)}</span>
</span>
</span>
</td>
<td>
<Select
value={row.vcs}
options={VCS_OPTIONS}
variant="ghost"
className={styles.mappingSelect}
aria-label={tx`VCS of ${name}`}
onChange={(v) => setVcs(row.key, v)}
/>
</td>
</tr>
);
})
)}
</tbody>
{unregisteredRows.length > 0 && (
<tbody className={styles.unregisteredMappings} aria-label={tx("Unregistered roots")}>
<tr className={styles.mappingGroupHeader}>
<td colSpan={2}>
<T>Unregistered roots</T>
</td>
</tr>
{unregisteredRows.map(renderRow)}
</tbody>
)}
</table>
</div>
</div>
);
function renderRow(row: (typeof rows)[number]) {
const directory = mappingKey(root!.replaceAll("\\", "/"), row.path.replaceAll("\\", "/"));
const name = directory === "." ? tx("<Project>") : directory;
const leaf = name.lastIndexOf("/") + 1;
const isSelected = selection.keys.has(row.key);
return (
<tr
key={row.key}
ref={isSelected && selection.anchor === row.key ? revealRow : undefined}
aria-selected={isSelected}
className={clsx(isSelected && styles.selectedRow)}
onClick={(event) => selectMapping(event, row)}
>
<td title={row.path}>
<span className={styles.mappingDirectory}>
<Icon name="folder" size={16} className={styles.mappingIcon} />
<span className={styles.mappingPath}>
{leaf > 0 && <span className={styles.mappingParent}>{name.slice(0, leaf)}</span>}
<span className={styles.mappingName}>{name.slice(leaf)}</span>
</span>
</span>
</td>
<td>
{row.unregistered ? (
<T>Git</T>
) : (
<Select
value="git"
options={VCS_OPTIONS}
variant="ghost"
className={styles.mappingSelect}
aria-label={tx`VCS of ${name}`}
onChange={(v) => setVcs(row.key, v)}
/>
)}
</td>
</tr>
);
}
function selectMapping(event: MouseEvent<HTMLTableRowElement>, 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,
};
});
}
}
// ---------------------------------------------------------------------------
+70 -1
View File
@@ -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)");
});
});
+16 -6
View File
@@ -239,18 +239,28 @@ export function refreshNow(): Promise<void> {
);
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<void> {
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)) {
+1
View File
@@ -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",
+1
View File
@@ -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": "当前文件所在目录相对于项目的路径",