Lutra/ui/tests/project/ProjectTree.test.ts
danny fc8ae6c2e3 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>
2026-10-25 17:40:30 +01:00

295 lines
12 KiB
TypeScript

/**
* Tests for the Project tool window: empty state, lazy expansion, keyboard
* 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`.
*/
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { createPinia, setActivePinia } from "pinia";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const invoke = vi.hoisted(() => vi.fn());
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. */
interface EngineEntry {
/** Display name. */
name: string;
/** Project-relative path. */
path: string;
/** Engine kind. */
kind: "directory" | "file" | "other";
/** Matched by an ignore rule. */
ignored: boolean;
/** Lutra's role for the entry. */
role: "normal" | "library" | "excluded";
}
/** In-memory folder listings by directory, as `project.children` returns them. */
let folder: Record<string, EngineEntry[]>;
/** Directories whose mock listing reports `truncated: true`. */
let truncatedDirs: Set<string>;
/**
* Builds an entry.
*
* @param path - project-relative path.
* @param kind - entry kind.
* @param ignored - ignore flag.
*/
function entry(path: string, kind: "dir" | "file", ignored = false): EngineEntry {
const engineKind = kind === "dir" ? "directory" : "file";
const role = path === "node_modules" ? "excluded" : path === "vendor" ? "library" : "normal";
return { name: path.split("/").pop() ?? path, path, kind: engineKind, ignored, role };
}
/** Mock engine: answers `project.children`, accepts other commands. */
function engine(command: string, args: { command: string; params: { dir?: string } }): unknown {
if (command !== "engine_execute") {
return Promise.reject(new Error(`unexpected ${command}`));
}
if (args.command === "project.children") {
const dir = args.params.dir ?? "";
const entries = folder[dir];
return entries
? Promise.resolve({ dir, entries, truncated: truncatedDirs.has(dir) })
: Promise.reject(Object.assign(new Error(`cannot list ${dir}`), { code: "not_found" }));
}
return Promise.resolve(null);
}
/** Mounts the tool window and opens the mock project through an event. */
async function mountOpen(): Promise<VueWrapper> {
const wrapper = mount(ProjectToolWindow, { attachTo: document.body });
emitEngineEvent({ kind: "projectOpened", root: "/tmp/demo", name: "demo" });
await flushPromises();
return wrapper;
}
/** Visible entry paths, in order. */
function paths(wrapper: VueWrapper): string[] {
return wrapper.findAll("[data-test=tree-row]").map((row) => row.attributes("data-path") ?? "");
}
/**
* Presses a key on the tree and waits for the engine.
*
* @param wrapper - the mounted tool window.
* @param key - the key name.
*/
async function press(wrapper: VueWrapper, key: string): Promise<void> {
await wrapper.get("[data-test=project-tree]").trigger("keydown", { key });
await flushPromises();
}
/** Path of the selected row, or null. */
function selectedPath(wrapper: VueWrapper): string | null {
const row = wrapper.find("[data-test=tree-row][aria-selected=true]");
return row.exists() ? (row.attributes("data-path") ?? null) : null;
}
/** Calls of `project.children`, as the `dir` params. */
function childrenCalls(): string[] {
return invoke.mock.calls
.filter((call) => (call[1] as { command: string }).command === "project.children")
.map((call) => (call[1] as { params: { dir: string } }).params.dir);
}
describe("ProjectToolWindow", () => {
let wrapper: VueWrapper | null = null;
beforeEach(() => {
setActivePinia(createPinia());
invoke.mockReset();
invoke.mockImplementation(engine);
truncatedDirs = new Set();
folder = {
"": [entry("src", "dir"), entry("vendor", "dir"), entry("node_modules", "dir", true), entry("index.php", "file")],
src: [entry("src/Controller", "dir"), entry("src/App.php", "file")],
"src/Controller": [entry("src/Controller/Home.php", "file")],
};
});
afterEach(() => {
wrapper?.unmount();
wrapper = null;
});
it("shows the empty state and runs the open-folder command", async () => {
wrapper = mount(ProjectToolWindow);
expect(wrapper.find("[data-test=project-empty]").exists()).toBe(true);
await wrapper.get("[data-test=open-folder]").trigger("click");
await flushPromises();
expect(invoke).toHaveBeenCalledWith("engine_execute", { command: "project.openDialog", params: {} });
});
it("shows an open-folder failure", async () => {
invoke.mockRejectedValue({ code: "internal", message: "no dialog" });
wrapper = mount(ProjectToolWindow);
await wrapper.get("[data-test=open-folder]").trigger("click");
await flushPromises();
expect(wrapper.get("[data-test=project-error]").text()).toBe("no dialog");
});
it("lists the root after ProjectOpened and dims ignored entries", async () => {
wrapper = await mountOpen();
expect(paths(wrapper)).toEqual(["src", "vendor", "node_modules", "index.php"]);
expect(childrenCalls()).toEqual([""]);
const rows = wrapper.findAll("[data-test=tree-row]");
expect(rows[2]?.classes()).toContain("tree__row--dimmed");
expect(rows[0]?.classes()).not.toContain("tree__row--dimmed");
});
it("expands lazily on chevron click and collapses again", async () => {
wrapper = await mountOpen();
await wrapper.findAll("[data-test=tree-chevron]")[0]?.trigger("click");
await flushPromises();
expect(paths(wrapper)).toEqual(["src", "src/Controller", "src/App.php", "vendor", "node_modules", "index.php"]);
expect(childrenCalls()).toEqual(["", "src"]);
await wrapper.findAll("[data-test=tree-chevron]")[0]?.trigger("click");
await flushPromises();
expect(paths(wrapper)).toEqual(["src", "vendor", "node_modules", "index.php"]);
await wrapper.findAll("[data-test=tree-chevron]")[0]?.trigger("click");
await flushPromises();
expect(childrenCalls()).toEqual(["", "src"]);
});
it("navigates with the keyboard", async () => {
wrapper = await mountOpen();
await wrapper.get("[data-test=project-tree]").trigger("focus");
expect(selectedPath(wrapper)).toBe("src");
await press(wrapper, "ArrowRight");
expect(paths(wrapper)).toContain("src/App.php");
expect(selectedPath(wrapper)).toBe("src");
await press(wrapper, "ArrowRight");
expect(selectedPath(wrapper)).toBe("src/Controller");
await press(wrapper, "Enter");
expect(paths(wrapper)).toContain("src/Controller/Home.php");
await press(wrapper, "ArrowDown");
expect(selectedPath(wrapper)).toBe("src/Controller/Home.php");
await press(wrapper, "Enter");
expect(invoke).toHaveBeenCalledWith("engine_execute", {
command: "file.open",
params: { path: "src/Controller/Home.php" },
});
await press(wrapper, "ArrowLeft");
expect(selectedPath(wrapper)).toBe("src/Controller");
await press(wrapper, "ArrowLeft");
expect(paths(wrapper)).not.toContain("src/Controller/Home.php");
await press(wrapper, "ArrowUp");
expect(selectedPath(wrapper)).toBe("src");
await press(wrapper, "ArrowUp");
expect(selectedPath(wrapper)).toBe("src");
await press(wrapper, "End");
expect(selectedPath(wrapper)).toBe("index.php");
await press(wrapper, "ArrowDown");
expect(selectedPath(wrapper)).toBe("index.php");
await press(wrapper, "Home");
expect(selectedPath(wrapper)).toBe("src");
const tree = wrapper.get("[data-test=project-tree]");
expect(tree.attributes("aria-activedescendant")).toBe(wrapper.get("[aria-selected=true]").attributes("id"));
});
it("reloads a loaded directory on TreeChanged and drops removed entries", async () => {
wrapper = await mountOpen();
await wrapper.get("[data-test=project-tree]").trigger("focus");
await press(wrapper, "ArrowRight");
await press(wrapper, "ArrowRight");
await press(wrapper, "ArrowRight");
expect(selectedPath(wrapper)).toBe("src/Controller");
folder.src = [entry("src/App.php", "file"), entry("src/Kernel.php", "file")];
emitEngineEvent({ kind: "treeChanged", dir: "src" });
await flushPromises();
expect(paths(wrapper)).toEqual(["src", "src/App.php", "src/Kernel.php", "vendor", "node_modules", "index.php"]);
expect(selectedPath(wrapper)).toBeNull();
const store = useProjectStore();
expect(store.expanded.has("src/Controller")).toBe(false);
expect(store.dirs["src/Controller"]).toBeUndefined();
});
it("ignores TreeChanged for directories never loaded", async () => {
wrapper = await mountOpen();
emitEngineEvent({ kind: "treeChanged", dir: "vendor" });
await flushPromises();
expect(childrenCalls()).toEqual([""]);
});
it("shows a project.children error in the tree instead of throwing", async () => {
wrapper = await mountOpen();
await wrapper.findAll("[data-test=tree-chevron]")[1]?.trigger("click");
await flushPromises();
const error = wrapper.get("[data-test=tree-error]");
expect(error.text()).toBe("cannot list vendor");
expect(paths(wrapper)).toEqual(["src", "vendor", "node_modules", "index.php"]);
});
it("keeps old entries when a refresh fails", async () => {
wrapper = await mountOpen();
Reflect.deleteProperty(folder, "");
emitEngineEvent({ kind: "treeChanged", dir: "" });
await flushPromises();
expect(wrapper.get("[data-test=tree-error]").text()).toBe("cannot list");
expect(paths(wrapper)).toEqual(["src", "vendor", "node_modules", "index.php"]);
});
it("shows a truncated note after a directory the engine listed only partly", async () => {
truncatedDirs = new Set(["src"]);
wrapper = await mountOpen();
expect(wrapper.find("[data-test=tree-truncated]").exists()).toBe(false);
await wrapper.findAll("[data-test=tree-chevron]")[0]?.trigger("click");
await flushPromises();
const notes = wrapper.findAll("[data-test=tree-truncated]");
expect(notes).toHaveLength(1);
expect(notes[0]?.text()).toBe(t("project.tree.truncated"));
expect(notes[0]?.attributes("role")).toBeUndefined();
const order = wrapper
.findAll("[data-test=tree-row], [data-test=tree-truncated]")
.map((row) => row.attributes("data-path") ?? "note");
expect(order).toEqual(["src", "src/Controller", "src/App.php", "note", "vendor", "node_modules", "index.php"]);
await press(wrapper, "End");
expect(selectedPath(wrapper)).toBe("index.php");
});
it("returns to the empty state on ProjectClosed and unsubscribes on unmount", async () => {
wrapper = await mountOpen();
emitEngineEvent({ kind: "projectClosed" });
await flushPromises();
expect(wrapper.find("[data-test=project-empty]").exists()).toBe(true);
wrapper.unmount();
wrapper = null;
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();
});
});