/** * Tests for the editor area and the editor store: opening tabs (from the * tree and from engine events), editing through CodeMirror into * `buffer.edit`, the dirty marker, closing (middle click, shortcut, the * Save / Don't Save / Cancel question), saving through the global keymap * (`commands/store.ts`) with shortcuts loaded from the engine's command * list, the notice for files changed on disk, and the UI command * `editor.reveal` (open and closed files, CRLF text, bad params). * The engine is a fake behind the mocked Tauri `invoke`. */ import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; import { EditorView } 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 { useEditorStore } from "../../src/stores/editor"; import { useNotificationsStore } from "../../src/stores/notifications"; /** A buffer of the fake engine. */ interface FakeBuffer { path: string; text: string; version: number; saved: number; } /** Fake engine state. */ let buffers: Map; /** Files on the fake disk. */ let disk: Record; /** Next buffer id. */ let nextId: number; /** Every `engine_execute` call, in order. */ let calls: { command: string; params: Record }[]; /** * 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: b.text.includes("\r\n") ? "crlf" : "lf", } : null; } /** * Rejects like the shell does with an engine error. * * @param code - error code. */ function fail(code: string): Promise { 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): Promise { 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"); } if (p.baseVersion !== b.version) { return fail("stale_version"); } 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; emitEditorEvent({ kind: "bufferChanged", id, version: b.version }); 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 "file.saveAll": { const saved: number[] = []; for (const [bid, buffer] of buffers) { if (buffer.version !== buffer.saved) { disk[buffer.path] = buffer.text; buffer.saved = buffer.version; saved.push(bid); } } return Promise.resolve({ saved, failed: [] }); } 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 "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); } } /** Pinia of the current test, installed in every mounted component. */ let pinia: Pinia; /** Mounted components to unmount after each test. */ let mounted: VueWrapper[] = []; /** Mounts the editor area and starts the global keymap. */ async function mountArea(): Promise { await useCommandsStore(pinia).start(); const wrapper = mount(EditorArea, { attachTo: document.body, slots: { default: "empty" }, global: { plugins: [pinia] }, }); mounted.push(wrapper); await flushPromises(); return wrapper; } /** The CodeMirror view inside a wrapper. */ function viewOf(wrapper: VueWrapper): EditorView { const el = wrapper.find(".cm-editor").element; const view = EditorView.findFromDOM(el as HTMLElement); if (!view) { throw new Error("no editor view"); } return view; } /** * Presses a key on the window. * * @param init - key event properties. */ async function press(init: KeyboardEventInit): Promise { window.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...init })); await flushPromises(); } /** Commands sent to the engine, without project and listing calls. */ function commands(): string[] { return calls.map((c) => c.command).filter((c) => !c.startsWith("project.")); } /** * jsdom has no layout; CodeMirror measures text ranges, so give ranges * empty rectangles. */ function stubRangeGeometry(): void { const empty = (): DOMRectList => { const list: DOMRect[] = []; return Object.assign(list, { item: () => null }); }; Range.prototype.getClientRects = empty; Range.prototype.getBoundingClientRect = () => new DOMRect(0, 0, 0, 0); } /** Fresh Pinia and a fake engine with two files on its disk. */ function resetFakeEngine(): void { stubRangeGeometry(); pinia = createPinia(); setActivePinia(pinia); buffers = new Map(); disk = { "a.php": " }) => { if (cmd === "engine_list_commands") { return Promise.resolve([ { id: "file.save", label: "Save", menuPath: null, defaultShortcut: "Mod+S", params: "", enabled: true }, { id: "file.saveAll", label: "Save All", menuPath: null, defaultShortcut: "Mod+Alt+S", params: "", enabled: true }, { id: "buffer.close", label: "Close", menuPath: null, defaultShortcut: "Mod+W", params: "", enabled: true }, ]); } 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}`)); }); } /** Stops the global keymap and unmounts every mounted component. */ async function unmountAll(): Promise { await flushPromises(); useCommandsStore(pinia).stop(); for (const wrapper of mounted) { wrapper.unmount(); } mounted = []; } /** * Pays the one-time cost of the first editor outside any test: mounts the * editor area and the project tree, opens a file from the tree and * unmounts again. The first CodeMirror view in a jsdom worker injects the * base theme and runs every extension cold, and the first render of the * Vue components is slower too (about 0.5 s together on an idle machine, * several seconds under load). Without this, the first test that opened a * file paid that cost inside its own 5 s budget and timed out under load. */ async function warmUpEditor(): Promise { resetFakeEngine(); await mountArea(); const tree = mount(ProjectToolWindow, { attachTo: document.body, global: { plugins: [pinia] } }); mounted.push(tree); emitEngineEvent({ kind: "projectOpened", root: "/tmp/demo", name: "demo" }); await flushPromises(); await tree.find("[data-path='a.php']").trigger("dblclick"); await flushPromises(); await unmountAll(); } beforeAll(warmUpEditor); beforeEach(resetFakeEngine); afterEach(unmountAll); describe("EditorArea", () => { it("shows the slot without tabs and opens a file from the project tree", async () => { const area = await mountArea(); expect(area.text()).toContain("empty"); const tree = mount(ProjectToolWindow, { attachTo: document.body, global: { plugins: [pinia] } }); mounted.push(tree); emitEngineEvent({ kind: "projectOpened", root: "/tmp/demo", name: "demo" }); await flushPromises(); await tree.find("[data-path='a.php']").trigger("dblclick"); await flushPromises(); const tabs = area.findAll("[data-test=editor-tab]"); expect(tabs.map((t) => t.text())).toEqual(["a.php"]); expect(viewOf(area).state.doc.toString()).toBe(" { const area = await mountArea(); const editor = useEditorStore(pinia); await editor.openFile("a.php"); await flushPromises(); const view = viewOf(area); view.dispatch({ changes: { from: 5, insert: " // hi" } }); view.dispatch({ changes: { from: 0, insert: "#" } }); await flushPromises(); expect(buffers.get(1)?.text).toBe("# { const area = await mountArea(); await useEditorStore(pinia).openFile("b.txt"); await flushPromises(); const b = buffers.get(1); if (!b) { throw new Error("no buffer"); } b.text = "honey bee\n"; b.version = 2; emitEditorEvent({ kind: "bufferChanged", id: 1, version: 2 }); await flushPromises(); expect(viewOf(area).state.doc.toString()).toBe("honey bee\n"); }); it("switches tabs and closes a clean tab with a middle click", async () => { const area = await mountArea(); const editor = useEditorStore(pinia); await editor.openFile("a.php"); await editor.openFile("b.txt"); await flushPromises(); expect(editor.activeId).toBe(2); await area.findAll("[data-test=editor-tab]")[0]?.trigger("click"); expect(viewOf(area).state.doc.toString()).toContain(" t.text())).toEqual(["a.php"]); expect(commands()).toContain("buffer.close"); }); it("asks before closing a dirty tab: cancel, don't save, save", async () => { const area = await mountArea(); const editor = useEditorStore(pinia); await editor.openFile("a.php"); await flushPromises(); viewOf(area).dispatch({ changes: { from: 0, insert: "x" } }); await flushPromises(); await press({ key: "w", code: "KeyW", ctrlKey: true }); expect(area.find("[data-test=close-prompt]").exists()).toBe(true); await area.find("[data-test=close-cancel]").trigger("click"); await flushPromises(); expect(area.find("[data-test=close-prompt]").exists()).toBe(false); expect(editor.tabs).toHaveLength(1); await area.find("[data-test=tab-close]").trigger("click"); await flushPromises(); await area.find("[data-test=close-save]").trigger("click"); await flushPromises(); expect(disk["a.php"]).toBe("x { const area = await mountArea(); const editor = useEditorStore(pinia); await editor.openFile("a.php"); await editor.openFile("b.txt"); await flushPromises(); viewOf(area).dispatch({ changes: { from: 0, insert: "B" } }); await press({ key: "s", code: "KeyS", ctrlKey: true }); expect(disk["b.txt"]).toBe("Bbee\n"); expect(calls.at(-1)).toEqual({ command: "file.save", params: { id: 2 } }); expect(area.find("[data-test=tab-dirty]").exists()).toBe(false); await area.findAll("[data-test=editor-tab]")[0]?.trigger("click"); viewOf(area).dispatch({ changes: { from: 0, insert: "A" } }); await press({ key: "ß", code: "KeyS", ctrlKey: true, altKey: true }); expect(disk["a.php"]).toBe("A { const area = await mountArea(); await execute("file.open", { path: "b.txt" }); emitEditorEvent({ kind: "bufferOpened", id: 1, path: "b.txt" }); await flushPromises(); expect(area.findAll("[data-test=editor-tab]").map((t) => t.text())).toEqual(["b.txt"]); emitEditorEvent({ kind: "bufferClosed", id: 1 }); await flushPromises(); expect(area.findAll("[data-test=editor-tab]")).toHaveLength(0); }); it("activates the last opened buffer even when its fetch finishes first", async () => { const area = await mountArea(); await execute("file.open", { path: "a.php" }); await execute("file.open", { path: "b.txt" }); let releaseFirst: () => void = () => undefined; const fallback = invoke.getMockImplementation(); invoke.mockImplementation((cmd: string, args?: { command: string; params: Record }) => { if (args?.command === "buffer.get" && args.params.id === 1) { return new Promise((resolve) => { releaseFirst = () => { resolve(describeBuffer(1)); }; }); } return fallback?.(cmd, args) as Promise; }); emitEditorEvent({ kind: "bufferOpened", id: 1, path: "a.php" }); emitEditorEvent({ kind: "bufferOpened", id: 2, path: "b.txt" }); await flushPromises(); releaseFirst(); await flushPromises(); const editor = useEditorStore(pinia); expect(editor.tabs.map((t) => t.path).sort()).toEqual(["a.php", "b.txt"]); expect(editor.activeId).toBe(2); expect(area.find("[aria-selected=true]").text()).toBe("b.txt"); }); it("switches to an open tab when the engine reports bufferFocused", async () => { const area = await mountArea(); const editor = useEditorStore(pinia); await editor.openFile("a.php"); await editor.openFile("b.txt"); await flushPromises(); expect(editor.activeId).toBe(2); emitEditorEvent({ kind: "bufferFocused", id: 1 }); await flushPromises(); expect(editor.activeId).toBe(1); expect(area.find("[aria-selected=true]").text()).toBe("a.php"); emitEditorEvent({ kind: "bufferFocused", id: 99 }); expect(editor.activeId).toBe(1); }); it("lets bufferFocused outrank an adoption that is still fetching", async () => { await mountArea(); const editor = useEditorStore(pinia); await editor.openFile("a.php"); await flushPromises(); await execute("file.open", { path: "b.txt" }); let release: () => void = () => undefined; const fallback = invoke.getMockImplementation(); invoke.mockImplementation((cmd: string, args?: { command: string; params: Record }) => { if (args?.command === "buffer.get" && args.params.id === 2) { return new Promise((resolve) => { release = () => { resolve(describeBuffer(2)); }; }); } return fallback?.(cmd, args) as Promise; }); emitEditorEvent({ kind: "bufferOpened", id: 2, path: "b.txt" }); emitEditorEvent({ kind: "bufferFocused", id: 1 }); release(); await flushPromises(); expect(editor.tabs.map((t) => t.path).sort()).toEqual(["a.php", "b.txt"]); expect(editor.activeId).toBe(1); }); it("shows a notice when a dirty file changes on disk, and an open error", async () => { const area = await mountArea(); const editor = useEditorStore(pinia); await editor.openFile("a.php"); await flushPromises(); emitEditorEvent({ kind: "fileChangedOnDisk", id: 1, path: "a.php", removed: false }); await flushPromises(); expect(area.find("[data-test=editor-notice]").text()).toContain("changed on disk"); await area.find("[data-test=notice-dismiss]").trigger("click"); expect(area.find("[data-test=editor-notice]").exists()).toBe(false); await editor.openFile("missing.php"); await flushPromises(); expect(area.find("[data-test=editor-error]").text()).toContain("not_found"); }); it("opens a 1 MB file and records the time", async () => { const line = " { beforeEach(() => { disk["c.php"] = " { vi.restoreAllMocks(); }); it("opens a closed file, activates it, places the cursor and centres it", async () => { const scroll = vi.spyOn(EditorView, "scrollIntoView"); const area = await mountArea(); const editor = useEditorStore(pinia); await editor.openFile("a.php"); await flushPromises(); await useCommandsStore(pinia).dispatch("editor.reveal", { path: "c.php", line: 3, column: 9 }); await flushPromises(); expect(calls.filter((c) => c.command === "file.open").map((c) => c.params.path)).toEqual(["a.php", "c.php"]); expect(editor.activeTab?.path).toBe("c.php"); const view = viewOf(area); const head = view.state.selection.main.head; expect(view.state.doc.lineAt(head).number).toBe(4); expect(view.state.sliceDoc(head, head + 3)).toBe("😀z"); expect(scroll).toHaveBeenLastCalledWith(head, { y: "center" }); }); it("activates an open tab without opening the file again", async () => { const area = await mountArea(); const editor = useEditorStore(pinia); await editor.openFile("c.php"); await editor.openFile("b.txt"); await flushPromises(); await useCommandsStore(pinia).execute("editor.reveal", { path: "c.php", line: 1, column: 9 }); await flushPromises(); expect(calls.filter((c) => c.command === "file.open")).toHaveLength(2); expect(editor.activeTab?.path).toBe("c.php"); expect(viewOf(area).state.selection.main.head).toBe(6 + 9); }); it("maps positions in CRLF text through the engine line breaks", async () => { const area = await mountArea(); const editor = useEditorStore(pinia); await useCommandsStore(pinia).dispatch("editor.reveal", { path: "w.php", line: 2, column: 1 }); await flushPromises(); const view = viewOf(area); const head = view.state.selection.main.head; expect(head).toBe(15); expect(view.state.sliceDoc(head, head + 1)).toBe("b"); const engineText = disk["w.php"] ?? ""; const crlfBefore = engineText.slice(0, 16).split("\r\n").length - 1; expect(engineText.charAt(head + crlfBefore)).toBe("b"); expect(editor.activeTab?.path).toBe("w.php"); }); it("clamps positions past the end", async () => { const area = await mountArea(); await useCommandsStore(pinia).dispatch("editor.reveal", { path: "w.php", line: 0, column: 99 }); await flushPromises(); expect(viewOf(area).state.selection.main.head).toBe(5); await useCommandsStore(pinia).dispatch("editor.reveal", { path: "w.php", line: 99, column: 0 }); await flushPromises(); expect(viewOf(area).state.selection.main.head).toBe(viewOf(area).state.doc.length); }); it("centres the cursor of the active tab without a path (palette)", async () => { const scroll = vi.spyOn(EditorView, "scrollIntoView"); const area = await mountArea(); await useEditorStore(pinia).openFile("c.php"); await flushPromises(); viewOf(area).dispatch({ selection: { anchor: 8 } }); await useCommandsStore(pinia).execute("editor.reveal"); await flushPromises(); expect(viewOf(area).state.selection.main.head).toBe(8); expect(scroll).toHaveBeenLastCalledWith(8, { y: "center" }); }); it("reports bad params and files that cannot be opened", async () => { await mountArea(); const commands = useCommandsStore(pinia); await commands.dispatch("editor.reveal", { path: 3, line: 0, column: 0 }); await commands.dispatch("editor.reveal", { path: "c.php", line: "1" }); await commands.dispatch("editor.reveal", { path: "missing.php", line: 0, column: 0 }); await flushPromises(); const texts = useNotificationsStore(pinia).toasts.map((t) => t.text); expect(texts).toHaveLength(3); expect(texts[0]).toContain("needs a path"); expect(texts[1]).toContain("needs a path"); expect(texts[2]).toContain("not_found"); expect(useEditorStore(pinia).tabs).toHaveLength(0); }); });