The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.
TypeScript code-editorcross-platformdapdatabase-clientdebuggerdesktop-appdeveloper-toolsgithttp-clientideintellijlsprusttauriterminal
fix(diff): Jump to Source from a commit's file, next to Next Difference (#103)
itning8d4c8885ca0e
diff --git a/src/features/vcs/DiffEditor.tsx b/src/features/vcs/DiffEditor.tsxindex 398bd016c..0c4266ac9 100644--- a/src/features/vcs/DiffEditor.tsx+++ b/src/features/vcs/DiffEditor.tsx@@ -12,7 +12,7 @@ import {goToPreviousChunk,rejectChunk,unifiedMergeView,- type Chunk,+ Chunk,} from "@codemirror/merge";import { attachDocument, embeddedEditorExtensions, type DocumentAttachment } from "@/editor/api";import { setContext } from "@/platform/context";@@ -82,6 +82,23 @@ export function chunkLines(chunk: Chunk, a: Text, b: Text) {return { fromA: fromA!, toA: toA!, fromB: fromB!, toB: toB! };}+/** The 0-based line of `to` matching `line` of `from`, given the chunks between them. */+export function mapLine(chunks: readonly Chunk[], line: number, from: Text, to: Text): number {+ const span = (start: number, end: number, doc: Text) => {+ const first = doc.lineAt(Math.min(start, doc.length)).number - 1;+ return [first, end > start ? doc.lineAt(Math.min(end - 1, doc.length)).number : first] as const;+ };+ let shift = 0;+ for (const c of chunks) {+ const [fromA, toA] = span(c.fromA, c.toA, from);+ if (line < fromA) break;+ const [fromB, toB] = span(c.fromB, c.toB, to);+ if (line < toA) return Math.min(fromB + (line - fromA), Math.max(fromB, toB - 1));+ shift = toB - toA;+ }+ return Math.max(0, Math.min(line + shift, to.lines - 1));+}+/** Joins the open document of a file-backed side (working file, Compare Files); null for revisions / texts. */async function attachSide(side: DiffSide, path: string): Promise<DocumentAttachment | null> {const file = sideFile(side, path);@@ -372,21 +389,49 @@ export function DiffEditor({ input }: { input: EditorInput }) {[updateChunkInfo, data],);+ // A file-backed side is the source; for a diff of revisions (Git Log, Compare) the+ // working copy of the path is, while it exists. Probed once per diff.+ const fileSource = sideFile(left, path) ?? sideFile(right, path);+ const [onDisk, setOnDisk] = useState<string | null>(null);+ useEffect(() => {+ if (fileSource) return;+ let alive = true;+ void call(commands.fsProbe(path)).then(+ () => alive && setOnDisk(path),+ () => alive && setOnDisk(null),+ );+ return () => {+ alive = false;+ };+ }, [path, fileSource]);+ const worktreeSource = onDisk === path ? path : null;+ const source = fileSource ?? worktreeSource;+const jumpToSource = useCallback(() => {const views = viewsRef.current;const fileA = sideFile(left, path);const fileB = sideFile(right, path);- const useA = focusedSide.current === "a" && !!views?.a && !!fileA;- const v = useA ? views!.a! : views?.b;- const file = useA ? fileA : (fileB ?? fileA);+ const onA = focusedSide.current === "a" && !!views?.a;+ const v = onA ? views!.a! : views?.b;+ const own = onA ? fileA : fileB;+ const file = own ?? fileB ?? fileA ?? worktreeSource;if (!file) return;- const head = v ? v.state.selection.main.head : 0;- const line = v ? v.state.doc.lineAt(head) : null;- void editorService().openFile(file, {- selection: { line: line ? line.number - 1 : 0, col: line ? head - line.from : 0 },- focus: true,+ const open = (line: number, col: number) =>+ void editorService().openFile(file, { selection: { line, col }, focus: true });+ if (!v) return open(0, 0);+ const head = v.state.selection.main.head;+ const at = v.state.doc.lineAt(head);+ if (own) return open(at.number - 1, head - at.from);+ // The pane shows another version of the file: follow the diff to the line there.+ const from = v.state.doc;+ const known = file === fileB ? views?.b.state.doc : file === fileA ? views?.a?.state.doc : undefined;+ void (known ? Promise.resolve(known.toString()) : readWorkingText(file)).then((text) => {+ if (text === null) return open(at.number - 1, head - at.from);+ const to = Text.of(text.split(/\r?\n/));+ const line = mapLine(Chunk.build(from, to), at.number - 1, from, to);+ open(line, to.line(line + 1).text === at.text ? head - at.from : 0);});- }, [left, right, path]);+ }, [left, right, path, worktreeSource]);const currentChunk = (): { chunk: Chunk; index: number } | undefined => {const v = viewsRef.current?.b;@@ -456,7 +501,7 @@ export function DiffEditor({ input }: { input: EditorInput }) {const identical = ready && chunkInfo.count === 0 && (attached?.a?.text() ?? statics?.a) === (attached?.b?.text() ?? statics?.b);// Staging applies to local changes against HEAD / the index only.const canStage = editableB && isWorktree(right) && left.type === "rev" && !!useVcs.getState().root;- const hasSource = !!sideFile(left, path) || !!sideFile(right, path);+ const hasSource = !!source;return (<div@@ -475,6 +520,9 @@ export function DiffEditor({ input }: { input: EditorInput }) {<div className={styles.toolbar} role="toolbar" aria-label={tx("Diff")}><IconButton icon="arrow-up" title="Previous Difference" shortcut={shortcutLabel("diff.prevDifference")} size="small" onClick={() => step(-1)} /><IconButton icon="arrow-down" title="Next Difference" shortcut={shortcutLabel("diff.nextDifference")} size="small" onClick={() => step(1)} />+ {hasSource && (+ <IconButton icon="edit" title="Jump to Source" shortcut={shortcutLabel("diff.jumpToSource")} size="small" onClick={jumpToSource} />+ )}<span className={styles.sep} /><IconButtonicon="split"@@ -538,9 +586,6 @@ export function DiffEditor({ input }: { input: EditorInput }) {)}<span className={styles.sep} /><IconButton icon="refresh" title="Refresh" size="small" onClick={() => void reload()} />- {hasSource && (- <IconButton icon="external-link" title="Jump to Source" shortcut={shortcutLabel("diff.jumpToSource")} size="small" onClick={jumpToSource} />- )}<span className={styles.count}>{!ready? ""diff --git a/src/features/vcs/__tests__/diffToolbar.test.tsx b/src/features/vcs/__tests__/diffToolbar.test.tsxnew file mode 100644index 000000000..45f9626a3--- /dev/null+++ b/src/features/vcs/__tests__/diffToolbar.test.tsx@@ -0,0 +1,146 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { render, screen, waitFor, within } from "@testing-library/react";+import type { EditorInput } from "@/workbench/contributions";+import { Chunk } from "@codemirror/merge";+import { Text } from "@codemirror/state";+import { EditorView } from "@codemirror/view";+import { iconMarkup } from "@/ui";++const probe = vi.fn();+const openFile = vi.fn();+const texts: Record<string, string> = { HEAD: "a\n", abc123: "a\n" };+let working = "a\n";++vi.mock("@/platform/ipc", async (importOriginal) => {+ const real = await importOriginal<typeof import("@/platform/ipc")>();+ return {+ ...real,+ commands: {+ ...real.commands,+ fsProbe: (path: string) => probe(path),+ vcsFileAt: (_path: string, rev: string) => Promise.resolve({ status: "ok", data: texts[rev] }),+ fsReadText: () => Promise.resolve({ status: "ok", data: working }),+ },+ };+});++vi.mock("@/workbench/contributions", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/workbench/contributions")>()),+ editorService: () => ({ openFile }),+}));++import { DiffEditor, mapLine } from "../DiffEditor";++/** Git Log opens a commit's file: both sides are revisions. */+const input = {+ kind: "diff",+ key: "diff:test",+ data: {+ path: "/p/a.ts",+ left: { type: "rev", rev: "HEAD" },+ right: { type: "rev", rev: "abc123" },+ },+} as unknown as EditorInput;++/** `d` attributes of an SVG, which is what tells two icons apart. */+const paths = (html: string) => [...html.matchAll(/ d="([^"]+)"/g)].map((m) => m[1]);++beforeEach(() => {+ probe.mockReset();+ openFile.mockReset();+ texts.HEAD = texts.abc123 = working = "a\n";+ probe.mockResolvedValue({ status: "ok", data: { size: 3, binary: false, tooLarge: false } });+});++describe("Diff toolbar", () => {+ it("puts Jump to Source right after Next Difference, in the navigation group", async () => {+ render(<DiffEditor input={input} />);+ await screen.findByRole("button", { name: "Jump to Source" });+ const toolbar = screen.getByRole("toolbar", { name: "Diff" });+ const buttons = within(toolbar).getAllByRole("button");+ expect(buttons.slice(0, 3).map((b) => b.getAttribute("aria-label"))).toEqual([+ "Previous Difference",+ "Next Difference",+ "Jump to Source",+ ]);+ // One group: no separator between the three, one after them.+ expect(buttons[1]!.nextElementSibling).toBe(buttons[2]);+ expect(buttons[2]!.nextElementSibling).not.toBe(buttons[3]);+ });++ it("shows a pencil for Jump to Source", async () => {+ render(<DiffEditor input={input} />);+ const button = await screen.findByRole("button", { name: "Jump to Source" });+ expect(paths(button.querySelector("svg")!.innerHTML)).toEqual(paths(iconMarkup("edit", 14)!));+ });++ it("jumps to the working copy of a file shown at a revision", async () => {+ render(<DiffEditor input={input} />);+ await screen.findByRole("button", { name: "Jump to Source" });+ expect(probe).toHaveBeenCalledWith("/p/a.ts");+ });++ it("has no Jump to Source when the file is gone from the working tree", async () => {+ probe.mockRejectedValue(new Error("no such file"));+ render(<DiffEditor input={input} />);+ await waitFor(() => expect(probe).toHaveBeenCalled());+ await waitFor(() => expect(screen.queryByRole("button", { name: "Jump to Source" })).toBeNull());+ });+});++const doc = (s: string) => Text.of(s.split("\n"));++describe("mapLine", () => {+ const from = doc("a\nb\nc\nd\ne\nf\ng\n");+ const to = doc("a\nX\nY\nb\nc\ne\nF1\nF2\ng\n");+ const map = (line: number) => mapLine(Chunk.build(from, to), line, from, to);++ it("shifts lines past an insertion and keeps lines before it", () => {+ expect(map(0)).toBe(0);+ expect(map(1)).toBe(3);+ expect(map(2)).toBe(4);+ });++ it("lands on the line after a removed block", () => {+ expect(map(3)).toBe(5);+ expect(map(4)).toBe(5);+ });++ it("keeps the offset inside a changed block and shifts past it", () => {+ expect(map(5)).toBe(6);+ expect(map(6)).toBe(8);+ });+});++describe("Jump to Source of a revision diff", () => {+ /** Parent, commit and working copy each add a line above the previous. */+ const setUp = () => {+ texts.HEAD = "a\nb\nc\nd\n";+ texts.abc123 = "a\nX\nY\nb\nc\nd\n";+ working = "new\na\nX\nY\nb\nc\nd\n";+ };+ const pane = async (index: number) => {+ await waitFor(() => expect(document.querySelectorAll(".cm-mergeViewEditor .cm-editor").length).toBe(2));+ return EditorView.findFromDOM(document.querySelectorAll<HTMLElement>(".cm-mergeViewEditor .cm-editor")[index]!)!;+ };+ const jumpFrom = async (index: number, line: number) => {+ const v = await pane(index);+ v.dispatch({ selection: { anchor: v.state.doc.line(line + 1).from + 1 } });+ v.contentDOM.dispatchEvent(new FocusEvent("focus"));+ (await screen.findByRole("button", { name: "Jump to Source" })).click();+ await waitFor(() => expect(openFile).toHaveBeenCalled());+ return openFile.mock.calls[0];+ };++ it("maps a line of the commit to the working copy", async () => {+ setUp();+ render(<DiffEditor input={input} />);+ expect(await jumpFrom(1, 2)).toEqual(["/p/a.ts", { selection: { line: 3, col: 1 }, focus: true }]);+ });++ it("maps a line of the parent through the diff to the working copy", async () => {+ setUp();+ render(<DiffEditor input={input} />);+ expect(await jumpFrom(0, 2)).toEqual(["/p/a.ts", { selection: { line: 5, col: 1 }, focus: true }]);+ });+});