fix(diff): open a diff at its first difference (#6471)

A diff opened without a line to show (double-click in the Commit tool window, Show Diff) started at the top of the file. The two-pane and staging-area diffs now open at their first difference unless a line or a remembered caret is given. The all-in-one diff opens at the first difference of the file it was opened for, once, repeating the scroll until the change is drawn since lines below the drawn ones have estimated heights.

Fixes #6427
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-11-27 19:19:02 +08:00
1 джерело 2e965810e9
коміт 51ccb68b72
5 files changed
+60 -8

No files matched your search

+10
Переглянути файл
@@ -71,6 +71,7 @@ const Block = memo(function Block({
heights,
viewStates,
entriesCache,
onFirstChangeShown,
}: {
entry: CombinedDiffItem;
index: number;
@@ -85,6 +86,8 @@ const Block = memo(function Block({
viewStates: Map<string, DiffViewState>;
/** Git entries of the blocks, so a block back in view shows without asking Git again. */
entriesCache: DiffEntriesCache;
/** Set on the block the diff opened at, until it has shown its first difference. */
onFirstChangeShown?: () => void;
}) {
const item = entry.data;
// A block mounted collapsed creates its diff once expanded.
@@ -176,6 +179,7 @@ const Block = memo(function Block({
input={input}
documentOwner={combinedDiffDocumentOwner(tabKey, input.key)}
viewState={viewState}
onFirstChangeShown={onFirstChangeShown}
fit
/>
</div>
@@ -242,6 +246,11 @@ export function CombinedDiffView({
const [heights] = useState(() => new Map<string, number>());
const [viewStates] = useState(() => new Map<string, DiffViewState>());
const [entriesCache] = useState<DiffEntriesCache>(() => new Map());
// IDEA's combined diff opens at the first difference of the file it was opened for.
const firstChange = useRef<string | null>(reveal ?? entries[0]?.key ?? null);
const firstChangeShown = useCallback(() => {
firstChange.current = null;
}, []);
const keys = useMemo(() => entries.map((e) => e.key), [entries]);
// Each diff's own key, hashing its texts: worked out once, not on every scroll frame.
const diffKeys = useMemo(() => items.map((item) => diffInput(item).key), [items]);
@@ -345,6 +354,7 @@ export function CombinedDiffView({
heights={heights}
viewStates={viewStates}
entriesCache={entriesCache}
onFirstChangeShown={firstChange.current === key ? firstChangeShown : undefined}
/>
</div>
))}
+31 -4
Переглянути файл
@@ -398,6 +398,11 @@ export interface DiffEditorProps {
fit?: boolean;
/** Kept by a host that unmounts the diff (an all-in-one diff block scrolled away) to restore it. */
viewState?: DiffViewState;
/**
* The all-in-one diff's block it opened at: shows its first difference once loaded, then calls
* this, so the block comes back where it was left when scrolled away and back.
*/
onFirstChangeShown?: () => void;
}
export function DiffEditor(props: DiffEditorProps) {
@@ -478,6 +483,7 @@ function TwoPaneDiff({
onClose,
fit = false,
viewState,
onFirstChangeShown,
gitModes,
metadataLoading,
}: DiffEditorProps & { gitModes?: [string | null, string | null]; metadataLoading: boolean }) {
@@ -1214,10 +1220,14 @@ function TwoPaneDiff({
[],
);
// Reveal the requested line (or the first / last difference) once per request.
// Reveal the requested line (or the first / last difference) once per request. Without either,
// a diff opens at its first difference, as IDEA's does; of the all-in-one diff's blocks, only the
// one it opened at.
const revealed = useRef<string | null>(null);
const reveal =
data.reveal ?? (data.line == null && (onFirstChangeShown || (!fit && !viewState)) ? "first" : undefined);
const revealKey =
data.line == null && !data.reveal ? null : `${input.key}:${data.line}:${data.col}:${data.lineSide}:${data.reveal}`;
data.line == null && !reveal ? null : `${input.key}:${data.line}:${data.col}:${data.lineSide}:${reveal}`;
useEffect(() => {
let v = viewsRef.current?.b;
if (!v || revealKey === null || revealed.current === revealKey || !ready) return;
@@ -1231,15 +1241,32 @@ function TwoPaneDiff({
at = target.from + Math.min(data.col ?? 0, target.length);
} else {
const chunks = getChunks(v.state)?.chunks ?? [];
at = (data.reveal === "last" ? chunks[chunks.length - 1] : chunks[0])?.fromB;
at = (reveal === "last" ? chunks[chunks.length - 1] : chunks[0])?.fromB;
}
if (at === undefined) return;
if (data.line != null) revealPos(v, at);
else v.dispatch({ selection: { anchor: at }, effects: EditorView.scrollIntoView(at, { y: "center" }) });
if (!data.reveal && data.line == null) onFirstChangeShown?.();
// A block of the all-in-one diff is scrolled by its host: the lines below the ones drawn have
// estimated heights, so the first scroll falls short. Scroll again until the change is drawn in view.
if (fit && data.line == null) {
const view = v;
const settle = (tries: number) =>
requestAnimationFrame(() => {
if (!view.dom.isConnected || tries === 0) return;
const at_ = Math.min(at!, view.state.doc.length);
const c = view.coordsAtPos(at_);
if (c && c.top >= 0 && c.bottom <= window.innerHeight) return;
view.dispatch({ effects: EditorView.scrollIntoView(at_, { y: "center" }) });
settle(tries - 1);
});
settle(5);
}
// Keep keyboard navigation in the revealed pane after moving to another file.
if (data.reveal || v === viewsRef.current?.a) v.focus();
updateChunkInfo();
}, [ready, statics, revealKey, data.line, data.col, data.lineSide, data.reveal, updateChunkInfo]);
// eslint-disable-next-line react-hooks/exhaustive-deps -- shown once per request, whoever asks
}, [ready, statics, revealKey, data.line, data.col, data.lineSide, data.reveal, reveal, updateChunkInfo]);
// IDEA: past the last (first) difference F7 (Shift+F7) first hints, then moves along the chain.
const [navHint, setNavHint] = useState<string | null>(null);
+4 -2
Переглянути файл
@@ -350,8 +350,10 @@ export function StagingDiff({
if (!next || !shown) return;
revealedRequest.current = request;
const remembered = position.current;
if (!remembered && data.reveal && snapshot?.model.changes.length) {
reveal(next, data.reveal === "first" ? 0 : snapshot.model.changes.length - 1);
// Without a line to show, the diff opens at its first difference, as IDEA's does.
const to = data.reveal ?? (data.line == null ? "first" : undefined);
if (!remembered && to && snapshot?.model.changes.length) {
reveal(next, to === "first" ? 0 : snapshot.model.changes.length - 1);
return;
}
const initial = data.lineSide === "middle" ? 1 : data.lineSide === "left" ? 0 : 2;
+2 -1
Переглянути файл
@@ -57,7 +57,8 @@ const diff = (right: object) =>
({
kind: "diff",
key: `diff:${JSON.stringify(right)}`,
data: { path: "/p/a.ts", left: { type: "rev", rev: "HEAD" }, right },
// Opened at the top (not at the first difference) so searches start from the first line.
data: { path: "/p/a.ts", left: { type: "rev", rev: "HEAD" }, right, line: 0 },
}) as unknown as EditorInput;
const revisions = diff({ type: "rev", rev: "abc123" });
+13 -1
Переглянути файл
@@ -760,7 +760,8 @@ describe("Diff navigation caret", () => {
const { mounted, view } = await reveal(mode);
try {
const button = await screen.findByRole("button", { name: label });
if (fromEnd) view().dispatch({ selection: { anchor: view().state.doc.length } });
// The diff opens at its only difference: start before or after it.
view().dispatch({ selection: { anchor: fromEnd ? view().state.doc.length : 0 } });
// A click leaves focus on the button, outside the panes.
button.focus();
expect(view().hasFocus).toBe(false);
@@ -772,9 +773,19 @@ describe("Diff navigation caret", () => {
}
});
it.each(["split", "unified"] as const)("opens the %s viewer at the first difference (#6427)", async (mode) => {
const { mounted, view } = await reveal(mode);
try {
await waitFor(() => expect(view().state.doc.lineAt(view().state.selection.main.head).number).toBe(2));
} finally {
mounted.unmount();
}
});
it.each(["split", "unified"] as const)("leaves the scrolling to the smooth scroll in the %s viewer", async (mode) => {
const { mounted, view } = await reveal(mode);
try {
view().dispatch({ selection: { anchor: 0 } });
// A scrollIntoView in the same update sets scrollTop at once and cuts the animation off.
let instant = false;
view().dispatch({
@@ -801,6 +812,7 @@ describe("Diff navigation caret", () => {
const { mounted, view } = await reveal("split");
try {
const next = await screen.findByRole("button", { name: "Next Difference" });
view().dispatch({ selection: { anchor: 0 } });
next.focus();
expect(view().hasFocus).toBe(false);
next.dispatchEvent(new KeyboardEvent("keydown", { key: "F7", code: "F7", bubbles: true, cancelable: true }));