A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
refactor(editor): derive the menu bar from a registry instead of a nested array
esengine1af0f54cb56a
diff --git a/desktop/src/i18n/messages/menu.ts b/desktop/src/i18n/messages/menu.tsindex ec557b22f..ebb5b0bdd 100644--- a/desktop/src/i18n/messages/menu.ts+++ b/desktop/src/i18n/messages/menu.ts@@ -13,6 +13,8 @@ export const menuMessages = defineMessages({'menu.entity': { en: 'Entity', zh: '实体' },'menu.view': { en: 'View', zh: '视图' },'menu.build': { en: 'Build', zh: '构建' },+ // Where contributed commands land; the strip hides it while it holds nothing.+ 'menu.tools': { en: 'Tools', zh: '工具' },'menu.window': { en: 'Window', zh: '窗口' },'menu.help': { en: 'Help', zh: '帮助' },diff --git a/desktop/src/layout/MenuBar.tsx b/desktop/src/layout/MenuBar.tsxindex 6cdaf83cb..f49c65fca 100644--- a/desktop/src/layout/MenuBar.tsx+++ b/desktop/src/layout/MenuBar.tsx@@ -12,11 +12,42 @@ import { ProjectStore } from '@/project/ProjectStore';import { EditorHistory } from '@/engine/EditorHistory';import { MenuItems, handleMenuListKey, type MenuItem } from '@/components/Menu';import { commands, formatKeybinding } from '@/commands';+import { menuBarMenus, menuItemGroups, menuRegistry, menuItemRegistry } from '@/layout/menus';import { t } from '@/i18n';-interface MenuDef {- title: string;- items: MenuItem[];+/**+ * One menu's rows, built from the menu registry at render time — so enablement and+ * checked state read fresh from the domain stores every time a menu opens, exactly+ * as the hand-written array's cmdItem() calls did.+ *+ * Separators are derived from the item groups, never authored: a gated or retracted+ * row can't leave a dangling separator behind.+ */+function menuItemsFor(location: string): MenuItem[] {+ const out: MenuItem[] = [];+ for (const group of menuItemGroups(location)) {+ const rows: MenuItem[] = [];+ for (const item of group) {+ if (!item.command) {+ if (item.label && item.run) rows.push({ label: item.label(), onClick: item.run });+ continue;+ }+ const command = commands.get(item.command);+ if (!command) continue; // the command went away with its plugin+ const chord = commands.keybindingFor(item.command);+ rows.push({+ label: item.label?.() ?? command.label,+ shortcut: chord ? formatKeybinding(chord) : undefined,+ onClick: () => commands.run(item.command!),+ disabled: !commands.isEnabled(item.command),+ checked: commands.isChecked(item.command),+ });+ }+ if (!rows.length) continue;+ if (out.length) out.push({ sep: true });+ out.push(...rows);+ }+ return out;}function Mark() {@@ -43,19 +74,10 @@ export function MenuBar() {const project = useSyncExternalStore(ProjectStore.subscribe, ProjectStore.getSnapshot);// Unsaved-changes star next to the scene name (UE's modified-document indicator).const dirty = useSyncExternalStore(EditorHistory.subscribe, EditorHistory.isDirty);-- // Build a menu item from a registered command — one source for label, shortcut- // hint, action, enablement, and checked state.- const cmdItem = (id: string): MenuItem => {- const c = commands.get(id)!;- return {- label: c.label,- shortcut: c.keybinding ? formatKeybinding(c.keybinding) : undefined,- onClick: () => commands.run(id),- disabled: !commands.isEnabled(id),- checked: commands.isChecked(id),- };- };+ // Re-render when the menu set changes, so a contributed row appears (and a+ // retracted one disappears) without waiting for some other store to tick.+ useSyncExternalStore(menuItemRegistry.subscribe.bind(menuItemRegistry), menuItemRegistry.getRevision.bind(menuItemRegistry));+ useSyncExternalStore(menuRegistry.subscribe.bind(menuRegistry), menuRegistry.getRevision.bind(menuRegistry));// Close the open menu on an outside click or Escape (Escape hands focus back// to the menu's own button so keyboard flow continues at the menubar).@@ -78,102 +100,11 @@ export function MenuBar() {};}, [open]);- const menus: MenuDef[] = [- {- title: t('menu.file'),- items: [- cmdItem('scene.new'),- { sep: true },- cmdItem('project.open'),- { sep: true },- cmdItem('project.save'),- cmdItem('project.saveAs'),- { sep: true },- cmdItem('project.close'),- ],- },- {- title: t('menu.edit'),- items: [- cmdItem('edit.undo'),- cmdItem('edit.redo'),- { sep: true },- cmdItem('entity.cut'),- cmdItem('entity.copy'),- cmdItem('entity.paste'),- cmdItem('entity.delete'),- { sep: true },- cmdItem('edit.selectAll'),- cmdItem('entity.deselect'),- ],- },- {- title: t('menu.entity'),- items: [- cmdItem('entity.add'),- cmdItem('tilemap.new'),- cmdItem('tilemap.newCollisionLayer'),- { sep: true },- cmdItem('entity.duplicate'),- cmdItem('entity.delete'),- { sep: true },- cmdItem('entity.deselect'),- ],- },- {- title: t('menu.view'),- items: [- cmdItem('view.toggleGrid'),- cmdItem('view.toggleGizmos'),- cmdItem('view.toggleColliders'),- cmdItem('view.toggleTileCollision'),- cmdItem('view.togglePreviewFx'),- { sep: true },- cmdItem('view.toggleMinimap'),- cmdItem('view.toggleStats'),- cmdItem('view.toggleCoords'),- cmdItem('view.togglePerf'),- { sep: true },- cmdItem('view.toggleCoordSpace'),- cmdItem('view.togglePivotMode'),- cmdItem('view.toggleSnapping'),- ],- },- {- title: t('menu.build'),- items: [- cmdItem('project.export'),- { sep: true },- cmdItem('build.scripts'),- cmdItem('project.extractSchemas'),- ],- },- {- title: t('menu.window'),- items: [- // Reset only the dock layout — rebuild in place (keeps scene/engine/undo),- // guarded so a wedged dirty asset-editor tab can't vanish unwarned. A real- // command, so it's in the palette + rebindable.- cmdItem('view.resetLayout'),- { sep: true },- // Same destination as File ▸ Close Project — run the guarded command so- // leaving a project can't silently drop unsaved scene + asset edits.- { label: t('menu.backToLauncher'), onClick: () => commands.run('project.close') },- ],- },- {- title: t('menu.help'),- items: [- cmdItem('help.about'),- cmdItem('help.checkUpdates'),- { sep: true },- cmdItem('palette.open'),- cmdItem('help.shortcuts'),- { sep: true },- cmdItem('help.openLogs'),- ],- },- ];+ // Menus and their rows both come from the registry; a menu holding no visible+ // rows is dropped, so an empty dropdown can never open.+ const menus = menuBarMenus()+ .map((m) => ({ id: m.id, title: m.title(), items: menuItemsFor(m.id) }))+ .filter((m) => m.items.length > 0);return (<div className="menubar" ref={barRef}>@@ -186,17 +117,17 @@ export function MenuBar() {<nav className="menus">{menus.map((m) => (<div- key={m.title}+ key={m.id}className="menubar__menu"style={{ position: 'relative', display: 'flex' }}onKeyDown={(e) => {- if (open !== m.title) return;+ if (open !== m.id) return;// ←/→ walk the menubar while a menu is open; ↓/↑ and typeahead// navigate the open dropdown (the shared menu-list handler).if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {e.preventDefault();- const i = menus.findIndex((mm) => mm.title === open);- const next = menus[(i + (e.key === 'ArrowRight' ? 1 : -1) + menus.length) % menus.length].title;+ const i = menus.findIndex((mm) => mm.id === open);+ const next = menus[(i + (e.key === 'ArrowRight' ? 1 : -1) + menus.length) % menus.length].id;setOpen(next);btnRefs.current.get(next)?.focus();return;@@ -206,19 +137,19 @@ export function MenuBar() {><buttonref={(el) => {- if (el) btnRefs.current.set(m.title, el);- else btnRefs.current.delete(m.title);+ if (el) btnRefs.current.set(m.id, el);+ else btnRefs.current.delete(m.id);}}- className={`menu${open === m.title ? ' is-open' : ''}`}+ className={`menu${open === m.id ? ' is-open' : ''}`}type="button"aria-haspopup="menu"- aria-expanded={open === m.title}- onClick={() => setOpen((o) => (o === m.title ? null : m.title))}- onMouseEnter={() => setOpen((o) => (o ? m.title : o))}+ aria-expanded={open === m.id}+ onClick={() => setOpen((o) => (o === m.id ? null : m.id))}+ onMouseEnter={() => setOpen((o) => (o ? m.id : o))}>{m.title}</button>- {open === m.title && (+ {open === m.id && (<div className="menu-dropdown" role="menu"><MenuItems items={m.items} onSelect={() => setOpen(null)} /></div>diff --git a/desktop/src/layout/menus.ts b/desktop/src/layout/menus.tsnew file mode 100644index 000000000..6f561a87e--- /dev/null+++ b/desktop/src/layout/menus.ts@@ -0,0 +1,187 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file menus.ts+ * @brief THE authority for the menu bar — which menus exist and what sits in each.+ * MenuBar renders from here, so adding a menu entry is one registration+ * instead of an edit to a hand-written nested array.+ *+ * An entry is normally just a COMMAND REFERENCE: the command registry already owns+ * its label, shortcut hint, enablement, and checked state, so a menu row restates+ * none of it (the old array called cmdItem(id) for exactly this reason). `label` ++ * `run` exist for the rare row with no command behind it.+ *+ * Separators are derived, never authored: items carry a `group`, groups render in+ * the order declared by their menu's `groups` list, and a separator goes between+ * adjacent non-empty groups. That way a gated or contributed item can never leave a+ * dangling separator or two in a row.+ *+ * Kept free of React and of the command registry itself — MenuBar joins the two, so+ * this module stays a leaf that anything can consult.+ */+import { t } from '@/i18n';+import { ContributionRegistry, type Disposable, type Owner } from '@/contrib/ContributionRegistry';++/**+ * A menu-bar menu id, or (later) a context-menu location such as `outliner/item`.+ * Open by design: context menus join this registry once they carry a target.+ */+export type MenuLocation = string;++export interface MenuBarMenu {+ id: MenuLocation;+ title: () => string;+ /** Left-to-right position in the strip. */+ order: number;+ /** Group ids in render order; a separator falls between adjacent non-empty ones. */+ groups: string[];+}++export interface MenuContribution {+ /** Unique within the registry — a command row uses the command id. */+ id: string;+ location: MenuLocation;+ /** Which of the menu's `groups` this row belongs to (unknown ⇒ renders last). */+ group: string;+ /** Position within the group; ties fall back to registration order. */+ order?: number;+ /** Command id — its label, shortcut, enablement and checked state drive the row. */+ command?: string;+ /** Overrides the command's label (same action, menu-specific wording); the only+ * thing a row may restate. Required for a row with no `command`. */+ label?: () => string;+ /** Action for a row with no command behind it. */+ run?: () => void;+ /** Hide the row entirely when this returns false (distinct from disabled). */+ when?: () => boolean;+}++const MENUS: MenuBarMenu[] = [+ { id: 'file', title: () => t('menu.file'), order: 10, groups: ['new', 'open', 'save', 'close'] },+ { id: 'edit', title: () => t('menu.edit'), order: 20, groups: ['history', 'clipboard', 'selection'] },+ { id: 'entity', title: () => t('menu.entity'), order: 30, groups: ['create', 'modify', 'selection'] },+ { id: 'view', title: () => t('menu.view'), order: 40, groups: ['show', 'overlays', 'gizmo'] },+ { id: 'build', title: () => t('menu.build'), order: 50, groups: ['package', 'scripts'] },+ // Where contributed commands land by default. Rendered only once something is in+ // it — an empty dropdown is broken UI, so the strip hides a menu with no rows.+ { id: 'tools', title: () => t('menu.tools'), order: 60, groups: ['tools'] },+ { id: 'window', title: () => t('menu.window'), order: 70, groups: ['layout', 'navigate'] },+ { id: 'help', title: () => t('menu.help'), order: 80, groups: ['about', 'help', 'diagnostics'] },+];++/** A command row, spelled as compactly as the old `cmdItem(id)` call it replaces. */+const cmd = (location: MenuLocation, group: string, command: string): MenuContribution => ({+ id: `${location}/${command}`,+ location,+ group,+ command,+});++const BUILTIN_ITEMS: MenuContribution[] = [+ cmd('file', 'new', 'scene.new'),+ cmd('file', 'open', 'project.open'),+ cmd('file', 'save', 'project.save'),+ cmd('file', 'save', 'project.saveAs'),+ cmd('file', 'close', 'project.close'),++ cmd('edit', 'history', 'edit.undo'),+ cmd('edit', 'history', 'edit.redo'),+ cmd('edit', 'clipboard', 'entity.cut'),+ cmd('edit', 'clipboard', 'entity.copy'),+ cmd('edit', 'clipboard', 'entity.paste'),+ cmd('edit', 'clipboard', 'entity.delete'),+ cmd('edit', 'selection', 'edit.selectAll'),+ cmd('edit', 'selection', 'entity.deselect'),++ cmd('entity', 'create', 'entity.add'),+ cmd('entity', 'create', 'tilemap.new'),+ cmd('entity', 'create', 'tilemap.newCollisionLayer'),+ cmd('entity', 'modify', 'entity.duplicate'),+ cmd('entity', 'modify', 'entity.delete'),+ cmd('entity', 'selection', 'entity.deselect'),++ cmd('view', 'show', 'view.toggleGrid'),+ cmd('view', 'show', 'view.toggleGizmos'),+ cmd('view', 'show', 'view.toggleColliders'),+ cmd('view', 'show', 'view.toggleTileCollision'),+ cmd('view', 'show', 'view.togglePreviewFx'),+ cmd('view', 'overlays', 'view.toggleMinimap'),+ cmd('view', 'overlays', 'view.toggleStats'),+ cmd('view', 'overlays', 'view.toggleCoords'),+ cmd('view', 'overlays', 'view.togglePerf'),+ cmd('view', 'gizmo', 'view.toggleCoordSpace'),+ cmd('view', 'gizmo', 'view.togglePivotMode'),+ cmd('view', 'gizmo', 'view.toggleSnapping'),++ cmd('build', 'package', 'project.export'),+ cmd('build', 'scripts', 'build.scripts'),+ cmd('build', 'scripts', 'project.extractSchemas'),++ // Resets only the dock layout, rebuilt in place (keeps scene/engine/undo), and+ // guarded so a wedged dirty asset-editor tab can't vanish unwarned.+ cmd('window', 'layout', 'view.resetLayout'),+ {+ // The same guarded command as File ▸ Close Project, worded for where it leads —+ // never a second exit path that could skip the unsaved-changes prompt.+ ...cmd('window', 'navigate', 'project.close'),+ id: 'window/backToLauncher',+ label: () => t('menu.backToLauncher'),+ },++ cmd('help', 'about', 'help.about'),+ cmd('help', 'about', 'help.checkUpdates'),+ cmd('help', 'help', 'palette.open'),+ cmd('help', 'help', 'help.shortcuts'),+ cmd('help', 'diagnostics', 'help.openLogs'),+];++const menuContrib = new ContributionRegistry<MenuBarMenu>('menu');+const itemContrib = new ContributionRegistry<MenuContribution>('menu item');+menuContrib.registerAll('core', MENUS);+itemContrib.registerAll('core', BUILTIN_ITEMS);++export const menuRegistry = menuContrib;+export const menuItemRegistry = itemContrib;++export function registerMenu(menu: MenuBarMenu, owner: Owner = 'core'): Disposable {+ return menuContrib.register(owner, menu);+}++export function registerMenuItem(item: MenuContribution, owner: Owner = 'core'): Disposable {+ return itemContrib.register(owner, item);+}++/** Menu-bar menus in strip order. */+export function menuBarMenus(): MenuBarMenu[] {+ return [...menuContrib.all()].sort((a, b) => a.order - b.order);+}++/**+ * Items of one location, grouped and ordered for rendering: an array of non-empty+ * groups, each an array of items. `when`-gated rows are already dropped, so the+ * caller inserts one separator between consecutive returned groups and nothing else.+ * Groups the menu doesn't declare render last, in registration order.+ */+export function menuItemGroups(location: MenuLocation): MenuContribution[][] {+ const declared = menuContrib.get(location)?.groups ?? [];+ const visible = itemContrib.all().filter((i) => i.location === location && (i.when?.() ?? true));+ const rank = (group: string) => {+ const i = declared.indexOf(group);+ return i === -1 ? declared.length : i;+ };+ const byGroup = new Map<string, MenuContribution[]>();+ for (const item of visible) {+ const list = byGroup.get(item.group);+ if (list) list.push(item);+ else byGroup.set(item.group, [item]);+ }+ return [...byGroup.entries()]+ .sort(([a], [b]) => rank(a) - rank(b))+ .map(([, items]) => [...items].sort((a, b) => (a.order ?? 0) - (b.order ?? 0)));+}++/** Retract every menu + item of one owner (plugin unload / disable). */+export function disposeMenuOwner(owner: Owner): void {+ itemContrib.disposeOwner(owner);+ menuContrib.disposeOwner(owner);+}diff --git a/desktop/tests/menu-registry.test.ts b/desktop/tests/menu-registry.test.tsnew file mode 100644index 000000000..ea8bafd55--- /dev/null+++ b/desktop/tests/menu-registry.test.ts@@ -0,0 +1,131 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The menu-bar registry MenuBar renders from. The central assertion pins the+ * exact command order and separator placement the hand-written nested array+ * used to produce, so deriving the strip is provably behavior-preserving.+ * Beyond that: rows restate nothing a command already owns, separators are+ * derived (never dangling), and contributed rows are retractable.+ */+import { describe, it, expect, vi } from 'vitest';+import {+ menuBarMenus, menuItemGroups, registerMenuItem, disposeMenuOwner, menuItemRegistry,+} from '@/layout/menus';+import { commands } from '@/commands';++/** The command ids of a location, with `null` marking each derived separator. */+const layout = (location: string): (string | null)[] =>+ menuItemGroups(location).flatMap((group, i) => [+ ...(i > 0 ? [null] : []),+ ...group.map((item) => item.command ?? item.id),+ ]);++describe('menu registry', () => {+ it('keeps the menu strip in its established order', () => {+ expect(menuBarMenus().map((m) => m.id)).toEqual([+ 'file', 'edit', 'entity', 'view', 'build', 'tools', 'window', 'help',+ ]);+ });++ it('reproduces the legacy menu contents, separators included', () => {+ expect(layout('file')).toEqual([+ 'scene.new', null, 'project.open', null, 'project.save', 'project.saveAs', null, 'project.close',+ ]);+ expect(layout('edit')).toEqual([+ 'edit.undo', 'edit.redo', null,+ 'entity.cut', 'entity.copy', 'entity.paste', 'entity.delete', null,+ 'edit.selectAll', 'entity.deselect',+ ]);+ expect(layout('entity')).toEqual([+ 'entity.add', 'tilemap.new', 'tilemap.newCollisionLayer', null,+ 'entity.duplicate', 'entity.delete', null,+ 'entity.deselect',+ ]);+ expect(layout('view')).toEqual([+ 'view.toggleGrid', 'view.toggleGizmos', 'view.toggleColliders', 'view.toggleTileCollision', 'view.togglePreviewFx', null,+ 'view.toggleMinimap', 'view.toggleStats', 'view.toggleCoords', 'view.togglePerf', null,+ 'view.toggleCoordSpace', 'view.togglePivotMode', 'view.toggleSnapping',+ ]);+ expect(layout('build')).toEqual(['project.export', null, 'build.scripts', 'project.extractSchemas']);+ expect(layout('window')).toEqual(['view.resetLayout', null, 'project.close']);+ expect(layout('help')).toEqual([+ 'help.about', 'help.checkUpdates', null, 'palette.open', 'help.shortcuts', null, 'help.openLogs',+ ]);+ });++ it('ships the Tools menu empty, so the strip has nothing to render for it', () => {+ // MenuBar drops a menu with no rows — the location exists for contributions,+ // but an empty dropdown must never be openable.+ expect(menuItemGroups('tools')).toEqual([]);+ });++ it('every command row points at a registered command', () => {+ for (const menu of menuBarMenus()) {+ for (const group of menuItemGroups(menu.id)) {+ for (const item of group) {+ if (item.command) {+ expect(commands.get(item.command), `${menu.id}: ${item.command}`).toBeDefined();+ } else {+ expect(item.label, `${menu.id}: ${item.id} needs a label`).toBeDefined();+ expect(item.run, `${menu.id}: ${item.id} needs an action`).toBeDefined();+ }+ }+ }+ }+ });++ it('restates nothing a command already owns, except a deliberate label override', () => {+ const overrides = menuBarMenus()+ .flatMap((m) => menuItemGroups(m.id).flat())+ .filter((i) => i.command && i.label);+ // Back to Launcher is the one row worded differently from its command+ // (Close Project) — everything else must read its label off the command.+ expect(overrides.map((i) => i.id)).toEqual(['window/backToLauncher']);+ });++ it('a contributed row joins a group and is retracted with its owner', () => {+ registerMenuItem({ id: 'acme.bake', location: 'tools', group: 'tools', command: 'edit.undo' }, 'plugin:acme');+ expect(layout('tools')).toEqual(['edit.undo']);++ disposeMenuOwner('plugin:acme');+ expect(menuItemGroups('tools')).toEqual([]);+ });++ it('a contributed row lands after the built-ins of its group', () => {+ registerMenuItem({ id: 'acme.exportPlus', location: 'build', group: 'package', command: 'edit.redo' }, 'plugin:acme');+ expect(layout('build')).toEqual(['project.export', 'edit.redo', null, 'build.scripts', 'project.extractSchemas']);+ disposeMenuOwner('plugin:acme');+ });++ it('a row in an undeclared group renders last rather than vanishing', () => {+ registerMenuItem({ id: 'acme.odd', location: 'build', group: 'not-a-group', command: 'edit.undo' }, 'plugin:acme');+ expect(layout('build')).toEqual([+ 'project.export', null, 'build.scripts', 'project.extractSchemas', null, 'edit.undo',+ ]);+ disposeMenuOwner('plugin:acme');+ });++ it('a `when`-gated row leaves no dangling separator', () => {+ let visible = true;+ registerMenuItem(+ { id: 'acme.gated', location: 'tools', group: 'tools', command: 'edit.undo', when: () => visible },+ 'plugin:acme',+ );+ expect(layout('tools')).toEqual(['edit.undo']);+ visible = false;+ // The whole group disappears — not an empty group that would emit a separator.+ expect(menuItemGroups('tools')).toEqual([]);+ disposeMenuOwner('plugin:acme');+ });++ it('a contributed row cannot displace a built-in row', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ menuItemRegistry.register('plugin:evil', {+ id: 'file/project.save', location: 'file', group: 'new', command: 'entity.delete',+ });+ expect(layout('file')).toEqual([+ 'scene.new', null, 'project.open', null, 'project.save', 'project.saveAs', null, 'project.close',+ ]);+ warn.mockRestore();+ });+});