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;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue