Lutra/ui/tests/menu/AppMenu.test.ts
danny 8360ffc2e2 M4.3: side-by-side diff viewer with next/previous change
vcs.showDiff {path?, staged?} (Mod+Alt+Shift+D) opens a "Diff: <name>"
tab in the editor area: @codemirror/merge (MIT, loaded lazily, 27 kB /
9.7 kB gzip), with the index (or HEAD for the staged view) read-only on
the left, line breaks normalised to LF, and the working copy on the right,
editable through its normal engine buffer. vcs.nextChange (Alt+Shift+])
and vcs.previousChange (Alt+Shift+[) move between chunks. Binary, too
large, failed and deleted files show a notice. Entry points: the Changes
window, a new project tree context menu (Open, Show Diff; right click or
Shift+F10) and the palette/menu. Colours come from the --lt-vcs-* tokens.
21 Vitest tests; parity docs updated (Git 6% -> 8%, est.).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:44:56 +01:00

380 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Tests of the app menu (M3.9): the model (`buildMenu` grouping, order and
* labels, `typeAhead`), and the component: opening from the button, from
* `menu.open` and from a `uiCommand`, shortcuts and dimmed disabled items,
* the keyboard (arrows, Home/End, Enter, Escape, type-ahead), running
* engine and UI commands from it, and the modal rule (a launcher that any
* other command closes). 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";
import { defineComponent, h } from "vue";
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 { useModalsStore } from "../../src/commands/modals";
import { useCommandsStore, type PaletteEntry } from "../../src/commands/store";
import { UI_COMMANDS } from "../../src/commands/uiCommands";
import AppMenu from "../../src/components/menu/AppMenu.vue";
import { buildMenu, typeAhead } from "../../src/components/menu/menu";
import CommandPalette from "../../src/components/palette/CommandPalette.vue";
import SettingsDialog from "../../src/components/settings/SettingsDialog.vue";
/** Engine commands the fake lists. */
const ENGINE_COMMANDS = [
{ id: "app.about", label: "About Lutra", menuPath: "Help/About Lutra", defaultShortcut: null, params: "", enabled: true, ui: false },
{ id: "app.quit", label: "Quit", menuPath: "File/Quit", defaultShortcut: "Mod+Q", params: "", enabled: true, ui: false },
{ id: "buffer.close", label: "Close Buffer", menuPath: "File/Close Tab", defaultShortcut: "Mod+W", params: "", enabled: false, ui: false },
{ id: "buffer.edit", label: "Edit Buffer", menuPath: null, defaultShortcut: null, params: "", enabled: true, ui: false },
{ id: "file.save", label: "Save", menuPath: "File/Save", defaultShortcut: "Mod+S", params: "", enabled: true, ui: false },
{ id: "file.saveAll", label: "Save All", menuPath: "File/Save All", defaultShortcut: "Mod+Alt+S", params: "", enabled: true, ui: false },
{ id: "project.close", label: "Close Project", menuPath: "File/Close Project", defaultShortcut: null, params: "", enabled: false, ui: false },
{ id: "project.openDialog", label: "Open Folder…", menuPath: "File/Open Folder…", defaultShortcut: "Mod+O", params: "", enabled: true, ui: false },
];
/** The engine event callbacks, one per subscription. */
let listeners: ((payload: unknown) => void)[];
/** Every `engine_execute` call, in order. */
let calls: { command: string; params: unknown }[];
/** Pinia of the current test. */
let pinia: Pinia;
/** Mounted components, unmounted after each test. */
let mounted: VueWrapper[];
/** The fake engine's listing: its commands plus the registered UI commands. */
function listing(): unknown[] {
const registered = calls.find((c) => c.command === "ui.registerCommands")?.params as
| { commands: { id: string; labelKey: string; menuPath?: string; defaultShortcut?: string }[] }
| undefined;
const ui = (registered?.commands ?? []).map((c) => ({
id: c.id,
label: c.labelKey,
labelKey: c.labelKey,
menuPath: c.menuPath ?? null,
defaultShortcut: c.defaultShortcut ?? null,
params: "",
enabled: true,
ui: true,
}));
return [...ENGINE_COMMANDS, ...ui];
}
/**
* Sends an engine event to every subscriber.
*
* @param payload - the event.
*/
async function emit(payload: unknown): Promise<void> {
for (const listener of listeners) {
listener(payload);
}
await flushPromises();
}
/**
* Presses a key on the focused element (or the body).
*
* @param init - key event properties.
*/
async function press(init: KeyboardEventInit): Promise<void> {
const target = document.activeElement ?? document.body;
target.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...init }));
await flushPromises();
}
/** The `menu.open` shortcut, `Alt+M`. */
const MENU_KEY: KeyboardEventInit = { key: "m", code: "KeyM", altKey: true };
/** A focusable button standing in for the editor. */
const Host = defineComponent({
setup: () => () => h("button", { id: "host-button" }, "host"),
});
/** Mounts the editor stand-in, the menu and the other modals, and starts the commands. */
async function mountApp(): Promise<VueWrapper> {
const host = mount(Host, { attachTo: document.body });
const menu = mount(AppMenu, { attachTo: document.body, global: { plugins: [pinia] } });
const palette = mount(CommandPalette, { attachTo: document.body, global: { plugins: [pinia] } });
const settings = mount(SettingsDialog, { attachTo: document.body, global: { plugins: [pinia] } });
mounted.push(host, menu, palette, settings);
await useCommandsStore(pinia).start();
await flushPromises();
document.getElementById("host-button")?.focus();
return menu;
}
/** Whether the dropdown is shown. */
function menuShown(): boolean {
return document.querySelector("[data-test=menu]") !== null;
}
/** The command id of the focused item, or null. */
function focusedCommand(): string | null {
const active = document.activeElement;
return active instanceof HTMLElement ? (active.dataset.command ?? null) : null;
}
/** The items' command ids in display order. */
function itemIds(): string[] {
return [...document.querySelectorAll<HTMLElement>("[data-test=menu-item]")].map((el) => el.dataset.command ?? "");
}
/**
* Builds a palette entry for the model tests.
*
* @param id - command id.
* @param menuPath - its menu path.
* @param ui - whether it is a UI command.
*/
function entry(id: string, menuPath: string | null, ui = false): PaletteEntry {
return { id, label: `label of ${id}`, shortcut: null, enabled: true, menuPath, ui };
}
beforeEach(() => {
pinia = createPinia();
setActivePinia(pinia);
listeners = [];
calls = [];
mounted = [];
listen.mockReset();
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
listeners.push((payload) => {
callback({ payload });
});
return Promise.resolve(() => undefined);
});
invoke.mockReset();
invoke.mockImplementation((cmd: string, args?: { command: string; params: unknown }) => {
if (cmd === "engine_list_commands") {
return Promise.resolve(listing());
}
if (cmd === "engine_execute" && args) {
calls.push({ command: args.command, params: args.params });
if (args.command === "settings.list") {
return Promise.resolve([]);
}
if (args.command === "settings.get") {
return Promise.resolve({ values: {} });
}
}
return Promise.resolve(null);
});
});
afterEach(() => {
useCommandsStore(pinia).stop();
for (const wrapper of mounted) {
wrapper.unmount();
}
document.body.innerHTML = "";
});
describe("buildMenu", () => {
it("groups by the first segment in Lutra's order, unknown groups before Help", () => {
const groups = buildMenu([
entry("app.about", "Help/About Lutra"),
entry("x.tool", "Tools/Thing"),
entry("goto.fileOpen", "Go/File…", true),
entry("file.save", "File/Save"),
entry("palette.open", "View/Command Palette", true),
entry("buffer.edit", null),
]);
expect(groups.map((g) => g.key)).toEqual(["File", "View", "Go", "Tools", "Help"]);
expect(groups.map((g) => g.label)).toEqual(["File", "View", "Go", "Tools", "Help"]);
});
it("orders known items and sorts the others by label after them", () => {
const groups = buildMenu([
entry("zzz.other", "File/Another"),
entry("app.quit", "File/Quit"),
entry("project.openDialog", "File/Open Folder…"),
entry("aaa.other", "File/Bother"),
entry("file.save", "File/Save"),
]);
expect(groups[0]?.items.map((i) => i.id)).toEqual(["project.openDialog", "file.save", "app.quit", "zzz.other", "aaa.other"]);
});
it("labels engine commands by their path and UI commands by their catalog label", () => {
const groups = buildMenu([
entry("buffer.close", "File/Close Tab"),
entry("deep.one", "File/Recent/Project A"),
entry("settings.open", "View/Settings…", true),
]);
expect(groups[0]?.items.map((i) => i.label)).toEqual(["Close Tab", "Recent › Project A"]);
expect(groups[1]?.items.map((i) => i.label)).toEqual(["label of settings.open"]);
});
it("skips empty paths and trims segments", () => {
const groups = buildMenu([entry("a.b", "/"), entry("c.d", ""), entry("e.f", " File / Save ")]);
expect(groups).toHaveLength(1);
expect(groups[0]?.items[0]?.label).toBe("Save");
});
});
describe("typeAhead", () => {
const labels = ["Open Folder…", "Save", "Save All", "Close Tab", "Settings…"];
it("finds the next item with the typed initial and cycles", () => {
expect(typeAhead(labels, "s", 0)).toBe(1);
expect(typeAhead(labels, "s", 1)).toBe(2);
expect(typeAhead(labels, "s", 4)).toBe(1);
});
it("matches longer text from the focused item on, case-insensitively", () => {
expect(typeAhead(labels, "SE", 1)).toBe(4);
expect(typeAhead(labels, "sa", 1)).toBe(1);
});
it("returns -1 without a match", () => {
expect(typeAhead(labels, "x", 0)).toBe(-1);
expect(typeAhead([], "s", -1)).toBe(-1);
expect(typeAhead(labels, "", 0)).toBe(-1);
});
});
describe("AppMenu", () => {
it("registers menu.open with its shortcut and gives commands menu paths", () => {
const spec = UI_COMMANDS.find((c) => c.id === "menu.open");
expect(spec?.defaultShortcut).toBe("Alt+M");
expect(UI_COMMANDS.find((c) => c.id === "settings.open")?.menuPath).toBe("View/Settings…");
expect(UI_COMMANDS.find((c) => c.id === "goto.fileOpen")?.menuPath).toBe("Go/File…");
expect(UI_COMMANDS.find((c) => c.id === "terminal.open")?.menuPath).toBe("View/Terminal");
});
it("opens from the button with groups, shortcuts and dimmed disabled items", async () => {
const menu = await mountApp();
expect(menuShown()).toBe(false);
await menu.find("[data-test=menu-button]").trigger("click");
await flushPromises();
expect(menuShown()).toBe(true);
expect(menu.find("[data-test=menu-button]").attributes("aria-expanded")).toBe("true");
const headings = [...document.querySelectorAll("[data-test=menu-group]")].map((g) => g.querySelector(".app-menu__heading")?.textContent.trim());
expect(headings).toEqual(["File", "Edit", "View", "Go", "Git", "Help"]);
expect(itemIds()).toEqual([
"project.openDialog",
"file.save",
"file.saveAll",
"buffer.close",
"project.close",
"app.quit",
"editor.complete",
"editor.parameterInfo",
"editor.quickDocumentation",
"palette.open",
"view.toggleProjectTree",
"view.toggleStructure",
"find.open",
"terminal.open",
"problems.open",
"settings.open",
"goto.fileOpen",
"goto.classOpen",
"goto.symbolOpen",
"vcs.openChanges",
"vcs.commit",
"vcs.nextChange",
"vcs.previousChange",
"vcs.refresh",
"vcs.showDiff",
"app.about",
]);
const close = document.querySelector("[data-command='buffer.close']");
expect(close?.textContent).toContain("Close Tab");
expect(close?.querySelector("[data-test=menu-shortcut]")?.textContent).toBe("Ctrl+W");
expect(close?.getAttribute("aria-disabled")).toBe("true");
expect(close?.classList.contains("app-menu__item--disabled")).toBe(true);
expect(document.querySelector("[data-command='settings.open']")?.textContent).toContain("Settings…");
expect(focusedCommand()).toBe("project.openDialog");
await menu.find("[data-test=menu-button]").trigger("click");
expect(menuShown()).toBe(false);
});
it("opens with Alt+M and from a uiCommand", async () => {
await mountApp();
await press(MENU_KEY);
expect(menuShown()).toBe(true);
await press({ key: "Escape" });
expect(menuShown()).toBe(false);
expect(document.activeElement?.id).toBe("host-button");
await emit({ kind: "uiCommand", id: "menu.open", params: {} });
expect(menuShown()).toBe(true);
expect(useModalsStore(pinia).current).toBe("menu");
});
it("moves with arrows, Home and End, wrapping", async () => {
await mountApp();
await press(MENU_KEY);
await press({ key: "ArrowUp" });
expect(focusedCommand()).toBe("app.about");
await press({ key: "ArrowDown" });
expect(focusedCommand()).toBe("project.openDialog");
await press({ key: "ArrowDown" });
expect(focusedCommand()).toBe("file.save");
await press({ key: "End" });
expect(focusedCommand()).toBe("app.about");
await press({ key: "Home" });
expect(focusedCommand()).toBe("project.openDialog");
});
it("jumps by typed text", async () => {
await mountApp();
await press(MENU_KEY);
await press({ key: "s" });
expect(focusedCommand()).toBe("file.save");
await press({ key: "e" });
expect(focusedCommand()).toBe("settings.open");
});
it("runs Settings with Enter: the menu closes and the dialog opens", async () => {
await mountApp();
await press(MENU_KEY);
await press({ key: "s" });
await press({ key: "e" });
await press({ key: "Enter" });
expect(menuShown()).toBe(false);
expect(document.querySelector("[data-test=settings]")).not.toBeNull();
expect(useModalsStore(pinia).current).toBe("settings");
});
it("runs an engine command on click and ignores disabled items", async () => {
await mountApp();
await press(MENU_KEY);
document.querySelector<HTMLElement>("[data-command='project.close']")?.click();
await flushPromises();
expect(menuShown()).toBe(true);
expect(calls.map((c) => c.command)).not.toContain("project.close");
await press({ key: "End" });
document.querySelector<HTMLElement>("[data-command='project.openDialog']")?.click();
await flushPromises();
expect(menuShown()).toBe(false);
expect(calls.map((c) => c.command)).toContain("project.openDialog");
});
it("closes on a click outside", async () => {
await mountApp();
await press(MENU_KEY);
document.querySelector("[data-test=menu-backdrop]")?.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true }));
await flushPromises();
expect(menuShown()).toBe(false);
});
it("is a launcher: another command or modal closes it", async () => {
await mountApp();
await press(MENU_KEY);
await press({ key: "s", code: "KeyS", ctrlKey: true });
expect(menuShown()).toBe(false);
expect(calls.map((c) => c.command)).toContain("file.save");
await press(MENU_KEY);
await emit({ kind: "uiCommand", id: "palette.open", params: {} });
expect(menuShown()).toBe(false);
expect(document.querySelector("[data-test=palette]")).not.toBeNull();
await press(MENU_KEY);
expect(document.querySelector("[data-test=palette]")).toBeNull();
expect(menuShown()).toBe(true);
});
});