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.

fix(editor): the Create popover offers the project's components, not the editor's

yhhb4dc61024e2c
diff --git a/desktop/src/components/CreatePopover.tsx b/desktop/src/components/CreatePopover.tsx
index c5e99fd34..b3e3219d5 100644
--- a/desktop/src/components/CreatePopover.tsx
+++ b/desktop/src/components/CreatePopover.tsx
@@ -12,8 +12,7 @@
*/
import { useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
-import { entitySources, userComponentSources, matchSources, CREATE_CATEGORY_ORDER, type EntitySource } from '@/engine/entitySources';
-import { ProjectStore } from '@/project/ProjectStore';
+import { allEntitySources, matchSources, CREATE_CATEGORY_ORDER, type EntitySource } from '@/engine/entitySources';
import { SearchField } from '@/components/SearchField';
import { useDialogFocus } from '@/components/dialogFocus';
import { usePanelWindow } from '@/components/PanelWindow';
@@ -53,9 +52,9 @@ export function CreatePopover({
const shellRef = useRef<HTMLDivElement>(null);
useDialogFocus(shellRef);
- // Static builtins + the user's own components + the project's prefab assets;
- // computed once when the popover opens.
- const all = useMemo(() => [...entitySources(), ...userComponentSources(), ...ProjectStore.prefabSources()], []);
+ // Static builtins + the project's own components + its prefab assets. Computed
+ // once per open, which is once per mount — the popover is unmounted when closed.
+ const all = useMemo(() => allEntitySources(), []);
const results = useMemo(() => matchSources(all, query), [all, query]);
const groups = useMemo(() => groupByCategory(results), [results]);
diff --git a/desktop/src/engine/entitySources.ts b/desktop/src/engine/entitySources.ts
index fa4482357..a27de98dd 100644
--- a/desktop/src/engine/entitySources.ts
+++ b/desktop/src/engine/entitySources.ts
@@ -16,10 +16,10 @@
*/
import type { LucideIcon } from 'lucide-react';
import { CircleDot, LayoutPanelTop, ToggleLeft, SlidersHorizontal, List, ChevronDown, SquareMousePointer, RectangleHorizontal, Box, Type, Image as ImageIcon, SquareDashed, ScrollText, AppWindow, TextCursorInput, Grid3x3, MapPin, Scan } from 'lucide-react';
-import { BUILTIN_UI_PREFABS, BUILTIN_UI_WIDGET_NAMES, PREFAB_FORMAT_VERSION, getUserComponents, applyThemeToWorld, type PrefabData } from 'esengine';
+import { BUILTIN_UI_PREFABS, BUILTIN_UI_WIDGET_NAMES, PREFAB_FORMAT_VERSION, applyThemeToWorld, type PrefabData } from 'esengine';
import type { EntityId } from '@/types';
import { ContributionRegistry } from '@/contrib/ContributionRegistry';
-import { componentByName, componentDefaults, prettyLabel, componentCategory } from './schema';
+import { componentByName, componentDefaults, prettyLabel, componentCategory, userComponentNames } from './schema';
import { componentGlyph } from '@/components/icons';
import { SceneCommands } from './SceneCommands';
import { EngineHost } from './EngineHost';
@@ -324,9 +324,15 @@ export const ENTITY_SOURCES: EntitySource[] = [
* — the dynamic half of "cover all cases" (REARCH ENTITY_CREATION E4).
*/
export function userComponentSources(): EntitySource[] {
- // `Marker` is an engine component but ships a CURATED Create preset above (with its own
- // icon + category), so drop it from the generic user-component list to avoid a duplicate.
- return [...getUserComponents().keys()].filter((name) => name !== 'Marker').map((name) => ({
+ // From `schemas.json` — the SAME source the Details panel's Add Component reads.
+ // The engine's own getUserComponents() registry cannot answer this: the editor
+ // never executes project code, so a project's components are never in it and this
+ // list was empty for every project.
+ //
+ // A name the engine registry already answers to is an engine component, and those
+ // reach the picker through their own curated preset (with a real icon and
+ // category) — take that one rather than a second, generic entry.
+ return userComponentNames().filter((name) => !componentByName(name)).map((name) => ({
id: `component:${name}`,
label: prettyLabel(name),
category: 'Scripts',
@@ -353,9 +359,30 @@ export function entitySources(): readonly EntitySource[] {
return sourceContrib.all();
}
-/** The source with this id, or null. */
+/**
+ * Everything an entity can be born from RIGHT NOW: the static catalog plus the
+ * sources that come and go with the open project. Recomputed per call — the
+ * project's components and prefabs change while the editor runs.
+ *
+ * Every surface that offers "create an entity" reads this one list, so the Create
+ * popover, the menus, and the automation/MCP catalog cannot drift apart into
+ * offering different things.
+ */
+export function allEntitySources(): EntitySource[] {
+ return [...entitySources(), ...userComponentSources(), ...projectPrefabSources()];
+}
+
+/** Project prefab sources, injected by ProjectStore (which owns the asset registry)
+ * so this module stays free of a project dependency. */
+let projectPrefabSources: () => EntitySource[] = () => [];
+export function setProjectPrefabSources(fn: () => EntitySource[]): void {
+ projectPrefabSources = fn;
+}
+
+/** The source with this id, or null — over the SAME list the pickers offer, so an
+ * id that appears in a catalog can always be spawned. */
export function sourceById(id: string): EntitySource | null {
- return sourceContrib.get(id) ?? null;
+ return sourceContrib.get(id) ?? allEntitySources().find((s) => s.id === id) ?? null;
}
/** Case-insensitive filter over label + category + keywords, for the Create popover. */
diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.ts
index 5efd0dd06..d162a6924 100644
--- a/desktop/src/engine/schema.ts
+++ b/desktop/src/engine/schema.ts
@@ -316,6 +316,16 @@ export function userSchema(name: string): UserComponentSchema | undefined {
return userSchemas.get(name);
}
+/** Every project component the editor knows of, by name.
+ *
+ * The editor never runs project code, so the engine's own `getUserComponents()`
+ * registry holds only what the EDITOR realm defined — never the open project's
+ * components. `schemas.json` is how a project's components reach the editor, so
+ * it is what every surface offering them has to read. */
+export function userComponentNames(): string[] {
+ return [...userSchemas.keys()];
+}
+
/** Whether a component field renders as a color (registry colorKeys, then schema). */
export function isColorKey(compType: string, key: string): boolean {
const def = componentByName(compType);
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index c4fa449e1..a4188460c 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -52,7 +52,7 @@ import { Particle, getComponent } from 'esengine';
import { actionNames, actionParams, conditionNames } from '@/ai/actionCatalog';
import { applyFxPreview, initFxPreviewEditRestart } from './engine/fxPreview';
import { commands } from './commands/registry';
-import { entitySources, sourceById, createFromSource, type TileGridConfig } from './engine/entitySources';
+import { allEntitySources, sourceById, createFromSource, type TileGridConfig } from './engine/entitySources';
import { createTilemapFromTileset, createCollisionLayer } from './tilemap/createTilemap';
import { applySceneOps, type SceneOp } from './engine/sceneOps';
import { layerTilesetRefs, loadLayerTilesetModel } from './tilemap/layerTilesetModel';
@@ -159,8 +159,10 @@ if (new URLSearchParams(location.search).has('automation')) {
/** Create a blank scene FILE under `destDir` (Content Browser "New Scene"). */
createSceneFile: (destDir: string, name?: string | null) =>
ProjectStore.createSceneFile(destDir, name ?? undefined),
- /** The Create-popover catalog: every ready-made entity the editor can spawn. */
- listEntityTemplates: () => entitySources().map(({ id, label, category }) => ({ id, label, category })),
+ /** The Create-popover catalog: every ready-made entity the editor can spawn —
+ * including the open project's own components and prefabs, so automation sees
+ * the same list a person does. */
+ listEntityTemplates: () => allEntitySources().map(({ id, label, category }) => ({ id, label, category })),
/** Create a TilemapLayer from an .estileset with an optional grid layout
* (orientation/stagger/hex) — drives the New-Tilemap flow headlessly. */
createTilemap: (tilesetPath: string, grid?: TileGridConfig) => createTilemapFromTileset(tilesetPath, grid),
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index 723a866ea..43ca80bcc 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -16,7 +16,7 @@ import { EditorHistory } from '@/engine/EditorHistory';
import { expandScenePrefabs, collapseScenePrefabs } from '@/engine/PrefabInstance';
import { SceneCommands } from '@/engine/SceneCommands';
import { Boxes } from 'lucide-react';
-import { spritePrefab, setCanvasDesignSeed, setProjectCameraFit, type EntitySource } from '@/engine/entitySources';
+import { spritePrefab, setCanvasDesignSeed, setProjectCameraFit, setProjectPrefabSources, type EntitySource } from '@/engine/entitySources';
import { setPrefabBaseResolver } from '@/engine/SceneQuery';
import { setUserSchemas, userSchema, setBitmaskSource, setEnumSource, type UserComponentSchema } from '@/engine/schema';
import { installDragonBonesEnumSources, clearDragonBonesNameCache } from '@/engine/dragonBonesNames';
@@ -274,6 +274,9 @@ class ProjectStoreImpl {
fsRefresh.subscribe(() => clearDragonBonesNameCache());
// New Canvas entities seed their design resolution from the project setting.
setCanvasDesignSeed(() => this.designResolution());
+ // The project's .esprefab assets join the one create-source list, so the picker
+ // and the automation catalog offer them without either reassembling the list.
+ setProjectPrefabSources(() => this.prefabSources());
// The device preview reads the project camera fit so its letterbox matches the
// runtime (WYSIWYG when the fit is on).
setProjectCameraFit(() => {
diff --git a/desktop/tests/user-component-sources.test.ts b/desktop/tests/user-component-sources.test.ts
index 4e507edd3..5d259e44a 100644
--- a/desktop/tests/user-component-sources.test.ts
+++ b/desktop/tests/user-component-sources.test.ts
@@ -1,22 +1,29 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
- * @file userComponentSources (REARCH ENTITY_CREATION E4) — a user's defineComponent
+ * @file userComponentSources (REARCH ENTITY_CREATION E4) — a project's own
* components appear in the Create popover as plain Transform + that-component
- * entities, bucketed under 'Scripts', with zero per-component wiring. Pure TS;
- * getUserComponents is mocked to a deterministic set.
+ * entities, bucketed under 'Scripts', with zero per-component wiring.
+ *
+ * Driven through `setUserSchemas`, which is the real seam: `schemas.json` is
+ * how a project's components reach an editor that never runs project code.
+ * This file used to mock the engine's `getUserComponents()` instead, and
+ * passed while the shipped list was empty for every project — that registry
+ * only ever holds what the EDITOR realm itself defined.
*/
-import { describe, it, expect, vi } from 'vitest';
-
-vi.mock('esengine', async (importOriginal) => {
- const actual = (await importOriginal()) as Record<string, unknown>;
- return { ...actual, getUserComponents: () => new Map([['Health', {}], ['Inventory', {}]]) };
-});
+import { describe, it, expect, afterEach } from 'vitest';
import { userComponentSources } from '@/engine/entitySources';
+import { setUserSchemas, type UserComponentSchema } from '@/engine/schema';
+
+const schema = (name: string, def: Record<string, unknown> = {}): UserComponentSchema =>
+ ({ name, isTag: false, default: def, colorKeys: [] });
+
+afterEach(() => setUserSchemas([]));
describe('userComponentSources (Create-entity E4 dynamic sources)', () => {
- it('makes one Scripts-category source per user component', () => {
+ it('makes one Scripts-category source per project component', () => {
+ setUserSchemas([schema('Health', { hp: 100 }), schema('Inventory')]);
const srcs = userComponentSources();
expect(srcs.map((s) => s.label)).toEqual(expect.arrayContaining(['Health', 'Inventory']));
expect(srcs).toHaveLength(2);
@@ -27,8 +34,21 @@ describe('userComponentSources (Create-entity E4 dynamic sources)', () => {
});
it('build() yields a plain entity carrying Transform + the component', async () => {
+ setUserSchemas([schema('Health', { hp: 100 })]);
const health = userComponentSources().find((s) => s.label === 'Health')!;
const p = await health.build({ parent: null });
expect(p.entities[0].components.map((c) => c.type)).toEqual(['Transform', 'Health']);
});
+
+ it('lists nothing when the project has declared no components', () => {
+ setUserSchemas([]);
+ expect(userComponentSources()).toEqual([]);
+ });
+
+ it('leaves an engine component to its own curated preset', () => {
+ // Marker is an engine component and reaches the picker through a preset with a
+ // real icon and category; a generic entry would be a second, worse duplicate.
+ setUserSchemas([schema('Marker'), schema('Health')]);
+ expect(userComponentSources().map((s) => s.label)).toEqual(['Health']);
+ });
});
diff --git a/docs/astro/src/content/docs/guides/editor.mdx b/docs/astro/src/content/docs/guides/editor.mdx
index 51c0e2860..b9e8c9fb4 100644
--- a/docs/astro/src/content/docs/guides/editor.mdx
+++ b/docs/astro/src/content/docs/guides/editor.mdx
@@ -28,8 +28,8 @@ A project is a folder on disk. The pieces the editor cares about:
| `.esengine/workspace.json` | Editor-local state (last-opened scene, panel layout). Gitignored. |
| `assets/scenes/*.esscene` | Your scenes. |
| `assets/…` | Textures, materials, tilesets, and other assets, each with a `.meta` sidecar. |
-| `src/components.ts` | Where you declare your project's components and behaviors. |
-| `src/main.ts` | The startup entry — where you register systems. |
+| `src/components.ts` | The **declaration entry** — the editor evaluates this module and everything it imports to learn your components. Declare them anywhere; re-export them from here. See [Scripting](/docs/guides/scripting/#where-declarations-live). |
+| `src/main.ts` | The **startup entry** — where you register systems. This is what runs the game; the editor never evaluates it. |
Assets are referenced portably by UUID (`@uuid:…`) rather than by path, so moving or
renaming a file doesn't break references.
diff --git a/docs/astro/src/content/docs/guides/scripting.mdx b/docs/astro/src/content/docs/guides/scripting.mdx
index 4ccc9c066..7977ec011 100644
--- a/docs/astro/src/content/docs/guides/scripting.mdx
+++ b/docs/astro/src/content/docs/guides/scripting.mdx
@@ -52,6 +52,42 @@ const spawn = defineSystem([Commands()], (cmds) => {
two doors to the same data.
</Aside>
+## Where declarations live
+
+The editor knows about your components without ever running your game: it evaluates
+**one entry module** and reads back whatever declared itself. That entry is
+`src/components.ts` by default — the manifest's `scripts.register`, if you want it
+somewhere else.
+
+The rule is *reachability*, not location. `defineBehavior` and `defineComponent`
+register when the call runs, so a module nobody imports never registers anything.
+Spread declarations across as many files as you like and pull them in from the entry:
+
+```typescript
+// src/components.ts — the editor's view of your project
+export * from './behaviors/patrol';
+export * from './components/health';
+```
+
+A behavior the entry cannot reach still *works at runtime*, because the game starts
+from `src/main.ts` — which is exactly what makes this confusing. What you lose is the
+editor: no fields in the Details panel (the component round-trips but shows as
+unknown), no entry under **Scripts** in the Create-entity popover, and no
+`registerAction` / `registerCondition` names in the behavior-tree and event-binding
+palettes.
+
+<Aside type="caution">
+ The entry and everything it imports must be **pure declarations**. The editor
+ evaluates that module graph in an isolated context with no engine and no wasm —
+ systems are queued, never run. Startup side effects belong in `src/main.ts`; keep
+ the two entries separate rather than pointing `scripts.register` at your `main.ts`.
+</Aside>
+
+Saving any file under `src/` re-extracts, so new fields appear in the Details panel a
+moment after you save. If a component never shows up, look at
+`.esengine/cache/schemas.json`: absent there means it was never reached; present there
+but missing in the inspector is a different problem.
+
## The lifecycle
Each hook is optional; define only the ones you need.
diff --git a/docs/astro/src/content/docs/zh-cn/guides/editor.mdx b/docs/astro/src/content/docs/zh-cn/guides/editor.mdx
index e4f73c34f..d58384b3e 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/editor.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/editor.mdx
@@ -26,8 +26,8 @@ Estella 编辑器是一个桌面应用(Electron + React),带 UE5 风格的**可
| `.esengine/workspace.json` | 编辑器本地状态(上次打开的场景、面板布局)。被 gitignore。 |
| `assets/scenes/*.esscene` | 你的场景。 |
| `assets/…` | 纹理、材质、瓦片集等资产,每个带一个 `.meta` 边车文件。 |
-| `src/components.ts` | 声明项目组件与行为的地方。 |
-| `src/main.ts` | 启动入口——注册系统的地方。 |
+| `src/components.ts` | **声明入口**——编辑器会求值这个模块以及它 import 到的一切,以此认识你的组件。组件定义在哪都行,从这里 re-export 出来即可。见[脚本](/zh-cn/docs/guides/scripting/#声明放在哪里)。 |
+| `src/main.ts` | **启动入口**——注册系统的地方。跑游戏的是它;编辑器从不求值它。 |
资产按 UUID(`@uuid:…`)可移植地引用,而不是按路径,所以移动或重命名文件不会断掉引用。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/scripting.mdx b/docs/astro/src/content/docs/zh-cn/guides/scripting.mdx
index 6d2bae723..84e101cea 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/scripting.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/scripting.mdx
@@ -47,6 +47,34 @@ const spawn = defineSystem([Commands()], (cmds) => {
实体上,在那里调 `speed`。代码和编辑器是通往同一份数据的两扇门。
</Aside>
+## 声明放在哪里
+
+编辑器不运行你的游戏也能认识你的组件:它会**求值一个入口模块**,然后读回其中声明过的东西。
+这个入口默认是 `src/components.ts`——想放别处,改清单里的 `scripts.register`。
+
+规则是**可达性**,不是位置。`defineBehavior` 和 `defineComponent` 在调用发生时才注册,
+所以没人 import 的模块什么也不会注册。声明想分几个文件都行,从入口把它们接进来:
+
+```typescript
+// src/components.ts —— 编辑器眼中的你的项目
+export * from './behaviors/patrol';
+export * from './components/health';
+```
+
+入口够不到的行为**运行时照样能跑**,因为游戏是从 `src/main.ts` 启动的——这也正是它容易让人困惑的地方。
+丢的是编辑器那一侧:细节面板里没有字段(组件仍能无损往返,但显示为未知)、创建实体弹窗的
+**脚本** 分类里不出现、行为树与事件绑定的调色板里也没有 `registerAction` / `registerCondition` 的名字。
+
+<Aside type="caution">
+ 入口以及它 import 到的一切必须是**纯声明**。编辑器是在一个隔离上下文里求值这张模块图的,
+ 没有引擎也没有 wasm——系统只入队,从不运行。启动期副作用属于 `src/main.ts`;
+ 让两个入口各司其职,别把 `scripts.register` 指向 `main.ts`。
+</Aside>
+
+保存 `src/` 下的任何文件都会重新提取一次,所以保存后片刻新字段就会出现在细节面板里。
+如果某个组件始终不出现,去看 `.esengine/cache/schemas.json`:不在里面说明它压根没被够到;
+在里面但检视器仍然空着,那是另一个问题。
+
## 生命周期
每个钩子都是可选的;只定义你需要的那些。