M4.4: Git gutter change markers and status colours in tree and tabs

- git.lineChanges {id} -> {ranges: [{kind, startLine, endLine}], version}:
  the buffer against its index blob, line diff with similar (Myers +
  Replace, no Compact) off the lock, CRLF-safe; index texts cached per
  path and dropped on gitChanged (State::emit -> git_lines::observe)
- editor gutter markers for added, modified and deleted lines, queried
  150 ms after edits, on show and on gitChanged, mapped through edits
- vcsStatus store (git.status on projectOpened and gitChanged, no
  polling) colouring file names in the project tree and editor tabs with
  the --lt-vcs-* tokens; contrast also checked on the active tab
- tests: unit and property tests, real-repo engine tests, Vitest
- docs: architecture, parity, gaps, roadmap, ui-parity, ROADMAP

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-25 17:36:59 +01:00
parent 56dadc91dc
commit fc8ae6c2e3
24 changed files with 1970 additions and 20 deletions

View file

@ -0,0 +1,338 @@
/**
* Git change markers in the editor gutter (M4.4): a bar beside added and
* modified lines and a notch where lines were deleted, against the file's
* version in the Git index.
*
* - **Source:** `git.lineChanges {id}` (a pending outcome, so through
* `runWaiting`), asked when the view shows the state, 150 ms after the
* last edit ({@link GIT_GUTTER_DEBOUNCE_MS}) and when
* {@link refreshGitGutters} is called (every `gitChanged`, from the
* status store). Before asking, the plugin waits until the buffer sync is
* idle and drops the answer if the document changed meanwhile; that
* change has scheduled a new query.
* - **Between answers** the markers are mapped through the edits, so they
* move with the text; lines typed since the last answer stay unmarked
* until the next one.
* - **Lines** are 0-based in the engine and split at the same breaks as
* CodeMirror's (`\n`, `\r\n`, `\r`). A `deleted` range at the line count
* (lines removed at the end) marks the bottom of the last line.
* - Failures leave the markers as they are: markers are best effort while
* typing, and the Changes window reports git problems.
*
* Colours come from `--lt-vcs-added`, `--lt-vcs-modified` and
* `--lt-vcs-deleted`.
*/
import { RangeSet, RangeSetBuilder, StateEffect, StateField, type EditorState, type Extension, type Text } from "@codemirror/state";
import { EditorView, GutterMarker, ViewPlugin, gutter, type PluginValue, 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 GIT_GUTTER_DEBOUNCE_MS = 150;
/** What a range of lines changed. */
export type LineChangeKind = "added" | "modified" | "deleted";
/** One range of `git.lineChanges`: 0-based lines, the end exclusive. */
export interface LineChange {
/** What changed. */
kind: LineChangeKind;
/** The first line. */
startLine: number;
/** The line after the last; equal to `startLine` for `deleted`. */
endLine: number;
}
/** How the gutter reaches the engine; replaced in tests. */
export interface GitGutterTransport {
/** Runs a command and resolves with its untrusted result. */
query(command: string, params: JsonValue): Promise<{ ok: true; value: unknown } | { ok: false }>;
}
/** The transport through the engine IPC, off the shell's main thread. */
export const engineGitGutterTransport: GitGutterTransport = {
query: (command, params) => runWaiting<unknown>(command, params),
};
/** Whether a value is a non-negative integer. */
function isLine(value: unknown): value is number {
return typeof value === "number" && Number.isInteger(value) && value >= 0;
}
/**
* Reads the ranges of a `git.lineChanges` result; malformed ranges are
* skipped.
*
* @param value - the untrusted result.
* @returns the ranges, or null when the result has no list.
*/
export function readLineChanges(value: unknown): LineChange[] | null {
if (typeof value !== "object" || value === null) {
return null;
}
const ranges = (value as Record<string, unknown>).ranges;
if (!Array.isArray(ranges)) {
return null;
}
const out: LineChange[] = [];
for (const range of ranges as unknown[]) {
if (typeof range !== "object" || range === null) {
continue;
}
const { kind, startLine, endLine } = range as Record<string, unknown>;
if ((kind === "added" || kind === "modified" || kind === "deleted") && isLine(startLine) && isLine(endLine) && endLine >= startLine) {
out.push({ kind, startLine, endLine });
}
}
return out;
}
/** A marker class: the three kinds, plus deleted lines below the last line. */
type MarkerClass = LineChangeKind | "deleted-end";
/** The tooltip of each marker class, from the catalog. */
const TITLES: Record<MarkerClass, () => string> = {
added: () => t("editor.gitGutter.added"),
modified: () => t("editor.gitGutter.modified"),
deleted: () => t("editor.gitGutter.deleted"),
"deleted-end": () => t("editor.gitGutter.deleted"),
};
/** One gutter marker; equal markers share their DOM. */
class GitMarker extends GutterMarker {
/**
* @param kind - what it marks.
*/
constructor(readonly kind: MarkerClass) {
super();
}
override eq(other: GutterMarker): boolean {
return other instanceof GitMarker && other.kind === this.kind;
}
override toDOM(): Node {
const element = document.createElement("div");
element.className = `lt-git-marker lt-git-marker--${this.kind}`;
element.title = TITLES[this.kind]();
element.dataset.test = "git-marker";
element.dataset.kind = this.kind;
return element;
}
}
/** One marker instance per class. */
const MARKERS: Record<MarkerClass, GitMarker> = {
added: new GitMarker("added"),
modified: new GitMarker("modified"),
deleted: new GitMarker("deleted"),
"deleted-end": new GitMarker("deleted-end"),
};
/**
* Builds the markers of `ranges` in `doc`: one per line of an added or
* modified range, one on the line after a deletion (on the last line when
* the deletion was at the end). Lines past the document are ignored; a
* line takes the first marker that reaches it.
*
* @param doc - the document the ranges were computed for.
* @param ranges - the ranges, in line order.
*/
export function buildMarkers(doc: Text, ranges: readonly LineChange[]): RangeSet<GutterMarker> {
const builder = new RangeSetBuilder<GutterMarker>();
let next = 1;
for (const range of ranges) {
if (range.kind === "deleted") {
const atEnd = range.startLine >= doc.lines;
const number = atEnd ? doc.lines : range.startLine + 1;
if (number >= next) {
const line = doc.line(number);
builder.add(line.from, line.from, MARKERS[atEnd ? "deleted-end" : "deleted"]);
next = number + 1;
}
continue;
}
const first = Math.max(range.startLine + 1, next);
const last = Math.min(range.endLine, doc.lines);
for (let number = first; number <= last; number += 1) {
const line = doc.line(number);
builder.add(line.from, line.from, MARKERS[range.kind]);
}
next = Math.max(next, last + 1);
}
return builder.finish();
}
/** Replaces the markers of a state. */
const setGitMarkers = StateEffect.define<RangeSet<GutterMarker>>();
/** The markers of a state, mapped through edits between answers. */
const gitMarkers = 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(setGitMarkers)) {
next = effect.value;
}
}
return next;
},
});
/**
* The markers a state carries, for tests and inspection.
*
* @param state - an editor state built with {@link gitGutterExtensions}.
* @returns the marker kind by 1-based line number; empty without the
* extension.
*/
export function gitMarkerLines(state: EditorState): Record<number, string> {
const out: Record<number, string> = {};
const set = state.field(gitMarkers, false);
if (set === undefined) {
return out;
}
const cursor = set.iter();
while (cursor.value !== null) {
if (cursor.value instanceof GitMarker) {
out[state.doc.lineAt(cursor.from).number] = cursor.value.kind;
}
cursor.next();
}
return out;
}
/** Live plugins, refreshed by {@link refreshGitGutters}. */
const live = new Set<{ schedule(delay: number): void }>();
/** Asks every editor shown now to query its markers again (`gitChanged`). */
export function refreshGitGutters(): void {
for (const plugin of live) {
plugin.schedule(0);
}
}
/**
* The plugin that queries the markers of one view's state.
*
* @param buffer - the engine buffer the state shows.
* @param transport - how to reach the engine.
*/
function gitGutterPlugin(buffer: AssistBuffer, transport: GitGutterTransport): Extension {
return ViewPlugin.define((view): PluginValue => {
const life = { alive: true };
let timer: 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 markers for the current document and applies them. */
async function run(): Promise<void> {
const doc = view.state.doc;
await buffer.idle();
if (!current(doc)) {
return;
}
asked += 1;
const mine = asked;
const result = await transport.query("git.lineChanges", { id: buffer.id });
if (!current(doc) || mine !== asked || !result.ok) {
return;
}
const ranges = readLineChanges(result.value);
if (ranges !== null) {
view.dispatch({ effects: setGitMarkers.of(buildMarkers(doc, ranges)) });
}
}
const handle = {
schedule(delay: number): void {
if (!life.alive) {
return;
}
if (timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(() => {
timer = null;
void run();
}, delay);
},
};
live.add(handle);
handle.schedule(0);
return {
update(update: ViewUpdate): void {
if (update.docChanged) {
handle.schedule(GIT_GUTTER_DEBOUNCE_MS);
}
},
destroy(): void {
life.alive = false;
live.delete(handle);
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
},
};
});
}
/** Marker styles from the status tokens. */
const gitGutterTheme: Extension = EditorView.theme({
".lt-git-gutter .cm-gutterElement": {
width: "4px",
padding: "0",
},
".lt-git-marker": {
height: "100%",
},
".lt-git-marker--added": {
backgroundColor: "var(--lt-vcs-added)",
},
".lt-git-marker--modified": {
backgroundColor: "var(--lt-vcs-modified)",
},
".lt-git-marker--deleted": {
background: "linear-gradient(to bottom, var(--lt-vcs-deleted) 0 3px, transparent 3px)",
},
".lt-git-marker--deleted-end": {
background: "linear-gradient(to top, var(--lt-vcs-deleted) 0 3px, transparent 3px)",
},
});
/**
* The Git change marker extensions of an editor state.
*
* @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.
*/
export function gitGutterExtensions(
buffer: AssistBuffer | undefined,
transport: GitGutterTransport = engineGitGutterTransport,
): Extension {
if (buffer === undefined) {
return [];
}
return [
gitMarkers,
gutter({
class: "lt-git-gutter",
markers: (view) => view.state.field(gitMarkers),
initialSpacer: () => MARKERS.added,
}),
gitGutterTheme,
gitGutterPlugin(buffer, transport),
];
}