Skip to content

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.

refactor(editor): replace Create submenu cascade with a searchable popover

yhh0362b05ea84d
diff --git a/desktop/src/components/CreatePopover.tsx b/desktop/src/components/CreatePopover.tsx
new file mode 100644
index 000000000..6c46ca3f9
--- /dev/null
+++ b/desktop/src/components/CreatePopover.tsx
@@ -0,0 +1,128 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file CreatePopover.tsx — the "Create entity" picker.
+ *
+ * One anchored popover (search box + grouped, keyboard-navigable list) in place
+ * of cascading Create submenus: no flyout geometry, so nothing zigzags or folds
+ * over an earlier level near the window edge, and it scales as the template
+ * catalog grows. Mirrors Godot's "Create Node" / Unity's "Add Component".
+ */
+import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react';
+import { createPortal } from 'react-dom';
+import { Search } from 'lucide-react';
+import { flattenCatalog, matchCatalog, type EntityTemplate } from '@/engine/entityTemplates';
+
+export function CreatePopover({
+ x,
+ y,
+ onPick,
+ onClose,
+}: {
+ x: number;
+ y: number;
+ onPick: (t: EntityTemplate) => void;
+ onClose: () => void;
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+ const [pos, setPos] = useState({ left: x, top: y });
+ const [query, setQuery] = useState('');
+ const [active, setActive] = useState(0);
+
+ const all = useMemo(() => flattenCatalog(), []);
+ const results = useMemo(() => matchCatalog(all, query), [all, query]);
+
+ // Keep the active row in range as the filter narrows.
+ useEffect(() => setActive((i) => Math.min(i, Math.max(0, results.length - 1))), [results.length]);
+
+ // Clamp to the viewport once, before paint (as the context menu does).
+ useLayoutEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+ const r = el.getBoundingClientRect();
+ const pad = 8;
+ const left = x + r.width > window.innerWidth - pad ? Math.max(pad, window.innerWidth - r.width - pad) : x;
+ const top = y + r.height > window.innerHeight - pad ? Math.max(pad, window.innerHeight - r.height - pad) : y;
+ setPos({ left, top });
+ }, [x, y]);
+
+ useEffect(() => {
+ const close = () => onClose();
+ const onEsc = (e: globalThis.KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
+ window.addEventListener('mousedown', close);
+ window.addEventListener('scroll', close, true);
+ window.addEventListener('keydown', onEsc);
+ return () => {
+ window.removeEventListener('mousedown', close);
+ window.removeEventListener('scroll', close, true);
+ window.removeEventListener('keydown', onEsc);
+ };
+ }, [onClose]);
+
+ const pick = (i: number) => {
+ const e = results[i];
+ if (!e) return;
+ onClose();
+ onPick(e.template);
+ };
+
+ const onKey = (ev: KeyboardEvent<HTMLDivElement>) => {
+ if (ev.key === 'ArrowDown') { ev.preventDefault(); setActive((i) => Math.min(i + 1, results.length - 1)); }
+ else if (ev.key === 'ArrowUp') { ev.preventDefault(); setActive((i) => Math.max(i - 1, 0)); }
+ else if (ev.key === 'Enter') { ev.preventDefault(); pick(active); }
+ };
+
+ // `results` is already in display order, so the flat `active` index lines up
+ // with the rendered rows; category headers are drawn on each change.
+ let lastCategory = '';
+
+ return createPortal(
+ <div
+ ref={ref}
+ className="ctx"
+ role="dialog"
+ style={{ left: pos.left, top: pos.top, width: 240, maxHeight: 320, display: 'flex', flexDirection: 'column' }}
+ onMouseDown={(e) => e.stopPropagation()}
+ onKeyDown={onKey}
+ >
+ <div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '6px 8px', borderBottom: '1px solid rgba(255,255,255,0.08)' }}>
+ <Search size={13} style={{ opacity: 0.5, flex: '0 0 auto' }} />
+ <input
+ autoFocus
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Create…"
+ style={{ flex: 1, minWidth: 0, background: 'transparent', border: 0, outline: 'none', color: 'inherit', font: 'inherit' }}
+ />
+ </div>
+ <div style={{ overflowY: 'auto', padding: '4px 0' }}>
+ {results.length === 0 ? (
+ <div style={{ padding: '6px 10px', opacity: 0.5 }}>No matches</div>
+ ) : (
+ results.map((e, idx) => {
+ const header = e.category !== lastCategory ? e.category : null;
+ lastCategory = e.category;
+ return (
+ <div key={`${e.category}/${e.template.label}`}>
+ {header ? (
+ <div style={{ padding: '4px 10px 2px', fontSize: 11, textTransform: 'uppercase', letterSpacing: 0.4, opacity: 0.45 }}>{header}</div>
+ ) : null}
+ <button
+ type="button"
+ role="menuitem"
+ className="ctx-item"
+ style={idx === active ? { background: 'rgba(255,255,255,0.10)' } : undefined}
+ onMouseEnter={() => setActive(idx)}
+ onClick={() => pick(idx)}
+ >
+ <span className="cl">{e.template.label}</span>
+ </button>
+ </div>
+ );
+ })
+ )}
+ </div>
+ </div>,
+ document.body,
+ );
+}
diff --git a/desktop/src/components/Menu.tsx b/desktop/src/components/Menu.tsx
index 9de2ec661..f223d6f84 100644
--- a/desktop/src/components/Menu.tsx
+++ b/desktop/src/components/Menu.tsx
@@ -4,13 +4,12 @@
* @file Menu.tsx
* @brief Shared menu primitives — one implementation behind the menu-bar
* dropdowns and every right-click context menu, so item rendering
- * (labels, shortcuts, checkmarks, disabled state, separators, nested
- * submenus) and the context-menu dismiss behaviour live in one place.
+ * (labels, shortcuts, checkmarks, disabled state, separators) and the
+ * context-menu dismiss behaviour live in a single place.
*/
-import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react';
+import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
-import { Check, ChevronRight } from 'lucide-react';
-import { submenuPlacement } from './menuPlacement';
+import { Check } from 'lucide-react';
export type MenuItem =
| { sep: true }
@@ -22,96 +21,39 @@ export type MenuItem =
checked?: boolean;
icon?: ReactNode;
danger?: boolean;
- }
- | { label: string; submenu: MenuItem[]; icon?: ReactNode; disabled?: boolean };
-
-type Variant = 'bar' | 'ctx';
-const cls = (v: Variant, ctx: string, bar: string) => (v === 'ctx' ? ctx : bar);
-
-/** One menu row: separator, a flyout submenu, or a leaf action. */
-function MenuNode({ item, variant, close }: { item: MenuItem; variant: Variant; close: () => void }) {
- const [open, setOpen] = useState(false);
- const rowRef = useRef<HTMLDivElement>(null);
- const flyRef = useRef<HTMLDivElement>(null);
- // Hidden until measured, so the flip/shift is the first thing painted (no flash).
- const [flyStyle, setFlyStyle] = useState<CSSProperties>({ position: 'absolute', left: '100%', top: 0, visibility: 'hidden' });
-
- // Keep the flyout inside the Electron window: open left when it would overflow the
- // right edge, and shift up when it would run past the bottom (measured before paint).
- useLayoutEffect(() => {
- if (!open) return;
- const row = rowRef.current;
- const fly = flyRef.current;
- if (!row || !fly) return;
- const r = row.getBoundingClientRect();
- const f = fly.getBoundingClientRect();
- setFlyStyle(submenuPlacement(r, f, window.innerWidth, window.innerHeight));
- }, [open]);
-
- if ('sep' in item) return <div className={cls(variant, 'ctx-sep', 'menu-dropdown__sep')} />;
-
- const itemClass = cls(variant, 'ctx-item', 'menu-dropdown__item');
- const leadClass = cls(variant, 'ci', 'menu-dropdown__check');
- const labelClass = cls(variant, 'cl', 'menu-dropdown__label');
- const trailClass = cls(variant, 'ck', 'menu-dropdown__shortcut');
-
- if ('submenu' in item) {
- return (
- <div
- ref={rowRef}
- style={{ position: 'relative' }}
- onMouseEnter={() => setOpen(true)}
- onMouseLeave={() => setOpen(false)}
- >
- <button type="button" role="menuitem" className={itemClass} disabled={item.disabled} aria-haspopup="true" aria-expanded={open}>
- <span className={leadClass}>{item.icon}</span>
- <span className={labelClass}>{item.label}</span>
- <span className={trailClass}><ChevronRight size={13} strokeWidth={2.2} /></span>
- </button>
- {open ? (
- <div
- ref={flyRef}
- className={cls(variant, 'ctx', 'menu-dropdown')}
- role="menu"
- style={flyStyle}
- onMouseDown={(e) => e.stopPropagation()}
- >
- {item.submenu.map((sub, j) => <MenuNode key={j} item={sub} variant={variant} close={close} />)}
- </div>
- ) : null}
- </div>
- );
- }
-
- const danger = variant === 'ctx' && item.danger ? ' danger' : '';
- const checkSize = variant === 'ctx' ? 2.4 : 2.2;
- return (
- <button
- type="button"
- role="menuitem"
- className={itemClass + danger}
- disabled={item.disabled}
- onClick={() => {
- close();
- item.onClick();
- }}
- >
- <span className={leadClass}>{item.checked ? <Check size={13} strokeWidth={checkSize} /> : item.icon}</span>
- <span className={labelClass}>{item.label}</span>
- {item.shortcut ? <span className={trailClass}>{item.shortcut}</span> : null}
- </button>
- );
-}
+ };
/**
- * The contents of a menu — separators, submenus and item buttons. Renders inside a
+ * The contents of a menu — separators and item buttons. Renders inside a
* positioned `.menu-dropdown` container (the menu-bar provides one; ContextMenu
* provides its own). Closes the menu via `onSelect` before running the action.
*/
export function MenuItems({ items, onSelect }: { items: MenuItem[]; onSelect: () => void }) {
return (
<>
- {items.map((it, i) => <MenuNode key={i} item={it} variant="bar" close={onSelect} />)}
+ {items.map((it, i) =>
+ 'sep' in it ? (
+ <div key={i} className="menu-dropdown__sep" />
+ ) : (
+ <button
+ key={i}
+ type="button"
+ role="menuitem"
+ className="menu-dropdown__item"
+ disabled={it.disabled}
+ onClick={() => {
+ onSelect();
+ it.onClick();
+ }}
+ >
+ <span className="menu-dropdown__check">
+ {it.checked ? <Check size={13} strokeWidth={2.2} /> : null}
+ </span>
+ <span className="menu-dropdown__label">{it.label}</span>
+ {it.shortcut ? <span className="menu-dropdown__shortcut">{it.shortcut}</span> : null}
+ </button>
+ ),
+ )}
</>
);
}
@@ -172,7 +114,27 @@ export function ContextMenu({
style={{ left: pos.left, top: pos.top }}
onMouseDown={(e) => e.stopPropagation()}
>
- {items.map((it, i) => <MenuNode key={i} item={it} variant="ctx" close={onClose} />)}
+ {items.map((it, i) =>
+ 'sep' in it ? (
+ <div key={i} className="ctx-sep" />
+ ) : (
+ <button
+ key={i}
+ type="button"
+ role="menuitem"
+ className={`ctx-item${it.danger ? ' danger' : ''}`}
+ disabled={it.disabled}
+ onClick={() => {
+ onClose();
+ it.onClick();
+ }}
+ >
+ <span className="ci">{it.checked ? <Check size={13} strokeWidth={2.4} /> : it.icon}</span>
+ <span className="cl">{it.label}</span>
+ {it.shortcut ? <span className="ck">{it.shortcut}</span> : null}
+ </button>
+ ),
+ )}
</div>,
document.body,
);
diff --git a/desktop/src/components/menuPlacement.ts b/desktop/src/components/menuPlacement.ts
deleted file mode 100644
index 501324dd8..000000000
--- a/desktop/src/components/menuPlacement.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import type { CSSProperties } from 'react';
-
-export interface Box {
- left: number;
- right: number;
- top: number;
- width: number;
- height: number;
-}
-
-/**
- * Position a flyout submenu so it stays inside the window: open to the right of
- * its row by default, flip to the left when the right side would overflow (and
- * the left has room), and shift up when it would run past the bottom edge.
- * Pure so the placement is unit-tested without a DOM.
- */
-export function submenuPlacement(
- row: Box,
- fly: { width: number; height: number },
- viewportW: number,
- viewportH: number,
- pad = 8,
-): CSSProperties {
- const flipLeft = row.right + fly.width > viewportW - pad && row.left - fly.width > pad;
- const overflowY = Math.max(0, row.top + fly.height - (viewportH - pad));
- return {
- position: 'absolute',
- top: overflowY ? -overflowY : 0,
- visibility: 'visible',
- ...(flipLeft ? { right: '100%' } : { left: '100%' }),
- };
-}
diff --git a/desktop/src/engine/entityTemplates.ts b/desktop/src/engine/entityTemplates.ts
index a3dfa3276..31d5e2dd0 100644
--- a/desktop/src/engine/entityTemplates.ts
+++ b/desktop/src/engine/entityTemplates.ts
@@ -34,3 +34,22 @@ export const ENTITY_TEMPLATE_CATALOG: TemplateCategory[] = [
})),
},
];
+
+export interface CatalogEntry {
+ category: string;
+ template: EntityTemplate;
+}
+
+/** Flatten the catalog to a single searchable list (display order preserved). */
+export function flattenCatalog(catalog: TemplateCategory[] = ENTITY_TEMPLATE_CATALOG): CatalogEntry[] {
+ return catalog.flatMap((c) => c.items.map((template) => ({ category: c.label, template })));
+}
+
+/** Case-insensitive filter over item + category labels, for the Create popover. */
+export function matchCatalog(entries: CatalogEntry[], query: string): CatalogEntry[] {
+ const q = query.trim().toLowerCase();
+ if (!q) return entries;
+ return entries.filter(
+ (e) => e.template.label.toLowerCase().includes(q) || e.category.toLowerCase().includes(q),
+ );
+}
diff --git a/desktop/src/panels/Outliner.tsx b/desktop/src/panels/Outliner.tsx
index 72ec3a5cb..a0c901dc7 100644
--- a/desktop/src/panels/Outliner.tsx
+++ b/desktop/src/panels/Outliner.tsx
@@ -18,7 +18,8 @@ import { OutlinerRow } from '@/outliner/OutlinerRow';
import { OUTLINER_COLUMNS, TYPE_COLUMN, type OutlinerColumnContext } from '@/outliner/columns';
import { joinFolder, folderParent, folderName, normalizeFolder, isFolderUnder } from '@/outliner/folders';
import type { EntityId } from '@/types';
-import { ENTITY_TEMPLATE_CATALOG, type EntityTemplate } from '@/engine/entityTemplates';
+import { type EntityTemplate } from '@/engine/entityTemplates';
+import { CreatePopover } from '@/components/CreatePopover';
// Must match .row height in outliner.css — the fixed row size the virtual list windows by.
const ROW_H = 24;
@@ -90,6 +91,7 @@ export function Outliner() {
const [renaming, setRenaming] = useState<string | null>(null); // item key
const [drop, setDrop] = useState<{ key: string; pos: 'before' | 'on' | 'after' } | null>(null);
const [ctx, setCtx] = useState<{ x: number; y: number; item: OutlinerItem | null } | null>(null); // item null = empty-space menu
+ const [createAt, setCreateAt] = useState<{ x: number; y: number; parent: EntityId | null } | null>(null);
const [sortMenu, setSortMenu] = useState<{ x: number; y: number } | null>(null);
const [colsMenu, setColsMenu] = useState<{ x: number; y: number } | null>(null);
// Controlled scroll for reveal-on-select + keyboard nav (nonce re-fires same index).
@@ -311,13 +313,6 @@ export function Outliner() {
const id = SceneCommands.createFromTemplate(t.prefab, under);
if (id != null) select(id);
};
- const createMenu = (parent: EntityId | null): MenuItem => ({
- label: 'Create',
- submenu: ENTITY_TEMPLATE_CATALOG.map((cat) => ({
- label: cat.label,
- submenu: cat.items.map((t) => ({ label: t.label, onClick: () => createTemplate(t, parent) })),
- })),
- });
const selectionOrTarget = (id: EntityId): EntityId[] => {
const ids = useSelection.getState().selectedIds;
return ids.has(id) ? [...ids] : [id];
@@ -471,7 +466,7 @@ export function Outliner() {
// Empty-space (scene) menu.
return [
{ label: 'Add Entity', onClick: addEntity },
- createMenu(null),
+ { label: 'Create…', onClick: () => setCreateAt({ x: ctx.x, y: ctx.y, parent: null }) },
{ label: 'New Folder', onClick: () => newFolder('', null) },
{ sep: true },
{ label: 'Expand All', onClick: expandAll },
@@ -525,7 +520,7 @@ export function Outliner() {
{ label: 'Unparent', onClick: () => selectionOrTarget(id).forEach((i) => SceneCommands.setParent(i, null)) },
{ sep: true },
{ label: 'Add Entity', onClick: addEntity },
- createMenu(id),
+ { label: 'Create…', onClick: () => setCreateAt({ x: ctx.x, y: ctx.y, parent: id }) },
];
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ctx]);
@@ -657,6 +652,14 @@ export function Outliner() {
)}
{ctx && !gameMode && <ContextMenu x={ctx.x} y={ctx.y} items={ctxItems} onClose={() => setCtx(null)} />}
+ {createAt && (
+ <CreatePopover
+ x={createAt.x}
+ y={createAt.y}
+ onClose={() => setCreateAt(null)}
+ onPick={(t) => createTemplate(t, createAt.parent)}
+ />
+ )}
{sortMenu && !gameMode && (
<ContextMenu
x={sortMenu.x}
diff --git a/desktop/tests/create-catalog.test.ts b/desktop/tests/create-catalog.test.ts
new file mode 100644
index 000000000..830fc3366
--- /dev/null
+++ b/desktop/tests/create-catalog.test.ts
@@ -0,0 +1,30 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { flattenCatalog, matchCatalog } from '@/engine/entityTemplates';
+
+describe('Create catalog (searchable template list)', () => {
+ it('flattens categories into a list, preserving order + carrying category', () => {
+ const all = flattenCatalog();
+ expect(all.length).toBeGreaterThan(0);
+ expect(all.every((e) => e.category !== '' && e.template.label !== '')).toBe(true);
+ expect(all.map((e) => e.template.label)).toEqual(expect.arrayContaining(['Button', 'Slider']));
+ });
+
+ it('matches on item label, case-insensitively', () => {
+ const all = flattenCatalog();
+ const r = matchCatalog(all, 'BUT');
+ expect(r.map((e) => e.template.label)).toEqual(['Button']);
+ });
+
+ it('matches on category label', () => {
+ const all = flattenCatalog();
+ expect(matchCatalog(all, 'ui').length).toBe(all.length); // every current template is UI
+ });
+
+ it('empty query returns everything; no match returns nothing', () => {
+ const all = flattenCatalog();
+ expect(matchCatalog(all, ' ')).toEqual(all);
+ expect(matchCatalog(all, 'zzzzz')).toEqual([]);
+ });
+});
diff --git a/desktop/tests/menu-placement.test.ts b/desktop/tests/menu-placement.test.ts
deleted file mode 100644
index 94ce9cf95..000000000
--- a/desktop/tests/menu-placement.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-// SPDX-License-Identifier: Apache-2.0
-// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import { describe, it, expect } from 'vitest';
-import { submenuPlacement } from '@/components/menuPlacement';
-
-const fly = { width: 180, height: 200 };
-const row = (over: Partial<{ left: number; right: number; top: number }>) =>
- ({ left: 100, right: 240, top: 100, width: 140, height: 24, ...over });
-
-describe('submenuPlacement (keeps flyouts inside the window)', () => {
- it('opens to the right when there is room', () => {
- const s = submenuPlacement(row({}), fly, 1200, 800);
- expect(s.left).toBe('100%');
- expect(s.right).toBeUndefined();
- });
-
- it('flips left when the right edge would overflow', () => {
- const s = submenuPlacement(row({ left: 1000, right: 1150 }), fly, 1200, 800);
- expect(s.right).toBe('100%');
- expect(s.left).toBeUndefined();
- });
-
- it('stays right when neither side fits (degrades, not flips into worse overflow)', () => {
- const s = submenuPlacement(row({ left: 50, right: 250 }), fly, 300, 800);
- expect(s.left).toBe('100%'); // left has no room (50 - 180 < pad), so keep right
- });
-
- it('shifts up when it would run past the bottom', () => {
- const s = submenuPlacement(row({ top: 700 }), fly, 1200, 800); // 700 + 200 = 900 > 792
- expect(s.top).toBe(-108);
- });
-
- it('no vertical shift when it fits', () => {
- expect(submenuPlacement(row({ top: 100 }), fly, 1200, 800).top).toBe(0);
- });
-});