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

@ -8,7 +8,8 @@
* `theme.ts`; a failed theme report raises an error toast) and the global
* keymap with the UI commands (see `commands/store.ts`), and loads the settings so the
* editor font size applies from the start (see `stores/settings.ts`).
* Starts autosave (see `stores/autosave.ts`).
* Starts autosave (see `stores/autosave.ts`) and the Git status colours
* (see `stores/vcsStatus.ts`).
*/
import { onMounted, onUnmounted } from "vue";
import { useCommandsStore } from "./commands/store";
@ -24,6 +25,7 @@ import { useAppStore } from "./stores/app";
import { useAutosaveStore } from "./stores/autosave";
import { useNotificationsStore } from "./stores/notifications";
import { useSettingsStore } from "./stores/settings";
import { useVcsStatusStore } from "./stores/vcsStatus";
import { startTheme } from "./theme";
const app = useAppStore();
@ -31,6 +33,7 @@ const notifications = useNotificationsStore();
const commands = useCommandsStore();
const settings = useSettingsStore();
const autosave = useAutosaveStore();
const vcsStatus = useVcsStatusStore();
/** Stops following the theme; set while mounted. */
let stopTheme: (() => void) | null = null;
@ -41,6 +44,7 @@ onMounted(() => {
void commands.start();
void settings.start();
autosave.start();
vcsStatus.start();
void app.loadAbout();
});
@ -49,6 +53,7 @@ onUnmounted(() => {
stopTheme = null;
commands.stop();
autosave.stop();
vcsStatus.stop();
settings.stop();
notifications.stop();
});

View file

@ -4,13 +4,16 @@
*
* A click activates a tab, a middle click or the close button closes it,
* Left/Right move between tabs. A dot marks unsaved changes. Closing a
* dirty tab asks first (see the editor store).
* dirty tab asks first (see the editor store). Names are coloured by their
* Git status (`--lt-vcs-*`, M4.4).
*/
import { X } from "@lucide/vue";
import { t } from "../../i18n";
import { useEditorStore } from "../../stores/editor";
import { useVcsStatusStore } from "../../stores/vcsStatus";
const editor = useEditorStore();
const vcs = useVcsStatusStore();
/**
* Closes a tab on a middle click.
@ -67,7 +70,11 @@ function onKeydown(event: KeyboardEvent): void {
@mousedown.middle.prevent
@auxclick="onAuxClick($event, tab.id)"
>
<span class="tabs__name">{{ tab.name }}</span>
<span
class="tabs__name"
:class="vcs.colourOf(tab.path) ? `tabs__name--vcs-${vcs.colourOf(tab.path)}` : undefined"
:data-vcs="vcs.colourOf(tab.path) ?? undefined"
>{{ tab.name }}</span>
<span
v-if="tab.dirty"
class="tabs__dirty"
@ -127,6 +134,30 @@ function onKeydown(event: KeyboardEvent): void {
outline-offset: -1px;
}
.tabs__name--vcs-added {
color: var(--lt-vcs-added);
}
.tabs__name--vcs-modified {
color: var(--lt-vcs-modified);
}
.tabs__name--vcs-deleted {
color: var(--lt-vcs-deleted);
}
.tabs__name--vcs-untracked {
color: var(--lt-vcs-untracked);
}
.tabs__name--vcs-ignored {
color: var(--lt-vcs-ignored);
}
.tabs__name--vcs-conflicted {
color: var(--lt-vcs-conflicted);
}
.tabs__dirty {
width: 7px;
height: 7px;

View file

@ -5,7 +5,8 @@
* `--lt-*` tokens, including the syntax tokens (`--lt-syntax-*`) and
* 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`).
* `--lt-editor-match-bg`, `--lt-font-size-editor`). Buffers also get Git
* change markers in the gutter (`gitGutter.ts`).
*/
import { EditorView } from "@codemirror/view";
import type { Extension } from "@codemirror/state";
@ -14,6 +15,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 { gitGutterExtensions } from "./gitGutter";
/**
* Colours of the highlight classes (`language.ts`), one `--lt-syntax-*`
@ -122,5 +124,6 @@ export function editorExtensions(path = "", buffer?: AssistBuffer): Extension {
lintExtensions(path),
assistExtensions(path, buffer),
navExtensions(),
gitGutterExtensions(buffer),
];
}

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),
];
}

View file

@ -8,16 +8,20 @@
* to the parent, Enter opens a file or toggles a folder. Double-click does
* the same as Enter. Ignored and excluded entries are dimmed. A directory
* the engine listed only partly ends with a "listing truncated" note.
* File names are coloured by their Git status (`--lt-vcs-*`, M4.4); inside
* a repository, ignored entries take the ignored colour.
*/
import { ChevronDown, ChevronRight, File, FileCode, Folder, FolderOpen } from "@lucide/vue";
import { computed, nextTick, ref } from "vue";
import { t } from "../../i18n";
import { parentOf, useProjectStore, type TreeRow } from "../../stores/project";
import { useEditorStore } from "../../stores/editor";
import { useVcsStatusStore, type VcsColour } from "../../stores/vcsStatus";
import type { TreeEntry } from "./engineEvents";
const project = useProjectStore();
const editor = useEditorStore();
const vcs = useVcsStatusStore();
/** The tree element, for keeping the selected row in view. */
const treeEl = ref<HTMLElement | null>(null);
@ -64,6 +68,18 @@ function isDimmed(entry: TreeEntry): boolean {
return entry.ignored || entry.excluded === true;
}
/**
* The Git status colour of an entry's name: a file's status, else the
* ignored colour for an ignored entry inside a repository.
*
* @param entry - the entry.
* @returns the token name, or null for the normal colour.
*/
function vcsColour(entry: TreeEntry): VcsColour | null {
const colour = entry.kind === "file" ? vcs.colourOf(entry.path) : null;
return colour ?? (vcs.repo && entry.ignored ? "ignored" : null);
}
/**
* Whether a file name looks like PHP source, for the code icon.
*
@ -277,7 +293,11 @@ function onFocus(): void {
:size="16"
/>
</span>
<span class="tree__name">{{ row.entry.name }}</span>
<span
class="tree__name"
:class="vcsColour(row.entry) ? `tree__name--vcs-${vcsColour(row.entry)}` : undefined"
:data-vcs="vcsColour(row.entry) ?? undefined"
>{{ row.entry.name }}</span>
</div>
<div
v-else-if="row.kind === 'loading'"
@ -376,4 +396,28 @@ function onFocus(): void {
overflow: hidden;
text-overflow: ellipsis;
}
.tree__name--vcs-added {
color: var(--lt-vcs-added);
}
.tree__name--vcs-modified {
color: var(--lt-vcs-modified);
}
.tree__name--vcs-deleted {
color: var(--lt-vcs-deleted);
}
.tree__name--vcs-untracked {
color: var(--lt-vcs-untracked);
}
.tree__name--vcs-ignored {
color: var(--lt-vcs-ignored);
}
.tree__name--vcs-conflicted {
color: var(--lt-vcs-conflicted);
}
</style>

View file

@ -64,6 +64,9 @@
"editor.assist.kind.variable": "Variable",
"editor.assist.signature.count": "{index} of {count}",
"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",
"editor.gitGutter.modified": "Changed since the staged version",
"editor.notice.changedOnDisk": "{name} changed on disk. Your unsaved changes are kept; saving overwrites the file.",
"editor.notice.removedOnDisk": "{name} was deleted on disk. Your text is kept; saving writes it again.",
"editor.reveal.invalidParams": "editor.reveal needs a path (string), line and column (numbers)",

244
ui/src/stores/vcsStatus.ts Normal file
View file

@ -0,0 +1,244 @@
/**
* Git status of the project's files for colouring file names in the
* project tree and the editor tabs (M4.4).
*
* - **Source:** `git.status` (a pending outcome, so through `runWaiting`)
* on start, when a project opens and on every `gitChanged`; never
* polled. One query runs at a time; requests made while it runs share
* one more query after it.
* - **Colour:** {@link statusColour} folds a file's index and work tree
* states into one of the `--lt-vcs-*` tokens. Ignored files are not in
* `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.
*
* Results are untrusted: malformed files are skipped, a failed query
* keeps the last state and shows nothing (the Changes window reports git
* problems).
*/
import { defineStore } from "pinia";
import { shallowRef } from "vue";
import { onEngineEvent, runWaiting, type EngineEventPayload } from "../ipc";
import { refreshGitGutters } from "../components/editor/gitGutter";
/** A file state as `git.status` names it. */
export type GitFileState =
| "unmodified"
| "modified"
| "added"
| "deleted"
| "renamed"
| "copied"
| "untracked"
| "ignored"
| "conflicted";
/** The status token names (`--lt-vcs-<name>`). */
export type VcsColour = "added" | "modified" | "deleted" | "untracked" | "ignored" | "conflicted";
/** Every state `git.status` may report. */
const STATES = new Set<string>([
"unmodified",
"modified",
"added",
"deleted",
"renamed",
"copied",
"untracked",
"ignored",
"conflicted",
]);
/** Whether a value is a file state. */
function isState(value: unknown): value is GitFileState {
return typeof value === "string" && STATES.has(value);
}
/**
* The colour of a file from its two states: conflicts first, then
* untracked, ignored, added, deleted, and any other change as modified.
*
* @param index - the staged side.
* @param worktree - the work tree side.
* @returns the token name, or null for an unchanged file.
*/
export function statusColour(index: GitFileState, worktree: GitFileState): VcsColour | null {
const sides = [index, worktree];
if (sides.includes("conflicted")) {
return "conflicted";
}
if (sides.includes("untracked")) {
return "untracked";
}
if (sides.includes("ignored")) {
return "ignored";
}
if (index === "added") {
return worktree === "deleted" ? null : "added";
}
if (sides.includes("deleted")) {
return "deleted";
}
if (sides.some((side) => side !== "unmodified")) {
return "modified";
}
return null;
}
/**
* Reads the colours of a `git.status` result.
*
* @param value - the untrusted result.
* @returns colour by project-relative path, and whether a repository is
* open; null when the result is not an object.
*/
export function readStatus(value: unknown): { colours: Map<string, VcsColour>; repo: boolean } | null {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
return null;
}
const record = value as Record<string, unknown>;
const colours = new Map<string, VcsColour>();
const files = Array.isArray(record.files) ? (record.files as unknown[]) : [];
for (const file of files) {
if (typeof file !== "object" || file === null) {
continue;
}
const { path, index, worktree } = file as Record<string, unknown>;
if (typeof path !== "string" || !isState(index) || !isState(worktree)) {
continue;
}
const colour = statusColour(index, worktree);
if (colour !== null) {
colours.set(path, colour);
}
}
const repo = record.available === true && typeof record.repo === "object" && record.repo !== null;
return { colours, repo };
}
/** How the store reaches the engine; replaced in tests. */
export interface VcsStatusTransport {
/** Runs `git.status`. */
status(): Promise<{ ok: true; value: unknown } | { ok: false }>;
}
/** The transport through the engine IPC. */
const engineTransport: VcsStatusTransport = {
status: () => runWaiting<unknown>("git.status", {}),
};
export const useVcsStatusStore = defineStore("vcsStatus", () => {
/** Colour by project-relative path, for changed files only. */
const colours = shallowRef<ReadonlyMap<string, VcsColour>>(new Map());
/** Whether the project is inside a repository with a usable git. */
const repo = shallowRef(false);
let transport: VcsStatusTransport = engineTransport;
let running: Promise<void> | null = null;
const queued = { again: false };
let generation = 0;
let unsubscribe: (() => void) | null = null;
/**
* Replaces the transport (tests).
*
* @param next - the transport.
*/
function configure(next: VcsStatusTransport): void {
transport = next;
}
/** Runs `git.status` once and applies it unless the project changed. */
async function query(): Promise<void> {
const asked = generation;
const result = await transport.status();
if (!result.ok || asked !== generation) {
return;
}
const read = readStatus(result.value);
if (read !== null) {
colours.value = read.colours;
repo.value = read.repo;
}
}
/** Whether a refresh was asked for while the last query ran. */
function wantsAgain(): boolean {
return queued.again;
}
/**
* Refreshes the status: starts a query, or, while one runs, makes sure
* one more runs after it.
*
* @returns resolves when the status is current.
*/
function refresh(): Promise<void> {
if (running !== null) {
queued.again = true;
return running;
}
running = (async () => {
do {
queued.again = false;
await query();
} while (wantsAgain());
running = null;
})();
return running;
}
/** Forgets everything (project closed). */
function clear(): void {
generation += 1;
colours.value = new Map();
repo.value = false;
}
/**
* The colour of a file name.
*
* @param path - project-relative path with `/`.
* @returns the token name, or null when unchanged or unknown.
*/
function colourOf(path: string): VcsColour | null {
return colours.value.get(path) ?? null;
}
/** Handles one engine event. */
function handle(event: EngineEventPayload): void {
switch (event.kind) {
case "projectOpened":
clear();
void refresh();
break;
case "projectClosed":
clear();
break;
case "gitChanged":
void refresh();
refreshGitGutters();
break;
default:
break;
}
}
/** Starts following the engine and queries once; repeated calls do nothing. */
function start(): void {
if (unsubscribe !== null) {
return;
}
unsubscribe = onEngineEvent(handle);
void refresh();
}
/** Stops following the engine. */
function stop(): void {
unsubscribe?.();
unsubscribe = null;
}
return { colours, repo, configure, refresh, clear, colourOf, handle, start, stop };
});

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();
});
});