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): data-drive the Create-entity registry (EntitySource)

esengineb05b13eba727
diff --git a/desktop/src/components/CreatePopover.tsx b/desktop/src/components/CreatePopover.tsx
index 2d7080e64..3ff6eefd1 100644
--- a/desktop/src/components/CreatePopover.tsx
+++ b/desktop/src/components/CreatePopover.tsx
@@ -4,39 +4,28 @@
* @file CreatePopover.tsx — the "Create entity" picker.
*
* A centered command-palette modal (search + category-grouped, keyboard-navigable
- * list) for creating entities from the template catalog. Shares the UE5-aligned
- * `.ac` picker shell + behaviour with AddComponentMenu, so the two read as one
- * design and the scrim/scroll dismissal is consistent: clicks inside stay open,
- * the wheel scrolls the list (never dismisses), only the scrim / Esc close it.
+ * list) for creating entities from the source registry. Each row's icon comes from
+ * the source itself — the picker holds no icon knowledge. Shares the `.ac` picker
+ * shell + behaviour with AddComponentMenu, so the two read as one design and the
+ * scrim/scroll dismissal is consistent: clicks inside stay open, the wheel scrolls
+ * the list (never dismisses), only the scrim / Esc close it.
*/
import { useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
-import { Box, Image, Video, Lightbulb, Sparkles, LayoutDashboard, ToggleLeft, SlidersHorizontal } from 'lucide-react';
-import { flattenCatalog, matchCatalog, type CatalogEntry, type EntityTemplate } from '@/engine/entityTemplates';
+import { ENTITY_SOURCES, matchSources, type EntitySource } from '@/engine/entitySources';
import { SearchField } from '@/components/SearchField';
import { useDialogFocus } from '@/components/dialogFocus';
-const ICONS: Record<string, typeof Box> = {
- Empty: Box,
- Sprite: Image,
- Camera: Video,
- Light: Lightbulb,
- Particles: Sparkles,
- Canvas: LayoutDashboard,
- Toggle: ToggleLeft,
- Slider: SlidersHorizontal,
-};
-
-/** Group consecutive entries by category (the catalog is already category-ordered). */
-function groupByCategory(entries: CatalogEntry[]) {
- const groups: { category: string; items: CatalogEntry[] }[] = [];
- for (const e of entries) {
+/** Group consecutive sources by category (the registry is already category-ordered). */
+function groupByCategory(items: EntitySource[]) {
+ const groups: { category: string; items: EntitySource[] }[] = [];
+ for (const it of items) {
let g = groups[groups.length - 1];
- if (!g || g.category !== e.category) {
- g = { category: e.category, items: [] };
+ if (!g || g.category !== it.category) {
+ g = { category: it.category, items: [] };
groups.push(g);
}
- g.items.push(e);
+ g.items.push(it);
}
return groups;
}
@@ -45,7 +34,7 @@ export function CreatePopover({
onPick,
onClose,
}: {
- onPick: (t: EntityTemplate) => void;
+ onPick: (s: EntitySource) => void;
onClose: () => void;
}) {
const [query, setQuery] = useState('');
@@ -55,8 +44,7 @@ export function CreatePopover({
const shellRef = useRef<HTMLDivElement>(null);
useDialogFocus(shellRef);
- const all = useMemo(() => flattenCatalog(), []);
- const results = useMemo(() => matchCatalog(all, query), [all, query]);
+ const results = useMemo(() => matchSources(ENTITY_SOURCES, query), [query]);
const groups = useMemo(() => groupByCategory(results), [results]);
useEffect(() => inputRef.current?.focus(), []);
@@ -76,15 +64,15 @@ export function CreatePopover({
};
}, [onClose]);
- const commit = (t: EntityTemplate) => {
+ const commit = (s: EntitySource) => {
onClose();
- onPick(t);
+ onPick(s);
};
const onKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'ArrowDown') { e.preventDefault(); setActive((a) => Math.min(results.length - 1, a + 1)); }
else if (e.key === 'ArrowUp') { e.preventDefault(); setActive((a) => Math.max(0, a - 1)); }
- else if (e.key === 'Enter') { e.preventDefault(); const it = results[active]; if (it) commit(it.template); }
+ else if (e.key === 'Enter') { e.preventDefault(); const it = results[active]; if (it) commit(it); }
else if (e.key === 'Escape') { e.preventDefault(); onClose(); }
};
@@ -114,19 +102,19 @@ export function CreatePopover({
{g.items.map((it) => {
const idx = results.indexOf(it);
const isActive = idx === active;
- const Icon = ICONS[it.template.label] ?? Box;
+ const Icon = it.icon;
return (
<button
- key={`${it.category}/${it.template.label}`}
+ key={it.id}
ref={isActive ? activeRef : undefined}
type="button"
className={`ac-item${isActive ? ' sel' : ''}`}
onMouseEnter={() => setActive(idx)}
- onClick={() => commit(it.template)}
+ onClick={() => commit(it)}
>
<span className="ai"><Icon size={16} /></span>
<span className="at">
- <div className="an">{it.template.label}</div>
+ <div className="an">{it.label}</div>
</span>
<span className="ak">↵</span>
</button>
diff --git a/desktop/src/engine/entitySources.ts b/desktop/src/engine/entitySources.ts
new file mode 100644
index 000000000..a4871da4c
--- /dev/null
+++ b/desktop/src/engine/entitySources.ts
@@ -0,0 +1,126 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file entitySources.ts — the Create-entity registry.
+ *
+ * One data-driven list of `EntitySource`s the Create popover is generated from.
+ * Each source carries its own label / category / icon and a `build` that expands
+ * into a PrefabData; creation always routes through the single
+ * SceneCommands.create pipeline via `createFromSource`. New items — including the
+ * future async / asset-driven sources — slot in here without touching the picker
+ * UI. (REARCH_ENTITY_CREATION E2.)
+ */
+import type { LucideIcon } from 'lucide-react';
+import { CircleDot, Image, Camera, Sparkles, Lightbulb, LayoutPanelTop, ToggleLeft, SlidersHorizontal, List, ChevronDown, SquareMousePointer, RectangleHorizontal, Box } from 'lucide-react';
+import { BUILTIN_UI_PREFABS, BUILTIN_UI_WIDGET_NAMES, PREFAB_FORMAT_VERSION, type PrefabData } from 'esengine';
+import type { EntityId } from '@/types';
+import { componentByName, componentDefaults } from './schema';
+import { SceneCommands } from './SceneCommands';
+
+/** Where a source is created: the target parent + (for asset/drop sources) its origin. */
+export interface CreateContext {
+ parent: EntityId | null;
+ position?: { x: number; y: number };
+ assetPath?: string;
+}
+
+/** How a new entity is parented when the request carries no explicit target. */
+export type PlacementRule = 'as-requested' | 'under-canvas';
+
+/** A single, data-driven way to create an entity. */
+export interface EntitySource {
+ id: string;
+ label: string;
+ category: string;
+ icon: LucideIcon;
+ keywords?: string[];
+ /** Expand into a prefab to instantiate. Sync today; may be async (E3 asset sources). */
+ build(ctx: CreateContext): PrefabData | Promise<PrefabData>;
+ placement?: PlacementRule;
+ /** A prefab-linked source tags the subtree with this ref (instance = a delta). */
+ linkPrefabRef?: (ctx: CreateContext) => string | undefined;
+}
+
+/** Category display order in the Create popover (mirrors the Add-Component taxonomy style). */
+export const CREATE_CATEGORY_ORDER = ['Basic', '2D', 'UI', 'Prefabs', 'Scripts'];
+
+type CompSpec = string | [string, Record<string, unknown>];
+
+/** A one-entity template prefab from the registered component defaults + overrides. */
+function preset(name: string, comps: CompSpec[]): PrefabData {
+ const components = comps.map((c) => {
+ const [type, over] = Array.isArray(c) ? c : [c, undefined];
+ const def = componentByName(type);
+ const base = def ? structuredClone(componentDefaults(def)) : {};
+ return { type, data: over ? { ...base, ...over } : base };
+ });
+ return {
+ version: PREFAB_FORMAT_VERSION,
+ name,
+ rootEntityId: '0',
+ entities: [{ prefabEntityId: '0', name, parent: null, children: [], components, visible: true }],
+ };
+}
+
+/** A static preset source — its prefab is built once from the registered component defaults. */
+function presetSource(id: string, label: string, category: string, icon: LucideIcon, comps: CompSpec[]): EntitySource {
+ const prefab = preset(label, comps);
+ return { id, label, category, icon, build: () => prefab };
+}
+
+const UI_WIDGET_ICON: Record<string, LucideIcon> = {
+ Button: SquareMousePointer,
+ Toggle: ToggleLeft,
+ Slider: SlidersHorizontal,
+ Progress: RectangleHorizontal,
+ Dropdown: ChevronDown,
+ ListView: List,
+};
+
+export const ENTITY_SOURCES: EntitySource[] = [
+ presetSource('empty', 'Empty', 'Basic', CircleDot, ['Transform']),
+ presetSource('sprite', 'Sprite', '2D', Image, ['Transform', 'Sprite']),
+ presetSource('camera', 'Camera', '2D', Camera, [['Transform', { position: { x: 0, y: 0, z: 10 } }], 'Camera']),
+ presetSource('particles', 'Particles', '2D', Sparkles, ['Transform', 'ParticleEmitter']),
+ presetSource('light', 'Light', '2D', Lightbulb, ['Transform', 'Light2D']),
+ presetSource('canvas', 'Canvas', 'UI', LayoutPanelTop, ['Transform', ['Canvas', { designResolution: { x: 800, y: 600 }, scaleMode: 2 }], 'UINode']),
+ ...BUILTIN_UI_WIDGET_NAMES.map((name): EntitySource => ({
+ id: `ui-${name.toLowerCase()}`,
+ label: name,
+ category: 'UI',
+ icon: UI_WIDGET_ICON[name] ?? Box,
+ build: () => BUILTIN_UI_PREFABS[name]!,
+ placement: 'under-canvas',
+ })),
+];
+
+/** Case-insensitive filter over label + category + keywords, for the Create popover. */
+export function matchSources(sources: EntitySource[], query: string): EntitySource[] {
+ const q = query.trim().toLowerCase();
+ if (!q) return sources;
+ return sources.filter(
+ (s) =>
+ s.label.toLowerCase().includes(q) ||
+ s.category.toLowerCase().includes(q) ||
+ (s.keywords ?? []).some((k) => k.toLowerCase().includes(q)),
+ );
+}
+
+function resolvePlacement(rule: PlacementRule | undefined, ctx: CreateContext): EntityId | null {
+ if (rule === 'under-canvas') return ctx.parent ?? SceneCommands.findCanvas();
+ return ctx.parent;
+}
+
+/**
+ * Create an entity from a source: expand its prefab (possibly async), resolve where
+ * it lands, and route through the single SceneCommands.create pipeline. Returns the
+ * new root's source id; the caller handles selection.
+ */
+export async function createFromSource(source: EntitySource, ctx: CreateContext): Promise<EntityId | null> {
+ const prefab = await source.build(ctx);
+ return SceneCommands.create(prefab, {
+ parent: resolvePlacement(source.placement, ctx),
+ position: ctx.position,
+ linkPrefabRef: source.linkPrefabRef?.(ctx),
+ });
+}
diff --git a/desktop/src/engine/entityTemplates.ts b/desktop/src/engine/entityTemplates.ts
deleted file mode 100644
index 2fa7f7e5a..000000000
--- a/desktop/src/engine/entityTemplates.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-// 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" popover is generated from — instead of hand-adding a blank
- * entity and stacking components. Every template is a single PrefabData, so they
- * all instantiate through the same SceneCommands.createFromTemplate path: UI
- * controls are the SDK's generated widget prefabs; the rest are one-entity presets
- * built from the registered component defaults. New categories/items slot in here
- * without touching the menu code.
- */
-import { BUILTIN_UI_PREFABS, BUILTIN_UI_WIDGET_NAMES, PREFAB_FORMAT_VERSION, type PrefabData } from 'esengine';
-import { componentByName, componentDefaults } from './schema';
-
-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[];
-}
-
-type CompSpec = string | [string, Record<string, unknown>];
-
-/** A one-entity template prefab from the registered component defaults + overrides. */
-function preset(name: string, comps: CompSpec[]): PrefabData {
- const components = comps.map((c) => {
- const [type, over] = Array.isArray(c) ? c : [c, undefined];
- const def = componentByName(type);
- const base = def ? structuredClone(componentDefaults(def)) : {};
- return { type, data: over ? { ...base, ...over } : base };
- });
- return {
- version: PREFAB_FORMAT_VERSION,
- name,
- rootEntityId: '0',
- entities: [{ prefabEntityId: '0', name, parent: null, children: [], components, visible: true }],
- };
-}
-
-export const ENTITY_TEMPLATE_CATALOG: TemplateCategory[] = [
- {
- label: 'Basic',
- items: [{ label: 'Empty', prefab: preset('Empty', ['Transform']) }],
- },
- {
- label: '2D',
- items: [
- { label: 'Sprite', prefab: preset('Sprite', ['Transform', 'Sprite']) },
- { label: 'Camera', prefab: preset('Camera', [['Transform', { position: { x: 0, y: 0, z: 10 } }], 'Camera']) },
- { label: 'Particles', prefab: preset('Particles', ['Transform', 'ParticleEmitter']) },
- { label: 'Light', prefab: preset('Light', ['Transform', 'Light2D']) },
- ],
- },
- {
- label: 'UI',
- items: [
- {
- label: 'Canvas',
- prefab: preset('Canvas', ['Transform', ['Canvas', { designResolution: { x: 800, y: 600 }, scaleMode: 2 }], 'UINode']),
- },
- ...BUILTIN_UI_WIDGET_NAMES.map((name) => ({
- label: name,
- prefab: BUILTIN_UI_PREFABS[name]!,
- underCanvas: true,
- })),
- ],
- },
-];
-
-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 7e9b6fe91..f5d4b421f 100644
--- a/desktop/src/panels/Outliner.tsx
+++ b/desktop/src/panels/Outliner.tsx
@@ -20,7 +20,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 { type EntityTemplate } from '@/engine/entityTemplates';
+import { createFromSource, type EntitySource } from '@/engine/entitySources';
import { CreatePopover } from '@/components/CreatePopover';
import { Segmented } from '@/components/Segmented';
@@ -338,12 +338,10 @@ 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);
+ // Create a ready-made entity from a source (no add-component dance). Where it
+ // lands — e.g. UI controls under the Canvas — is the source's own concern now.
+ const createTemplate = (source: EntitySource, parent: EntityId | null) => {
+ void createFromSource(source, { parent }).then((id) => { if (id != null) select(id); });
};
const selectionOrTarget = (id: EntityId): EntityId[] => {
const ids = useSelection.getState().selectedIds;
diff --git a/desktop/tests/entity-sources.test.ts b/desktop/tests/entity-sources.test.ts
new file mode 100644
index 000000000..b46e472b2
--- /dev/null
+++ b/desktop/tests/entity-sources.test.ts
@@ -0,0 +1,52 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file entitySources registry (REARCH ENTITY_CREATION E2). The Create popover is
+ * generated from this data-driven list, so the guarantees are structural:
+ * the legacy catalog labels all survive the migration, every source carries
+ * an icon + a known category + a well-formed build(), placement is a field
+ * (not hardcoded), and search matches label/category/keyword. Pure TS.
+ */
+import { describe, it, expect } from 'vitest';
+import { ENTITY_SOURCES, matchSources, CREATE_CATEGORY_ORDER } from '@/engine/entitySources';
+
+const ctx = { parent: null };
+
+describe('entitySources registry (Create-entity E2)', () => {
+ it('covers every legacy catalog label (migration completeness)', () => {
+ const labels = ENTITY_SOURCES.map((s) => s.label);
+ for (const l of ['Empty', 'Sprite', 'Camera', 'Particles', 'Light', 'Canvas', 'Button', 'Toggle', 'Slider', 'Progress', 'Dropdown', 'ListView']) {
+ expect(labels).toContain(l);
+ }
+ });
+
+ it('every source has a unique id, an icon, and a category in the declared order', () => {
+ const ids = ENTITY_SOURCES.map((s) => s.id);
+ expect(new Set(ids).size).toBe(ids.length);
+ for (const s of ENTITY_SOURCES) {
+ expect(s.icon).toBeTruthy();
+ expect(CREATE_CATEGORY_ORDER).toContain(s.category);
+ }
+ });
+
+ it('build() yields a well-formed prefab whose root entity is present', async () => {
+ for (const s of ENTITY_SOURCES) {
+ const p = await s.build(ctx);
+ expect(p.rootEntityId).toBeDefined();
+ expect(p.entities.length).toBeGreaterThan(0);
+ expect(p.entities.some((e) => e.prefabEntityId === p.rootEntityId)).toBe(true);
+ }
+ });
+
+ it('placement is a data field: UI widgets go under the Canvas, others honor the parent', () => {
+ expect(ENTITY_SOURCES.find((s) => s.label === 'Button')!.placement).toBe('under-canvas');
+ expect(ENTITY_SOURCES.find((s) => s.label === 'Sprite')!.placement).toBeUndefined();
+ });
+
+ it('matchSources filters by label / category / keyword, case-insensitively', () => {
+ expect(matchSources(ENTITY_SOURCES, 'SPR').map((s) => s.label)).toContain('Sprite');
+ expect(matchSources(ENTITY_SOURCES, '2d').length).toBeGreaterThan(0);
+ expect(matchSources(ENTITY_SOURCES, '')).toHaveLength(ENTITY_SOURCES.length);
+ expect(matchSources(ENTITY_SOURCES, 'zzznope')).toHaveLength(0);
+ });
+});