/** * Tests of the Structure tool window (M2.7): reading the engine's outline * (malformed items dropped, depth cap), the visible rows and collapsed * nodes, the store following the active tab and `outlineChanged` (and * dropping stale answers), the window (empty states, icons and signatures, * keyboard navigation, jumps through `editor.reveal`), and the left stripe * with `view.toggleStructure` in the main layout. The engine is a fake * behind the mocked Tauri `invoke` and `listen`. */ import { flushPromises, mount, type VueWrapper } from "@vue/test-utils"; import { createPinia, setActivePinia, type Pinia } from "pinia"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const invoke = vi.hoisted(() => vi.fn()); const listen = vi.hoisted(() => vi.fn()); vi.mock("@tauri-apps/api/core", () => ({ invoke })); vi.mock("@tauri-apps/api/event", () => ({ listen })); import { useCommandsStore } from "../../src/commands/store"; import MainLayout from "../../src/components/layout/MainLayout.vue"; import StructureToolWindow from "../../src/components/structure/StructureToolWindow.vue"; import { MAX_DEPTH, flatten, parentKey, toOutline, useStructureStore } from "../../src/components/structure/structure"; import { useEditorStore } from "../../src/stores/editor"; /** Every `engine_execute` call, in order. */ let calls: { command: string; params: Record }[]; /** Engine event callbacks of every subscription. */ let listeners: ((event: { payload: unknown }) => void)[]; /** The outline the fake returns per buffer id. */ let outlines: Map; /** Answers of `syntax.outline` held back until released, if set. */ let held: (() => void)[] | null; /** Pinia of the current test. */ let pinia: Pinia; /** Mounted components, unmounted after each test. */ let mounted: VueWrapper[]; /** * Sends an engine event to every subscription. * * @param payload - the event. */ async function emit(payload: unknown): Promise { for (const listener of [...listeners]) { listener({ payload }); } await flushPromises(); } /** * An outline item as the engine sends it. * * @param kind - the kind. * @param name - the name. * @param line - line of the name. * @param children - nested items. * @param detail - signature, if any. */ function item(kind: string, name: string, line: number, children: unknown[] = [], detail?: string): unknown { const at = { line, column: 4 }; return { kind, name, ...(detail === undefined ? {} : { detail }), range: { start: at, end: at }, selectionRange: { start: at, end: { line, column: 4 + name.length } }, children, }; } /** The outline of a small class file. */ const SHOP = [ item("namespace", "App", 1, [ item("class", "Shop", 3, [ item("property", "$items", 5, [], "array"), item("method", "find", 7, [], "(int $id): ?Product"), item("method", "save", 9), ], "extends Base"), ]), ]; /** * Opens a fake tab in the editor store. * * @param id - buffer id. * @param path - file path. */ function openTab(id: number, path: string): void { const editor = useEditorStore(pinia); editor.tabs.push({ id, path, name: path, dirty: false, notice: null }); editor.activeId = id; } /** The `syntax.outline` ids requested, in order. */ function outlineRequests(): unknown[] { return calls.filter((c) => c.command === "syntax.outline").map((c) => c.params.id); } /** Names of the visible rows. */ function rowNames(wrapper: VueWrapper): string[] { return wrapper.findAll("[data-test=structure-row]").map((r) => r.get(".structure-tree__name").text()); } /** Mounts the window with an `editor.reveal` spy. */ async function mountStructure(): Promise<{ wrapper: VueWrapper; reveals: unknown[] }> { const reveals: unknown[] = []; useCommandsStore(pinia).provide("editor.reveal", { run: (params) => void reveals.push(params) }); const wrapper = mount(StructureToolWindow, { attachTo: document.body, global: { plugins: [pinia] } }); mounted.push(wrapper); await flushPromises(); return { wrapper, reveals }; } /** * Presses a key on the tree. * * @param wrapper - the window. * @param key - the key. */ async function key(wrapper: VueWrapper, key: string): Promise { await wrapper.get("[data-test=structure-tree]").trigger("keydown", { key }); } beforeEach(() => { pinia = createPinia(); setActivePinia(pinia); calls = []; listeners = []; outlines = new Map(); held = null; mounted = []; Element.prototype.scrollIntoView = () => undefined; invoke.mockReset(); listen.mockReset(); listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => { listeners.push(callback); return Promise.resolve(() => { listeners = listeners.filter((l) => l !== callback); }); }); invoke.mockImplementation((cmd: string, args?: { command: string; params: Record }) => { if (cmd === "engine_list_commands") { return Promise.resolve([]); } if (cmd !== "engine_execute" || !args) { return Promise.resolve(null); } calls.push({ command: args.command, params: args.params }); if (args.command === "syntax.outline") { const id = args.params.id as number; const answer = (): unknown => { const items = outlines.get(id); if (items === "fail") { return Promise.reject(Object.assign(new Error("failed"), { code: "failed", message: "no buffer" })); } return { items: items ?? [], truncated: id === 99, version: items === undefined ? null : 1 }; }; if (held) { const queue = held; return new Promise((resolve) => { queue.push(() => { resolve(answer()); }); }); } return Promise.resolve(answer()); } return Promise.resolve(null); }); }); afterEach(() => { for (const wrapper of mounted) { wrapper.unmount(); } }); describe("outline parsing", () => { it("keeps well-formed items and drops malformed ones", () => { const nodes = toOutline([ item("class", "A", 0, [item("method", "m", 1, [], "(): void"), { kind: "method", name: 3 }]), item("lambda", "x", 2), { kind: "function", name: "f", selectionRange: { start: { line: -1, column: 0 } } }, null, "class", ]); expect(nodes).toEqual([ { kind: "class", name: "A", detail: null, start: { line: 0, column: 4 }, children: [{ kind: "method", name: "m", detail: "(): void", start: { line: 1, column: 4 }, children: [] }], }, ]); expect(toOutline({ items: [] })).toEqual([]); }); it("caps the nesting depth", () => { let deep: unknown = item("function", "leaf", 0); for (let i = 0; i < MAX_DEPTH + 10; i += 1) { deep = item("class", `C${String(i)}`, 0, [deep]); } let depth = 0; let nodes = toOutline([deep]); while (nodes[0]) { depth += 1; nodes = nodes[0].children; } expect(depth).toBe(MAX_DEPTH); }); it("flattens with collapsed nodes and unique keys", () => { const nodes = toOutline([item("class", "A", 0, [item("method", "m", 1), item("method", "m", 2)]), item("class", "B", 3)]); const rows = flatten(nodes, new Set()); expect(rows.map((r) => [r.key, r.depth, r.parent, r.expanded])).toEqual([ ["/class:A", 0, true, true], ["/class:A/method:m", 1, false, false], ["/class:A/method:m#1", 1, false, false], ["/class:B", 0, false, false], ]); expect(flatten(nodes, new Set(["/class:A"])).map((r) => r.key)).toEqual(["/class:A", "/class:B"]); expect(parentKey("/class:A/method:m")).toBe("/class:A"); expect(parentKey("/class:A")).toBeNull(); }); }); describe("structure store", () => { it("follows the active tab and outlineChanged of that buffer only", async () => { outlines.set(3, SHOP); outlines.set(4, [item("function", "helper", 0)]); const store = useStructureStore(pinia); store.start(); await flushPromises(); expect(outlineRequests()).toEqual([]); openTab(3, "src/Shop.php"); await flushPromises(); expect(store.items.map((n) => n.name)).toEqual(["App"]); openTab(4, "src/helpers.php"); await flushPromises(); expect(store.items.map((n) => n.name)).toEqual(["helper"]); await emit({ kind: "outlineChanged", id: 3 }); expect(outlineRequests()).toEqual([3, 4]); outlines.set(4, [item("function", "helper2", 0)]); await emit({ kind: "outlineChanged", id: 4 }); expect(outlineRequests()).toEqual([3, 4, 4]); expect(store.items.map((n) => n.name)).toEqual(["helper2"]); store.stop(); await emit({ kind: "outlineChanged", id: 4 }); expect(outlineRequests()).toEqual([3, 4, 4]); }); it("drops an answer overtaken by a newer request", async () => { outlines.set(3, SHOP); outlines.set(4, [item("function", "helper", 0)]); const store = useStructureStore(pinia); store.start(); held = []; const queue = held; openTab(3, "a.php"); await flushPromises(); openTab(4, "b.php"); await flushPromises(); const [first, second] = queue; second?.(); await flushPromises(); first?.(); await flushPromises(); expect(store.items.map((n) => n.name)).toEqual(["helper"]); store.stop(); }); it("keeps collapsed nodes per buffer across refreshes", async () => { outlines.set(3, SHOP); outlines.set(4, SHOP); const store = useStructureStore(pinia); store.start(); openTab(3, "a.php"); await flushPromises(); store.setExpanded("/namespace:App/class:Shop", false); expect(store.rows.map((r) => r.node.name)).toEqual(["App", "Shop"]); await emit({ kind: "outlineChanged", id: 3 }); expect(store.rows.map((r) => r.node.name)).toEqual(["App", "Shop"]); openTab(4, "b.php"); await flushPromises(); expect(store.rows).toHaveLength(5); useEditorStore(pinia).activeId = 3; await flushPromises(); expect(store.rows).toHaveLength(2); store.stop(); }); }); describe("Structure tool window", () => { it("says when no file is open, a file has no declarations, is being read or is too large", async () => { const { wrapper } = await mountStructure(); expect(wrapper.get("[data-test=structure-empty]").text()).toBe("Open a file to see its structure"); openTab(5, "pending.php"); await flushPromises(); expect(wrapper.get("[data-test=structure-empty]").text()).toBe("Reading the file…"); outlines.set(6, []); openTab(6, "empty.php"); await flushPromises(); expect(wrapper.get("[data-test=structure-empty]").text()).toBe("No declarations in this file"); openTab(99, "huge.php"); await flushPromises(); expect(wrapper.get("[data-test=structure-empty]").text()).toBe("This file is too large to show its structure"); outlines.set(7, "fail"); openTab(7, "gone.php"); await flushPromises(); expect(wrapper.get("[data-test=structure-error]").text()).toBe("no buffer"); }); it("shows the tree with kind icons and signatures, and updates on outlineChanged", async () => { outlines.set(3, SHOP); openTab(3, "src/Shop.php"); const { wrapper } = await mountStructure(); expect(rowNames(wrapper)).toEqual(["App", "Shop", "$items", "find", "save"]); const rows = wrapper.findAll("[data-test=structure-row]"); expect(rows.map((r) => r.attributes("data-kind"))).toEqual(["namespace", "class", "property", "method", "method"]); expect(rows.map((r) => r.attributes("aria-level"))).toEqual(["1", "2", "3", "3", "3"]); expect(rows[3]?.get(".structure-tree__detail").text()).toBe("(int $id): ?Product"); expect(rows[3]?.get(".structure-tree__icon").attributes("title")).toBe("Method"); expect(rows[3]?.find("svg").exists()).toBe(true); expect(rows[1]?.attributes("aria-expanded")).toBe("true"); expect(rows[2]?.attributes("aria-expanded")).toBeUndefined(); outlines.set(3, [item("class", "Shop", 3, [item("method", "find", 7)])]); await emit({ kind: "outlineChanged", id: 3 }); expect(rowNames(wrapper)).toEqual(["Shop", "find"]); }); it("jumps to a declaration on click, the chevron only folds", async () => { outlines.set(3, SHOP); openTab(3, "src/Shop.php"); const { wrapper, reveals } = await mountStructure(); await wrapper.findAll("[data-test=structure-row]")[3]?.trigger("click"); await flushPromises(); expect(reveals).toEqual([{ path: "src/Shop.php", line: 7, column: 4 }]); expect(wrapper.findAll("[data-test=structure-row]")[3]?.attributes("aria-selected")).toBe("true"); await wrapper.findAll("[data-test=structure-chevron]")[1]?.trigger("click"); await flushPromises(); expect(rowNames(wrapper)).toEqual(["App", "Shop"]); expect(reveals).toHaveLength(1); }); it("walks, folds and jumps with the keyboard", async () => { outlines.set(3, SHOP); openTab(3, "src/Shop.php"); const { wrapper, reveals } = await mountStructure(); const tree = wrapper.get("[data-test=structure-tree]"); await tree.trigger("focus"); const selected = (): string | undefined => wrapper.find("[data-test=structure-row][aria-selected=true] .structure-tree__name").text(); expect(selected()).toBe("App"); expect(tree.attributes("aria-activedescendant")).toBe(wrapper.findAll("[data-test=structure-row]")[0]?.attributes("id")); await key(wrapper, "ArrowRight"); expect(selected()).toBe("Shop"); await key(wrapper, "ArrowLeft"); expect(rowNames(wrapper)).toEqual(["App", "Shop"]); await key(wrapper, "ArrowRight"); expect(rowNames(wrapper)).toHaveLength(5); await key(wrapper, "End"); expect(selected()).toBe("save"); await key(wrapper, "ArrowUp"); await key(wrapper, "Enter"); await flushPromises(); expect(reveals).toEqual([{ path: "src/Shop.php", line: 7, column: 4 }]); await key(wrapper, "ArrowLeft"); expect(selected()).toBe("Shop"); await key(wrapper, "Home"); expect(selected()).toBe("App"); await key(wrapper, "ArrowDown"); expect(selected()).toBe("Shop"); }); }); describe("left stripe and view.toggleStructure", () => { /** Mounts the main layout with the commands store started. */ async function mountLayout(): Promise { const wrapper = mount(MainLayout, { attachTo: document.body, global: { plugins: [pinia], stubs: { ProjectToolWindow: true, StatusBar: true } }, }); mounted.push(wrapper); await useCommandsStore(pinia).start(); await flushPromises(); return wrapper; } /** The title of the left tool window, or null when it is hidden. */ function leftTitle(wrapper: VueWrapper): string | null { const window = wrapper.find("[data-test=tool-window]"); return window.exists() ? window.get(".tool-window__title").text() : null; } it("is registered with its own shortcut", async () => { await mountLayout(); const registered = calls.find((c) => c.command === "ui.registerCommands")?.params.commands as { id: string; defaultShortcut?: string; }[]; expect(registered.find((c) => c.id === "view.toggleStructure")?.defaultShortcut).toBe("Mod+2"); }); it("switches between Project and Structure from the stripe and hides the shown one", async () => { const wrapper = await mountLayout(); const tabs = wrapper.findAll("[role=tab]"); expect(tabs.map((tab) => tab.attributes("aria-label"))).toEqual(["Project", "Structure"]); expect(tabs.map((tab) => tab.attributes("aria-selected"))).toEqual(["true", "false"]); expect(leftTitle(wrapper)).toBe("Project"); await wrapper.get("[data-test=stripe-structure]").trigger("click"); expect(leftTitle(wrapper)).toBe("Structure"); expect(wrapper.get("[data-test=structure-empty]").isVisible()).toBe(true); await wrapper.get("[data-test=stripe-structure]").trigger("click"); expect(leftTitle(wrapper)).toBeNull(); expect(wrapper.findAll("[role=tab]").map((tab) => tab.attributes("aria-selected"))).toEqual(["false", "false"]); await wrapper.get("[data-test=stripe-project]").trigger("click"); expect(leftTitle(wrapper)).toBe("Project"); }); it("toggles Structure from the shortcut and from an agent's uiCommand", async () => { outlines.set(3, SHOP); openTab(3, "src/Shop.php"); const wrapper = await mountLayout(); window.dispatchEvent(new KeyboardEvent("keydown", { key: "2", code: "Digit2", ctrlKey: true, bubbles: true })); await flushPromises(); expect(leftTitle(wrapper)).toBe("Structure"); expect(rowNames(wrapper)).toEqual(["App", "Shop", "$items", "find", "save"]); await emit({ kind: "uiCommand", id: "view.toggleStructure", params: {} }); expect(leftTitle(wrapper)).toBeNull(); await emit({ kind: "uiCommand", id: "view.toggleStructure", params: {} }); expect(leftTitle(wrapper)).toBe("Structure"); await emit({ kind: "uiCommand", id: "view.toggleProjectTree", params: {} }); expect(leftTitle(wrapper)).toBe("Project"); }); });