Lutra/ui/tests/editor/tabs.test.ts
danny 4c3d5cc460
Some checks failed
ci / ci (macos-15) (push) Has been cancelled
ci / ci (ubuntu-24.04) (push) Has been cancelled
ci / ci (windows-2025) (push) Has been cancelled
A2: tests follow history.show being registered next to A1's tab menu
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 17:04:08 +01:00

571 lines
21 KiB
TypeScript

/**
* Tests for tab management in the editor area (C10 A1): preview tabs from
* the project tree and their setting, pinning, bulk closes with one
* question for every unsaved file, the context menu, reopening a closed
* tab with its selection, splitting with one shared buffer, the stored
* layout per project and the public API for other areas. The engine is a
* fake behind the mocked Tauri `invoke`.
*/
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { EditorView, runScopeHandlers } from "@codemirror/view";
import { createPinia, setActivePinia, type Pinia } from "pinia";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
const invoke = vi.hoisted(() => vi.fn());
vi.mock("@tauri-apps/api/core", () => ({ invoke }));
import { useCommandsStore } from "../../src/commands/store";
import EditorArea from "../../src/components/editor/EditorArea.vue";
import { emitEditorEvent } from "../../src/components/editor/engineEvents";
import { emitEngineEvent } from "../../src/components/project/engineEvents";
import ProjectToolWindow from "../../src/components/project/ProjectToolWindow.vue";
import { COMMAND_IDS } from "../../src/components/editor/tabs/commands";
import { PREVIEW_SETTING, useEditorStore } from "../../src/stores/editor";
import { useSettingsStore } from "../../src/stores/settings";
/** A buffer of the fake engine. */
interface FakeBuffer {
path: string;
text: string;
version: number;
saved: number;
}
/** Fake engine state. */
let buffers: Map<number, FakeBuffer>;
/** Files on the fake disk. */
let disk: Record<string, string>;
/** Next buffer id. */
let nextId: number;
/** Every `engine_execute` call, in order. */
let calls: { command: string; params: Record<string, unknown> }[];
/** What `layout.get` returns. */
let storedLayout: unknown;
/** Pinia of the current test. */
let pinia: Pinia;
/** Mounted components to unmount after each test. */
let mounted: VueWrapper[] = [];
/**
* Describes a buffer as `file.open` and `buffer.get` do.
*
* @param id - buffer id.
*/
function describeBuffer(id: number): unknown {
const b = buffers.get(id);
return b ? { id, path: b.path, text: b.text, version: b.version, dirty: b.version !== b.saved, lineEnding: "lf" } : null;
}
/**
* Rejects like the shell does with an engine error.
*
* @param code - error code.
*/
function fail(code: string): Promise<never> {
return Promise.reject(Object.assign(new Error(code), { code, message: code }));
}
/**
* The fake engine's command handler.
*
* @param command - command id.
* @param p - params.
*/
function execute(command: string, p: Record<string, unknown>): Promise<unknown> {
const id = typeof p.id === "number" ? p.id : -1;
const b = buffers.get(id);
switch (command) {
case "file.open": {
const path = String(p.path);
for (const [existing, buffer] of buffers) {
if (buffer.path === path) {
return Promise.resolve(describeBuffer(existing));
}
}
const text = disk[path];
if (text === undefined) {
return fail("not_found");
}
const newId = nextId++;
buffers.set(newId, { path, text, version: 1, saved: 1 });
return Promise.resolve(describeBuffer(newId));
}
case "buffer.get":
return b ? Promise.resolve(describeBuffer(id)) : fail("failed");
case "buffer.edit": {
if (!b) {
return fail("failed");
}
let out = "";
let pos = 0;
for (const e of p.edits as { from: number; to: number; insert: string }[]) {
out += b.text.slice(pos, e.from) + e.insert;
pos = e.to;
}
const wasDirty = b.version !== b.saved;
b.text = out + b.text.slice(pos);
b.version += 1;
if (!wasDirty) {
emitEditorEvent({ kind: "dirtyChanged", id, dirty: true });
}
return Promise.resolve({ id, version: b.version, dirty: true });
}
case "file.save":
if (!b) {
return fail("failed");
}
disk[b.path] = b.text;
b.saved = b.version;
emitEditorEvent({ kind: "dirtyChanged", id, dirty: false });
return Promise.resolve({ id, version: b.version });
case "buffer.close":
if (!b) {
return fail("failed");
}
if (b.version !== b.saved && p.force !== true) {
return fail("unsaved_changes");
}
buffers.delete(id);
emitEditorEvent({ kind: "bufferClosed", id });
return Promise.resolve(null);
case "layout.get":
return Promise.resolve({ layout: storedLayout });
case "layout.set":
return Promise.resolve({ stored: true });
case "project.children":
return Promise.resolve({
dir: "",
entries: Object.keys(disk).map((path) => ({ name: path, path, kind: "file", ignored: false, role: "normal" })),
truncated: false,
});
default:
return Promise.resolve(null);
}
}
/**
* jsdom has no layout; CodeMirror measures text ranges, so give ranges
* empty rectangles.
*/
function stubRangeGeometry(): void {
const empty = (): DOMRectList => Object.assign([] as DOMRect[], { item: () => null });
Range.prototype.getClientRects = empty;
Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0);
}
/** Fresh Pinia and a fake engine with four files on its disk. */
function resetFakeEngine(): void {
stubRangeGeometry();
pinia = createPinia();
setActivePinia(pinia);
buffers = new Map();
disk = { "a.php": "<?php\necho 1;\n", "b.php": "<?php\necho 2;\n", "c.php": "<?php\necho 3;\n", "d.php": "<?php\n" };
nextId = 1;
calls = [];
storedLayout = null;
invoke.mockReset();
invoke.mockImplementation((cmd: string, args?: { command: string; params: Record<string, unknown> }) => {
if (cmd === "engine_list_commands") {
return Promise.resolve([]);
}
if (cmd === "engine_execute" && args) {
calls.push({ command: args.command, params: args.params });
return execute(args.command, args.params);
}
return Promise.reject(new Error(`unexpected ${cmd}`));
});
}
beforeEach(resetFakeEngine);
afterEach(async () => {
await flushPromises();
useCommandsStore(pinia).stop();
for (const wrapper of mounted) {
wrapper.unmount();
}
mounted = [];
vi.useRealTimers();
});
/** Mounts the editor area and starts the command store. */
async function mountArea(): Promise<VueWrapper> {
await useCommandsStore(pinia).start();
const wrapper = mount(EditorArea, { attachTo: document.body, slots: { default: "empty" }, global: { plugins: [pinia] } });
mounted.push(wrapper);
await flushPromises();
return wrapper;
}
/** Mounts the project tree with the fake project open. */
async function mountTree(): Promise<VueWrapper> {
const tree = mount(ProjectToolWindow, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(tree);
emitEngineEvent({ kind: "projectOpened", root: "/tmp/demo", name: "demo" });
await flushPromises();
return tree;
}
/**
* Names on the tab bar of a group, `*` marking previews and `^` pins.
*
* @param area - the mounted area.
* @param group - group index.
*/
function tabNames(area: VueWrapper, group = 0): string[] {
return area.findAll(`[data-test=editor-tabs][data-group='${String(group)}'] [data-test=editor-tab]`).map((tab) => {
const name = tab.find(".tabs__name").text();
return `${tab.attributes("data-pinned") ? "^" : ""}${name}${tab.attributes("data-preview") ? "*" : ""}`;
});
}
/**
* The CodeMirror view of a group.
*
* @param area - the mounted area.
* @param group - group index.
*/
function viewOf(area: VueWrapper, group = 0): EditorView {
const el = area.find(`[data-test=code-editor][data-group='${String(group)}'] .cm-editor`).element;
const view = EditorView.findFromDOM(el as HTMLElement);
if (!view) {
throw new Error("no editor view");
}
return view;
}
/**
* Opens files permanently, in order.
*
* @param paths - project-relative paths.
*/
async function openAll(...paths: string[]): Promise<void> {
const editor = useEditorStore(pinia);
for (const path of paths) {
await editor.openFile(path);
}
await flushPromises();
}
/**
* Makes a buffer dirty through its view.
*
* @param area - the mounted area.
* @param path - file to edit (activated first).
*/
async function makeDirty(area: VueWrapper, path: string): Promise<void> {
const editor = useEditorStore(pinia);
await editor.openFile(path);
await flushPromises();
viewOf(area).dispatch({ changes: { from: 0, insert: "x" } });
await flushPromises();
}
/**
* Mounts the area and the tree once and opens a file, so the cold start of
* the first CodeMirror view and the first render (seconds under load) is
* not paid inside the first test's time budget (see `EditorArea.test.ts`).
*/
beforeAll(async () => {
resetFakeEngine();
const area = await mountArea();
const tree = await mountTree();
await tree.find("[data-path='a.php']").trigger("dblclick");
await flushPromises();
expect(area.find(".cm-editor").exists()).toBe(true);
useCommandsStore(pinia).stop();
for (const wrapper of mounted) {
wrapper.unmount();
}
mounted = [];
}, 30_000);
describe("preview tabs", () => {
it("a single click opens a preview that the next one replaces; a double click keeps it", async () => {
const area = await mountArea();
const tree = await mountTree();
await tree.find("[data-path='a.php']").trigger("click");
await flushPromises();
expect(tabNames(area)).toEqual(["a.php*"]);
expect(area.find("[data-test=editor-tab] .tabs__name").element.closest(".tabs__tab--preview")).not.toBeNull();
await tree.find("[data-path='b.php']").trigger("click");
await flushPromises();
expect(tabNames(area)).toEqual(["b.php*"]);
expect(calls.filter((c) => c.command === "buffer.close").map((c) => c.params)).toEqual([{ id: 1, force: false }]);
await tree.find("[data-path='b.php']").trigger("dblclick");
await flushPromises();
await tree.find("[data-path='c.php']").trigger("click");
await flushPromises();
expect(tabNames(area)).toEqual(["b.php", "c.php*"]);
await area.findAll("[data-test=editor-tab]")[1]?.trigger("dblclick");
expect(tabNames(area)).toEqual(["b.php", "c.php"]);
});
it("editing a preview keeps it open", async () => {
const area = await mountArea();
const editor = useEditorStore(pinia);
await editor.openFile("a.php", { preview: true });
await flushPromises();
viewOf(area).dispatch({ changes: { from: 0, insert: "x" } });
await flushPromises();
await editor.openFile("b.php", { preview: true });
await flushPromises();
expect(tabNames(area)).toEqual(["a.php", "b.php*"]);
});
it("the setting turns previews off", async () => {
const area = await mountArea();
useSettingsStore(pinia).values[PREVIEW_SETTING] = false;
const editor = useEditorStore(pinia);
await editor.openFile("a.php", { preview: true });
await editor.openFile("b.php", { preview: true });
await flushPromises();
expect(tabNames(area)).toEqual(["a.php", "b.php"]);
});
});
describe("pinning and closing", () => {
it("pinned tabs sit left with a pin and survive close others and close all", async () => {
const area = await mountArea();
await openAll("a.php", "b.php", "c.php");
const commands = useCommandsStore(pinia);
await commands.execute(COMMAND_IDS.togglePin, { id: 3 });
await flushPromises();
expect(tabNames(area)).toEqual(["^c.php", "a.php", "b.php"]);
expect(area.findAll("[data-test=tab-pin]")).toHaveLength(1);
await commands.execute(COMMAND_IDS.closeOthers, { id: 1 });
await flushPromises();
expect(tabNames(area)).toEqual(["^c.php", "a.php"]);
await commands.execute(COMMAND_IDS.closeAll);
await flushPromises();
expect(tabNames(area)).toEqual(["^c.php"]);
});
it("closes to the left, to the right and the unmodified tabs", async () => {
const area = await mountArea();
await openAll("a.php", "b.php", "c.php", "d.php");
const editor = useEditorStore(pinia);
await editor.closeAction("right", 3);
await flushPromises();
expect(tabNames(area)).toEqual(["a.php", "b.php", "c.php"]);
await editor.closeAction("left", 2);
await flushPromises();
expect(tabNames(area)).toEqual(["b.php", "c.php"]);
await makeDirty(area, "c.php");
await editor.closeAction("unmodified");
await flushPromises();
expect(tabNames(area)).toEqual(["c.php"]);
});
it("asks once for every unsaved file and saves them all", async () => {
const area = await mountArea();
await openAll("a.php", "b.php", "c.php");
await makeDirty(area, "a.php");
await makeDirty(area, "b.php");
const editor = useEditorStore(pinia);
await editor.closeAction("all");
await flushPromises();
expect(editor.closePrompt?.items.map((i) => i.name)).toEqual(["a.php", "b.php"]);
expect(area.findAll("[data-test=close-list] li").map((li) => li.text())).toEqual(["a.php", "b.php"]);
expect(area.get("[data-test=close-save]").text()).toBe("Save All");
await area.get("[data-test=close-cancel]").trigger("click");
await flushPromises();
expect(tabNames(area)).toEqual(["a.php", "b.php", "c.php"]);
await editor.closeAction("all");
await flushPromises();
await area.get("[data-test=close-save]").trigger("click");
await flushPromises();
expect(tabNames(area)).toEqual([]);
expect(disk["a.php"]?.startsWith("x")).toBe(true);
expect(disk["b.php"]?.startsWith("x")).toBe(true);
});
it("discards every unsaved file with Don't Save", async () => {
const area = await mountArea();
await openAll("a.php", "b.php");
await makeDirty(area, "a.php");
const editor = useEditorStore(pinia);
await editor.closeAction("all");
await flushPromises();
expect(area.find("[data-test=close-list]").exists()).toBe(false);
await area.get("[data-test=close-discard]").trigger("click");
await flushPromises();
expect(tabNames(area)).toEqual([]);
expect(disk["a.php"]).toBe("<?php\necho 1;\n");
expect(calls.filter((c) => c.command === "buffer.close").map((c) => c.params.force)).toEqual([true, true]);
});
it("the context menu runs the tab commands for its tab", async () => {
const area = await mountArea();
await openAll("a.php", "b.php", "c.php");
await area.findAll("[data-test=editor-tab]")[1]?.trigger("contextmenu", { clientX: 10, clientY: 10 });
const items = area.findAll("[data-test=tab-menu-item]").map((i) => i.attributes("data-item"));
expect(items).toEqual([
"close",
COMMAND_IDS.closeOthers,
COMMAND_IDS.closeAll,
COMMAND_IDS.closeLeft,
COMMAND_IDS.closeRight,
COMMAND_IDS.closeUnmodified,
COMMAND_IDS.reopenClosed,
"pin",
"history.show",
COMMAND_IDS.splitRight,
COMMAND_IDS.splitDown,
COMMAND_IDS.moveToOtherGroup,
]);
await area.get(`[data-item='${COMMAND_IDS.closeOthers}']`).trigger("click");
await flushPromises();
expect(tabNames(area)).toEqual(["b.php"]);
expect(area.find("[data-test=tab-menu]").exists()).toBe(false);
});
});
describe("tab context menu and local history", () => {
it("shows Show Local History (C10 A2 registers history.show) and runs it with the path", async () => {
const area = await mountArea();
await openAll("a.php");
const shown: unknown[] = [];
useCommandsStore(pinia).provide("history.show", { run: (params) => void shown.push(params) });
await area.get("[data-test=editor-tab]").trigger("contextmenu", { clientX: 5, clientY: 5 });
await area.get("[data-item='history.show']").trigger("click");
await flushPromises();
expect(shown).toEqual([{ path: "a.php" }]);
});
});
describe("reopen closed tab", () => {
it("reopens the last closed tab at its place with its selection", async () => {
const area = await mountArea();
await openAll("a.php", "b.php", "c.php");
const editor = useEditorStore(pinia);
editor.activate(2);
await flushPromises();
viewOf(area).dispatch({ selection: { anchor: 3, head: 7 } });
expect(editor.canReopen).toBe(false);
await editor.requestClose(2);
await flushPromises();
expect(tabNames(area)).toEqual(["a.php", "c.php"]);
await useCommandsStore(pinia).execute(COMMAND_IDS.reopenClosed);
await flushPromises();
expect(tabNames(area)).toEqual(["a.php", "b.php", "c.php"]);
const selection = viewOf(area).state.selection.main;
expect([selection.anchor, selection.head]).toEqual([3, 7]);
expect(editor.canReopen).toBe(false);
});
});
describe("split", () => {
it("shows the same buffer in two groups with one text and one undo history", async () => {
const area = await mountArea();
await openAll("a.php", "b.php");
const editor = useEditorStore(pinia);
await useCommandsStore(pinia).execute(COMMAND_IDS.splitRight);
await flushPromises();
expect(area.findAll("[data-test=editor-pane]")).toHaveLength(2);
expect(tabNames(area, 0)).toEqual(["a.php", "b.php"]);
expect(tabNames(area, 1)).toEqual(["b.php"]);
expect(editor.focusedGroup).toBe(1);
viewOf(area, 1).dispatch({ changes: { from: 0, insert: "// " } });
await flushPromises();
expect(viewOf(area, 0).state.doc.toString()).toBe("// <?php\necho 2;\n");
runScopeHandlers(viewOf(area, 0), new KeyboardEvent("keydown", { key: "z", ctrlKey: true, metaKey: navigator.platform.startsWith("Mac") }), "editor");
await flushPromises();
expect(viewOf(area, 1).state.doc.toString()).toBe("<?php\necho 2;\n");
expect(buffers.get(2)?.text).toBe("<?php\necho 2;\n");
});
it("moves a tab across, focuses the other group and joins the groups again", async () => {
const area = await mountArea();
await openAll("a.php", "b.php", "c.php");
const editor = useEditorStore(pinia);
const commands = useCommandsStore(pinia);
await commands.execute(COMMAND_IDS.moveToOtherGroup, { id: 1 });
await flushPromises();
expect(tabNames(area, 0)).toEqual(["b.php", "c.php"]);
expect(tabNames(area, 1)).toEqual(["a.php"]);
await commands.execute(COMMAND_IDS.focusOtherGroup);
expect(editor.focusedGroup).toBe(0);
await commands.execute(COMMAND_IDS.splitDown);
await flushPromises();
expect(area.find(".editor-area__groups--down").exists()).toBe(true);
await commands.execute(COMMAND_IDS.unsplit);
await flushPromises();
expect(area.findAll("[data-test=editor-pane]")).toHaveLength(1);
});
it("closing a tab the other group still shows keeps the buffer", async () => {
const area = await mountArea();
await openAll("a.php");
const editor = useEditorStore(pinia);
editor.split("right");
await flushPromises();
await makeDirty(area, "a.php");
await editor.requestClose(1, 1);
await flushPromises();
expect(editor.closePrompt).toBeNull();
expect(calls.some((c) => c.command === "buffer.close")).toBe(false);
expect(area.findAll("[data-test=editor-pane]")).toHaveLength(1);
});
});
describe("stored layout", () => {
it("stores changes through layout.set and restores the layout when the project opens", async () => {
storedLayout = {
version: 1,
focused: 1,
orientation: "down",
groups: [
{ tabs: [{ path: "b.php", pinned: true }, { path: "gone.php" }, { path: "a.php" }], active: "a.php" },
{ tabs: [{ path: "c.php", preview: true }], active: "c.php" },
],
};
const area = await mountArea();
emitEditorEvent({ kind: "projectOpened", root: "/tmp/demo", name: "demo" });
await flushPromises();
await flushPromises();
expect(tabNames(area, 0)).toEqual(["^b.php", "a.php"]);
expect(tabNames(area, 1)).toEqual(["c.php*"]);
expect(area.find(".editor-area__groups--down").exists()).toBe(true);
const editor = useEditorStore(pinia);
expect(editor.focusedGroup).toBe(1);
expect(editor.groups[0]?.activeId).toBe(editor.tabOfPath("a.php")?.id);
expect(calls.some((c) => c.command === "layout.set")).toBe(false);
vi.useFakeTimers();
editor.unsplit();
await vi.advanceTimersByTimeAsync(400);
const set = calls.filter((c) => c.command === "layout.set");
expect(set).toHaveLength(1);
expect((set[0]?.params.layout as { groups: unknown[] }).groups).toHaveLength(1);
});
it("does not store the empty layout of a closing project", async () => {
await mountArea();
emitEditorEvent({ kind: "projectOpened", root: "/tmp/demo", name: "demo" });
await flushPromises();
await openAll("a.php");
vi.useFakeTimers();
emitEditorEvent({ kind: "projectClosed" });
await vi.advanceTimersByTimeAsync(400);
expect(calls.filter((c) => c.command === "layout.set")).toHaveLength(0);
});
});
describe("public API", () => {
it("finds the tab of a path and reloads a buffer from the engine", async () => {
const area = await mountArea();
await openAll("a.php");
const editor = useEditorStore(pinia);
expect(editor.tabOfPath("a.php")?.id).toBe(1);
expect(editor.tabOfPath("nope.php")).toBeUndefined();
const buffer = buffers.get(1);
if (buffer) {
buffer.text = "reloaded\n";
buffer.version += 1;
}
expect(editor.reloadBuffer(1)).toBe(true);
await flushPromises();
expect(viewOf(area).state.doc.toString()).toBe("reloaded\n");
expect(editor.reloadBuffer(99)).toBe(false);
});
});