M4.7: blame annotations in the editor gutter
- crates/vcs: blame.rs (git blame --porcelain, --contents - from a
buffer, revisions, untracked files and empty repositories give no
lines; property-tested parser, ISO dates without a date crate)
- engine: git.blame {path, rev?} -> {lines, version} through start_with;
an open buffer is blamed as it would be saved (line ending, BOM)
- ui: blame.ts gutter toggled per file (vcs.toggleBlame, Git menu, no
shortcut), date + author per run, bar coloured by age from tokens,
hover card with the full commit message, click opens the commit in
the Log (vcs.showCommit); refreshed on edits and gitChanged
- docs: architecture "Blame (M4.7)"
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
dc4a00ea0b
commit
2f758d76b9
18 changed files with 2003 additions and 3 deletions
|
|
@ -53,6 +53,8 @@ export const UI_COMMANDS: readonly UiCommandSpec[] = [
|
|||
{ id: "vcs.showHistory", labelKey: "command.vcs.showHistory", menuPath: "Git/Show History" },
|
||||
{ id: "vcs.stash", labelKey: "command.vcs.stash", menuPath: "Git/Stash Changes…" },
|
||||
{ id: "vcs.showStashes", labelKey: "command.vcs.showStashes", menuPath: "Git/Stashes…" },
|
||||
{ id: "vcs.showCommit", labelKey: "command.vcs.showCommit" },
|
||||
{ id: "vcs.toggleBlame", labelKey: "command.vcs.toggleBlame", menuPath: "Git/Annotate with Git Blame" },
|
||||
{ id: "vcs.showDiff", labelKey: "command.vcs.showDiff", menuPath: "Git/Show Diff", defaultShortcut: "Mod+Alt+Shift+D" },
|
||||
{ id: "vcs.nextChange", labelKey: "command.vcs.nextChange", menuPath: "Git/Next Change", defaultShortcut: "Alt+Shift+]" },
|
||||
{ id: "vcs.previousChange", labelKey: "command.vcs.previousChange", menuPath: "Git/Previous Change", defaultShortcut: "Alt+Shift+[" },
|
||||
|
|
|
|||
702
ui/src/components/editor/blame.ts
Normal file
702
ui/src/components/editor/blame.ts
Normal file
|
|
@ -0,0 +1,702 @@
|
|||
/**
|
||||
* Git blame annotations in the editor gutter (M4.7): beside each line the
|
||||
* date and author of the commit that last changed it, with a bar coloured
|
||||
* by the commit's age.
|
||||
*
|
||||
* - **Toggle:** per file ({@link toggleBlame}, the UI command
|
||||
* `vcs.toggleBlame` on the active tab). Every editor of that file shows
|
||||
* or hides the annotations; the choice lasts until the project changes
|
||||
* ({@link clearBlame}).
|
||||
* - **Source:** `git.blame {path}` (a pending outcome, so through
|
||||
* `runWaiting`). The engine blames the open buffer as it stands, so
|
||||
* unsaved lines show as not committed. Asked when shown, 500 ms after
|
||||
* the last edit ({@link BLAME_DEBOUNCE_MS}) and on {@link refreshBlame}
|
||||
* (every `gitChanged`, from the status store). Like the change markers,
|
||||
* the plugin waits for the buffer sync to be idle and drops answers for
|
||||
* a document that changed meanwhile. Between answers the annotations
|
||||
* move with the text; new lines stay blank until the next answer.
|
||||
* - **Look:** the first line of each run of lines from one commit shows
|
||||
* `date author`; the following lines only the bar. The bar's strength
|
||||
* follows the age (today, a week, a month, a year, older), mixed from
|
||||
* `--lt-accent`; lines not committed yet take `--lt-vcs-modified`.
|
||||
* - **Hover** shows hash, author, date and the commit message (the
|
||||
* subject at once, the full message from `git.showCommit`, cached per
|
||||
* hash). **Click** opens the commit in the Log (`vcs.showCommit`).
|
||||
* - Failures leave the annotations as they are.
|
||||
*/
|
||||
import { RangeSet, RangeSetBuilder, StateEffect, StateField, type EditorState, type Extension, type Text } from "@codemirror/state";
|
||||
import { EditorView, GutterMarker, ViewPlugin, gutter, showTooltip, type PluginValue, type Tooltip, type ViewUpdate } from "@codemirror/view";
|
||||
import { runWaiting, type JsonValue } from "../../ipc";
|
||||
import { t } from "../../i18n";
|
||||
import type { AssistBuffer } from "./assist";
|
||||
|
||||
/** Delay between the last edit and the query. */
|
||||
export const BLAME_DEBOUNCE_MS = 500;
|
||||
|
||||
/** Delay before the hover card shows. */
|
||||
export const BLAME_HOVER_MS = 300;
|
||||
|
||||
/** The UI command that opens a commit in the Log. */
|
||||
export const SHOW_COMMIT_COMMAND = "vcs.showCommit";
|
||||
|
||||
/** The UI command that shows or hides the annotations of the active file. */
|
||||
export const TOGGLE_BLAME_COMMAND = "vcs.toggleBlame";
|
||||
|
||||
/** Most commit messages cached for the hover card. */
|
||||
const MAX_MESSAGES = 200;
|
||||
|
||||
/** One line of `git.blame`. */
|
||||
export interface BlameLine {
|
||||
/** Full hash; all zeros for a line not committed yet. */
|
||||
hash: string;
|
||||
/** Author name. */
|
||||
author: string;
|
||||
/** Author date, ISO 8601. */
|
||||
date: string;
|
||||
/** Subject line. */
|
||||
summary: string;
|
||||
/** Line number in that commit, 1-based. */
|
||||
origLine: number;
|
||||
}
|
||||
|
||||
/** How the annotations reach the engine and the Log; replaced in tests. */
|
||||
export interface BlameTransport {
|
||||
/** Runs a command and resolves with its untrusted result. */
|
||||
query(command: string, params: JsonValue): Promise<{ ok: true; value: unknown } | { ok: false }>;
|
||||
/** Opens a commit in the Log. */
|
||||
openCommit(hash: string): void;
|
||||
}
|
||||
|
||||
/** Opens commits through the UI command; set by the layout. */
|
||||
let commitOpener: (hash: string) => void = () => undefined;
|
||||
|
||||
/**
|
||||
* Sets how a click opens a commit (the layout runs `vcs.showCommit`).
|
||||
*
|
||||
* @param open - the opener.
|
||||
*/
|
||||
export function setCommitOpener(open: (hash: string) => void): void {
|
||||
commitOpener = open;
|
||||
}
|
||||
|
||||
/** The transport through the engine IPC. */
|
||||
export const engineBlameTransport: BlameTransport = {
|
||||
query: (command, params) => runWaiting<unknown>(command, params),
|
||||
openCommit: (hash) => {
|
||||
commitOpener(hash);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether a hash is git's all-zero hash of lines not committed yet.
|
||||
*
|
||||
* @param hash - a hash from `git.blame`.
|
||||
*/
|
||||
export function isUncommitted(hash: string): boolean {
|
||||
return hash !== "" && /^0+$/.test(hash);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the lines of a `git.blame` result. A malformed line becomes an
|
||||
* empty entry, so the others keep their line numbers.
|
||||
*
|
||||
* @param value - the untrusted result.
|
||||
* @returns one entry per line (null for a malformed one), or null when
|
||||
* the result has no list.
|
||||
*/
|
||||
export function readBlame(value: unknown): (BlameLine | null)[] | null {
|
||||
if (typeof value !== "object" || value === null) {
|
||||
return null;
|
||||
}
|
||||
const lines = (value as Record<string, unknown>).lines;
|
||||
if (!Array.isArray(lines)) {
|
||||
return null;
|
||||
}
|
||||
return (lines as unknown[]).map((line) => {
|
||||
if (typeof line !== "object" || line === null) {
|
||||
return null;
|
||||
}
|
||||
const { hash, author, date, summary, origLine } = line as Record<string, unknown>;
|
||||
if (typeof hash !== "string" || !/^[0-9a-f]{4,64}$/i.test(hash) || typeof author !== "string" || typeof date !== "string") {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
hash,
|
||||
author,
|
||||
date,
|
||||
summary: typeof summary === "string" ? summary : "",
|
||||
origLine: typeof origLine === "number" && Number.isInteger(origLine) && origLine > 0 ? origLine : 0,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** One day in milliseconds. */
|
||||
const DAY = 86_400_000;
|
||||
|
||||
/** Upper bounds of the age levels 0 to 3; older is level 4. */
|
||||
const AGE_BOUNDS = [DAY, 7 * DAY, 31 * DAY, 365 * DAY];
|
||||
|
||||
/**
|
||||
* The age level of a commit date: 0 within a day, 1 a week, 2 a month,
|
||||
* 3 a year, 4 older (and for an unreadable date).
|
||||
*
|
||||
* @param iso - ISO 8601 date.
|
||||
* @param now - the current time in milliseconds.
|
||||
*/
|
||||
export function ageLevel(iso: string, now: number): number {
|
||||
const time = Date.parse(iso);
|
||||
if (Number.isNaN(time)) {
|
||||
return AGE_BOUNDS.length;
|
||||
}
|
||||
const age = Math.max(0, now - time);
|
||||
const level = AGE_BOUNDS.findIndex((bound) => age < bound);
|
||||
return level === -1 ? AGE_BOUNDS.length : level;
|
||||
}
|
||||
|
||||
/**
|
||||
* A short local date, `YYYY-MM-DD`.
|
||||
*
|
||||
* @param iso - ISO 8601 date.
|
||||
* @returns the date, or the input when it cannot be read.
|
||||
*/
|
||||
export function shortDate(iso: string): string {
|
||||
const date = new Date(iso);
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return iso;
|
||||
}
|
||||
const pad = (n: number): string => String(n).padStart(2, "0");
|
||||
return `${String(date.getFullYear())}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
||||
}
|
||||
|
||||
/** The text and look of one annotated line. */
|
||||
class BlameMarker extends GutterMarker {
|
||||
/**
|
||||
* @param line - the blame of the line.
|
||||
* @param first - the first line of a run from one commit (shows text).
|
||||
* @param level - the age level, or `"new"` for uncommitted lines.
|
||||
*/
|
||||
constructor(
|
||||
readonly line: BlameLine,
|
||||
readonly first: boolean,
|
||||
readonly level: number | "new",
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
/** Text inserted at the line's start pushes the annotation down with the line. */
|
||||
override startSide = 1;
|
||||
|
||||
/** Same side as the start, so the empty range survives mapping. */
|
||||
override endSide = 1;
|
||||
|
||||
override eq(other: GutterMarker): boolean {
|
||||
return other instanceof BlameMarker && other.line.hash === this.line.hash && other.first === this.first && other.level === this.level;
|
||||
}
|
||||
|
||||
override toDOM(): Node {
|
||||
const element = document.createElement("div");
|
||||
element.className = `lt-blame-marker lt-blame-marker--age-${String(this.level)}`;
|
||||
element.dataset.test = "blame-marker";
|
||||
element.dataset.hash = this.line.hash;
|
||||
if (this.first) {
|
||||
element.textContent = this.level === "new" ? t("editor.blame.notCommitted") : `${shortDate(this.line.date)} ${this.line.author}`;
|
||||
}
|
||||
return element;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the annotations of `lines` in `doc`: line `i` of the blame is
|
||||
* line `i + 1` of the document; lines past the document are ignored.
|
||||
*
|
||||
* @param doc - the document the blame was made for.
|
||||
* @param lines - the blame, in line order.
|
||||
* @param now - the current time in milliseconds.
|
||||
*/
|
||||
export function buildBlameMarkers(doc: Text, lines: readonly (BlameLine | null)[], now: number): RangeSet<GutterMarker> {
|
||||
const builder = new RangeSetBuilder<GutterMarker>();
|
||||
let previous: string | null = null;
|
||||
const count = Math.min(lines.length, doc.lines);
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const line = lines[index] ?? null;
|
||||
if (line === null) {
|
||||
previous = null;
|
||||
continue;
|
||||
}
|
||||
const level = isUncommitted(line.hash) ? "new" : ageLevel(line.date, now);
|
||||
const at = doc.line(index + 1).from;
|
||||
builder.add(at, at, new BlameMarker(line, line.hash !== previous, level));
|
||||
previous = line.hash;
|
||||
}
|
||||
return builder.finish();
|
||||
}
|
||||
|
||||
/** Replaces the annotations of a state. */
|
||||
const setBlame = StateEffect.define<RangeSet<GutterMarker>>();
|
||||
|
||||
/** The annotations of a state, mapped through edits between answers. */
|
||||
const blameMarkers = StateField.define<RangeSet<GutterMarker>>({
|
||||
create: () => RangeSet.empty,
|
||||
update(value, tr) {
|
||||
let next = value.map(tr.changes);
|
||||
for (const effect of tr.effects) {
|
||||
if (effect.is(setBlame)) {
|
||||
next = effect.value;
|
||||
}
|
||||
}
|
||||
return next;
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* The blame of the line at `pos`, if annotated.
|
||||
*
|
||||
* @param state - an editor state built with {@link blameExtensions}.
|
||||
* @param pos - a position on the line.
|
||||
*/
|
||||
function blameAt(state: EditorState, pos: number): BlameLine | null {
|
||||
const set = state.field(blameMarkers, false);
|
||||
if (set === undefined) {
|
||||
return null;
|
||||
}
|
||||
const line = state.doc.lineAt(pos);
|
||||
let found: BlameLine | null = null;
|
||||
set.between(line.from, line.from, (_from, _to, marker) => {
|
||||
if (marker instanceof BlameMarker) {
|
||||
found = marker.line;
|
||||
return false;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* The annotations a state carries, for tests and inspection.
|
||||
*
|
||||
* @param state - an editor state built with {@link blameExtensions}.
|
||||
* @returns by 1-based line number: hash, whether it shows text, the age
|
||||
* level; empty without the extension.
|
||||
*/
|
||||
export function blameMarkerLines(state: EditorState): Record<number, { hash: string; first: boolean; level: number | "new" }> {
|
||||
const out: Record<number, { hash: string; first: boolean; level: number | "new" }> = {};
|
||||
const set = state.field(blameMarkers, false);
|
||||
if (set === undefined) {
|
||||
return out;
|
||||
}
|
||||
const cursor = set.iter();
|
||||
while (cursor.value !== null) {
|
||||
if (cursor.value instanceof BlameMarker) {
|
||||
const { line, first, level } = cursor.value;
|
||||
out[state.doc.lineAt(cursor.from).number] = { hash: line.hash, first, level };
|
||||
}
|
||||
cursor.next();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** What the hover card shows: a line's blame at a document position. */
|
||||
interface Hover {
|
||||
/** Start of the hovered line. */
|
||||
pos: number;
|
||||
/** Its blame. */
|
||||
line: BlameLine;
|
||||
}
|
||||
|
||||
/** Shows (or, with null, hides) the hover card. */
|
||||
const setHover = StateEffect.define<Hover | null>();
|
||||
|
||||
/** Full commit messages by hash, for the hover card. */
|
||||
const messages = new Map<string, string>();
|
||||
|
||||
/**
|
||||
* Remembers a commit message, dropping the oldest beyond the cap.
|
||||
*
|
||||
* @param hash - the commit.
|
||||
* @param message - its full message.
|
||||
*/
|
||||
function rememberMessage(hash: string, message: string): void {
|
||||
if (messages.size >= MAX_MESSAGES) {
|
||||
const oldest = messages.keys().next().value;
|
||||
if (oldest !== undefined) {
|
||||
messages.delete(oldest);
|
||||
}
|
||||
}
|
||||
messages.set(hash, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the hover card of a line.
|
||||
*
|
||||
* @param line - the line's blame.
|
||||
* @returns the card's DOM and the element that holds the message.
|
||||
*/
|
||||
function hoverCard(line: BlameLine): { dom: HTMLElement; message: HTMLElement } {
|
||||
const dom = document.createElement("div");
|
||||
dom.className = "lt-blame-tooltip";
|
||||
dom.dataset.test = "blame-tooltip";
|
||||
const head = document.createElement("div");
|
||||
head.className = "lt-blame-tooltip__head";
|
||||
const message = document.createElement("div");
|
||||
message.className = "lt-blame-tooltip__message";
|
||||
if (isUncommitted(line.hash)) {
|
||||
head.textContent = t("editor.blame.notCommitted");
|
||||
message.textContent = t("editor.blame.notCommittedHint");
|
||||
} else {
|
||||
const date = new Date(line.date);
|
||||
const when = Number.isNaN(date.getTime()) ? line.date : date.toLocaleString();
|
||||
head.textContent = t("editor.blame.byLine", { hash: line.hash.slice(0, 8), author: line.author, date: when });
|
||||
message.textContent = messages.get(line.hash) ?? line.summary;
|
||||
const hint = document.createElement("div");
|
||||
hint.className = "lt-blame-tooltip__hint";
|
||||
hint.textContent = t("editor.blame.clickHint");
|
||||
dom.append(head, message, hint);
|
||||
return { dom, message };
|
||||
}
|
||||
dom.append(head, message);
|
||||
return { dom, message };
|
||||
}
|
||||
|
||||
/** How each view reaches the engine, for its hover card. */
|
||||
const transports = new WeakMap<EditorView, BlameTransport>();
|
||||
|
||||
/** The hover card; the card loads the full message once shown. */
|
||||
const hoverState = StateField.define<Hover | null>({
|
||||
create: () => null,
|
||||
update(value, tr) {
|
||||
let next = value;
|
||||
if (next !== null && tr.docChanged) {
|
||||
next = null;
|
||||
}
|
||||
for (const effect of tr.effects) {
|
||||
if (effect.is(setHover)) {
|
||||
next = effect.value;
|
||||
}
|
||||
}
|
||||
return next;
|
||||
},
|
||||
provide: (field) =>
|
||||
showTooltip.from(field, (hover): Tooltip | null => {
|
||||
if (hover === null) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
pos: hover.pos,
|
||||
above: false,
|
||||
create: (view) => {
|
||||
const { dom, message } = hoverCard(hover.line);
|
||||
const { hash } = hover.line;
|
||||
const transport = transports.get(view);
|
||||
if (transport !== undefined && !isUncommitted(hash) && !messages.has(hash)) {
|
||||
void transport.query("git.showCommit", { hash }).then((result) => {
|
||||
if (!result.ok || typeof result.value !== "object" || result.value === null) {
|
||||
return;
|
||||
}
|
||||
const text = (result.value as Record<string, unknown>).message;
|
||||
if (typeof text === "string") {
|
||||
rememberMessage(hash, text);
|
||||
message.textContent = text;
|
||||
}
|
||||
});
|
||||
}
|
||||
return { dom };
|
||||
},
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
/** Paths whose annotations are shown. */
|
||||
const shown = new Set<string>();
|
||||
|
||||
/** Live plugins, refreshed when the toggle or the repository changes. */
|
||||
const live = new Set<{ path: string; schedule(delay: number): void }>();
|
||||
|
||||
/**
|
||||
* Whether the annotations of a file are shown.
|
||||
*
|
||||
* @param path - project-relative path.
|
||||
*/
|
||||
export function isBlameShown(path: string): boolean {
|
||||
return shown.has(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows or hides the annotations of a file in every editor of it.
|
||||
*
|
||||
* @param path - project-relative path.
|
||||
* @param on - show (true) or hide.
|
||||
*/
|
||||
export function setBlameShown(path: string, on: boolean): void {
|
||||
if (on) {
|
||||
shown.add(path);
|
||||
} else {
|
||||
shown.delete(path);
|
||||
}
|
||||
for (const plugin of live) {
|
||||
if (plugin.path === path) {
|
||||
plugin.schedule(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggles the annotations of a file.
|
||||
*
|
||||
* @param path - project-relative path.
|
||||
* @returns whether they are shown now.
|
||||
*/
|
||||
export function toggleBlame(path: string): boolean {
|
||||
const on = !shown.has(path);
|
||||
setBlameShown(path, on);
|
||||
return on;
|
||||
}
|
||||
|
||||
/** Asks every annotated editor to query again (`gitChanged`). */
|
||||
export function refreshBlame(): void {
|
||||
for (const plugin of live) {
|
||||
if (shown.has(plugin.path)) {
|
||||
plugin.schedule(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Hides every annotation and forgets the messages (a project change). */
|
||||
export function clearBlame(): void {
|
||||
const paths = [...shown];
|
||||
shown.clear();
|
||||
messages.clear();
|
||||
for (const plugin of live) {
|
||||
if (paths.includes(plugin.path)) {
|
||||
plugin.schedule(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The plugin that queries the annotations of one view and runs its hover
|
||||
* card.
|
||||
*
|
||||
* @param path - the file.
|
||||
* @param buffer - the engine buffer the state shows.
|
||||
* @param transport - how to reach the engine.
|
||||
*/
|
||||
function blamePlugin(path: string, buffer: AssistBuffer, transport: BlameTransport): Extension {
|
||||
return ViewPlugin.define((view): PluginValue => {
|
||||
const life = { alive: true };
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
let hoverTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let asked = 0;
|
||||
|
||||
/**
|
||||
* Whether the plugin still lives and the view still shows `doc`.
|
||||
*
|
||||
* @param doc - the document a query was made for.
|
||||
*/
|
||||
function current(doc: Text): boolean {
|
||||
return life.alive && view.state.doc === doc;
|
||||
}
|
||||
|
||||
/** Queries the annotations (or clears them when hidden). */
|
||||
async function run(): Promise<void> {
|
||||
asked += 1;
|
||||
const mine = asked;
|
||||
if (!shown.has(path)) {
|
||||
if (view.state.field(blameMarkers).size > 0) {
|
||||
view.dispatch({ effects: [setBlame.of(RangeSet.empty as RangeSet<GutterMarker>), setHover.of(null)] });
|
||||
}
|
||||
return;
|
||||
}
|
||||
const doc = view.state.doc;
|
||||
await buffer.idle();
|
||||
if (!current(doc) || mine !== asked) {
|
||||
return;
|
||||
}
|
||||
const result = await transport.query("git.blame", { path });
|
||||
if (!current(doc) || mine !== asked || !result.ok || !shown.has(path)) {
|
||||
return;
|
||||
}
|
||||
const lines = readBlame(result.value);
|
||||
if (lines !== null) {
|
||||
view.dispatch({ effects: setBlame.of(buildBlameMarkers(doc, lines, Date.now())) });
|
||||
}
|
||||
}
|
||||
|
||||
/** Hides the hover card, if any. */
|
||||
function hideHover(): void {
|
||||
if (hoverTimer !== null) {
|
||||
clearTimeout(hoverTimer);
|
||||
hoverTimer = null;
|
||||
}
|
||||
if (life.alive && (view.state.field(hoverState, false) ?? null) !== null) {
|
||||
view.dispatch({ effects: setHover.of(null) });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hides the card when the pointer leaves the gutter and the card.
|
||||
*
|
||||
* @param event - the pointer event.
|
||||
*/
|
||||
function onPointer(event: Event): void {
|
||||
const target = event.target;
|
||||
if (target instanceof Element && (target.closest(".lt-blame-gutter") || target.closest(".lt-blame-tooltip"))) {
|
||||
return;
|
||||
}
|
||||
hideHover();
|
||||
}
|
||||
|
||||
const handle = {
|
||||
path,
|
||||
schedule(delay: number): void {
|
||||
if (!life.alive) {
|
||||
return;
|
||||
}
|
||||
if (timer !== null) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
timer = setTimeout(() => {
|
||||
timer = null;
|
||||
void run();
|
||||
}, delay);
|
||||
},
|
||||
hover(pos: number): void {
|
||||
const line = blameAt(view.state, pos);
|
||||
const now = view.state.field(hoverState, false);
|
||||
if (line === null) {
|
||||
hideHover();
|
||||
return;
|
||||
}
|
||||
if (now !== undefined && now !== null && now.pos === pos) {
|
||||
return;
|
||||
}
|
||||
if (hoverTimer !== null) {
|
||||
clearTimeout(hoverTimer);
|
||||
}
|
||||
hoverTimer = setTimeout(() => {
|
||||
hoverTimer = null;
|
||||
if (life.alive && blameAt(view.state, pos) === line) {
|
||||
view.dispatch({ effects: setHover.of({ pos, line }) });
|
||||
}
|
||||
}, BLAME_HOVER_MS);
|
||||
},
|
||||
};
|
||||
live.add(handle);
|
||||
plugins.set(view, handle);
|
||||
transports.set(view, transport);
|
||||
view.dom.addEventListener("mouseover", onPointer);
|
||||
handle.schedule(0);
|
||||
return {
|
||||
update(update: ViewUpdate): void {
|
||||
if (update.docChanged && shown.has(path)) {
|
||||
handle.schedule(BLAME_DEBOUNCE_MS);
|
||||
}
|
||||
},
|
||||
destroy(): void {
|
||||
life.alive = false;
|
||||
live.delete(handle);
|
||||
plugins.delete(view);
|
||||
transports.delete(view);
|
||||
view.dom.removeEventListener("mouseover", onPointer);
|
||||
for (const pending of [timer, hoverTimer]) {
|
||||
if (pending !== null) {
|
||||
clearTimeout(pending);
|
||||
}
|
||||
}
|
||||
timer = null;
|
||||
hoverTimer = null;
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** The plugin handle of each view, for the gutter's pointer handlers. */
|
||||
const plugins = new WeakMap<EditorView, { hover(pos: number): void }>();
|
||||
|
||||
/** Annotation styles from the theme tokens. */
|
||||
const blameTheme: Extension = EditorView.theme({
|
||||
".lt-blame-gutter .cm-gutterElement": {
|
||||
padding: "0",
|
||||
cursor: "pointer",
|
||||
},
|
||||
".lt-blame-marker": {
|
||||
boxSizing: "border-box",
|
||||
width: "22ch",
|
||||
height: "100%",
|
||||
padding: "0 6px 0 5px",
|
||||
overflow: "hidden",
|
||||
whiteSpace: "nowrap",
|
||||
textOverflow: "ellipsis",
|
||||
fontSize: "0.85em",
|
||||
color: "var(--lt-editor-gutter-fg)",
|
||||
borderLeft: "3px solid transparent",
|
||||
},
|
||||
".lt-blame-marker--age-0": { borderLeftColor: "var(--lt-accent)" },
|
||||
".lt-blame-marker--age-1": { borderLeftColor: "color-mix(in srgb, var(--lt-accent) 75%, var(--lt-editor-gutter-bg))" },
|
||||
".lt-blame-marker--age-2": { borderLeftColor: "color-mix(in srgb, var(--lt-accent) 50%, var(--lt-editor-gutter-bg))" },
|
||||
".lt-blame-marker--age-3": { borderLeftColor: "color-mix(in srgb, var(--lt-accent) 30%, var(--lt-editor-gutter-bg))" },
|
||||
".lt-blame-marker--age-4": { borderLeftColor: "color-mix(in srgb, var(--lt-accent) 15%, var(--lt-editor-gutter-bg))" },
|
||||
".lt-blame-marker--age-new": { borderLeftColor: "var(--lt-vcs-modified)", fontStyle: "italic" },
|
||||
".lt-blame-tooltip": {
|
||||
maxWidth: "60ch",
|
||||
padding: "6px 8px",
|
||||
},
|
||||
".lt-blame-tooltip__head": {
|
||||
color: "var(--lt-fg-muted)",
|
||||
marginBottom: "4px",
|
||||
},
|
||||
".lt-blame-tooltip__message": {
|
||||
whiteSpace: "pre-wrap",
|
||||
overflowWrap: "anywhere",
|
||||
maxHeight: "16em",
|
||||
overflowY: "auto",
|
||||
},
|
||||
".lt-blame-tooltip__hint": {
|
||||
color: "var(--lt-fg-muted)",
|
||||
marginTop: "6px",
|
||||
fontSize: "0.9em",
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* The blame annotation extensions of an editor state.
|
||||
*
|
||||
* @param path - the file's project-relative path.
|
||||
* @param buffer - the buffer it shows; none for states without one.
|
||||
* @param transport - how to reach the engine.
|
||||
* @returns the extensions; empty without a buffer or path.
|
||||
*/
|
||||
export function blameExtensions(
|
||||
path: string,
|
||||
buffer: AssistBuffer | undefined,
|
||||
transport: BlameTransport = engineBlameTransport,
|
||||
): Extension {
|
||||
if (buffer === undefined || path === "") {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
blameMarkers,
|
||||
hoverState,
|
||||
gutter({
|
||||
class: "lt-blame-gutter",
|
||||
markers: (view) => view.state.field(blameMarkers),
|
||||
domEventHandlers: {
|
||||
click(view, line, event) {
|
||||
const target = event.target instanceof HTMLElement ? event.target.closest<HTMLElement>(".lt-blame-marker") : null;
|
||||
const hash = target?.dataset.hash ?? blameAt(view.state, line.from)?.hash;
|
||||
if (hash === undefined || isUncommitted(hash)) {
|
||||
return false;
|
||||
}
|
||||
view.dispatch({ effects: setHover.of(null) });
|
||||
transport.openCommit(hash);
|
||||
return true;
|
||||
},
|
||||
mousemove(view, line) {
|
||||
plugins.get(view)?.hover(line.from);
|
||||
return false;
|
||||
},
|
||||
},
|
||||
}),
|
||||
blameTheme,
|
||||
blamePlugin(path, buffer, transport),
|
||||
];
|
||||
}
|
||||
|
|
@ -6,7 +6,8 @@
|
|||
* the editor tokens (`--lt-editor-selection-bg`, `--lt-editor-active-line-bg`,
|
||||
* `--lt-editor-cursor`, `--lt-editor-gutter-bg`, `--lt-editor-gutter-fg`,
|
||||
* `--lt-editor-match-bg`, `--lt-font-size-editor`). Buffers also get Git
|
||||
* change markers in the gutter (`gitGutter.ts`).
|
||||
* change markers in the gutter (`gitGutter.ts`) and, when toggled, blame
|
||||
* annotations (`blame.ts`).
|
||||
*/
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import type { Extension } from "@codemirror/state";
|
||||
|
|
@ -15,6 +16,7 @@ import { languageExtensions, type SYNTAX_CLASS, type SyntaxToken } from "./langu
|
|||
import { lintExtensions } from "./lint";
|
||||
import { assistExtensions, type AssistBuffer } from "./assist";
|
||||
import { navExtensions } from "./nav/navExtension";
|
||||
import { blameExtensions } from "./blame";
|
||||
import { gitGutterExtensions } from "./gitGutter";
|
||||
|
||||
/**
|
||||
|
|
@ -125,5 +127,6 @@ export function editorExtensions(path = "", buffer?: AssistBuffer): Extension {
|
|||
assistExtensions(path, buffer),
|
||||
navExtensions(),
|
||||
gitGutterExtensions(buffer),
|
||||
blameExtensions(path, buffer),
|
||||
];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -33,6 +33,10 @@
|
|||
* tab opens. The Log tab (M4.6) appears with `vcs.showLog` and with
|
||||
* `vcs.showHistory {path?}` (the history of a file or folder; without a
|
||||
* path, of the active editor tab's file); neither has a default shortcut.
|
||||
* `vcs.showCommit {hash}` (M4.7) shows the Log with that commit selected
|
||||
* (a click on a blame annotation); `vcs.toggleBlame {path?}` shows or
|
||||
* hides the blame annotations of a file (default: the active tab's). No
|
||||
* default shortcuts.
|
||||
*
|
||||
* A slim header bar along the top (M3.9) holds the app menu
|
||||
* ({@link AppMenu}); its `header` slot can replace it.
|
||||
|
|
@ -54,6 +58,7 @@ import { useChangesStore } from "../vcs/changes/changes";
|
|||
import LogToolWindow from "../vcs/log/LogToolWindow.vue";
|
||||
import { SHOW_HISTORY_COMMAND, SHOW_LOG_COMMAND, useLogStore } from "../vcs/log/log";
|
||||
import StashDialog from "../vcs/stash/StashDialog.vue";
|
||||
import { SHOW_COMMIT_COMMAND, TOGGLE_BLAME_COMMAND, setCommitOpener, toggleBlame } from "../editor/blame";
|
||||
import { useEditorStore } from "../../stores/editor";
|
||||
import { useProjectStore } from "../../stores/project";
|
||||
import ProjectToolWindow from "../project/ProjectToolWindow.vue";
|
||||
|
|
@ -174,6 +179,7 @@ onMounted(() => {
|
|||
problems.start();
|
||||
changes.start();
|
||||
vcsLog.start();
|
||||
setCommitOpener((hash) => void commands.execute(SHOW_COMMIT_COMMAND, { hash }));
|
||||
withdraw = [
|
||||
commands.provide("view.toggleProjectTree", {
|
||||
run: () => {
|
||||
|
|
@ -229,6 +235,28 @@ onMounted(() => {
|
|||
},
|
||||
enabled: () => project.root !== null,
|
||||
}),
|
||||
commands.provide(SHOW_COMMIT_COMMAND, {
|
||||
run: async (params) => {
|
||||
const hash = (params as { hash?: unknown } | null)?.hash;
|
||||
if (typeof hash !== "string" || !/^[0-9a-f]{4,64}$/i.test(hash)) {
|
||||
return;
|
||||
}
|
||||
bottomTool.value = "log";
|
||||
await vcsLog.open();
|
||||
await vcsLog.select(hash);
|
||||
},
|
||||
enabled: () => project.root !== null,
|
||||
}),
|
||||
commands.provide(TOGGLE_BLAME_COMMAND, {
|
||||
run: (params) => {
|
||||
const given = (params as { path?: unknown } | null)?.path;
|
||||
const path = typeof given === "string" && given !== "" ? given : editor.activeTab?.path;
|
||||
if (path !== undefined) {
|
||||
toggleBlame(path);
|
||||
}
|
||||
},
|
||||
enabled: () => project.root !== null,
|
||||
}),
|
||||
commands.provide("view.toggleStructure", {
|
||||
run: () => {
|
||||
toggleLeft("structure");
|
||||
|
|
@ -242,6 +270,7 @@ onBeforeUnmount(() => {
|
|||
fn();
|
||||
}
|
||||
withdraw = [];
|
||||
setCommitOpener(() => undefined);
|
||||
find.stop();
|
||||
terminal.stop();
|
||||
problems.stop();
|
||||
|
|
|
|||
|
|
@ -35,11 +35,13 @@
|
|||
"command.vcs.push": "Push",
|
||||
"command.vcs.refresh": "Refresh Changes",
|
||||
"command.vcs.resolveConflicts": "Resolve Conflicts…",
|
||||
"command.vcs.showCommit": "Show Commit in Log",
|
||||
"command.vcs.showDiff": "Show Diff",
|
||||
"command.vcs.showHistory": "Show History",
|
||||
"command.vcs.showLog": "Log",
|
||||
"command.vcs.showStashes": "Stashes…",
|
||||
"command.vcs.stash": "Stash Changes…",
|
||||
"command.vcs.toggleBlame": "Annotate with Git Blame",
|
||||
"command.view.toggleProjectTree": "Show or Hide Project",
|
||||
"command.view.toggleStructure": "Show or Hide Structure",
|
||||
"common.cancel": "Cancel",
|
||||
|
|
@ -81,6 +83,10 @@
|
|||
"editor.assist.kind.value": "Value",
|
||||
"editor.assist.kind.variable": "Variable",
|
||||
"editor.assist.signature.count": "{index} of {count}",
|
||||
"editor.blame.byLine": "{hash} · {author} · {date}",
|
||||
"editor.blame.clickHint": "Click to show this commit in the Log",
|
||||
"editor.blame.notCommitted": "Not committed yet",
|
||||
"editor.blame.notCommittedHint": "This line has changes that are not committed.",
|
||||
"editor.closePrompt.question": "Save changes to {name} before closing?",
|
||||
"editor.gitGutter.added": "Added since the staged version",
|
||||
"editor.gitGutter.deleted": "Lines deleted here since the staged version",
|
||||
|
|
|
|||
|
|
@ -20,7 +20,9 @@
|
|||
* `git.status`; the tree colours its ignored entries itself while a
|
||||
* repository is open.
|
||||
* - **Gutters:** every `gitChanged` also asks the editors' change markers
|
||||
* to refresh (`refreshGitGutters`), since the index may have changed.
|
||||
* to refresh (`refreshGitGutters`), since the index may have changed,
|
||||
* and the blame annotations (`refreshBlame`); a project change hides
|
||||
* them (`clearBlame`).
|
||||
* - **Lifetime:** {@link start} / {@link stop} are counted, so `App.vue`
|
||||
* and the main layout can both hold the store; the subscription ends
|
||||
* with the last holder.
|
||||
|
|
@ -28,6 +30,7 @@
|
|||
import { defineStore } from "pinia";
|
||||
import { computed, ref, shallowRef } from "vue";
|
||||
import { onEngineEvent, runWaiting, type EngineEventPayload } from "../ipc";
|
||||
import { clearBlame, refreshBlame } from "../components/editor/blame";
|
||||
import { refreshGitGutters } from "../components/editor/gitGutter";
|
||||
|
||||
/** Most files kept from one status. */
|
||||
|
|
@ -387,14 +390,17 @@ export const useVcsStatusStore = defineStore("vcsStatus", () => {
|
|||
switch (event.kind) {
|
||||
case "projectOpened":
|
||||
clear();
|
||||
clearBlame();
|
||||
void refresh();
|
||||
break;
|
||||
case "projectClosed":
|
||||
clear();
|
||||
clearBlame();
|
||||
break;
|
||||
case "gitChanged":
|
||||
void refresh();
|
||||
refreshGitGutters();
|
||||
refreshBlame();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
|
|
|
|||
321
ui/tests/editor/blame.test.ts
Normal file
321
ui/tests/editor/blame.test.ts
Normal file
|
|
@ -0,0 +1,321 @@
|
|||
/**
|
||||
* Tests of the blame annotations (M4.7, `blame.ts`): reading `git.blame`,
|
||||
* age levels, building annotations (runs, uncommitted lines, clamping),
|
||||
* the per-file toggle, the query when shown, the debounce after edits,
|
||||
* dropping answers for an old document, `refreshBlame` and `clearBlame`,
|
||||
* annotations mapped through edits, the hover card with the full message,
|
||||
* a click opening the commit, the commands, and colours from tokens only.
|
||||
*/
|
||||
import { EditorState, Text } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
BLAME_DEBOUNCE_MS,
|
||||
BLAME_HOVER_MS,
|
||||
SHOW_COMMIT_COMMAND,
|
||||
TOGGLE_BLAME_COMMAND,
|
||||
ageLevel,
|
||||
blameExtensions,
|
||||
blameMarkerLines,
|
||||
buildBlameMarkers,
|
||||
clearBlame,
|
||||
isBlameShown,
|
||||
isUncommitted,
|
||||
readBlame,
|
||||
refreshBlame,
|
||||
setBlameShown,
|
||||
shortDate,
|
||||
toggleBlame,
|
||||
type BlameLine,
|
||||
type BlameTransport,
|
||||
} from "../../src/components/editor/blame";
|
||||
import { UI_COMMANDS } from "../../src/commands/uiCommands";
|
||||
import type { JsonValue } from "../../src/ipc";
|
||||
|
||||
const A = "a".repeat(40);
|
||||
const B = "b".repeat(40);
|
||||
const ZERO = "0".repeat(40);
|
||||
const NOW = Date.parse("2026-10-29T12:00:00Z");
|
||||
|
||||
/** Views created by a test, destroyed after it. */
|
||||
let views: EditorView[] = [];
|
||||
|
||||
/** A blame line. */
|
||||
function line(hash: string, date = "2026-10-29T10:00:00+01:00", author = "Ann", summary = "Subject"): BlameLine {
|
||||
return { hash, author, date, summary, origLine: 1 };
|
||||
}
|
||||
|
||||
/** A fake engine answering `git.blame` and `git.showCommit`. */
|
||||
class FakeEngine implements BlameTransport {
|
||||
/** Every query, in order. */
|
||||
readonly calls: { command: string; params: JsonValue }[] = [];
|
||||
/** What `git.blame` answers. */
|
||||
answer: unknown = { lines: [], version: 1 };
|
||||
/** Whether queries fail. */
|
||||
fail = false;
|
||||
/** Commits opened. */
|
||||
readonly opened: string[] = [];
|
||||
|
||||
query(command: string, params: JsonValue): Promise<{ ok: true; value: unknown } | { ok: false }> {
|
||||
this.calls.push({ command, params });
|
||||
if (this.fail) {
|
||||
return Promise.resolve({ ok: false });
|
||||
}
|
||||
if (command === "git.showCommit") {
|
||||
return Promise.resolve({ ok: true, value: { message: "Subject\n\nThe full body." } });
|
||||
}
|
||||
expect(command).toBe("git.blame");
|
||||
return Promise.resolve({ ok: true, value: this.answer });
|
||||
}
|
||||
|
||||
openCommit(hash: string): void {
|
||||
this.opened.push(hash);
|
||||
}
|
||||
|
||||
/** The `git.blame` queries. */
|
||||
blames(): JsonValue[] {
|
||||
return this.calls.filter((c) => c.command === "git.blame").map((c) => c.params);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A view of `src/a.php` (buffer 7) showing `doc`.
|
||||
*
|
||||
* @param doc - the text.
|
||||
* @param engine - the fake engine.
|
||||
*/
|
||||
function viewOf(doc: string, engine: FakeEngine): EditorView {
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc,
|
||||
extensions: blameExtensions("src/a.php", { id: 7, idle: () => Promise.resolve() }, engine),
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
return view;
|
||||
}
|
||||
|
||||
/** Hashes of the annotations a view shows, by 1-based line. */
|
||||
function hashes(view: EditorView): Record<number, string> {
|
||||
const out: Record<number, string> = {};
|
||||
for (const [number, marker] of Object.entries(blameMarkerLines(view.state))) {
|
||||
out[Number(number)] = marker.hash;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Lets timers and promises run. */
|
||||
async function flush(ms = 0): Promise<void> {
|
||||
await vi.advanceTimersByTimeAsync(ms);
|
||||
for (let i = 0; i < 5; i += 1) {
|
||||
await Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(NOW);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const view of views) {
|
||||
view.destroy();
|
||||
}
|
||||
views = [];
|
||||
clearBlame();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("reading", () => {
|
||||
it("keeps line positions and drops malformed entries", () => {
|
||||
expect(
|
||||
readBlame({
|
||||
lines: [line(A), { hash: "nothex!", author: "x", date: "d" }, null, { hash: B, author: "Bo", date: "d", origLine: -2 }],
|
||||
}),
|
||||
).toEqual([line(A), null, null, { hash: B, author: "Bo", date: "d", summary: "", origLine: 0 }]);
|
||||
expect(readBlame({})).toBeNull();
|
||||
expect(readBlame("x")).toBeNull();
|
||||
});
|
||||
|
||||
it("knows uncommitted hashes, ages and short dates", () => {
|
||||
expect(isUncommitted(ZERO)).toBe(true);
|
||||
expect(isUncommitted(A)).toBe(false);
|
||||
expect(isUncommitted("")).toBe(false);
|
||||
expect(ageLevel("2026-10-29T08:00:00Z", NOW)).toBe(0);
|
||||
expect(ageLevel("2026-10-25T08:00:00Z", NOW)).toBe(1);
|
||||
expect(ageLevel("2026-10-10T08:00:00Z", NOW)).toBe(2);
|
||||
expect(ageLevel("2026-03-01T08:00:00Z", NOW)).toBe(3);
|
||||
expect(ageLevel("2020-01-01T08:00:00Z", NOW)).toBe(4);
|
||||
expect(ageLevel("not a date", NOW)).toBe(4);
|
||||
expect(ageLevel("2027-01-01T00:00:00Z", NOW)).toBe(0);
|
||||
expect(shortDate("2026-10-29T12:00:00")).toBe("2026-10-29");
|
||||
expect(shortDate("garbage")).toBe("garbage");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildBlameMarkers", () => {
|
||||
it("shows text on the first line of each run and clamps to the document", () => {
|
||||
const doc = Text.of(["a", "b", "c", "d"]);
|
||||
const set = buildBlameMarkers(doc, [line(A), line(A), null, line(A), line(ZERO), line(B)], NOW);
|
||||
const out: Record<number, [boolean, number | string]> = {};
|
||||
const cursor = set.iter();
|
||||
while (cursor.value !== null) {
|
||||
const marker = cursor.value as unknown as { first: boolean; level: number | string };
|
||||
out[doc.lineAt(cursor.from).number] = [marker.first, marker.level];
|
||||
cursor.next();
|
||||
}
|
||||
expect(out).toEqual({ 1: [true, 0], 2: [false, 0], 4: [true, 0] });
|
||||
const withNew = buildBlameMarkers(Text.of(["x", "y"]), [line(A), line(ZERO)], NOW);
|
||||
const levels: (number | string)[] = [];
|
||||
withNew.between(0, 3, (_f, _t, m) => {
|
||||
levels.push((m as unknown as { level: number | string }).level);
|
||||
});
|
||||
expect(levels).toEqual([0, "new"]);
|
||||
});
|
||||
|
||||
it("renders date and author, or a not-committed label", () => {
|
||||
const view = viewOf("a\nb\nc", new FakeEngine());
|
||||
const doc = view.state.doc;
|
||||
const set = buildBlameMarkers(doc, [line(A, "2026-10-29T10:00:00", "Ann"), line(A), line(ZERO)], NOW);
|
||||
const texts: string[] = [];
|
||||
set.between(0, doc.length, (_f, _t, marker) => {
|
||||
texts.push((marker.toDOM?.(view) as HTMLElement).textContent);
|
||||
});
|
||||
expect(texts).toEqual(["2026-10-29 Ann", "", "Not committed yet"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the gutter", () => {
|
||||
it("queries only while the file's annotations are shown", async () => {
|
||||
const engine = new FakeEngine();
|
||||
engine.answer = { lines: [line(A), line(B)], version: 1 };
|
||||
const view = viewOf("x\ny", engine);
|
||||
await flush();
|
||||
expect(engine.blames()).toEqual([]);
|
||||
expect(isBlameShown("src/a.php")).toBe(false);
|
||||
|
||||
expect(toggleBlame("src/a.php")).toBe(true);
|
||||
await flush();
|
||||
expect(engine.blames()).toEqual([{ path: "src/a.php" }]);
|
||||
expect(hashes(view)).toEqual({ 1: A, 2: B });
|
||||
expect(view.dom.querySelectorAll("[data-test=blame-marker]")).toHaveLength(2);
|
||||
|
||||
setBlameShown("src/other.php", true);
|
||||
await flush();
|
||||
expect(engine.blames()).toHaveLength(1);
|
||||
|
||||
expect(toggleBlame("src/a.php")).toBe(false);
|
||||
await flush();
|
||||
expect(hashes(view)).toEqual({});
|
||||
expect(engine.blames()).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("debounces edits, maps annotations through them and drops stale answers", async () => {
|
||||
const engine = new FakeEngine();
|
||||
engine.answer = { lines: [line(A), line(B)], version: 1 };
|
||||
setBlameShown("src/a.php", true);
|
||||
const view = viewOf("x\ny", engine);
|
||||
await flush();
|
||||
expect(hashes(view)).toEqual({ 1: A, 2: B });
|
||||
|
||||
view.dispatch({ changes: { from: 0, insert: "new\n" } });
|
||||
expect(hashes(view)).toEqual({ 2: A, 3: B });
|
||||
await flush(BLAME_DEBOUNCE_MS - 1);
|
||||
expect(engine.blames()).toHaveLength(1);
|
||||
engine.answer = { lines: [line(ZERO), line(A), line(B)], version: 2 };
|
||||
await flush(1);
|
||||
expect(engine.blames()).toHaveLength(2);
|
||||
expect(hashes(view)).toEqual({ 1: ZERO, 2: A, 3: B });
|
||||
|
||||
// An answer for a document that changed meanwhile is dropped.
|
||||
let release: () => void = () => undefined;
|
||||
const original = engine.query.bind(engine);
|
||||
engine.query = (command, params) =>
|
||||
new Promise((resolve) => {
|
||||
release = () => {
|
||||
void original(command, params).then(resolve);
|
||||
};
|
||||
});
|
||||
refreshBlame();
|
||||
await flush();
|
||||
view.dispatch({ changes: { from: 0, insert: "z" } });
|
||||
engine.answer = { lines: [line(B), line(B), line(B)], version: 3 };
|
||||
release();
|
||||
await flush();
|
||||
expect(hashes(view)).toEqual({ 1: ZERO, 2: A, 3: B });
|
||||
});
|
||||
|
||||
it("keeps annotations when a query fails and refreshes on gitChanged", async () => {
|
||||
const engine = new FakeEngine();
|
||||
engine.answer = { lines: [line(A)], version: 1 };
|
||||
setBlameShown("src/a.php", true);
|
||||
const view = viewOf("x", engine);
|
||||
await flush();
|
||||
engine.fail = true;
|
||||
refreshBlame();
|
||||
await flush();
|
||||
expect(engine.blames()).toHaveLength(2);
|
||||
expect(hashes(view)).toEqual({ 1: A });
|
||||
|
||||
clearBlame();
|
||||
await flush();
|
||||
expect(hashes(view)).toEqual({});
|
||||
expect(isBlameShown("src/a.php")).toBe(false);
|
||||
refreshBlame();
|
||||
await flush();
|
||||
expect(engine.blames()).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("opens the commit on click, but not for uncommitted lines", async () => {
|
||||
const engine = new FakeEngine();
|
||||
engine.answer = { lines: [line(A), line(ZERO)], version: 1 };
|
||||
setBlameShown("src/a.php", true);
|
||||
const view = viewOf("x\ny", engine);
|
||||
await flush();
|
||||
const markers = view.dom.querySelectorAll<HTMLElement>("[data-test=blame-marker]");
|
||||
markers[1]?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
markers[0]?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
expect(engine.opened).toEqual([A]);
|
||||
});
|
||||
|
||||
it("shows a hover card with the full message after a delay", async () => {
|
||||
const engine = new FakeEngine();
|
||||
engine.answer = { lines: [line(A, "2026-10-29T10:00:00+01:00", "Ann", "Subject")], version: 1 };
|
||||
setBlameShown("src/a.php", true);
|
||||
const view = viewOf("x", engine);
|
||||
await flush();
|
||||
const marker = view.dom.querySelector<HTMLElement>("[data-test=blame-marker]");
|
||||
marker?.dispatchEvent(new MouseEvent("mousemove", { bubbles: true }));
|
||||
await flush(BLAME_HOVER_MS - 1);
|
||||
expect(document.querySelector("[data-test=blame-tooltip]")).toBeNull();
|
||||
await flush(1);
|
||||
const card = document.querySelector("[data-test=blame-tooltip]");
|
||||
expect(card?.textContent).toContain(`${A.slice(0, 8)} · Ann`);
|
||||
expect(card?.textContent).toContain("The full body.");
|
||||
expect(engine.calls.filter((c) => c.command === "git.showCommit")).toEqual([{ command: "git.showCommit", params: { hash: A } }]);
|
||||
|
||||
view.contentDOM.dispatchEvent(new MouseEvent("mouseover", { bubbles: true }));
|
||||
await flush();
|
||||
expect(document.querySelector("[data-test=blame-tooltip]")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("commands", () => {
|
||||
it("registers Show Commit and Annotate without default shortcuts", () => {
|
||||
const specs = UI_COMMANDS.filter((c) => c.id === SHOW_COMMIT_COMMAND || c.id === TOGGLE_BLAME_COMMAND);
|
||||
expect(specs.map((c) => [c.id, c.menuPath, c.defaultShortcut])).toEqual([
|
||||
["vcs.showCommit", undefined, undefined],
|
||||
["vcs.toggleBlame", "Git/Annotate with Git Blame", undefined],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("colours", () => {
|
||||
it("come from tokens only", () => {
|
||||
const source = readFileSync(join(__dirname, "../../src/components/editor/blame.ts"), "utf8");
|
||||
expect(source).not.toMatch(/#[0-9a-f]{3,8}\b|rgba?\(/i);
|
||||
});
|
||||
});
|
||||
|
|
@ -276,6 +276,7 @@ describe("AppMenu", () => {
|
|||
"goto.classOpen",
|
||||
"goto.symbolOpen",
|
||||
"vcs.abortMerge",
|
||||
"vcs.toggleBlame",
|
||||
"vcs.branches",
|
||||
"vcs.openChanges",
|
||||
"vcs.clone",
|
||||
|
|
|
|||
|
|
@ -259,6 +259,7 @@ describe("CommandPalette", () => {
|
|||
expect(document.activeElement).toBe(wrapper.find("[data-test=palette-input]").element);
|
||||
expect(rows(wrapper)).toEqual([
|
||||
"vcs.abortMerge",
|
||||
"vcs.toggleBlame",
|
||||
"vcs.branches",
|
||||
"vcs.openChanges",
|
||||
"vcs.checkout",
|
||||
|
|
@ -290,6 +291,7 @@ describe("CommandPalette", () => {
|
|||
"vcs.resolveConflicts",
|
||||
"editor.reveal",
|
||||
"settings.open",
|
||||
"vcs.showCommit",
|
||||
"vcs.showDiff",
|
||||
"vcs.showHistory",
|
||||
"view.toggleProjectTree",
|
||||
|
|
|
|||
|
|
@ -4,7 +4,8 @@
|
|||
* `gitChanged` when HEAD moves, commit details, the Log window (rows,
|
||||
* badges, keyboard, filters, history chip), a file's diff at a commit in
|
||||
* the diff viewer (both sides read-only), `vcs.showHistory` and the tree's
|
||||
* context menu. The engine is a fake behind the mocked Tauri `invoke` and
|
||||
* context menu, and `vcs.showCommit` / `vcs.toggleBlame` from the main
|
||||
* layout (M4.7). The engine is a fake behind the mocked Tauri `invoke` and
|
||||
* `listen`.
|
||||
*/
|
||||
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
|
||||
|
|
@ -18,7 +19,9 @@ vi.mock("@tauri-apps/api/event", () => ({ listen }));
|
|||
|
||||
import { useCommandsStore } from "../../src/commands/store";
|
||||
import { UI_COMMANDS } from "../../src/commands/uiCommands";
|
||||
import { isBlameShown, SHOW_COMMIT_COMMAND, TOGGLE_BLAME_COMMAND } from "../../src/components/editor/blame";
|
||||
import EditorArea from "../../src/components/editor/EditorArea.vue";
|
||||
import MainLayout from "../../src/components/layout/MainLayout.vue";
|
||||
import TreeContextMenu from "../../src/components/project/TreeContextMenu.vue";
|
||||
import { commitDiffKey, useDiffStore } from "../../src/components/vcs/diff/diff";
|
||||
import { currentMerge } from "../../src/components/vcs/diff/navigation";
|
||||
|
|
@ -481,3 +484,32 @@ describe("commands", () => {
|
|||
expect(run).toHaveBeenCalledWith({ path: "src/a.php" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("blame commands in the main layout (M4.7)", () => {
|
||||
it("shows a commit in the Log and toggles a file's annotations", async () => {
|
||||
useProjectStore(pinia).root = { path: "/p", name: "p" };
|
||||
const wrapper = mount(MainLayout, {
|
||||
attachTo: document.body,
|
||||
global: { plugins: [pinia], stubs: { ProjectToolWindow: true, StatusBar: true } },
|
||||
});
|
||||
mounted.push(wrapper);
|
||||
const commands = useCommandsStore(pinia);
|
||||
await commands.start();
|
||||
await flushPromises();
|
||||
|
||||
await commands.execute(SHOW_COMMIT_COMMAND, { hash: "a" });
|
||||
await flushPromises();
|
||||
expect(callsOf("git.showCommit")).toEqual([]);
|
||||
await commands.execute(SHOW_COMMIT_COMMAND, { hash: "abcd" });
|
||||
await flushPromises();
|
||||
const log = useLogStore(pinia);
|
||||
expect(log.visible).toBe(true);
|
||||
expect(log.selected).toBe("abcd");
|
||||
expect(callsOf("git.showCommit").at(-1)).toEqual({ hash: "abcd" });
|
||||
|
||||
await commands.execute(TOGGLE_BLAME_COMMAND, { path: "src/a.php" });
|
||||
expect(isBlameShown("src/a.php")).toBe(true);
|
||||
await commands.execute(TOGGLE_BLAME_COMMAND, { path: "src/a.php" });
|
||||
expect(isBlameShown("src/a.php")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue