PM: merge M3.9 hamburger app menu

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	docs/architecture.md
#	docs/gaps.md
This commit is contained in:
danny 2026-10-19 18:26:05 +02:00
commit d4e1ba0981
14 changed files with 1004 additions and 25 deletions

View file

@ -2,7 +2,7 @@
* The modal rule (M1.15): at most one modal is open at a time.
*
* - **Exclusive modals:** the command palette, the go-to popup (M2.6), the
* settings dialog and the close question of a dirty tab. Opening one closes the one that is open
* app menu (M3.9), the settings dialog and the close question of a dirty tab. Opening one closes the one that is open
* (the close question closes as Cancel). Each reports itself with
* {@link useModalsStore}'s `opened` and `closed`; the close question is
* followed from the editor store, so the editor needs no code for it.
@ -15,14 +15,15 @@
* `palette.open` closes it first (see `store.ts` › `execute`), so a
* `uiCommand` from the control channel never leaves it open behind
* what the command shows. The go-to popup is a launcher too: any command
* but the go-to open commands closes it.
* but the go-to open commands closes it. So is the app menu (M3.9): any
* command but `menu.open` closes it.
*/
import { defineStore } from "pinia";
import { ref, watch } from "vue";
import { useEditorStore } from "../stores/editor";
/** The exclusive modals. */
export type ModalId = "palette" | "goto" | "settings" | "closePrompt";
export type ModalId = "palette" | "goto" | "menu" | "settings" | "closePrompt";
/** Store of the open exclusive modal. */
export const useModalsStore = defineStore("modals", () => {

View file

@ -15,7 +15,8 @@
* commands run with empty params.
* - **Errors:** a failed command raises an error toast (M1.12).
* - **Palette:** running any command but `palette.open` closes the palette
* first (the modal rule, `modals.ts`).
* first (the modal rule, `modals.ts`); likewise any command but
* `menu.open` closes the app menu (M3.9).
*/
import { defineStore } from "pinia";
import { computed, ref, shallowReactive } from "vue";
@ -49,11 +50,18 @@ export interface PaletteEntry {
shortcut: string | null;
/** Whether it can run now. */
enabled: boolean;
/** Menu path with `/` separators, or null if the command is in no menu (M3.9). */
menuPath: string | null;
/** Whether the frontend runs it (a UI command, label from the catalog). */
ui: boolean;
}
/** Most recently run commands remembered. */
export const MAX_RECENT = 20;
/** The UI command that opens the app menu, which therefore keeps it open. */
const MENU_OPEN = "menu.open";
/** The UI commands that open the go-to popup, which therefore keep it open. */
const GOTO_OPEN = new Set(["goto.fileOpen", "goto.classOpen", "goto.symbolOpen"]);
@ -151,6 +159,8 @@ export const useCommandsStore = defineStore("commands", () => {
label: labelOf(info),
shortcut: typeof info.defaultShortcut === "string" ? formatShortcut(info.defaultShortcut, mac) : null,
enabled: isEnabled(info.id),
menuPath: typeof info.menuPath === "string" && info.menuPath !== "" ? info.menuPath : null,
ui: info.ui === true,
})),
);
@ -187,8 +197,9 @@ export const useCommandsStore = defineStore("commands", () => {
* Runs a command the user chose (keyboard or palette): through its
* handler if a component supplied one, else through the engine. A
* disabled command does nothing. A failure raises an error toast. Any
* command but `palette.open` closes the palette before it runs, and any
* command but the go-to open commands closes the go-to popup.
* command but `palette.open` closes the palette before it runs, any
* command but the go-to open commands closes the go-to popup, and any
* command but `menu.open` closes the app menu.
*
* @param id - the command id.
* @param params - the params.
@ -204,6 +215,9 @@ export const useCommandsStore = defineStore("commands", () => {
if (!GOTO_OPEN.has(id)) {
modals.dismiss("goto");
}
if (id !== MENU_OPEN) {
modals.dismiss("menu");
}
const handler = handlers.get(id);
if (handler) {
try {

View file

@ -22,12 +22,13 @@ export interface UiCommandSpec {
/** The frontend's UI commands. */
export const UI_COMMANDS: readonly UiCommandSpec[] = [
{ id: "editor.reveal", labelKey: "command.editor.reveal" },
{ id: "find.open", labelKey: "command.find.open", defaultShortcut: "Mod+Alt+F" },
{ id: "goto.classOpen", labelKey: "command.goto.classOpen", defaultShortcut: "Mod+Alt+C" },
{ id: "goto.fileOpen", labelKey: "command.goto.fileOpen", defaultShortcut: "Mod+P" },
{ id: "goto.symbolOpen", labelKey: "command.goto.symbolOpen", defaultShortcut: "Mod+T" },
{ id: "palette.open", labelKey: "command.palette.open", defaultShortcut: "Mod+Shift+P" },
{ id: "settings.open", labelKey: "command.settings.open", defaultShortcut: "Mod+," },
{ id: "view.toggleProjectTree", labelKey: "command.view.toggleProjectTree", defaultShortcut: "Mod+1" },
{ id: "view.toggleStructure", labelKey: "command.view.toggleStructure", defaultShortcut: "Mod+2" },
{ id: "find.open", labelKey: "command.find.open", menuPath: "View/Find in Files…", defaultShortcut: "Mod+Alt+F" },
{ id: "goto.classOpen", labelKey: "command.goto.classOpen", menuPath: "Go/Class…", defaultShortcut: "Mod+Alt+C" },
{ id: "goto.fileOpen", labelKey: "command.goto.fileOpen", menuPath: "Go/File…", defaultShortcut: "Mod+P" },
{ id: "goto.symbolOpen", labelKey: "command.goto.symbolOpen", menuPath: "Go/Symbol…", defaultShortcut: "Mod+T" },
{ id: "menu.open", labelKey: "command.menu.open", defaultShortcut: "Alt+M" },
{ id: "palette.open", labelKey: "command.palette.open", menuPath: "View/Command Palette", defaultShortcut: "Mod+Shift+P" },
{ id: "settings.open", labelKey: "command.settings.open", menuPath: "View/Settings…", defaultShortcut: "Mod+," },
{ id: "view.toggleProjectTree", labelKey: "command.view.toggleProjectTree", menuPath: "View/Project", defaultShortcut: "Mod+1" },
{ id: "view.toggleStructure", labelKey: "command.view.toggleStructure", menuPath: "View/Structure", defaultShortcut: "Mod+2" },
];

View file

@ -19,6 +19,9 @@
* appears with the UI command `find.open` (`Mod+Alt+F`, supplied here so it
* works before the panel exists), collapses to its header and closes from
* its header; the Find store keeps the results while it is closed.
*
* A slim header bar along the top (M3.9) holds the app menu
* ({@link AppMenu}); its `header` slot can replace it.
*/
import { FolderTree, ListTree } from "@lucide/vue";
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
@ -29,6 +32,7 @@ import FindToolWindow from "../find/FindToolWindow.vue";
import ProjectToolWindow from "../project/ProjectToolWindow.vue";
import StatusBar from "../StatusBar.vue";
import StructureToolWindow from "../structure/StructureToolWindow.vue";
import AppMenu from "../menu/AppMenu.vue";
import BottomPanel from "./BottomPanel.vue";
import ToolWindow from "./ToolWindow.vue";
@ -100,6 +104,14 @@ onBeforeUnmount(() => {
<template>
<div class="main-layout">
<header
class="main-layout__header"
data-test="main-header"
>
<slot name="header">
<AppMenu />
</slot>
</header>
<div class="main-layout__row">
<nav
class="main-layout__stripe"
@ -163,6 +175,16 @@ onBeforeUnmount(() => {
height: 100%;
}
.main-layout__header {
display: flex;
align-items: center;
flex: none;
height: 28px;
padding: 0 var(--lt-space-s, 4px);
background: var(--lt-bg);
border-bottom: 1px solid var(--lt-border);
}
.main-layout__row {
display: flex;
flex: 1;

View file

@ -0,0 +1,376 @@
<script setup lang="ts">
/**
* The app menu (M3.9): a button with the Lucide `menu` icon at the top
* left of the window that opens a dropdown of every command with a menu
* path, grouped by the path's first segment (see `menu.ts`).
*
* - **Opening:** a click on the button (again closes it) or the UI command
* `menu.open` (`Alt+M`, Lutra's own; also over `uiCommand`). Opening
* refreshes the enabled states and focuses the first item.
* - **Items** show the command's shortcut; disabled ones are dimmed, stay
* focusable and do nothing.
* - **Keyboard:** arrows move (wrapping), Home/End jump, Enter or Space
* runs, Escape or Tab closes, typing a letter jumps to the next item
* starting with what was typed (the typed text resets after 500 ms).
* - **Modal rule:** the menu is an exclusive modal and a launcher: opening
* it closes the palette or another modal, and running any command but
* `menu.open` (keyboard, palette, `uiCommand`) closes it. A chosen
* command runs after the menu closed and gave the focus back.
*/
import { Menu } from "@lucide/vue";
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from "vue";
import { useModalsStore } from "../../commands/modals";
import { useCommandsStore } from "../../commands/store";
import { t } from "../../i18n";
import { buildMenu, typeAhead, type MenuItem } from "./menu";
/** Time after which type-ahead starts over, in milliseconds. */
const TYPE_AHEAD_RESET_MS = 500;
const commands = useCommandsStore();
const modals = useModalsStore();
/** Whether the dropdown is shown. */
const open = ref(false);
/** Index of the focused item in {@link flat}. */
const focused = ref(0);
/** The dropdown. */
const panel = ref<HTMLElement | null>(null);
/** The menu button. */
const button = ref<HTMLButtonElement | null>(null);
/** The element that had the focus before the menu opened. */
let returnFocus: HTMLElement | null = null;
/** What was typed for type-ahead. */
let typed = "";
/** Clears {@link typed}; set while typing. */
let typedTimer: ReturnType<typeof setTimeout> | null = null;
/** Withdraws the `menu.open` handler; set while mounted. */
let withdraw: (() => void) | null = null;
/** The groups of the menu. */
const groups = computed(() => buildMenu(commands.entries));
/** Every item in display order. */
const flat = computed<MenuItem[]>(() => groups.value.flatMap((group) => group.items));
/**
* The index of an item in {@link flat}.
*
* @param id - the command id.
*/
function indexOf(id: string): number {
return flat.value.findIndex((item) => item.id === id);
}
/**
* Focuses an item and remembers it as focused.
*
* @param index - index in {@link flat}.
*/
function focusItem(index: number): void {
if (index < 0 || index >= flat.value.length) {
return;
}
focused.value = index;
void nextTick(() => {
panel.value?.querySelector<HTMLElement>(`#lt-menu-${String(index)}`)?.focus();
});
}
/** Opens the menu, refreshes the enabled states and focuses the first item. */
async function show(): Promise<void> {
modals.opened("menu", close);
if (!open.value) {
const active = document.activeElement;
returnFocus = active instanceof HTMLElement ? active : null;
}
open.value = true;
focusItem(0);
await commands.refresh();
}
/** Closes the menu and gives the focus back. */
function close(): void {
if (!open.value) {
return;
}
open.value = false;
modals.closed("menu");
typed = "";
returnFocus?.focus();
returnFocus = null;
}
/** Opens the menu or, when it is open, closes it (the button). */
function toggle(): void {
if (open.value) {
close();
} else {
void show();
}
}
/**
* Runs an item's command if it is enabled; the menu closes first.
*
* @param item - the item.
*/
function choose(item: MenuItem | undefined): void {
if (!item?.enabled) {
return;
}
close();
void commands.execute(item.id);
}
/**
* Adds a typed character and moves to the next matching item.
*
* @param char - the character.
*/
function onType(char: string): void {
typed += char;
if (typedTimer !== null) {
clearTimeout(typedTimer);
}
typedTimer = setTimeout(() => {
typed = "";
typedTimer = null;
}, TYPE_AHEAD_RESET_MS);
const index = typeAhead(
flat.value.map((item) => item.label),
typed,
focused.value,
);
focusItem(index);
}
/**
* Keyboard handling inside the dropdown.
*
* @param event - the key press.
*/
function onKeydown(event: KeyboardEvent): void {
const count = flat.value.length;
switch (event.key) {
case "ArrowDown":
focusItem(count > 0 ? (focused.value + 1) % count : -1);
break;
case "ArrowUp":
focusItem(count > 0 ? (focused.value - 1 + count) % count : -1);
break;
case "Home":
focusItem(0);
break;
case "End":
focusItem(count - 1);
break;
case "Enter":
case " ":
choose(flat.value[focused.value]);
break;
case "Escape":
close();
break;
case "Tab":
close();
return;
default:
if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
onType(event.key);
break;
}
return;
}
event.preventDefault();
event.stopPropagation();
}
onMounted(() => {
withdraw = commands.provide("menu.open", { run: show });
});
onBeforeUnmount(() => {
withdraw?.();
withdraw = null;
if (typedTimer !== null) {
clearTimeout(typedTimer);
typedTimer = null;
}
if (open.value) {
modals.closed("menu");
}
});
defineExpose({ show, close });
</script>
<template>
<div class="app-menu">
<button
ref="button"
type="button"
class="app-menu__button"
:class="{ 'app-menu__button--open': open }"
aria-haspopup="menu"
:aria-expanded="open"
aria-controls="lt-app-menu"
:aria-label="t('menu.button')"
:title="t('menu.button')"
data-test="menu-button"
@mousedown.prevent
@click="toggle()"
>
<Menu :size="16" />
</button>
<div
v-if="open"
class="app-menu__backdrop"
data-test="menu-backdrop"
@mousedown.self.prevent="close()"
>
<div
id="lt-app-menu"
ref="panel"
class="app-menu__panel"
role="menu"
:aria-label="t('menu.label')"
data-test="menu"
@keydown="onKeydown"
>
<div
v-for="group in groups"
:key="group.key"
class="app-menu__group"
role="group"
:aria-labelledby="`lt-menu-group-${group.key}`"
data-test="menu-group"
>
<div
:id="`lt-menu-group-${group.key}`"
class="app-menu__heading"
role="presentation"
>
{{ group.label }}
</div>
<div
v-for="item in group.items"
:id="`lt-menu-${String(indexOf(item.id))}`"
:key="item.id"
class="app-menu__item"
:class="{
'app-menu__item--focused': indexOf(item.id) === focused,
'app-menu__item--disabled': !item.enabled,
}"
role="menuitem"
:tabindex="indexOf(item.id) === focused ? 0 : -1"
:aria-disabled="!item.enabled"
:data-command="item.id"
data-test="menu-item"
@mousemove="focusItem(indexOf(item.id))"
@mousedown.prevent
@click="choose(item)"
>
<span class="app-menu__label">{{ item.label }}</span>
<kbd
v-if="item.shortcut"
class="app-menu__shortcut"
data-test="menu-shortcut"
>{{ item.shortcut }}</kbd>
</div>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.app-menu {
display: flex;
align-items: center;
}
.app-menu__button {
display: inline-flex;
align-items: center;
justify-content: center;
padding: var(--lt-space-xs, 2px);
color: var(--lt-fg-muted);
background: transparent;
border: none;
border-radius: var(--lt-radius, 4px);
cursor: pointer;
}
.app-menu__button:hover,
.app-menu__button--open {
color: var(--lt-fg);
background: color-mix(in srgb, var(--lt-fg) 8%, transparent);
}
.app-menu__button:focus-visible {
outline: 2px solid var(--lt-accent);
}
.app-menu__backdrop {
position: fixed;
inset: 0;
z-index: 30;
}
.app-menu__panel {
position: absolute;
top: 28px;
left: 4px;
min-width: 260px;
max-height: calc(100vh - 40px);
overflow-y: auto;
padding: 4px 0;
color: var(--lt-fg);
background: var(--lt-bg);
border: 1px solid var(--lt-border);
border-radius: 6px;
}
.app-menu__group + .app-menu__group {
margin-top: 4px;
padding-top: 4px;
border-top: 1px solid var(--lt-border);
}
.app-menu__heading {
padding: 2px 12px;
font-size: 0.85em;
color: var(--lt-fg-muted);
}
.app-menu__item {
display: flex;
align-items: baseline;
gap: 24px;
padding: 4px 12px 4px 20px;
cursor: default;
outline: none;
}
.app-menu__item--focused {
background: var(--lt-editor-selection-bg);
}
.app-menu__item--disabled {
opacity: 0.55;
}
.app-menu__label {
flex: 1;
white-space: nowrap;
}
.app-menu__shortcut {
font: inherit;
color: var(--lt-fg-muted);
}
.app-menu__item--focused .app-menu__shortcut {
color: var(--lt-fg);
}
</style>

View file

@ -0,0 +1,173 @@
/**
* The app menu's model (M3.9): the commands that have a menu path, grouped
* by the path's first segment.
*
* - **Groups** come in Lutra's order (File, Edit, View, Go, Help); a group
* Lutra does not know goes before Help, sorted by name. Empty groups are
* left out. Known group names come from the catalog.
* - **Items** in a group follow {@link ITEM_ORDER}; others come after it,
* sorted by label.
* - **Labels:** a UI command shows its catalog label; an engine command
* shows the rest of its menu path (`File/Close Tab` → `Close Tab`), since
* the engine has no catalog and its path is written for menus. Deeper
* paths are joined with ` › `.
*/
import type { PaletteEntry } from "../../commands/store";
import { t } from "../../i18n";
/** One entry of the menu. */
export interface MenuItem {
/** Command id. */
id: string;
/** Text shown. */
label: string;
/** Formatted shortcut, or null. */
shortcut: string | null;
/** Whether it can run now; disabled items are dimmed and do nothing. */
enabled: boolean;
}
/** One group of the menu. */
export interface MenuGroup {
/** The first segment of the menu path, e.g. `File`. */
key: string;
/** Heading shown. */
label: string;
/** Items in display order. */
items: MenuItem[];
}
/** Known groups in display order. */
const GROUP_ORDER = ["File", "Edit", "View", "Go", "Help"];
/** Order of known commands inside their group. */
const ITEM_ORDER = [
"project.openDialog",
"file.save",
"file.saveAll",
"buffer.close",
"project.close",
"app.quit",
"palette.open",
"view.toggleProjectTree",
"view.toggleStructure",
"find.open",
"terminal.toggle",
"settings.open",
"goto.fileOpen",
"goto.classOpen",
"goto.symbolOpen",
"app.about",
];
/**
* The heading of a group: catalog text for Lutra's groups, else the name.
*
* @param key - the first segment of the menu path.
*/
function groupLabel(key: string): string {
switch (key) {
case "File":
return t("menu.group.file");
case "Edit":
return t("menu.group.edit");
case "View":
return t("menu.group.view");
case "Go":
return t("menu.group.go");
case "Help":
return t("menu.group.help");
default:
return key;
}
}
/**
* The sort rank of a group.
*
* @param key - the group name.
*/
function groupRank(key: string): number {
const index = GROUP_ORDER.indexOf(key);
if (index >= 0) {
return key === "Help" ? 1000 : index;
}
return 500;
}
/**
* The sort rank of an item.
*
* @param id - the command id.
*/
function itemRank(id: string): number {
const index = ITEM_ORDER.indexOf(id);
return index >= 0 ? index : ITEM_ORDER.length;
}
/**
* Splits a menu path into its non-empty segments.
*
* @param path - for example `File/Save`.
*/
function segments(path: string): string[] {
return path
.split("/")
.map((part) => part.trim())
.filter((part) => part !== "");
}
/**
* Builds the menu from the commands the palette knows.
*
* @param entries - the commands; those without a menu path are left out.
* @returns the groups in display order, none empty.
*/
export function buildMenu(entries: readonly PaletteEntry[]): MenuGroup[] {
const groups = new Map<string, MenuItem[]>();
for (const entry of entries) {
if (entry.menuPath === null) {
continue;
}
const [group, ...rest] = segments(entry.menuPath);
if (group === undefined) {
continue;
}
const label = entry.ui || rest.length === 0 ? entry.label : rest.join(" › ");
const items = groups.get(group) ?? [];
items.push({ id: entry.id, label, shortcut: entry.shortcut, enabled: entry.enabled });
groups.set(group, items);
}
return [...groups.entries()]
.sort(([a], [b]) => groupRank(a) - groupRank(b) || a.localeCompare(b))
.map(([key, items]) => ({
key,
label: groupLabel(key),
items: items.sort((a, b) => itemRank(a.id) - itemRank(b.id) || a.label.localeCompare(b.label)),
}));
}
/**
* Finds the next item whose label starts with the typed text, searching
* from the item after `from` and wrapping around; when the text is one
* character typed again, this cycles through the items with that initial.
*
* @param labels - item labels in display order.
* @param typed - what was typed, case-insensitive.
* @param from - index of the focused item, -1 for none.
* @returns the index, or -1 when no label matches.
*/
export function typeAhead(labels: readonly string[], typed: string, from: number): number {
const needle = typed.toLocaleLowerCase();
if (needle === "" || labels.length === 0) {
return -1;
}
const start = needle.length > 1 ? Math.max(from, 0) : from + 1;
for (let step = 0; step < labels.length; step += 1) {
const index = (start + step + labels.length) % labels.length;
if ((labels[index] ?? "").toLocaleLowerCase().startsWith(needle)) {
return index;
}
}
return -1;
}

View file

@ -10,6 +10,7 @@
"command.key.ctrl": "Ctrl",
"command.key.option": "Option",
"command.key.shift": "Shift",
"command.menu.open": "Open Main Menu",
"command.palette.open": "Command Palette",
"command.settings.open": "Settings…",
"command.unavailable": "{command} cannot run right now",
@ -68,6 +69,13 @@
"goto.placeholder.file": "File name or path",
"goto.placeholder.symbol": "Function, method, property or constant; Class::member",
"goto.switchHint": "Tab switches",
"menu.button": "Main menu",
"menu.group.edit": "Edit",
"menu.group.file": "File",
"menu.group.go": "Go",
"menu.group.help": "Help",
"menu.group.view": "View",
"menu.label": "Main menu",
"notification.close": "Close notification",
"notification.command.failed": "{command} failed: {message}",
"notification.project.notLocal": "The chosen folder is not on this computer: {reason}",

View file

@ -133,7 +133,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|command|project|editor|common|palette|theme|recovery|notification|settings|find|goto|structure)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
/^(app|command|project|editor|common|palette|theme|recovery|notification|settings|find|goto|structure|menu)\.[A-Za-z0-9]+(\.[A-Za-z0-9]+)*$/,
);
expect(typeof value).toBe("string");
expect(value.trim()).not.toBe("");

View file

@ -0,0 +1,368 @@
/**
* 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…");
});
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", "View", "Go", "Help"]);
expect(itemIds()).toEqual([
"project.openDialog",
"file.save",
"file.saveAll",
"buffer.close",
"project.close",
"app.quit",
"palette.open",
"view.toggleProjectTree",
"view.toggleStructure",
"find.open",
"settings.open",
"goto.fileOpen",
"goto.classOpen",
"goto.symbolOpen",
"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);
});
});

View file

@ -45,13 +45,13 @@ let mounted: VueWrapper[];
*/
function listing(): unknown[] {
const registered = calls.find((c) => c.command === "ui.registerCommands")?.params as
| { commands: { id: string; labelKey: string; defaultShortcut?: string }[] }
| { 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: null,
menuPath: c.menuPath ?? null,
defaultShortcut: c.defaultShortcut ?? null,
params: "",
enabled: true,
@ -166,7 +166,7 @@ describe("command store", () => {
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 });
expect(toggle).toEqual({ id: "view.toggleProjectTree", label: "Show or Hide Project", shortcut: "Ctrl+1", enabled: false, menuPath: "View/Project", ui: true });
});
it("keeps the UI commands when the engine refuses them, with an error toast", async () => {
@ -265,6 +265,7 @@ describe("CommandPalette", () => {
"goto.fileOpen",
"goto.symbolOpen",
"project.openDialog",
"menu.open",
"app.quit",
"editor.reveal",
"settings.open",
@ -286,7 +287,7 @@ describe("CommandPalette", () => {
const wrapper = await mountPalette();
await press(PALETTE_KEY);
await type(wrapper, "o");
expect(rows(wrapper).slice(0, 3)).toEqual(["project.openDialog", "find.open", "palette.open"]);
expect(rows(wrapper).slice(0, 3)).toEqual(["project.openDialog", "menu.open", "find.open"]);
await type(wrapper, "open f");
expect(rows(wrapper)[0]).toBe("project.openDialog");
await press({ key: "ArrowDown" });