diff --git a/e2e/gitAnnotateLayout.spec.ts b/e2e/gitAnnotateLayout.spec.ts index 6b607a9fec..757c8df65a 100644 --- a/e2e/gitAnnotateLayout.spec.ts +++ b/e2e/gitAnnotateLayout.spec.ts @@ -24,8 +24,9 @@ test("Git annotations align dates and full author names at UI text size", async ]; handlers.vcs_blame = () => lines; handlers.vcs_log = ({ query }) => { - const { branch } = query as { branch?: string }; - const line = lines.find(({ commit }) => commit === branch); + const { branch, path } = query as { branch?: string | null; path?: string | null }; + // The file's last commit, which Annotate draws bold, is the newer one. + const line = path && branch === "HEAD" ? lines[1] : lines.find(({ commit }) => commit === branch); if (!line) return []; return [ { @@ -73,6 +74,11 @@ test("Git annotations align dates and full author names at UI text size", async await expect .poll(async () => Math.abs((await firstAuthor.boundingBox())!.x - (await secondAuthor.boundingBox())!.x)) .toBeLessThan(1); + // The bold labels of the file's last commit still fit their columns. + await expect(secondAuthor).toHaveCSS("font-weight", "700"); + await expect(firstAuthor).toHaveCSS("font-weight", "400"); + for (const cell of [second.locator(".cm-vcs-blame-date"), secondAuthor]) + await expect.poll(() => cell.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(0); await first.hover(); const details = page.getByRole("dialog").filter({ has: page.getByTitle("Show Commit in Git Log") }); diff --git a/src/features/vcs/__tests__/blame.test.tsx b/src/features/vcs/__tests__/blame.test.tsx index 907c69b94c..bc7ff358d8 100644 --- a/src/features/vcs/__tests__/blame.test.tsx +++ b/src/features/vcs/__tests__/blame.test.tsx @@ -219,6 +219,7 @@ describe("git blame gutter and commit popup", () => { )!; fireEvent.contextMenu(firstLine); const items = mocks.menu.mock.calls[0]![1] as { label?: string; run?: () => void }[]; + mocks.log.mockClear(); items.find((i) => i.label === "Annotate Revision")!.run!(); await vi.waitFor(() => expect(mocks.openDiff).toHaveBeenCalled()); expect(mocks.log).not.toHaveBeenCalled(); @@ -233,6 +234,56 @@ describe("git blame gutter and commit popup", () => { ); }); + it("draws the lines of the file's current revision bold, as IDEA does", async () => { + let resolveLog!: (r: unknown) => void; + const log = new Promise((r) => (resolveLog = r)); + mocks.log.mockReturnValueOnce(log); + view = new EditorView({ + parent: document.body, + state: EditorState.create({ doc: "first\nsecond\nthird", extensions: [blameSlot()] }), + }); + const current = (v: EditorView) => + [...v.dom.querySelectorAll(".cm-vcs-blame [data-commit].cm-vcs-blame-current")].map( + (el) => el.dataset.commit, + ); + await toggleAnnotations(view, "/repo/src/main.py"); + // The gutter shows before the file's last commit is known. + expect(view.dom.querySelectorAll(`.cm-vcs-blame [data-commit="${sha}"]`).length).toBe(2); + expect(current(view)).toEqual([]); + await act(async () => resolveLog({ status: "ok", data: [fullCommit] })); + expect(current(view)).toEqual([sha, sha]); + expect(mocks.log).toHaveBeenCalledWith( + "/repo", + expect.objectContaining({ branch: "HEAD", path: "/repo/src/main.py", limit: 1 }), + ); + + // A new HEAD commit to the file moves the bold lines. + mocks.log.mockResolvedValue({ status: "ok", data: [{ ...fullCommit, id: otherSha }] }); + await act(async () => { + useVcs.setState({ branch: { head: "main", headCommit: "next" } as never }); + await vi.advanceTimersByTimeAsync(200); + }); + expect(current(view)).toEqual([otherSha]); + + // A historical annotation marks the last commit to the file at that revision, not at HEAD. + const historical = new EditorView({ + parent: document.body, + state: EditorState.create({ doc: "one\ntwo\nthree", extensions: [blameSlot()] }), + }); + try { + mocks.log.mockClear(); + await toggleAnnotations(historical, "/repo/src/old.py", "one\ntwo\nthree", sha); + await act(async () => {}); + expect(mocks.log).toHaveBeenCalledWith( + "/repo", + expect.objectContaining({ branch: sha, path: "/repo/src/old.py", limit: 1 }), + ); + expect(current(historical)).toEqual([otherSha]); + } finally { + historical.destroy(); + } + }); + it("offers no Show Diff on a line that is not committed yet", async () => { const zero = "0".repeat(40); mocks.blame.mockResolvedValue({ diff --git a/src/features/vcs/blame.ts b/src/features/vcs/blame.ts index 29eb4e1e3b..53258db70d 100644 --- a/src/features/vcs/blame.ts +++ b/src/features/vcs/blame.ts @@ -13,7 +13,7 @@ import { notifications } from "@/workbench/contributions"; import { closeBlamePopup, scheduleCloseBlamePopup, scheduleOpenBlamePopup } from "./BlamePopup"; import { formatPrettyDay } from "@/platform/dateFormat"; import { saveVcsSetting } from "./settingsUi"; -import { useVcs } from "./store"; +import { repoOf, useVcs } from "./store"; const ZERO = /^0+$/; @@ -72,6 +72,7 @@ class BlameMarker extends GutterMarker { readonly line: BlameLine, readonly labels: BlameLabels | undefined, readonly bg = "", + readonly current = false, ) { super(); } @@ -79,6 +80,7 @@ class BlameMarker extends GutterMarker { return ( o.line.commit === this.line.commit && o.bg === this.bg && + o.current === this.current && COLUMNS.every((column) => o.labels?.[column] === this.labels?.[column]) ); } @@ -100,6 +102,7 @@ class BlameMarker extends GutterMarker { el.style.backgroundColor = this.bg; } el.dataset.commit = this.line.commit; + if (this.current) el.classList.add("cm-vcs-blame-current"); return el; } } @@ -279,7 +282,9 @@ const annotateColumns = ViewPlugin.define( view.requestMeasure(measureBlameColumns); return { update(update: ViewUpdate) { - if (update.startState.field(blameField, false)?.labels !== update.state.field(blameField).labels) + const before = update.startState.field(blameField, false); + const after = update.state.field(blameField); + if (before?.labels !== after.labels || before.current !== after.current) view.requestMeasure(measureBlameColumns); }, destroy: useAnnotateColumns.subscribe(() => view.dispatch({})), @@ -361,11 +366,14 @@ function optionsMenu(): MenuItem { } const setBlame = StateEffect.define(); +/** The file's current revision (IDEA's FileAnnotation.getCurrentRevision): the last commit to it. */ +const setCurrentRevision = StateEffect.define(); interface BlameState { lines: BlameLine[]; markers: RangeSet; labels: Map; + current?: string | null; } function build(lines: BlameLine[], doc: Text): BlameState { @@ -390,10 +398,24 @@ function build(lines: BlameLine[], doc: Text): BlameState { return { lines, markers: RangeSet.of(out), labels }; } +/** Marks the lines last changed by `current`; the doc may have changed since `st` was built. */ +function markCurrent(st: BlameState, current: string | null | undefined): BlameState { + if (current === undefined) return st; + const out = []; + for (const it = st.markers.iter(); it.value; it.next()) { + const m = it.value as BlameMarker; + out.push(new BlameMarker(m.line, m.labels, m.bg, m.line.commit === current).range(it.from)); + } + return { ...st, markers: RangeSet.of(out), current }; +} + const blameField = StateField.define({ create: () => ({ lines: [], markers: RangeSet.empty, labels: new Map() }), update(value, tr) { - for (const e of tr.effects) if (e.is(setBlame)) return build(e.value, tr.state.doc); + for (const e of tr.effects) { + if (e.is(setBlame)) return markCurrent(build(e.value, tr.state.doc), value.current); + if (e.is(setCurrentRevision)) return markCurrent(value, e.value); + } return tr.docChanged ? { ...value, markers: value.markers.map(tr.changes) } : value; }, }); @@ -404,7 +426,8 @@ type BlameWidthMeasurement = { gutter: HTMLElement; widths: Record(".cm-vcs-blame"); - const labels = view.state.field(blameField, false)?.labels; + const st = view.state.field(blameField, false); + const labels = st?.labels; if (!gutter || !labels?.size || typeof CanvasRenderingContext2D === "undefined") return null; const context = view.dom.ownerDocument.createElement("canvas").getContext("2d"); if (!context) return null; @@ -416,6 +439,13 @@ const measureBlameColumns = { widths[column] = Math.max(widths[column], context.measureText(label).width); } } + // The current revision's labels are bold, so wider. + const current = st?.current && labels.get(st.current); + if (current) { + context.font = `bold ${context.font}`; + for (const column of COLUMNS) + widths[column] = Math.max(widths[column], context.measureText(current[column]).width); + } return { gutter, widths }; }, write(result: BlameWidthMeasurement | null) { @@ -435,6 +465,7 @@ interface BlameSource { class BlameRefresher implements PluginValue { private timer: ReturnType | undefined; private generation = 0; + private currentGeneration = 0; private readonly off: (() => void)[]; private readonly live: boolean; @@ -454,10 +485,14 @@ class BlameRefresher implements PluginValue { if (this.live) { this.off.push( useVcs.subscribe((s, p) => { - if (s.branch?.headCommit !== p.branch?.headCommit) this.schedule(100); + if (s.branch?.headCommit !== p.branch?.headCommit) { + this.schedule(100); + void this.loadCurrentRevision(); + } }), ); } + void this.loadCurrentRevision(); } update(u: ViewUpdate) { @@ -478,8 +513,20 @@ class BlameRefresher implements PluginValue { this.view.dispatch({ effects: setBlame.of(lines) }); } + /** Loaded after the gutter paints: `git log -1 -- ` can take a while in a long history. */ + private async loadCurrentRevision() { + const generation = ++this.currentGeneration; + const { path, revision } = this.source; + // An unset branch would walk every branch, not just HEAD. + const query = { branch: revision ?? "HEAD", path, author: null, text: null, skip: 0, limit: 1 }; + const [last] = (await call(commands.vcsLog(repoOf(path), query)).catch(() => null)) ?? []; + if (generation !== this.currentGeneration || !annotationsShown(this.view)) return; + this.view.dispatch({ effects: setCurrentRevision.of(last?.id ?? null) }); + } + destroy() { ++this.generation; + ++this.currentGeneration; clearTimeout(this.timer); for (const off of this.off) off(); } @@ -502,6 +549,8 @@ const blameTheme = EditorView.baseTheme({ color: "var(--fg-secondary)", whiteSpace: "nowrap", }, + // IDEA's Annotations › Last commit colour: bold, brighter than the other annotations. + ".cm-vcs-blame-line.cm-vcs-blame-current": { color: "var(--git-annotations-last-commit)", fontWeight: "bold" }, ".cm-vcs-blame-line > span": { flex: "none", overflow: "hidden", textOverflow: "ellipsis" }, ".cm-vcs-blame-date": { width: "min(var(--blame-date-width, 9ch), 14em)" }, ".cm-vcs-blame-author": { width: "min(var(--blame-author-width, 12ch), 18em)" }, diff --git a/src/platform/colorScheme.ts b/src/platform/colorScheme.ts index ef34302a12..3948cbd7c1 100644 --- a/src/platform/colorScheme.ts +++ b/src/platform/colorScheme.ts @@ -258,6 +258,12 @@ const BASE_ATTRIBUTES: readonly AttributeDef[] = [ bg: "--git-blame-subject-bg", fontStyle: true, }, + { + id: "gitAnnotationsLastCommit", + name: "Annotations › Last commit", + path: ["Git"], + fg: "--git-annotations-last-commit", + }, { id: "gitBranchChanged", name: "Project View › Changed decoration", diff --git a/src/platform/icls.test.ts b/src/platform/icls.test.ts index b09de3d23b..a099cdf15b 100644 --- a/src/platform/icls.test.ts +++ b/src/platform/icls.test.ts @@ -39,6 +39,7 @@ describe(".icls schemes", () => { it("round trips Diff & Merge change types, error stripes and the separator wave", () => { const { scheme } = parseIcls(`