feat(vcs): edit the compared folders in Compare Directories (#4975)

The left and right paths of Compare Directories are editable fields with a folder chooser beside each, as in IDEA. Enter, leaving the field or picking a folder compares the new pair, opened as its own tab in place of the current one; a path that isn't a folder, or the same folder on both sides, is refused with a message. The layout e2e test follows the editable fields and per-row synchronisation.

Closes #3925

Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com>
This commit is contained in:
LU XIANGRUI
2026-11-22 00:17:22 +08:00
committed by GitHub
co-authored by wildcatDownstairs
parent 0a7a292d82
commit db8f9a72b0
12 changed files with 155 additions and 40 deletions
+5 -6
View File
@@ -21,13 +21,12 @@
.path {
display: flex;
align-items: center;
gap: var(--space-2);
gap: var(--space-1);
min-width: 0;
}
.pathInput {
flex: 1;
min-width: 0;
min-height: var(--h-field);
padding-inline: var(--space-2);
border-radius: var(--radius-control);
background: var(--bg-field);
box-shadow: inset 0 0 0 1px var(--border);
}
.path:last-child {
grid-column: 3;
+106 -13
View File
@@ -29,12 +29,13 @@ import {
lazyComponent,
type IconName,
} from "@/ui";
import type { EditorInput } from "@/workbench/contributions";
import { editorService, type EditorInput } from "@/workbench/contributions";
import { choosePath } from "@/platform/choosePath";
import { upsertTask } from "@/workbench/tasks";
import { confirmDialog } from "./dialogs";
import { diffInput, openVcsDiff, type DiffData, type DiffSide } from "./diffInput";
import { compareFilesData, displayPath } from "./compareData";
import type { DirectoryCompareData } from "./directoryCompareKind";
import { compareFilesData } from "./compareData";
import { directoryCompareInput, type DirectoryCompareData } from "./directoryCompareKind";
import { formatSize, formatTime } from "./model";
import styles from "./DirectoryCompare.module.css";
import { useRowHeight } from "@/ui/density";
@@ -190,7 +191,18 @@ export function directoryRows(
export function DirectoryCompareEditor({ input }: { input: EditorInput }) {
const { left, right } = input.data as DirectoryCompareData;
return <DirectoryCompare left={left} right={right} />;
return (
<DirectoryCompare
left={left}
right={right}
onPathsChange={(l, r) => {
// ponytail: reopens as a new tab and closes this one; an in-place input update would keep the tab's position.
void editorService()
.openInput(directoryCompareInput(l, r), { focus: true })
.then(() => editorService().closeInput?.(input.key));
}}
/>
);
}
const COLUMNS = {
@@ -274,7 +286,69 @@ function SyncCell({
);
}
export function DirectoryCompare({ left, right }: { left: string; right: string }) {
/** An editable folder path with a chooser; Enter or leaving the field compares the typed folder. */
function PathField({
side,
path,
disabled,
onCommit,
}: {
side: "left" | "right";
path: string;
disabled: boolean;
onCommit: (path: string) => void;
}) {
const [draft, setDraft] = useState(path);
const label = side === "left" ? "Left folder" : "Right folder";
const commit = (next: string) => {
if (next.trim() && next.trim() !== path) onCommit(next.trim());
};
return (
<span className={styles.path}>
<Input
className={styles.pathInput}
aria-label={label}
title={path}
value={draft}
disabled={disabled}
onChange={(e) => setDraft(e.target.value)}
onBlur={() => commit(draft)}
onKeyDown={(e) => {
if (e.key === "Enter") commit(draft);
else if (e.key === "Escape" && draft !== path) {
e.stopPropagation();
setDraft(path);
}
}}
/>
<IconButton
icon="folder"
title="Browse…"
aria-label={side === "left" ? "Choose left folder" : "Choose right folder"}
size="small"
disabled={disabled}
onClick={async () => {
const picked = await choosePath({ directory: true, title: label, defaultPath: path });
if (picked) {
setDraft(picked);
commit(picked);
}
}}
/>
</span>
);
}
export function DirectoryCompare({
left,
right,
onPathsChange,
}: {
left: string;
right: string;
/** Compares other folders (the tab is replaced); without it the paths are read-only. */
onPathsChange?: (left: string, right: string) => void;
}) {
const rowHeight = useRowHeight(22);
const t = useTx();
const [entries, setEntries] = useState<DirectoryCompareEntry[]>([]);
@@ -288,6 +362,7 @@ export function DirectoryCompare({ left, right }: { left: string; right: string
const [operating, setOperating] = useState(false);
const [error, setError] = useState<string | null>(null);
const [operationError, setOperationError] = useState<string | null>(null);
const [pathError, setPathError] = useState<string | null>(null);
const [progress, setProgress] = useState<DirectoryCompareProgress | null>(null);
const [cancelled, setCancelled] = useState(false);
const cancel = useRef<() => void>(() => {});
@@ -369,6 +444,18 @@ export function DirectoryCompare({ left, right }: { left: string; right: string
if (data) void openVcsDiff(data);
};
const changePath = async (side: "left" | "right", path: string) => {
setPathError(null);
const next = side === "left" ? { left: path, right } : { left, right: path };
try {
if ((await call(commands.fsEntryKind(path))) !== "dir") throw new Error(tx`${path} is not a folder`);
if (next.left === next.right) throw new Error(tx("Choose two different folders"));
onPathsChange?.(next.left, next.right);
} catch (e) {
if (mounted.current) setPathError(e instanceof Error ? e.message : String(e));
}
};
const actionOf = (e: DirectoryCompareEntry) => actions.get(e.path) ?? syncChoices(e)[0]!;
const cycle = (e: DirectoryCompareEntry) => {
if (busy || operating) return;
@@ -576,15 +663,21 @@ export function DirectoryCompare({ left, right }: { left: string; right: string
)}
</div>
<div className={styles.paths}>
<span className={styles.path} title={left}>
<Icon name="folder" size={14} />
<span className={styles.text}>{tx`Left: ${displayPath(left)}`}</span>
</span>
<span className={styles.path} title={right}>
<Icon name="folder" size={14} />
<span className={styles.text}>{tx`Right: ${displayPath(right)}`}</span>
</span>
{(["left", "right"] as const).map((side) => (
<PathField
key={`${side}:${side === "left" ? left : right}`}
side={side}
path={side === "left" ? left : right}
disabled={!onPathsChange || operating}
onCommit={(path) => void changePath(side, path)}
/>
))}
</div>
{pathError && (
<div className={styles.error} role="alert">
{tx(pathError)}
</div>
)}
{error && (
<div className={styles.error} role="alert">
{tx(error)}
@@ -6,6 +6,8 @@ const mocks = vi.hoisted(() => ({
compare: vi.fn(),
cancel: vi.fn(),
sync: vi.fn(),
kind: vi.fn(),
choose: vi.fn(),
confirm: vi.fn(),
open: vi.fn(),
}));
@@ -17,6 +19,7 @@ vi.mock("@/platform/ipc", async (original) => {
...real.commands,
fsCompareDirectories: mocks.compare,
fsSynchronizeDirectories: mocks.sync,
fsEntryKind: mocks.kind,
cancelRequest: mocks.cancel,
},
};
@@ -27,6 +30,7 @@ vi.mock("@tauri-apps/api/core", async (original) => ({
onmessage = () => {};
},
}));
vi.mock("@/platform/choosePath", () => ({ choosePath: mocks.choose }));
vi.mock("../DiffEditor", () => ({
DiffEditor: ({ input }: { input: unknown }) => <div data-testid="diff">{JSON.stringify(input)}</div>,
}));
@@ -67,6 +71,7 @@ beforeEach(() => {
vi.clearAllMocks();
mocks.compare.mockResolvedValue(ok(rows));
mocks.sync.mockResolvedValue(ok([]));
mocks.kind.mockResolvedValue(ok("dir"));
mocks.confirm.mockResolvedValue(true);
});
afterEach(cleanup);
@@ -234,6 +239,33 @@ describe("disk directory comparison", () => {
localStorage.removeItem("openidea.directoryCompare.mode");
});
it("compares other folders typed into the path fields or chosen with the folder chooser", async () => {
const change = vi.fn();
render(<DirectoryCompare left="/p/left" right="/p/right" onPathsChange={change} />);
const leftField = screen.getByRole("textbox", { name: "Left folder" });
expect(leftField).toHaveValue("/p/left");
fireEvent.change(leftField, { target: { value: "/p/other" } });
fireEvent.keyDown(leftField, { key: "Enter" });
await waitFor(() => expect(change).toHaveBeenCalledWith("/p/other", "/p/right"));
expect(mocks.kind).toHaveBeenCalledWith("/p/other");
// A file, or the folder already on the other side, is refused with a message.
mocks.kind.mockResolvedValueOnce(ok("file"));
const rightField = screen.getByRole("textbox", { name: "Right folder" });
fireEvent.change(rightField, { target: { value: "/p/file.txt" } });
fireEvent.blur(rightField);
expect(await screen.findByRole("alert")).toHaveTextContent("/p/file.txt is not a folder");
fireEvent.change(rightField, { target: { value: "/p/left" } });
fireEvent.keyDown(rightField, { key: "Enter" });
expect(await screen.findByText("Choose two different folders")).toBeInTheDocument();
fireEvent.keyDown(rightField, { key: "Escape" });
expect(rightField).toHaveValue("/p/right");
mocks.choose.mockResolvedValueOnce("/p/chosen");
fireEvent.click(screen.getByRole("button", { name: "Choose right folder" }));
await waitFor(() => expect(change).toHaveBeenCalledWith("/p/left", "/p/chosen"));
expect(mocks.choose).toHaveBeenCalledWith(expect.objectContaining({ directory: true, defaultPath: "/p/right" }));
expect(change).toHaveBeenCalledTimes(2);
});
it("streams progress, cancels on demand and on close, and ignores stale results after refresh", async () => {
let resolve!: (value: unknown) => void;
mocks.compare.mockImplementationOnce((_l, _r, _mode, _request, channel) => {
-2
View File
@@ -5513,8 +5513,6 @@
"Compared files": "Archivos comparados",
"Comparison cancelled": "Comparación cancelada",
"No matching differences": "No hay diferencias coincidentes",
"Left: {left}": "Izquierda: {left}",
"Right: {right}": "Derecha: {right}",
"Compared {compared} of {total} entries": "Se compararon {compared} de {total} entradas",
"Scanned {scanned} entries": "Se escanearon {scanned} entradas",
"Binary content": "Contenido binario",
-2
View File
@@ -5339,8 +5339,6 @@
"Compared files": "Fichiers comparés",
"Comparison cancelled": "Comparaison annulée",
"No matching differences": "Aucune différence correspondante",
"Left: {left}": "Gauche : {left}",
"Right: {right}": "Droite : {right}",
"Compared {compared} of {total} entries": "{compared} entrées comparées sur {total}",
"Scanned {scanned} entries": "{scanned} entrées analysées",
"Binary content": "Contenu binaire",
-2
View File
@@ -5581,8 +5581,6 @@
"Compared files": "비교된 파일",
"Comparison cancelled": "비교가 취소되었습니다",
"No matching differences": "일치하는 차이점이 없습니다",
"Left: {left}": "왼쪽: {left}",
"Right: {right}": "오른쪽: {right}",
"Compared {compared} of {total} entries": "항목 {total}개 중 {compared}개 비교됨",
"Scanned {scanned} entries": "항목 {scanned}개 스캔됨",
"Binary content": "바이너리 내용",
-2
View File
@@ -5465,8 +5465,6 @@
"Compared files": "Porównywane pliki",
"Comparison cancelled": "Porównywanie anulowane",
"No matching differences": "Brak pasujących różnic",
"Left: {left}": "Lewa strona: {left}",
"Right: {right}": "Prawa strona: {right}",
"Compared {compared} of {total} entries": "Porównano {compared} z {total} wpisów",
"Scanned {scanned} entries": "Przeskanowano wpisy ({scanned})",
"Binary content": "Zawartość binarna",
-2
View File
@@ -5479,8 +5479,6 @@
"Compared files": "Arquivos comparados",
"Comparison cancelled": "Comparação cancelada",
"No matching differences": "Nenhuma diferença correspondente",
"Left: {left}": "Esquerda: {left}",
"Right: {right}": "Direita: {right}",
"Compared {compared} of {total} entries": "{compared} de {total} entradas comparadas",
"Scanned {scanned} entries": "{scanned} entradas verificadas",
"Binary content": "Conteúdo binário",
-2
View File
@@ -8185,8 +8185,6 @@
"Compared files": "Karşılaştırılan dosyalar",
"Comparison cancelled": "Karşılaştırma iptal edildi",
"No matching differences": "Eşleşen fark yok",
"Left: {left}": "Sol: {left}",
"Right: {right}": "Sağ: {right}",
"Compared {compared} of {total} entries": "{total} öğenin {compared} tanesi karşılaştırıldı",
"Scanned {scanned} entries": "{scanned} öğe tarandı",
"Binary content": "İkili içerik",
-2
View File
@@ -6510,8 +6510,6 @@
"Compared files": "比較的檔案",
"Comparison cancelled": "已取消比較",
"No matching differences": "沒有符合的差異",
"Left: {left}": "左側:{left}",
"Right: {right}": "右側:{right}",
"Compared {compared} of {total} entries": "已比較 {compared} / {total} 個條目",
"Scanned {scanned} entries": "已掃描 {scanned} 個條目",
"Binary content": "二進位制內容",
+6 -2
View File
@@ -6547,8 +6547,6 @@
"Compared files": "比较的文件",
"Comparison cancelled": "已取消比较",
"No matching differences": "没有匹配的差异",
"Left: {left}": "左侧:{left}",
"Right: {right}": "右侧:{right}",
"Compared {compared} of {total} entries": "已比较 {compared} / {total} 个条目",
"Scanned {scanned} entries": "已扫描 {scanned} 个条目",
"Binary content": "二进制内容",
@@ -6748,6 +6746,12 @@
"Synchronize": "同步",
"Synchronize {count} entries? {deletes} will be deleted and {overwrites} overwritten.": "同步 {count} 个条目?其中 {deletes} 个将被删除,{overwrites} 个将被覆盖。",
"Synchronizing directories": "正在同步目录",
"Left folder": "左侧文件夹",
"Right folder": "右侧文件夹",
"Choose left folder": "选择左侧文件夹",
"Choose right folder": "选择右侧文件夹",
"{path} is not a folder": "{path} 不是文件夹",
"Choose two different folders": "请选择两个不同的文件夹",
"Stop content comparison": "停止内容比较",
"Filter:": "筛选:",
"Local files": "本地文件",