Lutra/ui/tests/editor/gitGutter.test.ts
danny ce681871ad A3: keep gutter change markers on their line when text is inserted at its start
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 14:25:47 +01:00

255 lines
8.5 KiB
TypeScript

/**
* Tests of the Git change markers (M4.4, `gitGutter.ts`): reading
* `git.lineChanges`, building markers (deleted at the end, clamping,
* overlaps), the query when a view shows the state, the 150 ms debounce
* after edits, dropping answers for an old document, `refreshGitGutters`,
* markers mapped through edits, 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 {
GIT_GUTTER_DEBOUNCE_MS,
buildMarkers,
gitGutterExtensions,
gitMarkerLines,
readLineChanges,
refreshGitGutters,
type GitGutterTransport,
type LineChange,
} from "../../src/components/editor/gitGutter";
import type { JsonValue } from "../../src/ipc";
/** Views created by a test, destroyed after it. */
let views: EditorView[] = [];
/** A fake engine answering `git.lineChanges` with `answer`. */
class FakeEngine implements GitGutterTransport {
/** The params of every query, in order. */
readonly calls: JsonValue[] = [];
/** What the next queries answer. */
answer: unknown = { ranges: [], version: 1 };
/** Whether queries fail. */
fail = false;
/** Queries waiting to be answered, when held. */
held: (() => void)[] = [];
/** Whether to hold answers until released. */
hold = false;
query(command: string, params: JsonValue): Promise<{ ok: true; value: unknown } | { ok: false }> {
expect(command).toBe("git.lineChanges");
this.calls.push(params);
const answer = this.answer;
const result = this.fail ? ({ ok: false } as const) : ({ ok: true, value: answer } as const);
if (!this.hold) {
return Promise.resolve(result);
}
return new Promise((resolve) => {
this.held.push(() => {
resolve(result);
});
});
}
}
/** The kinds of the markers a view shows, by 1-based line number. */
function markers(view: EditorView): Record<number, string> {
return gitMarkerLines(view.state);
}
/** Kinds of the markers in a range set, by 1-based line. */
function markerLines(doc: Text, ranges: LineChange[]): Record<number, string> {
const out: Record<number, string> = {};
const set = buildMarkers(doc, ranges);
const cursor = set.iter();
while (cursor.value !== null) {
out[doc.lineAt(cursor.from).number] = (cursor.value as unknown as { kind: string }).kind;
cursor.next();
}
return out;
}
/**
* A view of 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: gitGutterExtensions({ id: 7, idle: () => Promise.resolve() }, engine),
}),
parent: document.body,
});
views.push(view);
return view;
}
/** 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();
});
afterEach(() => {
for (const view of views) {
view.destroy();
}
views = [];
vi.useRealTimers();
});
describe("readLineChanges", () => {
it("keeps well-formed ranges and drops the rest", () => {
expect(
readLineChanges({
ranges: [
{ kind: "added", startLine: 0, endLine: 2 },
{ kind: "moved", startLine: 0, endLine: 1 },
{ kind: "modified", startLine: 3, endLine: 2 },
{ kind: "deleted", startLine: -1, endLine: -1 },
{ kind: "deleted", startLine: 4, endLine: 4 },
"x",
null,
],
}),
).toEqual([
{ kind: "added", startLine: 0, endLine: 2 },
{ kind: "deleted", startLine: 4, endLine: 4 },
]);
expect(readLineChanges({})).toBeNull();
expect(readLineChanges(null)).toBeNull();
});
});
describe("buildMarkers", () => {
const doc = Text.of(["a", "b", "c", "d"]);
it("marks every line of a range and the line after a deletion", () => {
expect(
markerLines(doc, [
{ kind: "modified", startLine: 0, endLine: 1 },
{ kind: "deleted", startLine: 2, endLine: 2 },
{ kind: "added", startLine: 3, endLine: 4 },
]),
).toEqual({ 1: "modified", 3: "deleted", 4: "added" });
});
it("puts a deletion at the end on the last line and clamps past the document", () => {
expect(markerLines(doc, [{ kind: "deleted", startLine: 4, endLine: 4 }])).toEqual({ 4: "deleted-end" });
expect(markerLines(doc, [{ kind: "added", startLine: 2, endLine: 99 }])).toEqual({ 3: "added", 4: "added" });
});
it("gives a line to the first marker that reaches it", () => {
expect(
markerLines(doc, [
{ kind: "added", startLine: 0, endLine: 2 },
{ kind: "modified", startLine: 1, endLine: 3 },
]),
).toEqual({ 1: "added", 2: "added", 3: "modified" });
});
});
describe("the gutter", () => {
it("queries when the view shows the state and draws the markers", async () => {
const engine = new FakeEngine();
engine.answer = { ranges: [{ kind: "added", startLine: 1, endLine: 2 }], version: 1 };
const view = viewOf("a\nb\nc", engine);
await flush();
expect(engine.calls).toEqual([{ id: 7 }]);
expect(markers(view)).toEqual({ 2: "added" });
expect(view.dom.querySelector("[data-kind='added']")?.getAttribute("title")).toBe("Added since the staged version");
});
it("asks again 150 ms after the last edit, once", async () => {
const engine = new FakeEngine();
const view = viewOf("a\nb", engine);
await flush();
expect(engine.calls).toHaveLength(1);
view.dispatch({ changes: { from: 0, insert: "x" } });
await flush(GIT_GUTTER_DEBOUNCE_MS - 50);
view.dispatch({ changes: { from: 0, insert: "y" } });
await flush(GIT_GUTTER_DEBOUNCE_MS - 1);
expect(engine.calls).toHaveLength(1);
engine.answer = { ranges: [{ kind: "modified", startLine: 0, endLine: 1 }], version: 3 };
await flush(1);
expect(engine.calls).toHaveLength(2);
expect(markers(view)).toEqual({ 1: "modified" });
});
it("drops an answer for a document that changed meanwhile", async () => {
const engine = new FakeEngine();
engine.hold = true;
engine.answer = { ranges: [{ kind: "added", startLine: 0, endLine: 1 }], version: 1 };
const view = viewOf("a\nb", engine);
await flush();
expect(engine.held).toHaveLength(1);
view.dispatch({ changes: { from: 0, insert: "x" } });
engine.held.shift()?.();
await flush();
expect(markers(view)).toEqual({});
});
it("keeps the markers when a query fails", async () => {
const engine = new FakeEngine();
engine.answer = { ranges: [{ kind: "added", startLine: 0, endLine: 1 }], version: 1 };
const view = viewOf("a\nb", engine);
await flush();
engine.fail = true;
refreshGitGutters();
await flush();
expect(engine.calls).toHaveLength(2);
expect(markers(view)).toEqual({ 1: "added" });
});
it("refreshes on refreshGitGutters and maps markers through edits", async () => {
const engine = new FakeEngine();
engine.answer = { ranges: [{ kind: "modified", startLine: 1, endLine: 2 }], version: 1 };
const view = viewOf("a\nb\nc", engine);
await flush();
expect(markers(view)).toEqual({ 2: "modified" });
view.dispatch({ changes: { from: 0, insert: "new\n" } });
expect(markers(view)).toEqual({ 3: "modified" });
view.dispatch({ changes: { from: view.state.doc.line(3).from, insert: "typed\n" } });
expect(markers(view)).toEqual({ 4: "modified" });
engine.answer = { ranges: [], version: 2 };
refreshGitGutters();
await flush();
expect(markers(view)).toEqual({});
});
it("stops asking once the view is gone", async () => {
const engine = new FakeEngine();
const view = viewOf("a", engine);
await flush();
view.destroy();
views = [];
refreshGitGutters();
await flush(GIT_GUTTER_DEBOUNCE_MS);
expect(engine.calls).toHaveLength(1);
});
it("adds nothing without a buffer", () => {
expect(gitGutterExtensions(undefined)).toEqual([]);
});
});
describe("colours", () => {
it("come from the status tokens only", () => {
const source = readFileSync(join(__dirname, "../../src/components/editor/gitGutter.ts"), "utf8");
expect(source).toContain("var(--lt-vcs-added)");
expect(source).toContain("var(--lt-vcs-modified)");
expect(source).toContain("var(--lt-vcs-deleted)");
expect(source).not.toMatch(/#[0-9a-fA-F]{3,8}\b|rgb\(/);
});
});