M1.8: command palette, global keymap, UI commands
- Engine: ui.registerCommands (validated, replaces the previous set),
UI commands in listCommands with ui: true and labelKey, running one
through the engine emits uiCommand {id, params}.
- Frontend: ui/src/commands/ (keymap by key code, fuzzy ranking, Pinia
commands store with handlers, recents and error toasts), the command
palette (Mod+Shift+P), UI commands palette.open, settings.open (Mod+,,
disabled until M1.9b) and view.toggleProjectTree (Mod+1). The editor's
shortcuts.ts moved into the global keymap.
- Tests: engine and control-channel tests for registration and
uiCommand, Vitest for keymap, ranking, store, palette and App wiring.
- Docs: architecture, ui-parity, target-app-parity, gaps, roadmap,
ROADMAP, README.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2f8fef876b
commit
184b8a3468
33 changed files with 2282 additions and 233 deletions
|
|
@ -1,6 +1,8 @@
|
|||
/**
|
||||
* Tests for the root component: it loads product information on mount and
|
||||
* shows it, or the error, in the status bar.
|
||||
* shows it, or the error, in the status bar, and it wires the UI commands:
|
||||
* `Mod+1` hides and shows the Project tool window, `Mod+Shift+P` opens the
|
||||
* palette.
|
||||
*/
|
||||
import { flushPromises, mount } from "@vue/test-utils";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
|
|
@ -39,4 +41,25 @@ describe("App", () => {
|
|||
expect(bar.text()).toBe("engine unavailable");
|
||||
expect(bar.classes()).toContain("status-bar--error");
|
||||
});
|
||||
|
||||
it("toggles the project tree and opens the palette from the keyboard", async () => {
|
||||
invoke.mockImplementation((command: string) =>
|
||||
Promise.resolve(command === "engine_list_commands" ? [] : null),
|
||||
);
|
||||
const wrapper = mount(App, { attachTo: document.body });
|
||||
await flushPromises();
|
||||
const press = async (init: KeyboardEventInit): Promise<void> => {
|
||||
window.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...init }));
|
||||
await flushPromises();
|
||||
};
|
||||
expect(wrapper.find("[data-test=tool-window]").exists()).toBe(true);
|
||||
await press({ key: "1", code: "Digit1", ctrlKey: true });
|
||||
expect(wrapper.find("[data-test=tool-window]").exists()).toBe(false);
|
||||
expect(wrapper.find("[data-test=tool-window-stripe]").exists()).toBe(true);
|
||||
await press({ key: "1", code: "Digit1", ctrlKey: true });
|
||||
expect(wrapper.find("[data-test=tool-window]").exists()).toBe(true);
|
||||
await press({ key: "P", code: "KeyP", ctrlKey: true, shiftKey: true });
|
||||
expect(wrapper.find("[data-test=palette]").exists()).toBe(true);
|
||||
wrapper.unmount();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
86
ui/tests/commands/keymap.test.ts
Normal file
86
ui/tests/commands/keymap.test.ts
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
/**
|
||||
* Tests of the global keymap: parsing Lutra notation (`Mod` per platform),
|
||||
* matching by key code independent of what Alt and Shift type, building
|
||||
* the keymap from command descriptions and formatting shortcuts for
|
||||
* display.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildKeymap, commandFor, eventKey, formatShortcut, matches, parseShortcut } from "../../src/commands/keymap";
|
||||
|
||||
/**
|
||||
* A key event.
|
||||
*
|
||||
* @param init - its properties.
|
||||
*/
|
||||
function key(init: KeyboardEventInit): KeyboardEvent {
|
||||
return new KeyboardEvent("keydown", init);
|
||||
}
|
||||
|
||||
describe("parseShortcut", () => {
|
||||
it("maps Mod to Ctrl or Cmd", () => {
|
||||
expect(parseShortcut("Mod+Shift+P", false)).toEqual({ ctrl: true, meta: false, alt: false, shift: true, key: "p" });
|
||||
expect(parseShortcut("Mod+Shift+P", true)).toEqual({ ctrl: false, meta: true, alt: false, shift: true, key: "p" });
|
||||
});
|
||||
|
||||
it("reads punctuation, digits and the plus key", () => {
|
||||
expect(parseShortcut("Mod+,", false)?.key).toBe(",");
|
||||
expect(parseShortcut("Mod+1", false)?.key).toBe("1");
|
||||
expect(parseShortcut("Mod++", false)).toEqual({ ctrl: true, meta: false, alt: false, shift: false, key: "+" });
|
||||
});
|
||||
|
||||
it("rejects unknown modifiers and missing keys", () => {
|
||||
expect(parseShortcut("Hyper+S", false)).toBeNull();
|
||||
expect(parseShortcut("Mod+", false)).toBeNull();
|
||||
expect(parseShortcut("", false)).toBeNull();
|
||||
expect(parseShortcut("Mod++S", false)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("matching", () => {
|
||||
it("uses the key code for letters, digits and punctuation", () => {
|
||||
expect(eventKey(key({ key: "ß", code: "KeyS" }))).toBe("s");
|
||||
expect(eventKey(key({ key: "!", code: "Digit1" }))).toBe("1");
|
||||
expect(eventKey(key({ key: ";", code: "Comma" }))).toBe(",");
|
||||
expect(eventKey(key({ key: "F4", code: "F4" }))).toBe("f4");
|
||||
});
|
||||
|
||||
it("requires the exact modifiers", () => {
|
||||
const shortcut = parseShortcut("Mod+Shift+P", false);
|
||||
expect(shortcut).not.toBeNull();
|
||||
if (!shortcut) {
|
||||
return;
|
||||
}
|
||||
expect(matches(key({ key: "P", code: "KeyP", ctrlKey: true, shiftKey: true }), shortcut)).toBe(true);
|
||||
expect(matches(key({ key: "p", code: "KeyP", ctrlKey: true }), shortcut)).toBe(false);
|
||||
expect(matches(key({ key: "P", code: "KeyP", ctrlKey: true, shiftKey: true, altKey: true }), shortcut)).toBe(false);
|
||||
});
|
||||
|
||||
it("finds the command of a key press, the first listed winning", () => {
|
||||
const keymap = buildKeymap(
|
||||
[
|
||||
{ id: "palette.open", defaultShortcut: "Mod+Shift+P" },
|
||||
{ id: "settings.open", defaultShortcut: "Mod+," },
|
||||
{ id: "view.toggleProjectTree", defaultShortcut: "Mod+1" },
|
||||
{ id: "other.palette", defaultShortcut: "Mod+Shift+P" },
|
||||
{ id: "no.shortcut", defaultShortcut: null },
|
||||
{ id: "bad.shortcut", defaultShortcut: "Hyper+X" },
|
||||
],
|
||||
false,
|
||||
);
|
||||
expect(keymap.map((b) => b.command)).toEqual(["palette.open", "settings.open", "view.toggleProjectTree", "other.palette"]);
|
||||
expect(commandFor(keymap, key({ key: "P", code: "KeyP", ctrlKey: true, shiftKey: true }))).toBe("palette.open");
|
||||
expect(commandFor(keymap, key({ key: ",", code: "Comma", ctrlKey: true }))).toBe("settings.open");
|
||||
expect(commandFor(keymap, key({ key: "1", code: "Digit1", ctrlKey: true }))).toBe("view.toggleProjectTree");
|
||||
expect(commandFor(keymap, key({ key: "1", code: "Digit1", metaKey: true }))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatShortcut", () => {
|
||||
it("names the modifiers of the platform", () => {
|
||||
expect(formatShortcut("Mod+Shift+P", false)).toBe("Ctrl+Shift+P");
|
||||
expect(formatShortcut("Mod+Alt+S", true)).toBe("Option+Cmd+S");
|
||||
expect(formatShortcut("Mod+,", false)).toBe("Ctrl+,");
|
||||
expect(formatShortcut("Shift+F4", false)).toBe("Shift+F4");
|
||||
expect(formatShortcut("Nope+X", false)).toBeNull();
|
||||
});
|
||||
});
|
||||
94
ui/tests/commands/rank.test.ts
Normal file
94
ui/tests/commands/rank.test.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
/**
|
||||
* Tests of the palette ranking: the match tiers (prefix, word prefix,
|
||||
* word starts, substring, in-order characters), matching on the id as
|
||||
* well as the label, recently run commands first, and the order without a
|
||||
* query.
|
||||
*/
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Tier, matchText, rank, words } from "../../src/commands/rank";
|
||||
|
||||
/** Commands as the palette ranks them. */
|
||||
const COMMANDS = [
|
||||
{ id: "file.save", label: "Save" },
|
||||
{ id: "file.saveAll", label: "Save All" },
|
||||
{ id: "project.openDialog", label: "Open Folder…" },
|
||||
{ id: "project.close", label: "Close Project" },
|
||||
{ id: "buffer.close", label: "Close Tab" },
|
||||
{ id: "view.toggleProjectTree", label: "Show or Hide Project" },
|
||||
{ id: "palette.open", label: "Command Palette" },
|
||||
{ id: "app.quit", label: "Quit" },
|
||||
];
|
||||
|
||||
/**
|
||||
* The ids of the ranking.
|
||||
*
|
||||
* @param query - the query.
|
||||
* @param recent - recently run ids.
|
||||
*/
|
||||
function ids(query: string, recent: string[] = []): string[] {
|
||||
return rank(COMMANDS, query, recent).map((c) => c.id);
|
||||
}
|
||||
|
||||
describe("words", () => {
|
||||
it("splits at punctuation, spaces and camelCase", () => {
|
||||
expect(words("view.toggleProjectTree")).toEqual(["view", "toggle", "project", "tree"]);
|
||||
expect(words("Open Folder…")).toEqual(["open", "folder"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("matchText", () => {
|
||||
it("sorts matches into tiers", () => {
|
||||
expect(matchText("sav", "Save All")?.tier).toBe(Tier.Prefix);
|
||||
expect(matchText("all", "Save All")?.tier).toBe(Tier.WordPrefix);
|
||||
expect(matchText("hide proj", "Show or Hide Project")?.tier).toBe(Tier.WordPrefix);
|
||||
expect(matchText("shp", "Show or Hide Project")?.tier).toBe(Tier.WordStarts);
|
||||
expect(matchText("togpro", "view.toggleProjectTree")?.tier).toBe(Tier.WordStarts);
|
||||
expect(matchText("ave", "Save All")?.tier).toBe(Tier.Substring);
|
||||
expect(matchText("sel", "Save All")?.tier).toBe(Tier.Fuzzy);
|
||||
expect(matchText("xyz", "Save All")).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores case and surrounding spaces", () => {
|
||||
expect(matchText(" SAVE ", "save all")?.tier).toBe(Tier.Prefix);
|
||||
});
|
||||
});
|
||||
|
||||
describe("rank", () => {
|
||||
it("puts prefix and word-start matches before in-order characters", () => {
|
||||
expect(ids("clo")).toEqual(["buffer.close", "project.close", "project.openDialog"]);
|
||||
expect(ids("pro").slice(0, 3)).toEqual(["project.close", "project.openDialog", "view.toggleProjectTree"]);
|
||||
expect(ids("sa")[0]).toBe("file.save");
|
||||
});
|
||||
|
||||
it("matches the id too", () => {
|
||||
expect(ids("togglepro")).toEqual(["view.toggleProjectTree"]);
|
||||
expect(ids("app.quit")).toEqual(["app.quit"]);
|
||||
});
|
||||
|
||||
it("puts recent commands first within a tier", () => {
|
||||
expect(ids("clo", ["project.close"]).slice(0, 2)).toEqual(["project.close", "buffer.close"]);
|
||||
expect(ids("sav", ["file.saveAll"])).toEqual(["file.saveAll", "file.save"]);
|
||||
expect(ids("sav", ["project.close"])).toEqual(["file.save", "file.saveAll"]);
|
||||
});
|
||||
|
||||
it("does not let recency beat a better tier", () => {
|
||||
expect(ids("sa", ["view.toggleProjectTree"])[0]).toBe("file.save");
|
||||
});
|
||||
|
||||
it("lists everything without a query, recent first, then by label", () => {
|
||||
expect(ids("", ["app.quit", "file.save"])).toEqual([
|
||||
"app.quit",
|
||||
"file.save",
|
||||
"project.close",
|
||||
"buffer.close",
|
||||
"palette.open",
|
||||
"project.openDialog",
|
||||
"file.saveAll",
|
||||
"view.toggleProjectTree",
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns nothing for a query that matches nothing", () => {
|
||||
expect(ids("zzz")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
|
@ -2,8 +2,9 @@
|
|||
* 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 shortcuts loaded
|
||||
* from the engine's command list, and the notice for files changed on disk.
|
||||
* Save / Don't Save / Cancel question), saving through the global keymap
|
||||
* (`commands/store.ts`) with shortcuts loaded from the engine's command
|
||||
* list, and the notice for files changed on disk.
|
||||
* The engine is a fake behind the mocked Tauri `invoke`.
|
||||
*/
|
||||
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
|
||||
|
|
@ -14,6 +15,7 @@ import { afterEach, 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";
|
||||
|
|
@ -159,8 +161,9 @@ let pinia: Pinia;
|
|||
/** Mounted components to unmount after each test. */
|
||||
let mounted: VueWrapper[] = [];
|
||||
|
||||
/** Mounts the editor area. */
|
||||
/** Mounts the editor area and starts the global keymap. */
|
||||
async function mountArea(): Promise<VueWrapper> {
|
||||
await useCommandsStore(pinia).start();
|
||||
const wrapper = mount(EditorArea, {
|
||||
attachTo: document.body,
|
||||
slots: { default: "empty" },
|
||||
|
|
@ -236,6 +239,7 @@ beforeEach(() => {
|
|||
|
||||
afterEach(async () => {
|
||||
await flushPromises();
|
||||
useCommandsStore(pinia).stop();
|
||||
for (const wrapper of mounted) {
|
||||
wrapper.unmount();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,9 +27,12 @@ function sourceFiles(dir: string): string[] {
|
|||
});
|
||||
}
|
||||
|
||||
/** Every call of `t` with a literal first argument, by file. */
|
||||
/**
|
||||
* Every call of `t` with a literal first argument, and every literal
|
||||
* `labelKey` (UI commands, whose labels the palette looks up), by file.
|
||||
*/
|
||||
const usedKeys = sourceFiles(SRC).flatMap((file) =>
|
||||
[...readFileSync(file, "utf8").matchAll(/\bt\(\s*(["'`])([^"'`]*)\1/g)].map((m) => ({
|
||||
[...readFileSync(file, "utf8").matchAll(/(?:\bt\(|\blabelKey:)\s*(["'`])([^"'`]*)\1/g)].map((m) => ({
|
||||
file,
|
||||
key: m[2] ?? "",
|
||||
})),
|
||||
|
|
@ -105,7 +108,7 @@ describe("en.json", () => {
|
|||
it("uses flat dotted keys of known areas with string values", () => {
|
||||
for (const [key, value] of Object.entries(en)) {
|
||||
expect(key).toMatch(
|
||||
/^(app|project|editor|common|theme|recovery|notification)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
|
||||
/^(app|command|project|editor|common|palette|theme|recovery|notification)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
|
||||
);
|
||||
expect(typeof value).toBe("string");
|
||||
expect(value.trim()).not.toBe("");
|
||||
|
|
|
|||
350
ui/tests/palette/CommandPalette.test.ts
Normal file
350
ui/tests/palette/CommandPalette.test.ts
Normal file
|
|
@ -0,0 +1,350 @@
|
|||
/**
|
||||
* Tests of the command store and the palette: registering the UI commands
|
||||
* with the engine, the global keymap, running engine and UI commands
|
||||
* (error toasts for failures, disabled commands doing nothing), `uiCommand`
|
||||
* events from the engine, and the palette's keyboard handling, ranking,
|
||||
* shortcuts, dimmed disabled rows and recent commands. 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 { useCommandsStore } from "../../src/commands/store";
|
||||
import { UI_COMMANDS } from "../../src/commands/uiCommands";
|
||||
import CommandPalette from "../../src/components/palette/CommandPalette.vue";
|
||||
import { useNotificationsStore } from "../../src/stores/notifications";
|
||||
|
||||
/** Engine commands the fake lists. */
|
||||
const ENGINE_COMMANDS = [
|
||||
{ id: "app.quit", label: "Quit", menuPath: "File/Quit", defaultShortcut: "Mod+Q", 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 },
|
||||
{ id: "buffer.edit", label: "Edit Buffer", menuPath: null, defaultShortcut: null, params: "", enabled: true, ui: false },
|
||||
];
|
||||
|
||||
/** Every `engine_execute` call, in order. */
|
||||
let calls: { command: string; params: unknown }[];
|
||||
/** Engine commands that fail, with their error code. */
|
||||
let failing: Map<string, string>;
|
||||
/** The engine event callback the store subscribed with. */
|
||||
let deliver: ((payload: unknown) => void) | null;
|
||||
/** 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; defaultShortcut?: string }[] }
|
||||
| undefined;
|
||||
const ui = (registered?.commands ?? []).map((c) => ({
|
||||
id: c.id,
|
||||
label: c.labelKey,
|
||||
labelKey: c.labelKey,
|
||||
menuPath: null,
|
||||
defaultShortcut: c.defaultShortcut ?? null,
|
||||
params: "",
|
||||
enabled: true,
|
||||
ui: true,
|
||||
}));
|
||||
return [...ENGINE_COMMANDS, ...ui];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an engine event to the store.
|
||||
*
|
||||
* @param payload - the event.
|
||||
*/
|
||||
async function emit(payload: unknown): Promise<void> {
|
||||
deliver?.(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();
|
||||
}
|
||||
|
||||
/** Ctrl+Shift+P, the palette's shortcut off macOS. */
|
||||
const PALETTE_KEY = { key: "P", code: "KeyP", ctrlKey: true, shiftKey: true };
|
||||
|
||||
/** A focusable button standing in for the editor. */
|
||||
const Host = defineComponent({
|
||||
setup: () => () => h("button", { id: "host-button" }, "host"),
|
||||
});
|
||||
|
||||
/** Mounts the palette next to a focusable button and starts the store. */
|
||||
async function mountPalette(): Promise<VueWrapper> {
|
||||
const host = mount(Host, { attachTo: document.body });
|
||||
const wrapper = mount(CommandPalette, { attachTo: document.body, global: { plugins: [pinia] } });
|
||||
mounted.push(host, wrapper);
|
||||
await useCommandsStore(pinia).start();
|
||||
await flushPromises();
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ids of the palette's rows, in order.
|
||||
*
|
||||
* @param wrapper - the palette.
|
||||
*/
|
||||
function rows(wrapper: VueWrapper): string[] {
|
||||
return wrapper.findAll("[data-test=palette-row]").map((row) => row.attributes("data-command") ?? "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Types into the palette's search field.
|
||||
*
|
||||
* @param wrapper - the palette.
|
||||
* @param text - the query.
|
||||
*/
|
||||
async function type(wrapper: VueWrapper, text: string): Promise<void> {
|
||||
await wrapper.find("[data-test=palette-input]").setValue(text);
|
||||
await flushPromises();
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
pinia = createPinia();
|
||||
setActivePinia(pinia);
|
||||
calls = [];
|
||||
failing = new Map();
|
||||
deliver = null;
|
||||
mounted = [];
|
||||
Element.prototype.scrollIntoView = () => undefined;
|
||||
invoke.mockReset();
|
||||
listen.mockReset();
|
||||
listen.mockImplementation((_name: string, callback: (event: { payload: unknown }) => void) => {
|
||||
deliver = (payload) => {
|
||||
callback({ payload });
|
||||
};
|
||||
return Promise.resolve(() => undefined);
|
||||
});
|
||||
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 });
|
||||
const code = failing.get(args.command);
|
||||
if (code !== undefined) {
|
||||
return Promise.reject(Object.assign(new Error(code), { code, message: `${args.command} broke` }));
|
||||
}
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
return Promise.resolve(null);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
useCommandsStore(pinia).stop();
|
||||
for (const wrapper of mounted) {
|
||||
wrapper.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
describe("command store", () => {
|
||||
it("registers the UI commands and lists them from the engine", async () => {
|
||||
await mountPalette();
|
||||
const store = useCommandsStore(pinia);
|
||||
expect(calls[0]).toEqual({ command: "ui.registerCommands", params: { commands: UI_COMMANDS.map((c) => ({ ...c })) } });
|
||||
expect(store.infos.filter((c) => c.ui === true).map((c) => c.id)).toEqual(UI_COMMANDS.map((c) => c.id));
|
||||
expect(store.entries.map((e) => e.id)).not.toContain("buffer.edit");
|
||||
const toggle = store.entries.find((e) => e.id === "view.toggleProjectTree");
|
||||
expect(toggle).toEqual({ id: "view.toggleProjectTree", label: "Show or Hide Project", shortcut: "Ctrl+1", enabled: false });
|
||||
});
|
||||
|
||||
it("keeps the UI commands when the engine refuses them, with an error toast", async () => {
|
||||
failing.set("ui.registerCommands", "invalid_params");
|
||||
await mountPalette();
|
||||
const store = useCommandsStore(pinia);
|
||||
expect(store.entries.map((e) => e.id)).toContain("palette.open");
|
||||
expect(useNotificationsStore(pinia).toasts.map((t) => t.text)).toEqual([
|
||||
"ui.registerCommands failed: ui.registerCommands broke",
|
||||
]);
|
||||
});
|
||||
|
||||
it("runs engine commands from their shortcut and reports failures", async () => {
|
||||
await mountPalette();
|
||||
failing.set("project.openDialog", "failed");
|
||||
await press({ key: "o", code: "KeyO", ctrlKey: true });
|
||||
expect(calls.at(-1)).toEqual({ command: "project.openDialog", params: {} });
|
||||
expect(useNotificationsStore(pinia).toasts.map((t) => t.text)).toEqual([
|
||||
"project.openDialog failed: project.openDialog broke",
|
||||
]);
|
||||
});
|
||||
|
||||
it("runs provided handlers and skips disabled commands", async () => {
|
||||
await mountPalette();
|
||||
const store = useCommandsStore(pinia);
|
||||
let toggled = 0;
|
||||
let allowed = false;
|
||||
const withdraw = store.provide("view.toggleProjectTree", {
|
||||
run: () => {
|
||||
toggled += 1;
|
||||
},
|
||||
enabled: () => allowed,
|
||||
});
|
||||
const event = new KeyboardEvent("keydown", { key: "1", code: "Digit1", ctrlKey: true, bubbles: true, cancelable: true });
|
||||
window.dispatchEvent(event);
|
||||
await flushPromises();
|
||||
expect(toggled).toBe(0);
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
allowed = true;
|
||||
await press({ key: "1", code: "Digit1", ctrlKey: true });
|
||||
expect(toggled).toBe(1);
|
||||
withdraw();
|
||||
await press({ key: "1", code: "Digit1", ctrlKey: true });
|
||||
expect(toggled).toBe(1);
|
||||
expect(calls.map((c) => c.command)).toEqual(["ui.registerCommands"]);
|
||||
});
|
||||
|
||||
it("runs a uiCommand from the engine and warns about one nobody handles", async () => {
|
||||
await mountPalette();
|
||||
const store = useCommandsStore(pinia);
|
||||
const seen: unknown[] = [];
|
||||
store.provide("view.toggleProjectTree", {
|
||||
run: (params) => {
|
||||
seen.push(params);
|
||||
},
|
||||
});
|
||||
await emit({ kind: "uiCommand", id: "view.toggleProjectTree", params: { from: "agent" } });
|
||||
expect(seen).toEqual([{ from: "agent" }]);
|
||||
await emit({ kind: "uiCommand", id: "settings.open", params: {} });
|
||||
expect(useNotificationsStore(pinia).toasts.map((t) => t.text)).toEqual(["settings.open cannot run right now"]);
|
||||
expect(store.recent).toEqual(["view.toggleProjectTree"]);
|
||||
});
|
||||
|
||||
it("reports a handler that throws", async () => {
|
||||
await mountPalette();
|
||||
const store = useCommandsStore(pinia);
|
||||
store.provide("view.toggleProjectTree", {
|
||||
run: () => {
|
||||
throw new Error("boom");
|
||||
},
|
||||
});
|
||||
await store.execute("view.toggleProjectTree");
|
||||
expect(useNotificationsStore(pinia).toasts.map((t) => t.text)).toEqual(["view.toggleProjectTree failed: boom"]);
|
||||
});
|
||||
|
||||
it("reloads the enabled states when a project opens", async () => {
|
||||
await mountPalette();
|
||||
const before = invoke.mock.calls.filter(([cmd]) => cmd === "engine_list_commands").length;
|
||||
await emit({ kind: "projectOpened", root: "/p", name: "p" });
|
||||
expect(invoke.mock.calls.filter(([cmd]) => cmd === "engine_list_commands").length).toBe(before + 1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("CommandPalette", () => {
|
||||
it("opens with Mod+Shift+P and lists commands with shortcuts", async () => {
|
||||
const wrapper = await mountPalette();
|
||||
expect(wrapper.find("[data-test=palette]").exists()).toBe(false);
|
||||
await press(PALETTE_KEY);
|
||||
expect(wrapper.find("[data-test=palette]").exists()).toBe(true);
|
||||
expect(document.activeElement).toBe(wrapper.find("[data-test=palette-input]").element);
|
||||
expect(rows(wrapper)).toEqual([
|
||||
"project.close",
|
||||
"palette.open",
|
||||
"project.openDialog",
|
||||
"app.quit",
|
||||
"settings.open",
|
||||
"view.toggleProjectTree",
|
||||
]);
|
||||
const quit = wrapper.find("[data-command='app.quit']");
|
||||
expect(quit.find("[data-test=palette-shortcut]").text()).toBe("Ctrl+Q");
|
||||
expect(quit.text()).toContain("Quit");
|
||||
});
|
||||
|
||||
it("opens from a uiCommand the engine sends (control channel)", async () => {
|
||||
const wrapper = await mountPalette();
|
||||
await emit({ kind: "uiCommand", id: "palette.open", params: {} });
|
||||
expect(wrapper.find("[data-test=palette]").exists()).toBe(true);
|
||||
});
|
||||
|
||||
it("filters and moves with the arrow keys, runs with Enter", async () => {
|
||||
const wrapper = await mountPalette();
|
||||
await press(PALETTE_KEY);
|
||||
await type(wrapper, "o");
|
||||
expect(rows(wrapper).slice(0, 2)).toEqual(["project.openDialog", "palette.open"]);
|
||||
await type(wrapper, "open f");
|
||||
expect(rows(wrapper)[0]).toBe("project.openDialog");
|
||||
await press({ key: "ArrowDown" });
|
||||
await press({ key: "ArrowUp" });
|
||||
expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("project.openDialog");
|
||||
await press({ key: "Enter" });
|
||||
expect(wrapper.find("[data-test=palette]").exists()).toBe(false);
|
||||
expect(calls.at(-1)).toEqual({ command: "project.openDialog", params: {} });
|
||||
});
|
||||
|
||||
it("wraps around with the arrow keys", async () => {
|
||||
const wrapper = await mountPalette();
|
||||
await press(PALETTE_KEY);
|
||||
await press({ key: "ArrowUp" });
|
||||
expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("view.toggleProjectTree");
|
||||
await press({ key: "ArrowDown" });
|
||||
expect(wrapper.find("[aria-selected=true]").attributes("data-command")).toBe("project.close");
|
||||
});
|
||||
|
||||
it("dims disabled commands, which Enter and clicks do not run", async () => {
|
||||
const wrapper = await mountPalette();
|
||||
await press(PALETTE_KEY);
|
||||
await type(wrapper, "close proj");
|
||||
const row = wrapper.find("[data-command='project.close']");
|
||||
expect(row.attributes("aria-disabled")).toBe("true");
|
||||
expect(row.classes()).toContain("palette__row--disabled");
|
||||
await press({ key: "Enter" });
|
||||
await row.trigger("click");
|
||||
expect(wrapper.find("[data-test=palette]").exists()).toBe(true);
|
||||
expect(calls.map((c) => c.command)).not.toContain("project.close");
|
||||
await type(wrapper, "settings");
|
||||
expect(wrapper.find("[data-command='settings.open']").attributes("aria-disabled")).toBe("true");
|
||||
});
|
||||
|
||||
it("closes with Escape and gives the focus back", async () => {
|
||||
const wrapper = await mountPalette();
|
||||
const button = document.getElementById("host-button");
|
||||
button?.focus();
|
||||
await press(PALETTE_KEY);
|
||||
expect(document.activeElement).not.toBe(button);
|
||||
await press({ key: "Escape" });
|
||||
expect(wrapper.find("[data-test=palette]").exists()).toBe(false);
|
||||
expect(document.activeElement).toBe(button);
|
||||
expect(calls.map((c) => c.command)).toEqual(["ui.registerCommands"]);
|
||||
});
|
||||
|
||||
it("shows recently run commands first", async () => {
|
||||
const wrapper = await mountPalette();
|
||||
await press(PALETTE_KEY);
|
||||
await type(wrapper, "quit");
|
||||
await press({ key: "Enter" });
|
||||
await press(PALETTE_KEY);
|
||||
expect(rows(wrapper)[0]).toBe("app.quit");
|
||||
await wrapper.find("[data-command='project.openDialog']").trigger("click");
|
||||
await flushPromises();
|
||||
await press(PALETTE_KEY);
|
||||
expect(rows(wrapper).slice(0, 2)).toEqual(["project.openDialog", "app.quit"]);
|
||||
});
|
||||
|
||||
it("says when nothing matches", async () => {
|
||||
const wrapper = await mountPalette();
|
||||
await press(PALETTE_KEY);
|
||||
await type(wrapper, "zzzz");
|
||||
expect(rows(wrapper)).toEqual([]);
|
||||
expect(wrapper.find("[data-test=palette-empty]").text()).toBe("No matching commands");
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue