feat(vcs): bold the current revision's lines in the annotate gutter (#6594)

Lines last changed by the file's current revision are drawn bold in a last-commit colour in the Annotate gutter. The current revision is the last commit to the file at HEAD, or at the annotated revision for Annotate Revision and the diff/merge panes; it is read with vcs_log after the gutter paints and again when HEAD moves. The colour is a new token, --git-annotations-last-commit, listed under Color Scheme > Git > Annotations > Last commit and imported/exported as ANNOTATIONS_LAST_COMMIT_COLOR.

Refs #6397

Co-authored-by: audichuang <[email protected]>
Цей коміт міститься в:
audichuang authored and GitHub committed 2026-11-28 05:55:03 +08:00
1 джерело 75a15b7eed
коміт cc5d9d95e4
10 files changed
+131 -7

No files matched your search

+8 -2
Переглянути файл
@@ -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") });
+51
Переглянути файл
@@ -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<HTMLElement>(".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({
+54 -5
Переглянути файл
@@ -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<BlameLine[]>();
/** The file's current revision (IDEA's FileAnnotation.getCurrentRevision): the last commit to it. */
const setCurrentRevision = StateEffect.define<string | null>();
interface BlameState {
lines: BlameLine[];
markers: RangeSet<GutterMarker>;
labels: Map<string, BlameLabels>;
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<BlameState>({
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<AnnotateColum
const measureBlameColumns = {
read(view: EditorView): BlameWidthMeasurement | null {
const gutter = view.dom.querySelector<HTMLElement>(".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<typeof setTimeout> | 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 -- <path>` 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)" },
+6
Переглянути файл
@@ -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",
+3
Переглянути файл
@@ -39,6 +39,7 @@ describe(".icls schemes", () => {
it("round trips Diff & Merge change types, error stripes and the separator wave", () => {
const { scheme } = parseIcls(`<scheme name="Diff" parent_scheme="Darcula"><colors>
<option name="DIFF_SEPARATOR_WAVE" value="555555"/>
<option name="ANNOTATIONS_LAST_COMMIT_COLOR" value="ced0d6"/>
</colors><attributes>
<option name="DIFF_MODIFIED"><value>
<option name="BACKGROUND" value="385570"/><option name="ERROR_STRIPE_COLOR" value="43698d"/>
@@ -54,9 +55,11 @@ describe(".icls schemes", () => {
expect(scheme.attributes.diffChanged).toEqual({ background: "#385570", errorStripeColor: "#43698d" });
expect(scheme.attributes.diffConflict).toEqual({ errorStripeColor: "#8f5247" });
expect(scheme.attributes.diffSeparatorWave).toEqual({ foreground: "#555555" });
expect(scheme.attributes.gitAnnotationsLastCommit).toEqual({ foreground: "#ced0d6" });
const { id, customs } = importScheme({}, scheme);
const xml = exportIcls(id, customs);
expect(xml).toContain('<option name="DIFF_SEPARATOR_WAVE" value="555555" />');
expect(xml).toContain('<option name="ANNOTATIONS_LAST_COMMIT_COLOR" value="ced0d6" />');
expect(xml).toContain('name="DIFF_MODIFIED"');
expect(xml).toContain('<option name="ERROR_STRIPE_COLOR" value="43698d" />');
expect(parseIcls(xml).scheme.attributes).toMatchObject(scheme.attributes);
+1
Переглянути файл
@@ -267,6 +267,7 @@ const COLOR_NAMES: Record<string, [string, "foreground" | "background"]> = {
METHOD_SEPARATORS_COLOR: ["methodSeparator", "foreground"],
CONSOLE_BACKGROUND_KEY: ["consoleBackground", "background"],
DIFF_SEPARATOR_WAVE: ["diffSeparatorWave", "foreground"],
ANNOTATIONS_LAST_COMMIT_COLOR: ["gitAnnotationsLastCommit", "foreground"],
};
Object.assign(ATTRIBUTE_NAMES, {
+3
Переглянути файл
@@ -669,6 +669,9 @@
"Dark gray": "Dark gray",
"Magenta": "Magenta",
"Editor inline blame": "Editor inline blame",
"Annotations": "Annotations",
"Last commit": "Last commit",
"Annotations › Last commit": "Annotations › Last commit",
"Author": "Author",
"Date time": "Date time",
"Issue link": "Issue link",
+2
Переглянути файл
@@ -204,6 +204,8 @@
"Dark gray": "深灰色",
"Magenta": "品紅色",
"Editor inline blame": "編輯器內聯 Blame",
"Annotations": "註解",
"Annotations › Last commit": "註解 › 上一次提交",
"Date time": "日期時間",
"Issue link": "Issue 連結",
"Subject": "主題",
+2
Переглянути файл
@@ -549,6 +549,8 @@
"Dark gray": "深灰色",
"Magenta": "品红色",
"Editor inline blame": "编辑器内联 Blame",
"Annotations": "注解",
"Annotations › Last commit": "注解 › 上一次提交",
"Date time": "日期时间",
"Issue link": "Issue 链接",
"Subject": "主题",
+1
Переглянути файл
@@ -271,6 +271,7 @@ html[data-os="windows"] {
--git-blame-date: var(--fg-inlay);
--git-blame-issue: var(--fg-inlay);
--git-blame-subject: var(--fg-inlay);
--git-annotations-last-commit: var(--fg-emphasis);
--git-branch-changed: var(--accent);
--git-head-tags: var(--accent);
--git-local-branch: var(--accent);