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,253 @@
/**
* 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" });
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\(/);
});
});

View file

@ -1,7 +1,7 @@
/**
* Tests for the Project tool window: empty state, lazy expansion, keyboard
* navigation, refresh on `TreeChanged`, error display and the truncated
* listing note. The engine is
* navigation, refresh on `TreeChanged`, error display, the truncated
* listing note and Git status colours (M4.4). The engine is
* mocked: `invoke` answers `project.children` from an in-memory folder and
* events go through the local dispatcher in `engineEvents.ts`.
*/
@ -15,6 +15,7 @@ vi.mock("@tauri-apps/api/core", () => ({ invoke }));
import { emitEngineEvent } from "../../src/components/project/engineEvents";
import ProjectToolWindow from "../../src/components/project/ProjectToolWindow.vue";
import { useProjectStore } from "../../src/stores/project";
import { useVcsStatusStore } from "../../src/stores/vcsStatus";
import { t } from "../../src/i18n";
/** An entry as the engine's `project.children` returns it. */
@ -267,4 +268,28 @@ describe("ProjectToolWindow", () => {
emitEngineEvent({ kind: "projectOpened", root: "/tmp/other", name: "other" });
expect(useProjectStore().root).toBeNull();
});
it("colours file names by Git status, and ignored entries inside a repository", async () => {
const vcs = useVcsStatusStore();
vcs.configure({
status: () =>
Promise.resolve({
ok: true,
value: {
available: true,
repo: { root: "/tmp/demo", detached: false },
files: [{ path: "index.php", index: "unmodified", worktree: "modified" }],
},
}),
});
const mounted = await mountOpen();
wrapper = mounted;
await vcs.refresh();
await flushPromises();
const name = (path: string) => mounted.get(`[data-test=tree-row][data-path="${path}"] .tree__name`);
expect(name("index.php").attributes("data-vcs")).toBe("modified");
expect(name("index.php").classes()).toContain("tree__name--vcs-modified");
expect(name("node_modules").attributes("data-vcs")).toBe("ignored");
expect(name("src").attributes("data-vcs")).toBeUndefined();
});
});

View file

@ -9,7 +9,7 @@
* meant to vanish into it is exempt per theme (`TERMINAL_EXEMPT`). Every
* diagnostic severity (`--lt-diag-*`) and version-control status
* (`--lt-vcs-*`) colour reaches 4.5:1 on the editor background, the active
* line and the window background, and every completion kind icon colour
* line and the window background (and on the active tab, M4.4), and every completion kind icon colour
* reaches 3:1 on the popup and its selected row (H5). The
* themes come from
* `themes.json`, a snapshot that the Rust test `ui_snapshot_is_current`
@ -88,6 +88,13 @@ const STATUS_PAIRS: [string, string, number][] = [
...VCS.map((name) => `vcs-${name}`),
].flatMap((fg) => STATUS_BACKGROUNDS.map((bg): [string, string, number] => [fg, bg, TEXT]));
/** Status colours as tab names on the active tab (M4.4). */
const TAB_STATUS_PAIRS: [string, string, number][] = VCS.map((name): [string, string, number] => [
`vcs-${name}`,
"tab-active-bg",
TEXT,
]);
/** Every completion kind icon colour on the popup and its selected row. */
const KIND_PAIRS: [string, string, number][] = [...new Set(Object.values(KIND_COLOURS))].flatMap(
(fg): [string, string, number][] => [
@ -196,7 +203,7 @@ describe.each(themes)("theme $id", (theme) => {
expect(defined).toHaveLength(ANSI.length * 2);
});
it.each([...PAIRS, ...SYNTAX_PAIRS, ...STATUS_PAIRS, ...KIND_PAIRS, ...terminalPairs(theme.id)])("%s on %s reaches %d:1", (fg, bg, min) => {
it.each([...PAIRS, ...SYNTAX_PAIRS, ...STATUS_PAIRS, ...TAB_STATUS_PAIRS, ...KIND_PAIRS, ...terminalPairs(theme.id)])("%s on %s reaches %d:1", (fg, bg, min) => {
expect(contrast(token(fg), token(bg))).toBeGreaterThanOrEqual(min);
});
});

View file

@ -0,0 +1,155 @@
/**
* Tests of the Git status colours (M4.4, `stores/vcsStatus.ts`): folding
* index and work tree states into a colour, reading untrusted
* `git.status` results, one query at a time with one more after it,
* reacting to `projectOpened`, `projectClosed` and `gitChanged` (which
* also refreshes the gutters), and coloured tab names.
*/
import { flushPromises, mount } from "@vue/test-utils";
import { createPinia, setActivePinia } from "pinia";
import { beforeEach, describe, expect, it, vi } from "vitest";
const refreshGitGutters = vi.hoisted(() => vi.fn());
vi.mock("../../src/components/editor/gitGutter", () => ({ refreshGitGutters }));
import EditorTabs from "../../src/components/editor/EditorTabs.vue";
import { useEditorStore } from "../../src/stores/editor";
import { readStatus, statusColour, useVcsStatusStore, type VcsStatusTransport } from "../../src/stores/vcsStatus";
/** A `git.status` result with `files`. */
function status(files: unknown[]): unknown {
return { available: true, repo: { root: "/r", branch: "main", detached: false }, files };
}
/** A transport whose answers the test releases one by one. */
class HeldTransport implements VcsStatusTransport {
/** Queries waiting for an answer. */
readonly waiting: ((value: unknown) => void)[] = [];
status(): Promise<{ ok: true; value: unknown }> {
return new Promise((resolve) => {
this.waiting.push((value) => {
resolve({ ok: true, value });
});
});
}
}
beforeEach(() => {
setActivePinia(createPinia());
refreshGitGutters.mockReset();
});
describe("statusColour", () => {
it("puts conflicts first, then untracked, added, deleted and other changes", () => {
expect(statusColour("conflicted", "conflicted")).toBe("conflicted");
expect(statusColour("untracked", "untracked")).toBe("untracked");
expect(statusColour("added", "unmodified")).toBe("added");
expect(statusColour("added", "modified")).toBe("added");
expect(statusColour("added", "deleted")).toBeNull();
expect(statusColour("deleted", "unmodified")).toBe("deleted");
expect(statusColour("unmodified", "deleted")).toBe("deleted");
expect(statusColour("modified", "unmodified")).toBe("modified");
expect(statusColour("renamed", "modified")).toBe("modified");
expect(statusColour("unmodified", "unmodified")).toBeNull();
});
});
describe("readStatus", () => {
it("skips malformed files and notes whether a repository is open", () => {
const read = readStatus(
status([
{ path: "a.php", index: "unmodified", worktree: "modified" },
{ path: "b.php", index: "bogus", worktree: "modified" },
{ path: 3, index: "added", worktree: "unmodified" },
"x",
]),
);
expect(read?.repo).toBe(true);
expect([...(read?.colours ?? [])]).toEqual([["a.php", "modified"]]);
expect(readStatus({ available: true, repo: null, files: [] })?.repo).toBe(false);
expect(readStatus({ available: false, repo: null, files: [] })?.repo).toBe(false);
expect(readStatus("nope")).toBeNull();
});
});
describe("the store", () => {
it("runs one query at a time and one more for requests made meanwhile", async () => {
const transport = new HeldTransport();
const store = useVcsStatusStore();
store.configure(transport);
const first = store.refresh();
void store.refresh();
void store.refresh();
expect(transport.waiting).toHaveLength(1);
transport.waiting.shift()?.(status([{ path: "a.php", index: "unmodified", worktree: "modified" }]));
await flushPromises();
expect(store.colourOf("a.php")).toBe("modified");
expect(transport.waiting).toHaveLength(1);
transport.waiting.shift()?.(status([]));
await first;
expect(store.colourOf("a.php")).toBeNull();
expect(transport.waiting).toHaveLength(0);
});
it("refreshes on projectOpened and gitChanged, clears on projectClosed", async () => {
let answer = status([{ path: "n.php", index: "untracked", worktree: "untracked" }]);
const store = useVcsStatusStore();
const calls = vi.fn(() => Promise.resolve({ ok: true as const, value: answer }));
store.configure({ status: calls });
store.handle({ kind: "projectOpened", root: "/r", name: "r" });
await flushPromises();
expect(store.colourOf("n.php")).toBe("untracked");
expect(store.repo).toBe(true);
answer = status([{ path: "n.php", index: "added", worktree: "unmodified" }]);
store.handle({ kind: "gitChanged", available: true, repo: {}, filesChanged: true });
await flushPromises();
expect(store.colourOf("n.php")).toBe("added");
expect(refreshGitGutters).toHaveBeenCalledTimes(1);
store.handle({ kind: "projectClosed" });
expect(store.colourOf("n.php")).toBeNull();
expect(store.repo).toBe(false);
expect(calls).toHaveBeenCalledTimes(2);
});
it("ignores an answer for a project that closed meanwhile and keeps the state on failure", async () => {
const transport = new HeldTransport();
const store = useVcsStatusStore();
store.configure(transport);
void store.refresh();
store.clear();
transport.waiting.shift()?.(status([{ path: "a.php", index: "modified", worktree: "unmodified" }]));
await flushPromises();
expect(store.colourOf("a.php")).toBeNull();
store.configure({ status: () => Promise.resolve({ ok: true, value: status([{ path: "b.php", index: "deleted", worktree: "unmodified" }]) }) });
await store.refresh();
store.configure({ status: () => Promise.resolve({ ok: false }) });
await store.refresh();
expect(store.colourOf("b.php")).toBe("deleted");
});
});
describe("tabs", () => {
it("colour the names of changed files", async () => {
const store = useVcsStatusStore();
store.configure({
status: () => Promise.resolve({ ok: true, value: status([{ path: "src/A.php", index: "unmodified", worktree: "modified" }]) }),
});
await store.refresh();
const editor = useEditorStore();
editor.tabs = [
{ id: 1, path: "src/A.php", name: "A.php", dirty: false, notice: null },
{ id: 2, path: "src/B.php", name: "B.php", dirty: false, notice: null },
];
const wrapper = mount(EditorTabs);
await flushPromises();
const names = wrapper.findAll(".tabs__name");
expect(names[0]?.attributes("data-vcs")).toBe("modified");
expect(names[0]?.classes()).toContain("tabs__name--vcs-modified");
expect(names[1]?.attributes("data-vcs")).toBeUndefined();
wrapper.unmount();
});
});