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
feat(editor): Create menu that instantiates controls from a template catalog
yhhe21655ee5c73
diff --git a/desktop/src/components/Menu.tsx b/desktop/src/components/Menu.tsxindex f223d6f84..d57116b66 100644--- a/desktop/src/components/Menu.tsx+++ b/desktop/src/components/Menu.tsx@@ -4,12 +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) and the- * context-menu dismiss behaviour live in a single place.+ * (labels, shortcuts, checkmarks, disabled state, separators, nested+ * submenus) and the context-menu dismiss behaviour live in one place.*/import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';import { createPortal } from 'react-dom';-import { Check } from 'lucide-react';+import { Check, ChevronRight } from 'lucide-react';export type MenuItem =| { sep: true }@@ -21,39 +21,78 @@ 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);++ 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+ 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+ className={cls(variant, 'ctx', 'menu-dropdown')}+ role="menu"+ style={{ position: 'absolute', left: '100%', top: 0 }}+ 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 and item buttons. Renders inside a+ * The contents of a menu — separators, submenus 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) =>- '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>- ),- )}+ {items.map((it, i) => <MenuNode key={i} item={it} variant="bar" close={onSelect} />)}</>);}@@ -114,27 +153,7 @@ export function ContextMenu({style={{ left: pos.left, top: pos.top }}onMouseDown={(e) => e.stopPropagation()}>- {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>- ),- )}+ {items.map((it, i) => <MenuNode key={i} item={it} variant="ctx" close={onClose} />)}</div>,document.body,);diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex 05fa3d344..73e1e8536 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -508,6 +508,43 @@ export class SceneCommandsImpl {return rootId;}+ /**+ * Create plain, user-owned entities from a template prefab — the widget's+ * structure + styling expanded into ordinary entities with NO prefab-instance+ * link (the "Create → UI → Button" flow, à la Unity). Undoable; returns the+ * root's source id.+ */+ createFromTemplate(prefab: PrefabData, parent: EntityId | null): EntityId | null {+ if (!this.model.current) return null;+ const { entities, rootId } = expandInstance(+ prefab,+ { prefab: '', overrides: [], added: [], removed: [] },+ () => this.model.allocateSourceId(),+ );+ const root = entities.find((e) => e.id === rootId);+ if (!root) return null;+ root.parent = parent;++ const scene = entities.map((e): SceneEntity =>+ ({+ id: e.id, name: e.name, parent: e.parent, children: e.children,+ components: structuredClone(e.components), visible: e.visible,+ }) as unknown as SceneEntity,+ );+ const apply = (): void => { this.model.insertSubtree(scene); };+ apply();+ this.history.record(`Create ${prefab.name || 'Entity'}`, apply, () => {+ for (const id of this.model.collectSubtree(rootId)) this.model.removeEntityBySource(id);+ });+ return rootId;+ }++ /** The scene's Canvas entity (UI layout root), or null — the default parent for new UI. */+ findCanvas(): EntityId | null {+ const e = this.model.current?.entities.find((x) => x.components.some((c) => c.type === 'Canvas'));+ return e ? (e.id as EntityId) : null;+ }+/** Rename an entity (undoable). */renameEntity(sourceId: EntityId, name: string): void {const before = this.model.entityBySource(sourceId)?.name;diff --git a/desktop/src/engine/entityTemplates.ts b/desktop/src/engine/entityTemplates.tsnew file mode 100644index 000000000..a3dfa3276--- /dev/null+++ b/desktop/src/engine/entityTemplates.ts@@ -0,0 +1,36 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file entityTemplates.ts — the Create-menu catalog.+ *+ * One declarative registry of ready-made entities, grouped by category, that the+ * Outliner's "Create ▸" menu is generated from — instead of hand-adding a blank+ * entity and stacking components. UI controls come from the SDK's built-in widget+ * prefabs (generated from the factories). New categories (2D, lights, …) slot in+ * here without touching the menu code.+ */+import { BUILTIN_UI_PREFABS, BUILTIN_UI_WIDGET_NAMES, type PrefabData } from 'esengine';++export interface EntityTemplate {+ label: string;+ /** The subtree expanded into plain entities on create (SceneCommands.createFromTemplate). */+ prefab: PrefabData;+ /** UI controls default to the Canvas as parent when created from empty space. */+ underCanvas?: boolean;+}++export interface TemplateCategory {+ label: string;+ items: EntityTemplate[];+}++export const ENTITY_TEMPLATE_CATALOG: TemplateCategory[] = [+ {+ label: 'UI',+ items: BUILTIN_UI_WIDGET_NAMES.map((name) => ({+ label: name,+ prefab: BUILTIN_UI_PREFABS[name]!,+ underCanvas: true,+ })),+ },+];diff --git a/desktop/src/panels/Outliner.tsx b/desktop/src/panels/Outliner.tsxindex 18f9d7708..72ec3a5cb 100644--- a/desktop/src/panels/Outliner.tsx+++ b/desktop/src/panels/Outliner.tsx@@ -18,6 +18,7 @@ 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';// Must match .row height in outliner.css — the fixed row size the virtual list windows by.const ROW_H = 24;@@ -303,6 +304,20 @@ export function Outliner() {const id = SceneCommands.addEntity();if (id != null) select(id);};+ // Create a ready-made entity from a catalog template (no add-component dance).+ // UI controls land under `parent`, or the Canvas when created from empty space.+ const createTemplate = (t: EntityTemplate, parent: EntityId | null) => {+ const under = t.underCanvas ? (parent ?? SceneCommands.findCanvas()) : parent;+ 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];@@ -456,6 +471,7 @@ export function Outliner() {// Empty-space (scene) menu.return [{ label: 'Add Entity', onClick: addEntity },+ createMenu(null),{ label: 'New Folder', onClick: () => newFolder('', null) },{ sep: true },{ label: 'Expand All', onClick: expandAll },@@ -507,7 +523,9 @@ export function Outliner() {{ label: 'New Folder from Selection', onClick: () => newFolder('', selectionOrTarget(id)) },{ label: 'Move to Root', onClick: () => SceneCommands.moveToFolder(selectionOrTarget(id), null) },{ label: 'Unparent', onClick: () => selectionOrTarget(id).forEach((i) => SceneCommands.setParent(i, null)) },+ { sep: true },{ label: 'Add Entity', onClick: addEntity },+ createMenu(id),];// eslint-disable-next-line react-hooks/exhaustive-deps}, [ctx]);diff --git a/desktop/tests/engine-commands.test.ts b/desktop/tests/engine-commands.test.tsindex 5b5d4d04a..648516792 100644--- a/desktop/tests/engine-commands.test.ts+++ b/desktop/tests/engine-commands.test.ts@@ -14,7 +14,7 @@* ids; the World is asserted via session.model.runtimeFor.*/import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';-import { App, Transform, Parent, Sprite } from 'esengine';+import { App, Transform, Parent, Sprite, Interactable, BUILTIN_UI_PREFABS } from 'esengine';import type { ESEngineModule } from 'esengine';import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';@@ -177,4 +177,34 @@ describe.skipIf(!HAS_WASM)('SceneCommands / SceneQuery (headless World)', () =>S.commands.removeComponent(id, 'Transform');expect(host.world.has(e, Transform)).toBe(true);});++ it('createFromTemplate expands a widget prefab into plain, owned entities', () => {+ const root = S.commands.createFromTemplate(BUILTIN_UI_PREFABS.Button, null)!;+ expect(root).not.toBeNull();++ // Model: button root + one Text label child, and NO prefab-instance link.+ const rootEnt = S.model.entityBySource(root)!;+ expect(rootEnt.components.map((c) => c.type)).toEqual(+ expect.arrayContaining(['UINode', 'Interactable', 'StateMachine', 'StateVisuals']),+ );+ expect(rootEnt.children.length).toBe(1);+ const label = S.model.entityBySource(rootEnt.children[0])!;+ expect(label.components.map((c) => c.type)).toContain('Text');+ expect(S.model.prefabTag(root)).toBeFalsy();++ // World: the Reconciler projected the subtree (Interactable is core-registered+ // in the bare test App; the rest is asserted on the model above).+ expect(host.world.has(rt(root), Interactable)).toBe(true);+ expect(host.world.valid(rt(rootEnt.children[0]))).toBe(true);+ });++ it('createFromTemplate is undoable — tears the whole subtree back down', () => {+ const root = S.commands.createFromTemplate(BUILTIN_UI_PREFABS.Button, null)!;+ const child = S.model.entityBySource(root)!.children[0];+ const [e, ce] = [rt(root), rt(child)];+ expect(host.world.valid(e)).toBe(true);+ S.history.undo();+ expect(host.world.valid(e)).toBe(false);+ expect(host.world.valid(ce)).toBe(false);+ });});