fix(vcs): align the unstash dialog (#4935)

- Align the repository, current branch, stash list, and branch input in two columns using the workbench form font. Put Show Changes and Drop Stash beside the list and group the restore options beneath it.
- Add a repository picker for multi-repository projects. Each repository loads its own stash list before the actions become available. After a drop, the list stays visible while the actions wait for the refreshed selection. The fields stack on narrow windows.
This commit is contained in:
l0ng-ai
2026-11-21 10:48:32 +08:00
committed by GitHub
parent 189879f0fa
commit 732cfd6002
6 changed files with 362 additions and 45 deletions
+90
View File
@@ -0,0 +1,90 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("Unstash aligns its controls and restores the selected repository's stash", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1100, height: 700 });
await stubDesktop(page);
await page.evaluate(async () => {
const root = "/dev/acme-api";
const service = `${root}/service`;
const branchInfo = (repo: unknown) => ({
head: repo === service ? "release" : "main",
headCommit: "a1234567",
upstream: null,
ahead: 0,
behind: 0,
operation: null,
});
const handlers = window.__ipc.handlers;
handlers.vcs_branch_info = ({ repo }) => branchInfo(repo);
handlers.vcs_stashes = ({ repo }) =>
(repo === service ? ["Service cleanup", "Review cache changes"] : ["Update API totals"]).map(
(message, index) => ({
index,
message,
timeMs: null,
id: `stash-${index}`,
base: "a1234567",
}),
);
handlers.vcs_stash_apply = () => null;
const store = "/src/features/vcs/store.ts";
const { useVcs } = await import(/* @vite-ignore */ store);
useVcs.setState({ root, roots: [root, service], repo: root, branch: branchInfo(root), available: true });
const context = "/src/platform/context.ts";
const { setContext } = await import(/* @vite-ignore */ context);
setContext("vcsAvailable", true);
const actions = "/src/platform/actions.ts";
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction("vcs.unstash");
});
const dialog = page.getByRole("dialog", { name: "Unstash Changes", exact: true });
const label = dialog.getByText("As new branch:", { exact: true });
const branch = dialog.getByRole("textbox", { name: /^As new branch/ });
const changes = dialog.getByRole("button", { name: "Show Changes", exact: true });
const drop = dialog.getByRole("button", { name: "Drop Stash", exact: true });
const pop = dialog.getByRole("checkbox", { name: "Pop stash", exact: true });
const index = dialog.getByRole("checkbox", { name: "Reinstate index", exact: true });
const labelBox = (await label.boundingBox())!;
const branchBox = (await branch.boundingBox())!;
expect(labelBox.x + labelBox.width).toBeLessThan(branchBox.x);
await expect(label).toHaveCSS("font-size", await branch.evaluate((el) => getComputedStyle(el).fontSize));
const stashes = dialog.getByRole("radiogroup", { name: "Stashes:" });
const listBox = (await stashes.boundingBox())!;
const changesBox = (await changes.boundingBox())!;
const dropBox = (await drop.boundingBox())!;
expect(listBox.x + listBox.width).toBeLessThan(changesBox.x);
expect(Math.abs(changesBox.x - dropBox.x)).toBeLessThan(1);
expect(Math.abs((await pop.boundingBox())!.y - (await index.boundingBox())!.y)).toBeLessThan(1);
await expect(dialog.getByText("main", { exact: true })).toBeVisible();
await expect(stashes.getByRole("radio", { name: /Update API totals/ })).toBeChecked();
await branch.fill("api-copy");
await dialog.getByRole("button", { name: "Repository", exact: true }).click();
await page.getByRole("option", { name: "service", exact: true }).click();
await expect(dialog.getByText("release", { exact: true })).toBeVisible();
await expect(branch).toHaveValue("");
await expect(stashes.getByRole("radio", { name: /Update API totals/ })).toHaveCount(0);
const newest = stashes.getByRole("radio", { name: /Service cleanup/ });
await expect(newest).toBeChecked();
await newest.focus();
await newest.press("ArrowDown");
await expect(stashes.getByRole("radio", { name: /Review cache changes/ })).toBeChecked();
await page.setViewportSize({ width: 400, height: 620 });
const narrowLabel = (await label.boundingBox())!;
const narrowBranch = (await branch.boundingBox())!;
expect(narrowLabel.y + narrowLabel.height).toBeLessThan(narrowBranch.y);
expect(Math.abs(narrowLabel.x - narrowBranch.x)).toBeLessThan(1);
await branch.fill("review/cache");
await expect(pop).toBeChecked();
await expect(index).toBeDisabled();
await expect(dialog.getByRole("button", { name: "Create Branch", exact: true })).toBeEnabled();
await branch.clear();
await pop.check();
await index.check();
await dialog.getByRole("button", { name: "Pop Stash", exact: true }).click();
await expect
.poll(() => ipcCalls(page, "vcs_stash_apply"))
.toEqual([{ repo: "/dev/acme-api/service", index: 1, pop: true, reinstateIndex: true, branch: null }]);
});
+119
View File
@@ -0,0 +1,119 @@
.form {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
align-items: start;
gap: var(--space-2) var(--space-3);
padding: var(--space-3) var(--space-4);
font-size: var(--fs-ui);
}
.label,
.fact {
align-self: center;
}
.label,
.listLabel {
max-inline-size: 12em;
overflow-wrap: anywhere;
}
.listLabel {
padding-block-start: var(--space-1);
}
.fact {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.stashPanel {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: start;
gap: var(--space-2);
min-width: 0;
}
.stashes {
display: flex;
flex-direction: column;
gap: var(--space-0-5);
min-block-size: 112px;
max-block-size: 224px;
overflow: auto;
padding: var(--space-1);
border: 1px solid var(--border-input, var(--border));
border-radius: var(--radius-control);
background: var(--bg-input);
}
.stash {
flex: none;
min-block-size: var(--h-field);
padding-inline: var(--space-2);
border-radius: var(--radius-selection);
}
.stash:hover {
background: var(--bg-tree-hover);
}
.stash:has(input:checked) {
background: var(--bg-tree-selected);
}
.stashText {
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.status {
padding: var(--space-1) var(--space-2);
color: var(--fg-secondary);
}
.actions,
.options {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
.actions {
flex-direction: column;
}
.options {
grid-column: 2;
column-gap: var(--space-4);
}
@media (max-width: 540px) {
.stashPanel {
grid-template-columns: minmax(0, 1fr);
}
.actions {
flex-direction: row;
}
}
@media (max-width: 440px) {
.form {
grid-template-columns: minmax(0, 1fr);
}
.label,
.listLabel {
max-inline-size: none;
}
.listLabel {
padding-block-start: 0;
}
.options {
grid-column: 1;
}
}
@@ -8,6 +8,7 @@ const mocks = vi.hoisted(() => ({
diffs: [] as Array<{ repo: string | null; from: string; to: string }>,
applies: [] as Array<{ repo: string | null; index: number }>,
confirm: vi.fn(),
beforeRead: vi.fn<(repo: string | null) => Promise<void>>(),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
@@ -17,7 +18,10 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
...real,
commands: {
...real.commands,
vcsStashes: (repo: string | null) => ok(mocks.stashes.get(repo) ?? []),
vcsStashes: async (repo: string | null) => {
await mocks.beforeRead(repo);
return ok(mocks.stashes.get(repo) ?? []);
},
vcsStashDrop: (repo: string | null, index: number) => {
mocks.drops.push({ repo, index });
const list = mocks.stashes.get(repo) ?? [];
@@ -59,6 +63,7 @@ beforeEach(() => {
mocks.diffs = [];
mocks.applies = [];
mocks.confirm.mockReset().mockResolvedValue(true);
mocks.beforeRead.mockReset().mockResolvedValue(undefined);
useVcs.setState({ root: "/p", roots: ["/p/a", "/p/b"], repo: "/p/a", available: false });
});
@@ -124,7 +129,20 @@ it("selects the new last stash after dropping the last one, and disables both wh
await screen.findByText("stash@{1}: On dev: second");
expect(radio("stash@{1}")).toBeChecked();
fireEvent.click(screen.getByRole("button", { name: "Drop Stash" }));
let finishRefresh = () => {};
const refresh = new Promise<void>((resolve) => {
finishRefresh = resolve;
});
mocks.beforeRead.mockImplementation((repo) => (repo === "/p/b" ? refresh : Promise.resolve()));
try {
fireEvent.click(screen.getByRole("button", { name: "Drop Stash" }));
await waitFor(() => expect(mocks.beforeRead.mock.calls.filter(([repo]) => repo === "/p/b")).toHaveLength(2));
expect(screen.getByText("stash@{1}: On dev: second")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Apply Stash" })).toBeDisabled();
} finally {
mocks.beforeRead.mockResolvedValue(undefined);
finishRefresh();
}
await waitFor(() => expect(screen.queryByText("stash@{1}: On dev: second")).toBeNull());
expect(radio("stash@{0}")).toBeChecked();
+131 -43
View File
@@ -2,7 +2,7 @@
import { useEffect, useId, useState } from "react";
import type { FileStatus, Stash } from "@/bindings";
import { call, commands } from "@/platform/ipc";
import { Checkbox, Dialog, IconButton, Input, T } from "@/ui";
import { Button, Checkbox, Dialog, Input, Radio, T } from "@/ui";
import { notifications } from "@/workbench/contributions";
import { addedThenDeleted, groupOf, remainingOverrides, renamedFromPath } from "./changes";
import { runCommitChecks } from "./commitChecks";
@@ -17,9 +17,10 @@ import { logConsole, runOp, saveAll } from "./ops";
import { ensureCommitIdentity } from "./commitIdentity";
import { conflictsInstead, showCompareRevisions } from "./operations";
import { FileChecklist } from "./shelf";
import { currentRepo, loadStashes, refreshNow, useVcs } from "./store";
import { currentRepo, loadStashes, refreshNow, repoName, useVcs } from "./store";
import styles from "./common.module.css";
import rollbackStyles from "./RollbackDialog.module.css";
import unstashStyles from "./UnstashDialog.module.css";
import { tx } from "@/platform/i18n";
export function firstLine(message: string): string {
@@ -456,37 +457,71 @@ export function showUnstashDialog(index = 0, repo = currentRepo()) {
openDialog((close) => <UnstashDialog initial={index} repo={repo} onClose={close} />);
}
function UnstashDialog({ initial, repo, onClose }: { initial: number; repo: string | null; onClose: () => void }) {
const [stashes, setStashes] = useState<Stash[]>([]);
function UnstashDialog({
initial,
repo: initialRepo,
onClose,
}: {
initial: number;
repo: string | null;
onClose: () => void;
}) {
const id = useId();
const [{ repo, index }, setSelection] = useState({ repo: initialRepo, index: initial });
const roots = useVcs((s) => s.roots);
const projectRoot = useVcs((s) => s.root);
const root = repo ?? roots[0] ?? projectRoot;
const head = useBranchInfo(repo);
const currentBranch = head?.head ?? (head?.headCommit ? tx("Detached HEAD") : "—");
const [loaded, setLoaded] = useState<{ repo: string | null; tick: number; stashes: Stash[] } | null>(null);
const [tick, setTick] = useState(0);
const [dropping, setDropping] = useState(false);
const stashes = loaded?.repo === repo ? loaded.stashes : null;
const loading = stashes === null || loaded?.tick !== tick;
useEffect(() => {
let live = true;
void call(commands.vcsStashes(repo))
.then((value) => live && setStashes(value))
.catch((e) => logConsole("err", String(e)));
.then((stashes) => live && setLoaded({ repo, tick, stashes }))
.catch((e) => {
if (live) setLoaded({ repo, tick, stashes: [] });
logConsole("err", String(e));
});
return () => {
live = false;
};
}, [repo, tick]);
const [index, setIndex] = useState(initial);
const [pop, setPop] = useState(false);
const [reinstateIndex, setReinstateIndex] = useState(false);
const [branch, setBranch] = useState("");
const asBranch = branch.trim();
const chosen = stashes.find((s) => s.index === index) ?? stashes[0];
const chosen = stashes?.find((s) => s.index === index) ?? stashes?.[0];
const ready = !!chosen && !loading && !dropping;
const chooseRepo = (next: string) => {
if (root === next) return;
setSelection({ repo: next, index: 0 });
setLoaded(null);
setBranch("");
};
const view = () => {
if (!chosen) return;
if (!ready || !chosen) return;
const ref = `stash@{${chosen.index}}`;
showCompareRevisions(`${ref}^`, ref, `${ref}^`, ref, repo);
};
const drop = async () => {
if (!chosen || !(await dropStash(chosen.index, chosen.message, repo))) return;
// The older stashes move up: the next one takes the dropped one's index, else the new last one.
setIndex(Math.max(0, Math.min(chosen.index, stashes.length - 2)));
setTick((n) => n + 1);
if (!ready || !chosen || !stashes) return;
setDropping(true);
try {
if (!(await dropStash(chosen.index, chosen.message, repo))) return;
// The older stashes move up: the next one takes the dropped one's index, else the new last one.
const next = Math.max(0, Math.min(chosen.index, stashes.length - 2));
setSelection((selection) => (selection.repo === repo ? { repo, index: next } : selection));
setTick((n) => n + 1);
} finally {
setDropping(false);
}
};
const submit = () => {
if (!chosen) return;
if (!ready || !chosen) return;
onClose();
void unstash({ index: chosen.index, pop, reinstateIndex, branch: asBranch || null }, repo);
};
@@ -495,54 +530,107 @@ function UnstashDialog({ initial, repo, onClose }: { initial: number; repo: stri
open
title="Unstash Changes"
onClose={onClose}
width={520}
width={600}
buttons={[
{
label: asBranch ? "Create Branch" : pop ? "Pop Stash" : "Apply Stash",
role: "default",
disabled: !chosen,
disabled: !ready,
onClick: submit,
},
{ label: "Cancel", role: "cancel" },
]}
>
<form
className={styles.form}
className={unstashStyles.form}
onSubmit={(e) => {
e.preventDefault();
submit();
}}
>
<div className={styles.manageBar} role="toolbar" aria-label={tx("Stashes")}>
<IconButton icon="diff" title="Show Changes" size="small" disabled={!chosen} onClick={view} />
<IconButton icon="trash" title="Drop Stash" size="small" disabled={!chosen} onClick={() => void drop()} />
</div>
<div className={styles.choiceList} role="radiogroup" aria-label={tx("Stashes")}>
{stashes.length === 0 && (
<div className={styles.hint}>
<T>No stashes</T>
</div>
)}
{stashes.map((s) => (
<label key={s.index} className={styles.radioRow}>
<input type="radio" name="stash" checked={chosen?.index === s.index} onChange={() => setIndex(s.index)} />
<span className={styles.radioText}>
<span>{`stash@{${s.index}}: ${s.message}`}</span>
</span>
{roots.length > 1 ? (
<>
<label className={unstashStyles.label} htmlFor={`${id}-repo`}>
<T>Repository:</T>
</label>
))}
<RepoPicker id={`${id}-repo`} repo={repo} onChange={chooseRepo} />
</>
) : (
<>
<span className={unstashStyles.label}>
<T>Repository:</T>
</span>
<span className={unstashStyles.fact}>{root ? repoName(root) : "—"}</span>
</>
)}
<span className={unstashStyles.label}>
<T>Current branch:</T>
</span>
<span className={unstashStyles.fact} title={currentBranch}>
{currentBranch}
</span>
<span className={unstashStyles.listLabel} id={`${id}-stashes`}>
<T>Stashes:</T>
</span>
<div className={unstashStyles.stashPanel}>
<div
className={unstashStyles.stashes}
role="radiogroup"
aria-labelledby={`${id}-stashes`}
aria-busy={loading || dropping}
>
{stashes?.length ? (
stashes.map((stash) => {
const name = `stash@{${stash.index}}: ${stash.message}`;
return (
<Radio
key={stash.index}
className={unstashStyles.stash}
name={`${id}-stash`}
checked={chosen?.index === stash.index}
disabled={loading || dropping}
onChange={() => setSelection({ repo, index: stash.index })}
label={
<span className={unstashStyles.stashText} title={name}>
{name}
</span>
}
/>
);
})
) : (
<div className={unstashStyles.status}>
<T>{stashes === null ? "Loading…" : "No stashes"}</T>
</div>
)}
</div>
<div className={unstashStyles.actions}>
<Button disabled={!ready} onClick={view}>
Show Changes
</Button>
<Button disabled={!ready} onClick={() => void drop()}>
Drop Stash
</Button>
</div>
</div>
<Checkbox checked={pop || !!asBranch} disabled={!!asBranch} onChange={setPop} label="Pop stash" />
<Checkbox
checked={reinstateIndex || !!asBranch}
disabled={!!asBranch}
onChange={setReinstateIndex}
label="Reinstate index"
/>
<label className={styles.fieldLabel}>
<div className={unstashStyles.options}>
<Checkbox checked={pop || !!asBranch} disabled={!!asBranch} onChange={setPop} label="Pop stash" />
<Checkbox
checked={reinstateIndex || !!asBranch}
disabled={!!asBranch}
onChange={setReinstateIndex}
label="Reinstate index"
/>
</div>
<label className={unstashStyles.label} htmlFor={`${id}-branch`}>
<T>As new branch:</T>
</label>
<Input mono aria-label="As new branch" value={branch} onChange={(e) => setBranch(e.target.value)} />
<Input
id={`${id}-branch`}
aria-label={tx("As new branch")}
value={branch}
onChange={(e) => setBranch(e.target.value)}
/>
</form>
</Dialog>
);
+1
View File
@@ -557,6 +557,7 @@
"Markup": "Markup",
"Tag": "Tag",
"Repository:": "Repository:",
"Stashes:": "Stashes:",
"Current branch:": "Current branch:",
"Detached HEAD": "Detached HEAD",
"Reset type:": "Reset type:",
+1
View File
@@ -2970,6 +2970,7 @@
"Stash Selected Files…": "储藏所选文件…",
"Select the files to stash in the Commit view first": "请先在提交视图中选择要贮藏的文件",
"Stashes": "储藏",
"Stashes:": "储藏:",
"State": "状态",
"Status": "状态",
"Status bar": "状态栏",