M3.9: hamburger app menu

A slim header bar in MainLayout with a menu button (Lucide menu) whose
dropdown lists every command with a menuPath, grouped File, Edit, View,
Go, Help, with shortcuts and dimmed disabled entries. Keyboard: arrows,
Home/End, Enter/Space, Escape/Tab, type-ahead. menu.open (Alt+M) opens
it, also over uiCommand. It is an exclusive modal and a launcher under
the one-modal rule. Menu paths for the user-facing engine and UI
commands (buffer.close as File/Close Tab). Catalog strings, Vitest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-19 18:23:13 +02:00
parent 78709dd76b
commit 27ad30369c
14 changed files with 1004 additions and 25 deletions

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;
}