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.

feat(events): wire an entity event to a named action as data, not code

yhhf5ab754f2968
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 0e74b5e03..192d7c21e 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -256,11 +256,24 @@ async function runScreenshot(w: BrowserWindow, out: string): Promise<void> {
}
const selectName = process.env.ESTELLA_SHOT_SELECT;
if (selectName) {
- await exec(`(() => {
+ // The tree is nested (getSceneTree returns ROOTS), so the walk has to
+ // recurse — a flat find only ever reached top-level entities, and picked
+ // nothing for a name a level down, silently leaving the default selection.
+ const selected = await exec(`(() => {
const s = window.__estellaEditor.surface;
- const hit = (s.getSceneTree() || []).find((n) => n.name === ${JSON.stringify(selectName)});
+ const walk = (nodes) => {
+ for (const n of nodes || []) {
+ if (n.name === ${JSON.stringify(selectName)}) return n;
+ const hit = walk(n.children);
+ if (hit) return hit;
+ }
+ return null;
+ };
+ const hit = walk(s.getSceneTree());
if (hit) s.select(hit.id);
+ return hit ? hit.id : null;
})()`);
+ if (selected == null) console.log(`[select] no entity named ${selectName}`);
await waitFor('window.__estellaEditor.surface.getSelection() != null', 'entity selected'); // was sleep(800)
}
const selectAsset = process.env.ESTELLA_SHOT_ASSET;
diff --git a/desktop/src/components/aiSuggest.ts b/desktop/src/components/aiSuggest.ts
index f57a689b8..e36a245f9 100644
--- a/desktop/src/components/aiSuggest.ts
+++ b/desktop/src/components/aiSuggest.ts
@@ -22,6 +22,9 @@ const BUILTIN_DESC: Record<string, () => string> = {
'spriteAnim.restart': () => t('ai.desc.spriteAnimRestart'),
'spriteAnim.stop': () => t('ai.desc.spriteAnimStop'),
'spriteAnim.finished': () => t('ai.desc.spriteAnimFinished'),
+ 'fsm.fire': () => t('ai.desc.fsmFire'),
+ 'blackboard.set': () => t('ai.desc.blackboardSet'),
+ 'ui.setPage': () => t('ai.desc.uiSetPage'),
};
const decorate = (names: string[]): SuggestItem[] =>
diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.ts
index 370b8f2b3..004dfc1f4 100644
--- a/desktop/src/engine/SceneCommands.ts
+++ b/desktop/src/engine/SceneCommands.ts
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import type { SceneData, PrefabData, ControllerState, UIControllerData, GearBinding, GearTween, UIGearData, SyncPrefabResolver } from 'esengine';
+import type { SceneData, PrefabData, ControllerState, UIControllerData, GearBinding, GearTween, UIGearData, EventBindingData, EventBindingRow, SyncPrefabResolver } from 'esengine';
import { TilemapAPI, TilemapLiveSync, UIPositionType, DimensionUnit, AnchorAxis, writeFieldPath, type AnchorPreset } from 'esengine';
import type { EntityId, InspectorFieldType, InspectorFieldValue } from '@/types';
import { EditorHistory, EditorHistoryImpl } from './EditorHistory';
@@ -1706,6 +1706,51 @@ export class SceneCommandsImpl {
cur.filter((b) => !(b.controller === controller && b.component === component && b.property === property)));
}
+ // ── Authored event wires (EventBinding.rows) ──────────────────────────────
+ // Same shape as the gear commands above: read a cloned row list, write the
+ // whole list back as one undoable step. Emptying the list drops the component
+ // rather than leaving `{rows: []}` litter in the scene file.
+
+ private eventRowsOf(id: EntityId): EventBindingRow[] {
+ const d = this.model.entityBySource(id)?.components.find((c) => c.type === 'EventBinding')?.data as
+ | EventBindingData
+ | undefined;
+ return d?.rows ? structuredClone(d.rows) : [];
+ }
+
+ private writeEventRows(id: EntityId, label: string, next: EventBindingRow[]): void {
+ const cur = this.eventRowsOf(id);
+ if (valueEqual(cur, next)) return;
+ const apply = (list: EventBindingRow[]) => {
+ if (list.length === 0) this.model.removeComponent(id, 'EventBinding');
+ else this.model.setField(id, 'EventBinding', 'rows', structuredClone(list));
+ };
+ apply(next);
+ this.history.record(label, () => apply(next), () => apply(cur));
+ }
+
+ /** Append one authored wire. Undoable. */
+ addEventBinding(id: EntityId, row: EventBindingRow): void {
+ this.writeEventRows(id, 'Add Event Wire', [...this.eventRowsOf(id), row]);
+ }
+
+ /** Patch one row's fields (a key set to undefined is removed). Undoable. */
+ updateEventBinding(id: EntityId, index: number, patch: Partial<EventBindingRow>): void {
+ const cur = this.eventRowsOf(id);
+ if (index < 0 || index >= cur.length) return;
+ const merged = { ...cur[index], ...patch } as Record<string, unknown>;
+ for (const [k, v] of Object.entries(patch)) if (v === undefined || v === '') delete merged[k];
+ // `event` and `action` are the row's identity — never let a patch drop them.
+ if (patch.event !== undefined) merged.event = patch.event;
+ if (patch.action !== undefined) merged.action = patch.action;
+ this.writeEventRows(id, 'Edit Event Wire', cur.map((r, i) => (i === index ? (merged as unknown as EventBindingRow) : r)));
+ }
+
+ /** Remove one authored wire. Undoable. */
+ removeEventBinding(id: EntityId, index: number): void {
+ this.writeEventRows(id, 'Remove Event Wire', this.eventRowsOf(id).filter((_, i) => i !== index));
+ }
+
/** Set (or clear, with undefined) one gear binding's page-change transition. Undoable. */
setGearTween(id: EntityId, controller: string, component: string, property: string, tween?: GearTween): void {
const cur = this.gearBindingsOf(id);
diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.ts
index 527402f47..bfaee059f 100644
--- a/desktop/src/engine/schema.ts
+++ b/desktop/src/engine/schema.ts
@@ -37,7 +37,7 @@ export type AnyComp = Parameters<WorldT['has']>[1];
// Structural/relationship components that drive the tree, not the inspector —
// plus UIController/UIGear, whose authoring surface is the Controllers panel and
// the Details gear dots (their array-of-object data has no generic field control).
-const HIDDEN_COMPONENTS = new Set(['Parent', 'Children', 'Name', 'UIController', 'UIGear']);
+const HIDDEN_COMPONENTS = new Set(['Parent', 'Children', 'Name', 'UIController', 'UIGear', 'EventBinding']);
// Components whose enable flag drives the entity's RENDER visibility (the Outliner
// eye + hidden state). Disabling a non-render component (physics, audio, a script)
// turns that behaviour off without hiding the entity. Light2D/ShadowCaster2D belong
diff --git a/desktop/src/events/EventBindingSection.tsx b/desktop/src/events/EventBindingSection.tsx
new file mode 100644
index 000000000..5bcf134f0
--- /dev/null
+++ b/desktop/src/events/EventBindingSection.tsx
@@ -0,0 +1,232 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file EventBindingSection.tsx
+ * @brief The Details panel's Events section — authoring a wire from an entity
+ * event to a named action, with no code.
+ *
+ * One row is one {@link EventBindingRow}: "on `click`, run `ui.setPage` on
+ * `Panel` with `tabs:settings`". The vocabularies are borrowed, not invented —
+ * events from the SDK's `UIEventType`, actions/conditions from the same
+ * `aiRegistry` palette the FSM/BT editors use (so a game's `registerAction`
+ * shows up in all three), targets from the scene's entity names resolved by the
+ * runtime's nearest-first rule. Deliberately NOT a graph: a row has no
+ * branching, and anything needing logic points at an action (`fsm.fire`) that
+ * hands off to the editors that already do graphs.
+ *
+ * Lives beside its model rather than inside Details.tsx: the section is
+ * self-contained (reads the SceneModel, writes through SceneCommands, like the
+ * Controllers strip), and keeping the pair in one feature folder is what the
+ * `controller/` · `fsm/` · `bt/` folders already do.
+ */
+import { useState } from 'react';
+import { useSyncExternalStore } from 'react';
+import { ChevronDown, ChevronRight, CornerDownRight, MousePointerClick, Plus, SlidersHorizontal, X } from 'lucide-react';
+
+import { Select } from '@/components/Select';
+import { SuggestInput } from '@/components/SuggestInput';
+import { aiActionItems, aiConditionItems } from '@/components/aiSuggest';
+import { SceneStore } from '@/engine/SceneStore';
+import { SceneCommands } from '@/engine/SceneCommands';
+import { readEventRows, resolveTargetName, sceneEntityNames } from '@/events/eventBindingModel';
+import { useInspectorCollapse, isSectionCollapsed } from '@/store/inspectorCollapse';
+import { t } from '@/i18n';
+import type { EntityId } from '@/types';
+import { UIEventType } from 'esengine';
+import type { EventBindingRow } from 'esengine';
+
+const SECTION_KEY = '__events';
+/** The type strings the built-in widgets emit — suggestions, not a closed set. */
+const BUILTIN_EVENTS: string[] = Object.values(UIEventType);
+/** Empty target = "this entity"; the sentinel keeps the Select's value a string. */
+const SELF = '';
+
+export function EventBindingSection({ entityId, interactive }: { entityId: EntityId; interactive: boolean }) {
+ useSyncExternalStore(SceneStore.subscribe, SceneStore.getRevision);
+ const collapseExplicit = useInspectorCollapse((s) => s.explicit);
+ const toggleCollapse = useInspectorCollapse((s) => s.toggle);
+ const collapsed = isSectionCollapsed(collapseExplicit, SECTION_KEY);
+ const [expanded, setExpanded] = useState<Record<number, boolean>>({});
+
+ const rows = readEventRows(entityId);
+ // Non-interactive entities don't emit anything yet, so an empty section there
+ // would be pure noise — but an authored wire always shows, wherever it is.
+ if (!interactive && rows.length === 0) return null;
+
+ const addRow = () => {
+ SceneCommands.addEventBinding(entityId, { event: UIEventType.Click, action: '' });
+ if (collapsed) toggleCollapse(SECTION_KEY);
+ };
+
+ return (
+ <div className="evt-inline">
+ <div
+ className="evt-head"
+ role="button"
+ tabIndex={0}
+ onClick={() => toggleCollapse(SECTION_KEY)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ toggleCollapse(SECTION_KEY);
+ }
+ }}
+ >
+ <span className="evt-caret">
+ {collapsed ? <ChevronRight size={12} strokeWidth={2.4} /> : <ChevronDown size={12} strokeWidth={2.4} />}
+ </span>
+ <MousePointerClick size={12} strokeWidth={2} className="evt-head-icon" />
+ <span className="evt-title">{t('evt.section')}</span>
+ {rows.length > 0 && <span className="evt-count">{rows.length}</span>}
+ <button
+ type="button"
+ className="evt-add"
+ title={t('evt.add')}
+ onClick={(e) => {
+ e.stopPropagation();
+ addRow();
+ }}
+ >
+ <Plus size={12} strokeWidth={2.4} />
+ </button>
+ </div>
+
+ {!collapsed && (
+ <>
+ {rows.length === 0 && (
+ <div className="evt-empty">
+ <p>{t('evt.empty')}</p>
+ <p className="evt-empty-hint">{t('evt.emptyHint')}</p>
+ </div>
+ )}
+ {rows.map((row, i) => (
+ <EventRow
+ key={i}
+ entityId={entityId}
+ row={row}
+ index={i}
+ open={!!expanded[i] || !!row.guard || !!row.once}
+ onToggleMore={() => setExpanded((s) => ({ ...s, [i]: !s[i] }))}
+ />
+ ))}
+ </>
+ )}
+ </div>
+ );
+}
+
+function EventRow({
+ entityId,
+ row,
+ index,
+ open,
+ onToggleMore,
+}: {
+ entityId: EntityId;
+ row: EventBindingRow;
+ index: number;
+ open: boolean;
+ onToggleMore: () => void;
+}) {
+ const patch = (p: Partial<EventBindingRow>) => SceneCommands.updateEventBinding(entityId, index, p);
+ const enabled = row.enabled !== false;
+
+ // An authored value the built-in list doesn't know (a widget's own event, or
+ // an entity renamed since) still has to be selectable — append it rather than
+ // silently snapping the row to something else.
+ const eventOptions = BUILTIN_EVENTS.includes(row.event) ? BUILTIN_EVENTS : [...BUILTIN_EVENTS, row.event];
+ const names = sceneEntityNames();
+ const target = row.target ?? SELF;
+ const targetOptions = target === SELF || names.includes(target) ? names : [...names, target];
+ const dangling = target !== SELF && resolveTargetName(entityId, target) == null;
+
+ return (
+ <div className={`evt-row${enabled ? '' : ' off'}`}>
+ <div className="evt-row-head">
+ <input
+ type="checkbox"
+ className="evt-chk"
+ checked={enabled}
+ title={t('evt.rowEnabled')}
+ onChange={(e) => patch({ enabled: e.target.checked ? undefined : false })}
+ />
+ <Select
+ value={row.event}
+ options={eventOptions.map((v) => ({ value: v }))}
+ onChange={(v) => patch({ event: v })}
+ ariaLabel={t('evt.event')}
+ className="evt-sel"
+ />
+ <CornerDownRight size={11} strokeWidth={2} className="evt-arrow" />
+ <Select
+ value={target}
+ options={[{ value: SELF, label: t('evt.targetSelf') }, ...targetOptions.map((v) => ({ value: v }))]}
+ onChange={(v) => patch({ target: v === SELF ? undefined : v })}
+ ariaLabel={t('evt.target')}
+ className={`evt-sel${dangling ? ' bad' : ''}`}
+ />
+ <button
+ type="button"
+ className={`evt-more${open ? ' on' : ''}`}
+ title={t('evt.more')}
+ onClick={onToggleMore}
+ >
+ <SlidersHorizontal size={11} strokeWidth={2} />
+ </button>
+ <button
+ type="button"
+ className="evt-del"
+ title={t('evt.remove')}
+ onClick={() => SceneCommands.removeEventBinding(entityId, index)}
+ >
+ <X size={12} strokeWidth={2.4} />
+ </button>
+ </div>
+
+ {dangling && <div className="evt-warn">{t('evt.targetMissing', { name: target })}</div>}
+
+ <div className="evt-row-body">
+ <SuggestInput
+ key={`${index}-action-${row.action}`}
+ defaultValue={row.action}
+ items={aiActionItems()}
+ placeholder={t('evt.actionPh')}
+ ariaLabel={t('evt.action')}
+ onCommit={(v) => patch({ action: v.trim() })}
+ />
+ <input
+ className="evt-arg"
+ defaultValue={row.arg ?? ''}
+ key={`${index}-arg-${row.arg ?? ''}`}
+ placeholder={t('evt.argPh')}
+ spellCheck={false}
+ onBlur={(e) => patch({ arg: e.target.value.trim() || undefined })}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') (e.target as HTMLInputElement).blur();
+ }}
+ />
+ </div>
+
+ {open && (
+ <div className="evt-row-more">
+ <SuggestInput
+ key={`${index}-guard-${row.guard ?? ''}`}
+ defaultValue={row.guard ?? ''}
+ items={aiConditionItems()}
+ placeholder={t('evt.guardPh')}
+ ariaLabel={t('evt.guard')}
+ onCommit={(v) => patch({ guard: v.trim() || undefined })}
+ />
+ <label className="evt-once" title={t('evt.onceTip')}>
+ <input
+ type="checkbox"
+ checked={!!row.once}
+ onChange={(e) => patch({ once: e.target.checked ? true : undefined })}
+ />
+ {t('evt.once')}
+ </label>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/desktop/src/events/eventBindingModel.ts b/desktop/src/events/eventBindingModel.ts
new file mode 100644
index 000000000..6d174d86c
--- /dev/null
+++ b/desktop/src/events/eventBindingModel.ts
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file eventBindingModel.ts
+ * @brief Editor-side readers for EventBinding scene-model data.
+ *
+ * The Events section reads authored wires from the SceneModel (never from the
+ * live World — an entity's rows must be visible before play), and resolves a
+ * row's `target` name the way the runtime does. Mirrors controllerModel.ts, and
+ * for the same reason: one place decides what an authored wire means, so the
+ * inspector and the runtime can't drift.
+ */
+import { SceneModel } from '@/engine/SceneModel';
+import type { EntityId } from '@/types';
+import type { EventBindingData, EventBindingRow } from 'esengine';
+
+export function readEventRows(id: EntityId): EventBindingRow[] {
+ const d = SceneModel.entityBySource(id)?.components.find((c) => c.type === 'EventBinding')?.data as
+ | EventBindingData
+ | undefined;
+ return d?.rows ?? [];
+}
+
+/** Every distinct entity name in the scene, for the target picker. */
+export function sceneEntityNames(): string[] {
+ const seen = new Set<string>();
+ for (const e of SceneModel.current?.entities ?? []) {
+ if (e.name) seen.add(e.name);
+ }
+ return [...seen].sort((a, b) => a.localeCompare(b));
+}
+
+/**
+ * The entity a row's `target` names, resolved nearest-first from `from` — the
+ * model-side twin of the runtime's `resolveBindingTarget`: self, then self's
+ * subtree, then each ancestor's subtree, then any entity of that name. Null when
+ * the name matches nothing (the picker renders that as a dangling ref).
+ */
+export function resolveTargetName(from: EntityId, name: string): EntityId | null {
+ if (!name) return from;
+ const model = SceneModel.current;
+ if (!model) return null;
+
+ const inSubtree = (root: EntityId, skip: EntityId | null): EntityId | null => {
+ if (root === skip) return null;
+ const e = SceneModel.entityBySource(root);
+ if (!e) return null;
+ if (e.name === name) return root;
+ for (const child of e.children) {
+ const hit = inSubtree(child as EntityId, skip);
+ if (hit != null) return hit;
+ }
+ return null;
+ };
+
+ let node: EntityId | null = from;
+ let skip: EntityId | null = null;
+ while (node != null) {
+ const hit = inSubtree(node, skip);
+ if (hit != null) return hit;
+ skip = node;
+ node = (SceneModel.entityBySource(node)?.parent ?? null) as EntityId | null;
+ }
+ return (model.entities.find((e) => e.name === name)?.id as EntityId | undefined) ?? null;
+}
diff --git a/desktop/src/i18n/messages/events.ts b/desktop/src/i18n/messages/events.ts
new file mode 100644
index 000000000..219e8e837
--- /dev/null
+++ b/desktop/src/i18n/messages/events.ts
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file events.ts — the Details panel's Events section (authored event → action
+ * wiring). Action/condition names themselves are NOT translated: they are
+ * registry identifiers, like component field keys.
+ */
+import { defineMessages } from './types';
+
+export const eventMessages = defineMessages({
+ 'evt.section': { en: 'Events', zh: '事件' },
+ 'evt.add': { en: 'Add an event wire', zh: '添加事件连线' },
+ 'evt.empty': {
+ en: 'Nothing wired. Add a row to run an action when this entity fires an event — no code.',
+ zh: '尚未连线。添加一行,即可在该实体触发事件时执行动作——无需代码。',
+ },
+ 'evt.emptyHint': {
+ en: 'Actions come from the same registry the state machines use, so registerAction() shows up here too.',
+ zh: '动作来自与状态机相同的注册表,registerAction() 注册的动作也会出现在这里。',
+ },
+ 'evt.event': { en: 'Event', zh: '事件' },
+ 'evt.target': { en: 'Target', zh: '目标' },
+ 'evt.targetSelf': { en: 'This entity', zh: '自身' },
+ 'evt.targetMissing': { en: 'No entity named “{name}”', zh: '找不到名为“{name}”的实体' },
+ 'evt.targetTip': {
+ en: 'Which entity the action runs on — resolved by name, nearest first',
+ zh: '动作在哪个实体上执行——按名称就近解析',
+ },
+ 'evt.action': { en: 'Action', zh: '动作' },
+ 'evt.actionPh': { en: 'action name', zh: '动作名' },
+ 'evt.argPh': { en: 'argument', zh: '参数' },
+ 'evt.guard': { en: 'Condition', zh: '条件' },
+ 'evt.guardPh': { en: 'condition name (optional)', zh: '条件名(可选)' },
+ 'evt.once': { en: 'Once', zh: '仅一次' },
+ 'evt.onceTip': { en: 'Run at most once per play session', zh: '每次运行最多执行一次' },
+ 'evt.remove': { en: 'Remove this wire', zh: '删除该连线' },
+ 'evt.rowEnabled': { en: 'Enable this wire', zh: '启用该连线' },
+ 'evt.more': { en: 'Condition and once-only', zh: '条件与仅一次' },
+ 'evt.unknownAction': { en: 'Unknown action — free text is allowed', zh: '未知动作——允许自由输入' },
+
+ // Descriptions for the engine's own actions, editor-side (same policy as the
+ // FSM/BT palette: the sdk registry carries names, the editor carries prose).
+ 'ai.desc.fsmFire': {
+ en: 'Fire a trigger on the target’s state machine',
+ zh: '向目标的状态机发送一个触发器',
+ },
+ 'ai.desc.blackboardSet': {
+ en: 'Set a blackboard value — key=value',
+ zh: '设置黑板变量——key=value',
+ },
+ 'ai.desc.uiSetPage': {
+ en: 'Switch a UI controller to a page — controller:page',
+ zh: '将 UI 控制器切换到某一页——controller:page',
+ },
+});
diff --git a/desktop/src/i18n/messages/index.ts b/desktop/src/i18n/messages/index.ts
index c522b5826..69c47741d 100644
--- a/desktop/src/i18n/messages/index.ts
+++ b/desktop/src/i18n/messages/index.ts
@@ -38,6 +38,7 @@ import { materialMessages } from './material';
import { projectMessages } from './project';
import { controllerMessages } from './controllers';
import { animatorMessages } from './animator';
+import { eventMessages } from './events';
/** Every per-area module, for the uniqueness guard in i18n.test.ts. */
export const messageModules = {
@@ -61,6 +62,7 @@ export const messageModules = {
project: projectMessages,
controllers: controllerMessages,
animator: animatorMessages,
+ events: eventMessages,
} as const;
export const editorMessages = {
@@ -84,4 +86,5 @@ export const editorMessages = {
...projectMessages,
...controllerMessages,
...animatorMessages,
+ ...eventMessages,
} as const;
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index 46aa43934..05fa8d9a4 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -30,6 +30,7 @@ import './theme/flipbook.css';
import './theme/tilemap.css';
import './theme/ui-palette.css';
import './theme/controllers.css';
+import './theme/events.css';
import './theme/material.css';
import './theme/nodegraph.css';
import './theme/chrome.css';
@@ -45,7 +46,7 @@ import { dockApi } from './layout/dockApi';
import { EditorControlSurface } from './engine/EditorSession';
import { SceneModel } from './engine/SceneModel';
import { EngineHost } from './engine/EngineHost';
-import { Particle, getComponent } from 'esengine';
+import { Particle, aiRegistry, getComponent } from 'esengine';
import { applyFxPreview, initFxPreviewEditRestart } from './engine/fxPreview';
import { commands } from './commands/registry';
import { ENTITY_SOURCES, sourceById, createFromSource, type TileGridConfig } from './engine/entitySources';
@@ -128,6 +129,10 @@ if (new URLSearchParams(location.search).has('automation')) {
const particle = EngineHost.getResource(Particle);
return rt != null && particle ? particle.getAliveCount(rt) : -1;
},
+ /** The names the action/condition palettes offer in THIS realm — the one
+ * vocabulary `.esfsm` hooks, `.esbt` leaves and EventBinding rows share.
+ * Empty means the palettes fall back to free text (nothing registered). */
+ aiVocabulary: () => ({ actions: aiRegistry.actionNames(), conditions: aiRegistry.conditionNames() }),
/** Dispatch any registered editor command by id (the UI's own channel). */
runCommand: (id: string) => commands.run(id),
/** Save the open scene to disk (the toolbar Save, awaitable). */
diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsx
index 558873175..57de8f475 100644
--- a/desktop/src/panels/Details.tsx
+++ b/desktop/src/panels/Details.tsx
@@ -48,6 +48,7 @@ import {
type LucideIcon,
} from 'lucide-react';
import { AssetIcon } from '@/components/icons';
+import { EventBindingSection } from '@/events/EventBindingSection';
import { COMP_COLLIDER_SHAPE, type ColliderShapeKind } from '@/engine/colliderConvert';
import { AudioWavePreview } from '@/components/AudioWavePreview';
import { Toasts } from '@/store/Toasts';
@@ -3730,6 +3731,12 @@ function EditorDetails() {
{ids.length === 1 && visible.some((c) => c.name === 'UINode' || c.name === 'Canvas') && (
<ControllersInline entityId={ids[0]!} />
)}
+ {ids.length === 1 && (
+ <EventBindingSection
+ entityId={ids[0]!}
+ interactive={visible.some((c) => c.name === 'Interactable' || c.name === 'UINode' || c.name === 'Canvas')}
+ />
+ )}
{visible.map((comp) => (
<ComponentSection
key={comp.name}
diff --git a/desktop/src/theme/events.css b/desktop/src/theme/events.css
new file mode 100644
index 000000000..ad7616ce4
--- /dev/null
+++ b/desktop/src/theme/events.css
@@ -0,0 +1,46 @@
+/* SPDX-License-Identifier: Apache-2.0 */
+/* SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team */
+
+/* Events section (EventBindingSection): authored event → action wires, shown in
+ the Details inspector beside the Controllers strip. Same card vocabulary as
+ .ctrl-inline so the two authoring surfaces read as one family. */
+.evt-inline { display: flex; flex-direction: column; gap: 6px; padding: 8px; margin-bottom: 8px; background: var(--srf-2); border: 1px solid var(--border); border-radius: var(--r-sm); }
+
+.evt-head { display: flex; align-items: center; gap: 5px; cursor: pointer; user-select: none; }
+.evt-caret { display: inline-flex; align-items: center; color: var(--text-dim); }
+.evt-head-icon { color: var(--text-dim); }
+.evt-title { font-size: var(--fs-xs); font-weight: 600; color: var(--text); }
+.evt-head:hover .evt-title { color: var(--text); }
+.evt-count { font-size: 9px; color: var(--text-dim); background: var(--srf-4); border-radius: 8px; padding: 0 5px; }
+.evt-add { margin-left: auto; display: inline-flex; align-items: center; color: var(--text-dim); background: none; border: none; cursor: pointer; padding: 2px; border-radius: 3px; }
+.evt-add:hover { color: var(--text); background: var(--srf-4); }
+
+.evt-empty { display: flex; flex-direction: column; gap: 3px; padding: 2px; }
+.evt-empty p { margin: 0; font-size: var(--fs-2xs); color: var(--text-dim); line-height: 1.45; }
+.evt-empty-hint { opacity: 0.75; }
+
+.evt-row { display: flex; flex-direction: column; gap: 5px; padding: 7px; background: var(--srf-3); border: 1px solid var(--border); border-radius: var(--r-sm); }
+.evt-row.off { opacity: 0.5; }
+
+.evt-row-head { display: flex; align-items: center; gap: 5px; min-width: 0; }
+.evt-chk { flex: none; margin: 0; }
+.evt-arrow { flex: none; color: var(--text-dim); }
+.evt-row-head .evt-sel { flex: 1 1 0; min-width: 0; font-size: var(--fs-2xs); }
+.evt-row-head .evt-sel.bad { border-color: #ff5a5a; color: #ff5a5a; }
+.evt-more, .evt-del { flex: none; display: inline-flex; align-items: center; color: var(--text-dim); background: none; border: none; cursor: pointer; padding: 2px; border-radius: 3px; }
+.evt-more:hover { color: var(--text); background: var(--srf-4); }
+.evt-more.on { color: var(--acc); }
+.evt-del:hover { color: #ff5a5a; background: var(--srf-4); }
+
+.evt-warn { font-size: var(--fs-2xs); color: #ff5a5a; padding-left: 2px; }
+
+/* Action + argument share one line; the action picker takes the slack. */
+.evt-row-body { display: flex; align-items: center; gap: 5px; min-width: 0; }
+.evt-row-body > :first-child { flex: 1 1 60%; min-width: 0; }
+.evt-arg { flex: 1 1 40%; min-width: 0; font-size: var(--fs-2xs); color: var(--text); background: var(--srf-2); border: 1px solid var(--border); border-radius: var(--r-sm); padding: 3px 6px; font-family: var(--font-mono); }
+.evt-arg:focus { border-color: var(--acc); outline: none; }
+
+.evt-row-more { display: flex; align-items: center; gap: 6px; min-width: 0; }
+.evt-row-more > :first-child { flex: 1 1 auto; min-width: 0; }
+.evt-once { display: inline-flex; align-items: center; gap: 4px; flex: none; font-size: var(--fs-2xs); color: var(--text-dim); cursor: pointer; user-select: none; }
+.evt-once input { margin: 0; }
diff --git a/desktop/tests/event-binding-commands.test.ts b/desktop/tests/event-binding-commands.test.ts
new file mode 100644
index 000000000..ed2c56b0c
--- /dev/null
+++ b/desktop/tests/event-binding-commands.test.ts
@@ -0,0 +1,115 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file EventBinding authoring commands: rows round-trip through the scene
+ * model as one undo step each, emptying the list drops the component
+ * (no `{rows: []}` litter), and the editor-side target resolution
+ * matches the runtime's nearest-name rule.
+ */
+import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';
+import { App } from 'esengine';
+import type { ESEngineModule, EventBindingRow, SceneData } from 'esengine';
+import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';
+
+const host = vi.hoisted(() => ({ world: null as unknown as App['world'] }));
+vi.mock('@/engine/EngineHost', () => ({
+ EngineHost: {
+ mutableWorld: () => host.world,
+ get world() {
+ return host.world;
+ },
+ getResource: () => undefined,
+ },
+}));
+
+import { EditorSession } from '@/engine/EditorSession';
+
+const emptyScene = (): SceneData =>
+ ({ version: '1.0', name: 'test', entities: [] }) as unknown as SceneData;
+
+describe.skipIf(!HAS_WASM)('EventBinding authoring commands', () => {
+ let module: ESEngineModule;
+ let S: EditorSession;
+
+ beforeAll(async () => {
+ module = await loadWasmModule();
+ });
+ beforeEach(() => {
+ const app = App.new();
+ const registry = new module.Registry();
+ app.connectCpp(registry as never, module);
+ host.world = app.world;
+ S = EditorSession.create();
+ S.model.adopt(emptyScene(), new Map());
+ });
+ afterEach(() => S.dispose());
+
+ const compOf = (id: number) => S.model.entityBySource(id)?.components.find((c) => c.type === 'EventBinding');
+ const rowsOf = (id: number): EventBindingRow[] =>
+ ((compOf(id)?.data as { rows: EventBindingRow[] } | undefined)?.rows ?? []);
+
+ it('adds a row, creating the component on first use', () => {
+ const e = S.commands.addEntity()!;
+ expect(compOf(e)).toBeUndefined();
+
+ S.commands.addEventBinding(e, { event: 'click', action: 'ui.setPage', arg: 'tabs:home' });
+
+ expect(rowsOf(e)).toEqual([{ event: 'click', action: 'ui.setPage', arg: 'tabs:home' }]);
+ });
+
+ it('patches one row without touching its siblings', () => {
+ const e = S.commands.addEntity()!;
+ S.commands.addEventBinding(e, { event: 'click', action: 'a' });
+ S.commands.addEventBinding(e, { event: 'change', action: 'b' });
+
+ S.commands.updateEventBinding(e, 1, { target: 'Panel' });
+
+ expect(rowsOf(e)).toEqual([
+ { event: 'click', action: 'a' },
+ { event: 'change', action: 'b', target: 'Panel' },
+ ]);
+ });
+
+ it('clearing an optional field removes the key rather than storing ""', () => {
+ const e = S.commands.addEntity()!;
+ S.commands.addEventBinding(e, { event: 'click', action: 'a', target: 'Panel', arg: 'x' });
+
+ S.commands.updateEventBinding(e, 0, { target: '', arg: undefined });
+
+ expect(rowsOf(e)).toEqual([{ event: 'click', action: 'a' }]);
+ });
+
+ it('removing the last row drops the component (no empty-rows litter)', () => {
+ const e = S.commands.addEntity()!;
+ S.commands.addEventBinding(e, { event: 'click', action: 'a' });
+
+ S.commands.removeEventBinding(e, 0);
+
+ expect(compOf(e)).toBeUndefined();
+ });
+
+ it('each edit is one undo step, and undo restores the previous list', () => {
+ const e = S.commands.addEntity()!;
+ S.commands.addEventBinding(e, { event: 'click', action: 'a' });
+ S.commands.updateEventBinding(e, 0, { arg: 'one' });
+
+ S.history.undo();
+ expect(rowsOf(e)).toEqual([{ event: 'click', action: 'a' }]);
+
+ S.history.undo();
+ expect(compOf(e)).toBeUndefined();
+
+ S.history.redo();
+ expect(rowsOf(e)).toEqual([{ event: 'click', action: 'a' }]);
+ });
+
+ it('an out-of-range patch or removal is a no-op', () => {
+ const e = S.commands.addEntity()!;
+ S.commands.addEventBinding(e, { event: 'click', action: 'a' });
+
+ S.commands.updateEventBinding(e, 5, { arg: 'x' });
+ S.commands.removeEventBinding(e, 5);
+
+ expect(rowsOf(e)).toEqual([{ event: 'click', action: 'a' }]);
+ });
+});
diff --git a/examples/README.md b/examples/README.md
index fdd8dc3c3..8573b3929 100644
--- a/examples/README.md
+++ b/examples/README.md
@@ -43,6 +43,7 @@ for your own game.
| **ui-layout** | UI | Flexbox-style responsive UI layout. |
| **ui-list** | UI | A virtualized list and grid — `createListView`, live data, `scrollToIndex`. |
| **ui-controller** | UI | Shared UI controllers + declarative per-page gears: a tab bar, an `$interaction` button, and a tweened popup. |
+| **ui-events** | UI | Visual event binding — `EventBinding` rows wire a button's `click` to a named action (`ui.setPage`), including on another entity by name. `src/main.ts` is empty. |
| **chat** | UI | A chat log — virtualized ListView + TextInput composer with two-way binding. |
| **rich-text** | UI | A live rich-text playground — type markup (and 中文 via IME) into a TextInput and watch a `Text` render bold/italic/color/font-size runs. |
| **enemy-ai** | AI | A state machine drives enemies to patrol, sense the player, and chase via A* navigation. |
diff --git a/examples/ui-events/assets/scenes/main.esscene b/examples/ui-events/assets/scenes/main.esscene
new file mode 100644
index 000000000..6214261f2
--- /dev/null
+++ b/examples/ui-events/assets/scenes/main.esscene
@@ -0,0 +1,408 @@
+{
+ "version": "1.0",
+ "name": "UI Events (no code)",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 10 } } },
+ { "type": "Camera", "data": { "projectionType": 1, "orthoSize": 300, "isActive": true, "priority": 0 } }
+ ],
+ "visible": true
+ },
+ {
+ "id": 1,
+ "name": "Canvas",
+ "parent": null,
+ "children": [2, 3, 5, 7, 10],
+ "components": [
+ { "type": "Transform", "data": {} },
+ { "type": "Canvas", "data": { "designResolution": { "x": 800, "y": 600 }, "scaleMode": 2 } },
+ { "type": "UINode", "data": {} },
+ {
+ "type": "UIController",
+ "data": {
+ "controllers": [
+ { "name": "tabs", "pages": ["home", "settings"], "current": "home" }
+ ]
+ }
+ }
+ ],
+ "visible": true
+ },
+ {
+ "id": 2,
+ "name": "Title",
+ "parent": 1,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": {} },
+ {
+ "type": "UINode",
+ "data": {
+ "position": 1,
+ "width": { "value": 660, "unit": 0 },
+ "height": { "value": 40, "unit": 0 },
+ "insetLeft": { "value": 50, "unit": 1 },
+ "marginLeft": { "value": -330, "unit": 0 },
+ "insetTop": { "value": 36, "unit": 0 }
+ }
+ },
+ {
+ "type": "Text",
+ "data": {
+ "content": "These buttons run actions with no game code — the wires are Events rows",
+ "fontSize": 17,
+ "color": { "r": 0.9, "g": 0.92, "b": 0.96, "a": 1 },
+ "align": 1,
+ "verticalAlign": 1
+ }
+ }
+ ],
+ "visible": true
+ },
+ {
+ "id": 3,
+ "name": "HomeButton",
+ "parent": 1,
+ "children": [4],
+ "components": [
+ { "type": "Transform", "data": {} },
+ {
+ "type": "UINode",
+ "data": {
+ "position": 1,
+ "width": { "value": 170, "unit": 0 },
+ "height": { "value": 44, "unit": 0 },
+ "insetLeft": { "value": 50, "unit": 1 },
+ "marginLeft": { "value": -180, "unit": 0 },
+ "insetTop": { "value": 108, "unit": 0 }
+ }
+ },
+ { "type": "UIVisual", "data": { "visualType": 1, "color": { "r": 0.19, "g": 0.21, "b": 0.26, "a": 1 } } },
+ { "type": "Interactable", "data": { "enabled": true, "blockRaycast": true, "raycastTarget": true } },
+ {
+ "type": "UIController",
+ "data": {
+ "controllers": [
+ { "name": "$interaction", "pages": ["normal", "hover", "pressed", "disabled", "focused"], "current": "normal" }
+ ]
+ }
+ },
+ {
+ "type": "UIGear",
+ "data": {
+ "bindings": [
+ {
+ "controller": "$interaction",
+ "component": "UIVisual",
+ "property": "color",
+ "pages": {
+ "normal": { "r": 0.19, "g": 0.21, "b": 0.26, "a": 1 },
+ "hover": { "r": 0.26, "g": 0.29, "b": 0.36, "a": 1 },
+ "pressed": { "r": 0.14, "g": 0.16, "b": 0.2, "a": 1 }
+ },
+ "tween": { "easing": 5, "duration": 0.12 }
+ }
+ ]
+ }
+ },
+ {
+ "type": "EventBinding",
+ "data": {
+ "rows": [
+ { "event": "click", "action": "ui.setPage", "arg": "tabs:home" },
+ { "event": "click", "action": "ui.setPage", "arg": "badge:off", "target": "Card" }
+ ]
+ }
+ }
+ ],
+ "visible": true
+ },
+ {
+ "id": 4,
+ "name": "HomeLabel",
+ "parent": 3,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": {} },
+ {
+ "type": "UINode",
+ "data": {
+ "position": 1,
+ "insetLeft": { "value": 0, "unit": 0 },
+ "insetRight": { "value": 0, "unit": 0 },
+ "insetTop": { "value": 0, "unit": 0 },
+ "insetBottom": { "value": 0, "unit": 0 }
+ }
+ },
+ {
+ "type": "Text",
+ "data": {
+ "content": "Home",
+ "fontSize": 16,
+ "color": { "r": 0.93, "g": 0.94, "b": 0.97, "a": 1 },
+ "align": 1,
+ "verticalAlign": 1
+ }
+ }
+ ],
+ "visible": true
+ },
+ {
+ "id": 5,
+ "name": "SettingsButton",
+ "parent": 1,
+ "children": [6],
+ "components": [
+ { "type": "Transform", "data": {} },
+ {
+ "type": "UINode",
+ "data": {
+ "position": 1,
+ "width": { "value": 170, "unit": 0 },
+ "height": { "value": 44, "unit": 0 },
+ "insetLeft": { "value": 50, "unit": 1 },
+ "marginLeft": { "value": 10, "unit": 0 },
+ "insetTop": { "value": 108, "unit": 0 }
+ }
+ },
+ { "type": "UIVisual", "data": { "visualType": 1, "color": { "r": 0.19, "g": 0.21, "b": 0.26, "a": 1 } } },
+ { "type": "Interactable", "data": { "enabled": true, "blockRaycast": true, "raycastTarget": true } },
+ {
+ "type": "UIController",
+ "data": {
+ "controllers": [
+ { "name": "$interaction", "pages": ["normal", "hover", "pressed", "disabled", "focused"], "current": "normal" }
+ ]
+ }
+ },
+ {
+ "type": "UIGear",
+ "data": {
+ "bindings": [
+ {
+ "controller": "$interaction",
+ "component": "UIVisual",
+ "property": "color",
+ "pages": {
+ "normal": { "r": 0.19, "g": 0.21, "b": 0.26, "a": 1 },
+ "hover": { "r": 0.26, "g": 0.29, "b": 0.36, "a": 1 },
+ "pressed": { "r": 0.14, "g": 0.16, "b": 0.2, "a": 1 }
+ },
+ "tween": { "easing": 5, "duration": 0.12 }
+ }
+ ]
+ }
+ },
+ {
+ "type": "EventBinding",
+ "data": {
+ "rows": [
+ { "event": "click", "action": "ui.setPage", "arg": "tabs:settings" },
+ { "event": "click", "action": "ui.setPage", "arg": "badge:on", "target": "Card" }
+ ]
+ }
+ }
+ ],
+ "visible": true
+ },
+ {
+ "id": 6,
+ "name": "SettingsLabel",
+ "parent": 5,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": {} },
+ {
+ "type": "UINode",
+ "data": {
+ "position": 1,
+ "insetLeft": { "value": 0, "unit": 0 },
+ "insetRight": { "value": 0, "unit": 0 },
+ "insetTop": { "value": 0, "unit": 0 },
+ "insetBottom": { "value": 0, "unit": 0 }
+ }
+ },
+ {
+ "type": "Text",
+ "data": {
+ "content": "Settings",
+ "fontSize": 16,
+ "color": { "r": 0.93, "g": 0.94, "b": 0.97, "a": 1 },
+ "align": 1,
+ "verticalAlign": 1
+ }
+ }
+ ],
+ "visible": true
+ },
+ {
+ "id": 7,
+ "name": "Card",
+ "parent": 1,
+ "children": [8, 9],
+ "components": [
+ { "type": "Transform", "data": {} },
+ {
+ "type": "UINode",
+ "data": {
+ "position": 1,
+ "width": { "value": 440, "unit": 0 },
+ "height": { "value": 230, "unit": 0 },
+ "insetLeft": { "value": 50, "unit": 1 },
+ "marginLeft": { "value": -220, "unit": 0 },
+ "insetTop": { "value": 186, "unit": 0 }
+ }
+ },
+ { "type": "UIVisual", "data": { "visualType": 1, "color": { "r": 0.22, "g": 0.45, "b": 0.78, "a": 1 } } },
+ {
+ "type": "UIController",
+ "data": {
+ "controllers": [
+ { "name": "badge", "pages": ["off", "on"], "current": "off" }
+ ]
+ }
+ },
+ {
+ "type": "UIGear",
+ "data": {
+ "bindings": [
+ {
+ "controller": "tabs",
+ "component": "UIVisual",
+ "property": "color",
+ "pages": {
+ "home": { "r": 0.22, "g": 0.45, "b": 0.78, "a": 1 },
+ "settings": { "r": 0.45, "g": 0.3, "b": 0.72, "a": 1 }
+ },
+ "tween": { "easing": 5, "duration": 0.2 }
+ }
+ ]
+ }
+ }
+ ],
+ "visible": true
+ },
+ {
+ "id": 8,
+ "name": "CardLabel",
+ "parent": 7,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": {} },
+ {
+ "type": "UINode",
+ "data": {
+ "position": 1,
+ "insetLeft": { "value": 24, "unit": 0 },
+ "insetRight": { "value": 24, "unit": 0 },
+ "insetTop": { "value": 0, "unit": 0 },
+ "insetBottom": { "value": 0, "unit": 0 }
+ }
+ },
+ {
+ "type": "Text",
+ "data": {
+ "content": "HOME — the click switched the \"tabs\" controller, and this card's colour and text are gears reading it.",
+ "fontSize": 16,
+ "wordWrap": true,
+ "color": { "r": 1, "g": 1, "b": 1, "a": 1 },
+ "align": 1,
+ "verticalAlign": 1
+ }
+ },
+ {
+ "type": "UIGear",
+ "data": {
+ "bindings": [
+ {
+ "controller": "tabs",
+ "component": "Text",
+ "property": "content",
+ "pages": {
+ "home": "HOME — the click switched the \"tabs\" controller, and this card's colour and text are gears reading it.",
+ "settings": "SETTINGS — the same button also set a page on another entity, by name: that is the row's Target field."
+ }
+ }
+ ]
+ }
+ }
+ ],
+ "visible": true
+ },
+ {
+ "id": 9,
+ "name": "Badge",
+ "parent": 7,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": {} },
+ {
+ "type": "UINode",
+ "data": {
+ "position": 1,
+ "width": { "value": 18, "unit": 0 },
+ "height": { "value": 18, "unit": 0 },
+ "insetRight": { "value": 14, "unit": 0 },
+ "insetTop": { "value": 14, "unit": 0 }
+ }
+ },
+ { "type": "UIVisual", "data": { "visualType": 1, "color": { "r": 1, "g": 0.78, "b": 0.25, "a": 0 } } },
+ {
+ "type": "UIGear",
+ "data": {
+ "bindings": [
+ {
+ "controller": "badge",
+ "component": "UIVisual",
+ "property": "color",
+ "pages": {
+ "off": { "r": 1, "g": 0.78, "b": 0.25, "a": 0 },
+ "on": { "r": 1, "g": 0.78, "b": 0.25, "a": 1 }
+ },
+ "tween": { "easing": 5, "duration": 0.2 }
+ }
+ ]
+ }
+ }
+ ],
+ "visible": true
+ },
+ {
+ "id": 10,
+ "name": "Hint",
+ "parent": 1,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": {} },
+ {
+ "type": "UINode",
+ "data": {
+ "position": 1,
+ "width": { "value": 660, "unit": 0 },
+ "height": { "value": 46, "unit": 0 },
+ "insetLeft": { "value": 50, "unit": 1 },
+ "marginLeft": { "value": -330, "unit": 0 },
+ "insetTop": { "value": 448, "unit": 0 }
+ }
+ },
+ {
+ "type": "Text",
+ "data": {
+ "content": "src/main.ts is empty. Select a button and open Details → Events to see the wire.",
+ "fontSize": 14,
+ "wordWrap": true,
+ "color": { "r": 0.62, "g": 0.66, "b": 0.73, "a": 1 },
+ "align": 1,
+ "verticalAlign": 1
+ }
+ }
+ ],
+ "visible": true
+ }
+ ]
+}
diff --git a/examples/ui-events/assets/scenes/main.esscene.meta b/examples/ui-events/assets/scenes/main.esscene.meta
new file mode 100644
index 000000000..39e5b81d5
--- /dev/null
+++ b/examples/ui-events/assets/scenes/main.esscene.meta
@@ -0,0 +1,8 @@
+{
+ "uuid": "88d5a42e-f9f1-4ea9-b300-551fabdc36be",
+ "version": "2.0",
+ "type": "scene",
+ "importer": {
+ "autoMigrate": true
+ }
+}
diff --git a/examples/ui-events/project.esproject b/examples/ui-events/project.esproject
new file mode 100644
index 000000000..f439a4b75
--- /dev/null
+++ b/examples/ui-events/project.esproject
@@ -0,0 +1,13 @@
+{
+ "formatVersion": "1",
+ "name": "UI Events (no code)",
+ "description": "Authored event wiring: buttons drive a UIController through EventBinding rows — the whole project ships zero gameplay code.",
+ "tag": "UI",
+ "version": "0.1.0",
+ "defaultScene": "assets/scenes/main.esscene",
+ "designResolution": {
+ "width": 800,
+ "height": 600
+ },
+ "spineVersion": "none"
+}
diff --git a/examples/ui-events/src/main.ts b/examples/ui-events/src/main.ts
new file mode 100644
index 000000000..aba71796c
--- /dev/null
+++ b/examples/ui-events/src/main.ts
@@ -0,0 +1,12 @@
+// UI Events — deliberately empty.
+//
+// Everything this project does is authored data: each button carries an
+// `EventBinding` row ("on click, run ui.setPage with tabs:settings"), and the
+// panel's colour + label are `UIGear`s reading the shared `tabs` controller.
+// Open the scene, select a button, and look at the Details panel's Events
+// section — that is the whole program.
+//
+// The entry point exists because a project has one; there is nothing to put in
+// it. Wiring only needs code when it needs LOGIC, and then the row points at an
+// action name (`fsm.fire`) instead of growing branches of its own.
+export {};
diff --git a/examples/ui-events/tsconfig.json b/examples/ui-events/tsconfig.json
new file mode 100644
index 000000000..0a8528b29
--- /dev/null
+++ b/examples/ui-events/tsconfig.json
@@ -0,0 +1,22 @@
+{
+ "compilerOptions": {
+ "target": "ES2020",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "declaration": false,
+ "outDir": "./dist",
+ "rootDir": ".",
+ "baseUrl": ".",
+ "paths": {
+ "esengine": ["./.esengine/sdk/index.d.ts"],
+ "esengine/wasm": ["./.esengine/sdk/wasm.d.ts"],
+ "@esengine/editor": ["./.esengine/editor/index.d.ts"]
+ }
+ },
+ "include": ["src/**/*"],
+ "exclude": ["node_modules"]
+}
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 31c016ea6..91f19bd34 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1335 stable · 17 beta · 1 deprecated
+Symbols: 1345 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -2492,6 +2492,71 @@ static new (commands: CommandsInstance, entity: Entity | null, name?: string): E
static prototype: EntityCommands
```
+## EntityEvent — interface
+```
+currentTarget: number
+data: TData
+defaultPrevented: boolean
+preventDefault: () => void
+propagationStopped: boolean
+stopPropagation: () => void
+target: number
+type: string
+```
+
+## EntityEventHandler — type
+```
+(event: EntityEvent<TData>) => void
+```
+
+## EntityEventQueue — class
+```
+clear: () => void
+drain: () => readonly EntityEvent[]
+emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => EntityEvent<TData>
+emitBubbled: (ancestor: Entity, rootEvent: EntityEvent) => EntityEvent
+on: { (entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe; (type: string, handler: EntityEventHandler): Unsubscribe; }
+query: (type: string) => readonly EntityEvent[]
+removeAll: (entity: Entity) => void
+static new (): EntityEventQueue
+static prototype: EntityEventQueue
+```
+
+## EntityEvents — const
+```
+ResourceDef<EntityEventQueue>
+```
+
+## EventBinding — const
+```
+ComponentDef<EventBindingData>
+```
+
+## EventBindingData — interface
+```
+rows: EventBindingRow[]
+```
+
+## EventBindingPlugin — class
+```
+build: (app: App) => void
+cleanup: () => void
+name: string
+static new (): EventBindingPlugin
+static prototype: EventBindingPlugin
+```
+
+## EventBindingRow — interface
+```
+action: string
+arg: string | undefined
+enabled: boolean | undefined
+event: string
+guard: string | undefined
+once: boolean | undefined
+target: string | undefined
+```
+
## EventDef — interface
```
_id: symbol
@@ -7388,20 +7453,20 @@ type: string
## UIEventHandler — type
```
-(event: UIEvent<TData>) => void
+(event: EntityEvent<TData>) => void
```
## UIEventQueue — class
```
clear: () => void
-drain: () => readonly UIEvent[]
-emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => UIEvent<TData>
-emitBubbled: (ancestor: Entity, rootEvent: UIEvent) => UIEvent
-on: { (entity: Entity, type: string, handler: UIEventHandler): Unsubscribe; (type: string, handler: UIEventHandler): Unsubscribe; }
-query: (type: string) => readonly UIEvent[]
+drain: () => readonly EntityEvent[]
+emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => EntityEvent<TData>
+emitBubbled: (ancestor: Entity, rootEvent: EntityEvent) => EntityEvent
+on: { (entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe; (type: string, handler: EntityEventHandler): Unsubscribe; }
+query: (type: string) => readonly EntityEvent[]
removeAll: (entity: Entity) => void
-static new (): UIEventQueue
-static prototype: UIEventQueue
+static new (): EntityEventQueue
+static prototype: EntityEventQueue
```
## UIEventType — type
@@ -7411,7 +7476,7 @@ typeof UIEventType[keyof typeof UIEventType]
## UIEvents — const
```
-ResourceDef<UIEventQueue>
+ResourceDef<EntityEventQueue>
```
## UIGear — const
@@ -8641,6 +8706,11 @@ DragPlugin
(channel: PropertyChannel, time: number): number
```
+## eventBindingPlugin — const
+```
+EventBindingPlugin
+```
+
## evictTextureDimensions — function
```
(handle: number): void
@@ -9656,6 +9726,11 @@ ReplicationPlugin
(index: TerrainIndex, neighbors: readonly boolean[]): number
```
+## resolveBindingTarget — function
+```
+(world: World, from: Entity, name: string): Entity | null
+```
+
## resolveChildEntity — function
```
(world: Pick<World, "tryGet">, rootEntity: Entity, childPath: string): Entity | null
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 6abcd9dfa..4eee4d765 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1354 stable · 22 beta · 1 deprecated
+Symbols: 1364 stable · 22 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -2500,6 +2500,71 @@ static new (commands: CommandsInstance, entity: Entity | null, name?: string): E
static prototype: EntityCommands
```
+## EntityEvent — interface
+```
+currentTarget: number
+data: TData
+defaultPrevented: boolean
+preventDefault: () => void
+propagationStopped: boolean
+stopPropagation: () => void
+target: number
+type: string
+```
+
+## EntityEventHandler — type
+```
+(event: EntityEvent<TData>) => void
+```
+
+## EntityEventQueue — class
+```
+clear: () => void
+drain: () => readonly EntityEvent[]
+emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => EntityEvent<TData>
+emitBubbled: (ancestor: Entity, rootEvent: EntityEvent) => EntityEvent
+on: { (entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe; (type: string, handler: EntityEventHandler): Unsubscribe; }
+query: (type: string) => readonly EntityEvent[]
+removeAll: (entity: Entity) => void
+static new (): EntityEventQueue
+static prototype: EntityEventQueue
+```
+
+## EntityEvents — const
+```
+ResourceDef<EntityEventQueue>
+```
+
+## EventBinding — const
+```
+ComponentDef<EventBindingData>
+```
+
+## EventBindingData — interface
+```
+rows: EventBindingRow[]
+```
+
+## EventBindingPlugin — class
+```
+build: (app: App) => void
+cleanup: () => void
+name: string
+static new (): EventBindingPlugin
+static prototype: EventBindingPlugin
+```
+
+## EventBindingRow — interface
+```
+action: string
+arg: string | undefined
+enabled: boolean | undefined
+event: string
+guard: string | undefined
+once: boolean | undefined
+target: string | undefined
+```
+
## EventDef — interface
```
_id: symbol
@@ -5240,7 +5305,7 @@ static prototype: QueryInstance<any>
## RESOURCE_BINDINGS — const
```
-{ readonly createTexture: "es_createTexture"; readonly createTextureKTX2: "es_createTextureKTX2"; readonly releaseTexture: "es_releaseTexture"; readonly getTextureDimensions: "es_getTextureDimensions"; }
+{ readonly createTexture: "es_rm_createTextureEx"; readonly createTextureKTX2: "es_createTextureKTX2"; readonly releaseTexture: "es_rm_releaseTexture"; readonly getTextureDimensions: "es_getTextureDimensions"; }
```
## RETIRED_COMPONENT_TYPES — const
@@ -7545,20 +7610,20 @@ type: string
## UIEventHandler — type
```
-(event: UIEvent<TData>) => void
+(event: EntityEvent<TData>) => void
```
## UIEventQueue — class
```
clear: () => void
-drain: () => readonly UIEvent[]
-emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => UIEvent<TData>
-emitBubbled: (ancestor: Entity, rootEvent: UIEvent) => UIEvent
-on: { (entity: Entity, type: string, handler: UIEventHandler): Unsubscribe; (type: string, handler: UIEventHandler): Unsubscribe; }
-query: (type: string) => readonly UIEvent[]
+drain: () => readonly EntityEvent[]
+emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => EntityEvent<TData>
+emitBubbled: (ancestor: Entity, rootEvent: EntityEvent) => EntityEvent
+on: { (entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe; (type: string, handler: EntityEventHandler): Unsubscribe; }
+query: (type: string) => readonly EntityEvent[]
removeAll: (entity: Entity) => void
-static new (): UIEventQueue
-static prototype: UIEventQueue
+static new (): EntityEventQueue
+static prototype: EntityEventQueue
```
## UIEventType — type
@@ -7568,7 +7633,7 @@ typeof UIEventType[keyof typeof UIEventType]
## UIEvents — const
```
-ResourceDef<UIEventQueue>
+ResourceDef<EntityEventQueue>
```
## UIGear — const
@@ -8838,6 +8903,11 @@ DragPlugin
(channel: PropertyChannel, time: number): number
```
+## eventBindingPlugin — const
+```
+EventBindingPlugin
+```
+
## evictTextureDimensions — function
```
(handle: number): void
@@ -9863,6 +9933,11 @@ ReplicationPlugin
(index: TerrainIndex, neighbors: readonly boolean[]): number
```
+## resolveBindingTarget — function
+```
+(world: World, from: Entity, name: string): Entity | null
+```
+
## resolveChildEntity — function
```
(world: Pick<World, "tryGet">, rootEntity: Entity, childPath: string): Entity | null
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index fe7a0cb0f..a3a770c27 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1334 stable · 19 beta · 1 deprecated
+Symbols: 1344 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -2487,6 +2487,71 @@ static new (commands: CommandsInstance, entity: Entity | null, name?: string): E
static prototype: EntityCommands
```
+## EntityEvent — interface
+```
+currentTarget: number
+data: TData
+defaultPrevented: boolean
+preventDefault: () => void
+propagationStopped: boolean
+stopPropagation: () => void
+target: number
+type: string
+```
+
+## EntityEventHandler — type
+```
+(event: EntityEvent<TData>) => void
+```
+
+## EntityEventQueue — class
+```
+clear: () => void
+drain: () => readonly EntityEvent[]
+emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => EntityEvent<TData>
+emitBubbled: (ancestor: Entity, rootEvent: EntityEvent) => EntityEvent
+on: { (entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe; (type: string, handler: EntityEventHandler): Unsubscribe; }
+query: (type: string) => readonly EntityEvent[]
+removeAll: (entity: Entity) => void
+static new (): EntityEventQueue
+static prototype: EntityEventQueue
+```
+
+## EntityEvents — const
+```
+ResourceDef<EntityEventQueue>
+```
+
+## EventBinding — const
+```
+ComponentDef<EventBindingData>
+```
+
+## EventBindingData — interface
+```
+rows: EventBindingRow[]
+```
+
+## EventBindingPlugin — class
+```
+build: (app: App) => void
+cleanup: () => void
+name: string
+static new (): EventBindingPlugin
+static prototype: EventBindingPlugin
+```
+
+## EventBindingRow — interface
+```
+action: string
+arg: string | undefined
+enabled: boolean | undefined
+event: string
+guard: string | undefined
+once: boolean | undefined
+target: string | undefined
+```
+
## EventDef — interface
```
_id: symbol
@@ -7383,20 +7448,20 @@ type: string
## UIEventHandler — type
```
-(event: UIEvent<TData>) => void
+(event: EntityEvent<TData>) => void
```
## UIEventQueue — class
```
clear: () => void
-drain: () => readonly UIEvent[]
-emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => UIEvent<TData>
-emitBubbled: (ancestor: Entity, rootEvent: UIEvent) => UIEvent
-on: { (entity: Entity, type: string, handler: UIEventHandler): Unsubscribe; (type: string, handler: UIEventHandler): Unsubscribe; }
-query: (type: string) => readonly UIEvent[]
+drain: () => readonly EntityEvent[]
+emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => EntityEvent<TData>
+emitBubbled: (ancestor: Entity, rootEvent: EntityEvent) => EntityEvent
+on: { (entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe; (type: string, handler: EntityEventHandler): Unsubscribe; }
+query: (type: string) => readonly EntityEvent[]
removeAll: (entity: Entity) => void
-static new (): UIEventQueue
-static prototype: UIEventQueue
+static new (): EntityEventQueue
+static prototype: EntityEventQueue
```
## UIEventType — type
@@ -7406,7 +7471,7 @@ typeof UIEventType[keyof typeof UIEventType]
## UIEvents — const
```
-ResourceDef<UIEventQueue>
+ResourceDef<EntityEventQueue>
```
## UIGear — const
@@ -8636,6 +8701,11 @@ DragPlugin
(channel: PropertyChannel, time: number): number
```
+## eventBindingPlugin — const
+```
+EventBindingPlugin
+```
+
## evictTextureDimensions — function
```
(handle: number): void
@@ -9661,6 +9731,11 @@ ReplicationPlugin
(index: TerrainIndex, neighbors: readonly boolean[]): number
```
+## resolveBindingTarget — function
+```
+(world: World, from: Entity, name: string): Entity | null
+```
+
## resolveChildEntity — function
```
(world: Pick<World, "tryGet">, rootEntity: Entity, childPath: string): Entity | null
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 9d06b6532..41b9f7037 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1355 stable · 17 beta · 1 deprecated
+Symbols: 1365 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -2487,6 +2487,71 @@ static new (commands: CommandsInstance, entity: Entity | null, name?: string): E
static prototype: EntityCommands
```
+## EntityEvent — interface
+```
+currentTarget: number
+data: TData
+defaultPrevented: boolean
+preventDefault: () => void
+propagationStopped: boolean
+stopPropagation: () => void
+target: number
+type: string
+```
+
+## EntityEventHandler — type
+```
+(event: EntityEvent<TData>) => void
+```
+
+## EntityEventQueue — class
+```
+clear: () => void
+drain: () => readonly EntityEvent[]
+emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => EntityEvent<TData>
+emitBubbled: (ancestor: Entity, rootEvent: EntityEvent) => EntityEvent
+on: { (entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe; (type: string, handler: EntityEventHandler): Unsubscribe; }
+query: (type: string) => readonly EntityEvent[]
+removeAll: (entity: Entity) => void
+static new (): EntityEventQueue
+static prototype: EntityEventQueue
+```
+
+## EntityEvents — const
+```
+ResourceDef<EntityEventQueue>
+```
+
+## EventBinding — const
+```
+ComponentDef<EventBindingData>
+```
+
+## EventBindingData — interface
+```
+rows: EventBindingRow[]
+```
+
+## EventBindingPlugin — class
+```
+build: (app: App) => void
+cleanup: () => void
+name: string
+static new (): EventBindingPlugin
+static prototype: EventBindingPlugin
+```
+
+## EventBindingRow — interface
+```
+action: string
+arg: string | undefined
+enabled: boolean | undefined
+event: string
+guard: string | undefined
+once: boolean | undefined
+target: string | undefined
+```
+
## EventDef — interface
```
_id: symbol
@@ -7598,20 +7663,20 @@ type: string
## UIEventHandler — type
```
-(event: UIEvent<TData>) => void
+(event: EntityEvent<TData>) => void
```
## UIEventQueue — class
```
clear: () => void
-drain: () => readonly UIEvent[]
-emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => UIEvent<TData>
-emitBubbled: (ancestor: Entity, rootEvent: UIEvent) => UIEvent
-on: { (entity: Entity, type: string, handler: UIEventHandler): Unsubscribe; (type: string, handler: UIEventHandler): Unsubscribe; }
-query: (type: string) => readonly UIEvent[]
+drain: () => readonly EntityEvent[]
+emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => EntityEvent<TData>
+emitBubbled: (ancestor: Entity, rootEvent: EntityEvent) => EntityEvent
+on: { (entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe; (type: string, handler: EntityEventHandler): Unsubscribe; }
+query: (type: string) => readonly EntityEvent[]
removeAll: (entity: Entity) => void
-static new (): UIEventQueue
-static prototype: UIEventQueue
+static new (): EntityEventQueue
+static prototype: EntityEventQueue
```
## UIEventType — type
@@ -7621,7 +7686,7 @@ typeof UIEventType[keyof typeof UIEventType]
## UIEvents — const
```
-ResourceDef<UIEventQueue>
+ResourceDef<EntityEventQueue>
```
## UIGear — const
@@ -8856,6 +8921,11 @@ DragPlugin
(channel: PropertyChannel, time: number): number
```
+## eventBindingPlugin — const
+```
+EventBindingPlugin
+```
+
## evictTextureDimensions — function
```
(handle: number): void
@@ -9881,6 +9951,11 @@ ReplicationPlugin
(index: TerrainIndex, neighbors: readonly boolean[]): number
```
+## resolveBindingTarget — function
+```
+(world: World, from: Entity, name: string): Entity | null
+```
+
## resolveChildEntity — function
```
(world: Pick<World, "tryGet">, rootEntity: Entity, childPath: string): Entity | null
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index aabaf479b..05dd061ae 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1345 stable · 17 beta · 1 deprecated
+Symbols: 1355 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -2487,6 +2487,71 @@ static new (commands: CommandsInstance, entity: Entity | null, name?: string): E
static prototype: EntityCommands
```
+## EntityEvent — interface
+```
+currentTarget: number
+data: TData
+defaultPrevented: boolean
+preventDefault: () => void
+propagationStopped: boolean
+stopPropagation: () => void
+target: number
+type: string
+```
+
+## EntityEventHandler — type
+```
+(event: EntityEvent<TData>) => void
+```
+
+## EntityEventQueue — class
+```
+clear: () => void
+drain: () => readonly EntityEvent[]
+emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => EntityEvent<TData>
+emitBubbled: (ancestor: Entity, rootEvent: EntityEvent) => EntityEvent
+on: { (entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe; (type: string, handler: EntityEventHandler): Unsubscribe; }
+query: (type: string) => readonly EntityEvent[]
+removeAll: (entity: Entity) => void
+static new (): EntityEventQueue
+static prototype: EntityEventQueue
+```
+
+## EntityEvents — const
+```
+ResourceDef<EntityEventQueue>
+```
+
+## EventBinding — const
+```
+ComponentDef<EventBindingData>
+```
+
+## EventBindingData — interface
+```
+rows: EventBindingRow[]
+```
+
+## EventBindingPlugin — class
+```
+build: (app: App) => void
+cleanup: () => void
+name: string
+static new (): EventBindingPlugin
+static prototype: EventBindingPlugin
+```
+
+## EventBindingRow — interface
+```
+action: string
+arg: string | undefined
+enabled: boolean | undefined
+event: string
+guard: string | undefined
+once: boolean | undefined
+target: string | undefined
+```
+
## EventDef — interface
```
_id: symbol
@@ -7390,20 +7455,20 @@ type: string
## UIEventHandler — type
```
-(event: UIEvent<TData>) => void
+(event: EntityEvent<TData>) => void
```
## UIEventQueue — class
```
clear: () => void
-drain: () => readonly UIEvent[]
-emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => UIEvent<TData>
-emitBubbled: (ancestor: Entity, rootEvent: UIEvent) => UIEvent
-on: { (entity: Entity, type: string, handler: UIEventHandler): Unsubscribe; (type: string, handler: UIEventHandler): Unsubscribe; }
-query: (type: string) => readonly UIEvent[]
+drain: () => readonly EntityEvent[]
+emit: <TData = unknown>(entity: Entity, type: string, data?: TData) => EntityEvent<TData>
+emitBubbled: (ancestor: Entity, rootEvent: EntityEvent) => EntityEvent
+on: { (entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe; (type: string, handler: EntityEventHandler): Unsubscribe; }
+query: (type: string) => readonly EntityEvent[]
removeAll: (entity: Entity) => void
-static new (): UIEventQueue
-static prototype: UIEventQueue
+static new (): EntityEventQueue
+static prototype: EntityEventQueue
```
## UIEventType — type
@@ -7413,7 +7478,7 @@ typeof UIEventType[keyof typeof UIEventType]
## UIEvents — const
```
-ResourceDef<UIEventQueue>
+ResourceDef<EntityEventQueue>
```
## UIGear — const
@@ -8660,6 +8725,11 @@ DragPlugin
(channel: PropertyChannel, time: number): number
```
+## eventBindingPlugin — const
+```
+EventBindingPlugin
+```
+
## evictTextureDimensions — function
```
(handle: number): void
@@ -9680,6 +9750,11 @@ ReplicationPlugin
(index: TerrainIndex, neighbors: readonly boolean[]): number
```
+## resolveBindingTarget — function
+```
+(world: World, from: Entity, name: string): Entity | null
+```
+
## resolveChildEntity — function
```
(world: Pick<World, "tryGet">, rootEntity: Entity, childPath: string): Entity | null
diff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.ts
index cec1e6f72..3305b044d 100644
--- a/sdk/src/core-runtime.ts
+++ b/sdk/src/core-runtime.ts
@@ -288,6 +288,26 @@ export {
type EventReaderDescriptor,
} from './event';
+// The per-entity, string-named channel (the other half of the story above:
+// `defineEvent` is the global typed bus, this is "what happened to THIS
+// entity"). `ui/` re-exports the same objects as UIEventQueue / UIEvents.
+export {
+ EntityEventQueue,
+ EntityEvents,
+ type EntityEvent,
+ type EntityEventHandler,
+} from './entityEvents';
+
+// Authored event → action wiring (the data form of `events.on(e, 'click', …)`).
+export {
+ EventBinding,
+ eventBindingPlugin,
+ EventBindingPlugin,
+ resolveBindingTarget,
+ type EventBindingRow,
+ type EventBindingData,
+} from './eventBinding';
+
// =============================================================================
// Commands
// =============================================================================
diff --git a/sdk/src/core-ui.ts b/sdk/src/core-ui.ts
index efb05abef..ccd708548 100644
--- a/sdk/src/core-ui.ts
+++ b/sdk/src/core-ui.ts
@@ -43,6 +43,9 @@ export {
UIInteraction,
UIEvents,
UIEventQueue,
+ // The value too, not just the union type: the editor's event picker and
+ // authored data both need the canonical type strings.
+ UIEventType,
UICameraInfo,
screenToUiWorld,
uiWorldToScreen,
@@ -65,7 +68,6 @@ export {
type InteractableData,
type UIInteractionData,
type UIEvent,
- type UIEventType,
type UIEventHandler,
type Unsubscribe,
type UICameraData,
diff --git a/sdk/src/entityEvents.ts b/sdk/src/entityEvents.ts
new file mode 100644
index 000000000..fd24a2252
--- /dev/null
+++ b/sdk/src/entityEvents.ts
@@ -0,0 +1,281 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file entityEvents.ts
+ * @brief EntityEventQueue — the entity-scoped, string-named event channel.
+ *
+ * The engine has two event channels and they answer different questions.
+ * `event.ts` is the GLOBAL, statically-typed bus: `defineEvent<T>()` gives a
+ * symbol-keyed, double-buffered stream that systems read as a batch ("all
+ * damage events this frame"). This file is the per-ENTITY one: an open string
+ * key ("click", "trigger_enter") dispatched synchronously to handlers
+ * subscribed for that entity, with bubbling to ancestors. It is what "this
+ * button was clicked" means, and it is the channel {@link EventBinding} wires
+ * authored data onto.
+ *
+ * It grew up inside `ui/` (as UIEventQueue) because widgets were its first
+ * producer, but nothing in it is UI-specific — the type strings are open and
+ * the queue never looks at a component. It lives here so non-UI producers and
+ * the core binding layer can speak it without importing `ui/`. The `ui/core/
+ * events.ts` names remain as aliases of these very objects.
+ */
+import { defineResource } from './resource';
+import type { Entity } from './types';
+import { log } from './logger';
+
+export interface EntityEvent<TData = unknown> {
+ /** Event type string (e.g. `'click'`, `'change'`). */
+ readonly type: string;
+ /** The entity where the event originated. */
+ readonly target: Entity;
+ /** The entity currently handling the event (differs from target during bubbling). */
+ readonly currentTarget: Entity;
+ /** User-provided payload (shape depends on `type`). */
+ readonly data: TData;
+ /** True if any handler called `stopPropagation()`. */
+ propagationStopped: boolean;
+ /** True if any handler called `preventDefault()`. */
+ defaultPrevented: boolean;
+ /** Stop the event from bubbling further up the parent chain. */
+ stopPropagation(): void;
+ /** Signal that the default action (if any) should be skipped. */
+ preventDefault(): void;
+}
+
+export type EntityEventHandler<TData = unknown> = (event: EntityEvent<TData>) => void;
+export type Unsubscribe = () => void;
+
+/**
+ * Entity event queue: pub/sub with bubbling support.
+ *
+ * @example
+ * ```ts
+ * const events = new EntityEventQueue();
+ * world.onDespawn(e => events.removeAll(e)); // one-time wiring
+ *
+ * events.on(buttonEntity, 'click', e => console.log('clicked'));
+ * events.emit(buttonEntity, 'click');
+ * ```
+ */
+export class EntityEventQueue {
+ private readonly entityHandlers_ = new Map<
+ Entity,
+ Map<string, Set<EntityEventHandler>>
+ >();
+ private readonly globalHandlers_ = new Map<string, Set<EntityEventHandler>>();
+ private pending_: EntityEvent[] = [];
+ private readonly activeKeys_ = new Set<string>();
+
+ /**
+ * Subscribe to an entity-specific event.
+ * Returns an unsubscribe function.
+ */
+ on(entity: Entity, type: string, handler: EntityEventHandler): Unsubscribe;
+ /**
+ * Subscribe to all events of a type, from any entity.
+ */
+ on(type: string, handler: EntityEventHandler): Unsubscribe;
+ on(
+ arg1: Entity | string,
+ arg2: string | EntityEventHandler,
+ arg3?: EntityEventHandler,
+ ): Unsubscribe {
+ // Entity-specific: on(entity, type, handler)
+ if (typeof arg1 === 'number' && typeof arg2 === 'string' && typeof arg3 === 'function') {
+ const entity = arg1 as Entity;
+ const type = arg2;
+ const handler = arg3;
+
+ let typeMap = this.entityHandlers_.get(entity);
+ if (!typeMap) {
+ typeMap = new Map();
+ this.entityHandlers_.set(entity, typeMap);
+ }
+ let set = typeMap.get(type);
+ if (!set) {
+ set = new Set();
+ typeMap.set(type, set);
+ }
+ set.add(handler);
+
+ return () => {
+ const tm = this.entityHandlers_.get(entity);
+ const s = tm?.get(type);
+ if (s) {
+ s.delete(handler);
+ if (s.size === 0) tm!.delete(type);
+ if (tm && tm.size === 0) this.entityHandlers_.delete(entity);
+ }
+ };
+ }
+
+ // Global: on(type, handler)
+ const type = arg1 as string;
+ const handler = arg2 as EntityEventHandler;
+
+ let set = this.globalHandlers_.get(type);
+ if (!set) {
+ set = new Set();
+ this.globalHandlers_.set(type, set);
+ }
+ set.add(handler);
+
+ return () => {
+ const s = this.globalHandlers_.get(type);
+ if (s) {
+ s.delete(handler);
+ if (s.size === 0) this.globalHandlers_.delete(type);
+ }
+ };
+ }
+
+ /**
+ * Remove all entity-specific handlers for `entity`.
+ * Wire this to `world.onDespawn` for automatic cleanup.
+ */
+ removeAll(entity: Entity): void {
+ this.entityHandlers_.delete(entity);
+ }
+
+ /**
+ * Emit an event for `entity`. Synchronously dispatches to registered
+ * handlers and queues the event for `drain()` / `query()`. Returns the
+ * event so callers can inspect propagationStopped / defaultPrevented
+ * (e.g. to drive bubbling to parents).
+ */
+ emit<TData = unknown>(
+ entity: Entity,
+ type: string,
+ data?: TData,
+ ): EntityEvent<TData> {
+ const event: EntityEvent<TData> = {
+ type,
+ target: entity,
+ currentTarget: entity,
+ data: data as TData,
+ propagationStopped: false,
+ defaultPrevented: false,
+ stopPropagation() {
+ this.propagationStopped = true;
+ },
+ preventDefault() {
+ this.defaultPrevented = true;
+ },
+ };
+ this.pending_.push(event);
+ this.dispatch_(entity, event);
+ return event;
+ }
+
+ /**
+ * Emit a bubbled event to an ancestor. Shares propagation state with
+ * the root event: calling stopPropagation on the bubbled event marks
+ * the root as stopped so callers can halt the bubbling walk.
+ *
+ * Callers are responsible for walking the parent chain; this queue
+ * does not know about hierarchy.
+ */
+ emitBubbled(ancestor: Entity, rootEvent: EntityEvent): EntityEvent {
+ if (rootEvent.propagationStopped) return rootEvent;
+
+ const bubbled: EntityEvent = {
+ type: rootEvent.type,
+ target: rootEvent.target,
+ currentTarget: ancestor,
+ data: rootEvent.data,
+ propagationStopped: false,
+ defaultPrevented: rootEvent.defaultPrevented,
+ stopPropagation() {
+ this.propagationStopped = true;
+ rootEvent.propagationStopped = true;
+ },
+ preventDefault() {
+ this.defaultPrevented = true;
+ (rootEvent as { defaultPrevented: boolean }).defaultPrevented = true;
+ },
+ };
+ this.pending_.push(bubbled);
+ this.dispatch_(ancestor, bubbled);
+ return bubbled;
+ }
+
+ /**
+ * Return all events queued since the last drain and clear the queue.
+ * Typically called once per frame by a UI system.
+ */
+ drain(): readonly EntityEvent[] {
+ const events = this.pending_;
+ this.pending_ = [];
+ return events;
+ }
+
+ /** Non-destructively inspect currently-pending events of a type. */
+ query(type: string): readonly EntityEvent[] {
+ return this.pending_.filter((e) => e.type === type);
+ }
+
+ /** Remove all handlers and pending events. */
+ clear(): void {
+ this.entityHandlers_.clear();
+ this.globalHandlers_.clear();
+ this.pending_ = [];
+ this.activeKeys_.clear();
+ }
+
+ private dispatch_(entity: Entity, event: EntityEvent): void {
+ // Re-entry guard: a handler that emits the same event on the same
+ // entity would recurse forever. Block recursion for (entity, type).
+ const key = `${entity as number}:${event.type}`;
+ if (this.activeKeys_.has(key)) return;
+ this.activeKeys_.add(key);
+
+ try {
+ const typeMap = this.entityHandlers_.get(entity);
+ if (typeMap) {
+ const set = typeMap.get(event.type);
+ if (set) {
+ // Snapshot so handler-side unsubscribe doesn't skip peers
+ for (const h of Array.from(set)) {
+ try {
+ h(event);
+ } catch (err) {
+ log.error(
+ 'ui',
+ `EntityEventQueue handler error [${event.type}]`,
+ err,
+ );
+ }
+ }
+ }
+ }
+
+ const global = this.globalHandlers_.get(event.type);
+ if (global) {
+ for (const h of Array.from(global)) {
+ try {
+ h(event);
+ } catch (err) {
+ log.error(
+ 'ui',
+ `EntityEventQueue handler error [${event.type}]`,
+ err,
+ );
+ }
+ }
+ }
+ } finally {
+ this.activeKeys_.delete(key);
+ }
+ }
+}
+
+/**
+ * Shared EntityEventQueue resource. A plugin inserts the authoritative
+ * instance on startup; systems access it via `Res(EntityEvents)`.
+ *
+ * The default value exists only so the resource is well-typed before
+ * the owning plugin constructs the real queue. Consumers should never
+ * see the placeholder at runtime — UIInteractionPlugin inserts its
+ * queue during `build()`.
+ */
+export const EntityEvents = defineResource<EntityEventQueue>(new EntityEventQueue(), 'EntityEvents');
diff --git a/sdk/src/eventBinding.ts b/sdk/src/eventBinding.ts
new file mode 100644
index 000000000..c4a6ec008
--- /dev/null
+++ b/sdk/src/eventBinding.ts
@@ -0,0 +1,335 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file eventBinding.ts
+ * @brief EventBinding — an authored wire from an entity event to a named action.
+ *
+ * The data form of `events.on(entity, 'click', …)`: a serializable component
+ * whose rows say "when THIS entity sees `click`, run the action named
+ * `ui.setPage` on `target`". It is deliberately a *wire*, not a program — there
+ * are no expressions, no branches, no scripts in the data. Anything with logic
+ * in it points at an action name, and a name can resolve to a whole `.esfsm`
+ * (via `fsm.fire`), which is where the engine already has a visual logic editor.
+ *
+ * Everything here reuses a seam that already exists rather than inventing a
+ * parallel one:
+ * · the event side is the entity event channel widgets already emit into
+ * ({@link EntityEventQueue}) — bubbling included, so a row on a panel hears
+ * its buttons;
+ * · the action side is the SAME `aiRegistry` that `.esfsm` state hooks and
+ * `.esbt` leaves resolve against, so one `registerAction` shows up in all
+ * three places and the editor palettes need no new source;
+ * · the target side resolves by NAME, nearest-first (self → subtree →
+ * ancestors' subtrees), mirroring how `UIGear` finds its controller.
+ * Nearest-wins is what keeps two instances of the same prefab from wiring
+ * into each other.
+ */
+import { defineComponent, Children, Name, Parent } from './component';
+import type { ChildrenData, NameData, ParentData } from './component';
+import type { App, Plugin } from './app';
+import type { Entity } from './types';
+import type { World } from './world';
+import { defineSystem, Schedule } from './system';
+import { Commands, type CommandsInstance } from './commands';
+import { Res, Time, type TimeData } from './resource';
+import { playModeOnly } from './env';
+import { log } from './logger';
+import { EntityEvents, EntityEventQueue, type EntityEvent, type Unsubscribe } from './entityEvents';
+import { Blackboard } from './ai/fsm/Blackboard';
+import { aiRegistry, type AiContext } from './ai/fsm/AiContext';
+import { AiFsm } from './ai/fsm/FsmPlugin';
+import { ensureBuiltinAiRegistrations } from './ai/builtins';
+
+/**
+ * One authored wire. `event` is an open string (the widget vocabulary lives in
+ * `UIEventType`, but any emitted name works); `action`/`guard` are
+ * `aiRegistry` names; `arg` is the action's per-reference argument, exactly as
+ * `.esfsm`/`.esbt` carry it.
+ */
+export interface EventBindingRow {
+ /** Event type to listen for on this entity, e.g. `'click'`. */
+ event: string;
+ /**
+ * Name of the entity the action runs on. Empty/omitted = the entity that
+ * carries the binding. Resolution is nearest-first, so a name inside a
+ * prefab instance finds that instance's copy.
+ */
+ target?: string;
+ /** Registered action name (`aiRegistry`), e.g. `'ui.setPage'`. */
+ action: string;
+ /** The action's argument, e.g. `'tabs:settings'`. */
+ arg?: string;
+ /** Registered condition name that must pass for the row to run. */
+ guard?: string;
+ /** Run at most once, then stay inert until the scene reloads. */
+ once?: boolean;
+ /** Authoring toggle — an unchecked row stays in the data but never fires. */
+ enabled?: boolean;
+}
+
+export interface EventBindingData {
+ rows: EventBindingRow[];
+}
+
+export const EventBinding = defineComponent<EventBindingData>('EventBinding', {
+ rows: [],
+});
+
+/**
+ * The entity named `name`, searched nearest-first from `from`: `from` itself,
+ * then its subtree, then each ancestor's subtree (skipping the branch already
+ * searched), and finally the world-wide name index as a fallback for scenes
+ * with no shared root. Returns null when nothing matches.
+ *
+ * Exported for tests and for editor-side parity checks.
+ */
+export function resolveBindingTarget(world: World, from: Entity, name: string): Entity | null {
+ if (!name) return from;
+
+ let node: Entity | null = from;
+ let skip: Entity | null = null;
+ while (node !== null && world.valid(node)) {
+ const hit = findInSubtree(world, node, name, skip);
+ if (hit !== null) return hit;
+ skip = node;
+ node = parentOf(world, node);
+ }
+ return world.findEntityByName(name);
+}
+
+function parentOf(world: World, entity: Entity): Entity | null {
+ if (!world.has(entity, Parent)) return null;
+ const parent = (world.get(entity, Parent) as ParentData).entity;
+ return world.valid(parent) ? parent : null;
+}
+
+function nameOf(world: World, entity: Entity): string {
+ return world.has(entity, Name) ? (world.get(entity, Name) as NameData).value : '';
+}
+
+/** Depth-first search of `root`'s subtree (root included), skipping one branch. */
+function findInSubtree(world: World, root: Entity, name: string, skip: Entity | null): Entity | null {
+ if (root === skip || !world.valid(root)) return null;
+ if (nameOf(world, root) === name) return root;
+ if (!world.has(root, Children)) return null;
+ for (const child of (world.get(root, Children) as ChildrenData).entities) {
+ const hit = findInSubtree(world, child as Entity, name, skip);
+ if (hit !== null) return hit;
+ }
+ return null;
+}
+
+/** What the dispatcher needs from its host — an App in production, fakes in tests. */
+export interface EventBindingHost {
+ world: World;
+ events: EntityEventQueue;
+ /** The blackboard actions read/write for `entity` (shared with the FSM layer). */
+ blackboardOf(entity: Entity): Blackboard;
+ /** Deferred structural ops for the action context; null outside a frame. */
+ commands(): CommandsInstance | null;
+ /** Current frame delta, for actions that care. */
+ dt(): number;
+}
+
+export interface EventBindingRuntime {
+ /** Re-subscribe to exactly the set of event types the scene now authors. */
+ sync(): void;
+ /** Drop every subscription and the `once` ledger. */
+ dispose(): void;
+}
+
+/**
+ * Runs authored rows when their event fires. Subscribes ONE global handler per
+ * distinct authored event type rather than one per (entity, event): rows can
+ * then be edited live — the editor rewrites the component and the next event
+ * reads the new data — and bubbling still reaches an ancestor's rows, because a
+ * bubbled event dispatches with `currentTarget` set to that ancestor.
+ */
+export function createEventBindingRuntime(host: EventBindingHost): EventBindingRuntime {
+ const { world, events } = host;
+ const subscriptions = new Map<string, Unsubscribe>();
+ /** Entity:row pairs already spent, for `once`. */
+ const fired = new Set<string>();
+
+ const runRow = (self: Entity, row: EventBindingRow): void => {
+ const action = aiRegistry.getAction(row.action);
+ if (!action) {
+ log.warn('events', `EventBinding: unknown action "${row.action}"`);
+ return;
+ }
+ const target = resolveBindingTarget(world, self, row.target ?? '');
+ if (target === null || !world.valid(target)) {
+ log.warn('events', `EventBinding: no entity named "${row.target}"`);
+ return;
+ }
+ const bb = host.blackboardOf(target);
+ const ctx: AiContext = {
+ entity: target,
+ dt: host.dt(),
+ blackboard: bb,
+ world,
+ commands: host.commands() as CommandsInstance,
+ get: (c) => world.get(target, c),
+ set: (c, d) => world.set(target, c, d),
+ has: (c) => world.has(target, c),
+ };
+ if (row.guard) {
+ const guard = aiRegistry.getCondition(row.guard);
+ if (!guard) {
+ log.warn('events', `EventBinding: unknown condition "${row.guard}"`);
+ return;
+ }
+ if (!guard(ctx, bb)) return;
+ }
+ action(ctx, bb, row.arg);
+ };
+
+ const handle = (event: EntityEvent): void => {
+ const self = event.currentTarget;
+ if (!world.valid(self) || !world.has(self, EventBinding)) return;
+ const data = world.get(self, EventBinding) as EventBindingData;
+ // Index-keyed `once`: reordering rows re-arms them, which is the same
+ // deal the rest of the authored-array surfaces (gears, tracks) offer.
+ for (let i = 0; i < data.rows.length; i++) {
+ const row = data.rows[i];
+ if (row.event !== event.type || row.enabled === false || !row.action) continue;
+ if (row.once) {
+ const key = `${self as number}:${i}`;
+ if (fired.has(key)) continue;
+ fired.add(key);
+ }
+ runRow(self, row);
+ }
+ };
+
+ return {
+ // Keep the subscribed type set equal to the union of authored types.
+ // Cheap (a set compare over a handful of components) and it makes rows
+ // added at runtime — a spawned prefab, an editor edit — live next frame.
+ sync(): void {
+ const wanted = new Set<string>();
+ for (const entity of world.getEntitiesWithComponents([EventBinding])) {
+ const data = world.get(entity, EventBinding) as EventBindingData;
+ for (const row of data.rows) {
+ if (row.event && row.action && row.enabled !== false) wanted.add(row.event);
+ }
+ }
+ for (const [type, off] of subscriptions) {
+ if (!wanted.has(type)) {
+ off();
+ subscriptions.delete(type);
+ }
+ }
+ for (const type of wanted) {
+ if (!subscriptions.has(type)) subscriptions.set(type, events.on(type, handle));
+ }
+ },
+ dispose(): void {
+ for (const off of subscriptions.values()) off();
+ subscriptions.clear();
+ fired.clear();
+ },
+ };
+}
+
+export class EventBindingPlugin implements Plugin {
+ name = 'eventBinding';
+
+ private runtime_: EventBindingRuntime | null = null;
+
+ build(app: App): void {
+ ensureBuiltinAiRegistrations();
+ ensureEventBindingActions();
+
+ const world = app.world;
+ // The queue belongs to whoever owns the event channel (the UI interaction
+ // plugin, today). Binding works with UI absent too — a physics trigger or
+ // game code can emit — so we insert one only if nobody has.
+ if (!app.hasResource(EntityEvents)) {
+ const queue = new EntityEventQueue();
+ app.insertResource(EntityEvents, queue);
+ world.onDespawn((e: Entity) => queue.removeAll(e));
+ }
+
+ // Blackboards are shared with the FSM layer when it is present, so a
+ // `fsm.fire` from a click lands in the very blackboard the entity's
+ // StateMachineAgent reads — the click → state-machine hand-off.
+ const localBoards = new Map<Entity, Blackboard>();
+ world.onDespawn((e: Entity) => localBoards.delete(e));
+
+ let commands_: CommandsInstance | null = null;
+ let dt_ = 0;
+
+ const runtime = createEventBindingRuntime({
+ world,
+ events: app.getResource(EntityEvents) as EntityEventQueue,
+ blackboardOf: (entity) => {
+ const fsm = app.hasResource(AiFsm) ? app.getResource(AiFsm) : null;
+ if (fsm) return fsm.blackboard(entity);
+ let bb = localBoards.get(entity);
+ if (!bb) localBoards.set(entity, (bb = new Blackboard()));
+ return bb;
+ },
+ commands: () => commands_,
+ dt: () => dt_,
+ });
+ this.runtime_ = runtime;
+
+ app.addSystemToSchedule(
+ Schedule.PreUpdate,
+ defineSystem(
+ [Res(Time), Commands()],
+ (time: TimeData, commands: CommandsInstance) => {
+ dt_ = time.delta;
+ commands_ = commands;
+ runtime.sync();
+ },
+ { name: 'EventBindingSystem' },
+ ),
+ { runIf: playModeOnly },
+ );
+ }
+
+ cleanup(): void {
+ this.runtime_?.dispose();
+ this.runtime_ = null;
+ }
+}
+
+/**
+ * Actions that only make sense once events can drive them. Registered with the
+ * same idempotent, game-wins policy as the other builtins.
+ *
+ * `fsm.fire` is the escape hatch that keeps the wire from growing into a
+ * language: a click fires a trigger, and the entity's `.esfsm` — the actual
+ * visual logic editor — decides what that means.
+ */
+export function ensureEventBindingActions(): void {
+ if (!aiRegistry.hasAction('fsm.fire')) {
+ aiRegistry.registerAction('fsm.fire', (_ctx, bb, arg) => {
+ if (arg) bb.fire(arg);
+ });
+ }
+ if (!aiRegistry.hasAction('blackboard.set')) {
+ // `key=value` — value parsed as JSON when it can be (numbers, booleans),
+ // else kept as the raw string, so both `hp=3` and `mode=hard` do the
+ // obvious thing.
+ aiRegistry.registerAction('blackboard.set', (_ctx, bb, arg) => {
+ if (!arg) return;
+ const eq = arg.indexOf('=');
+ if (eq < 0) return;
+ const key = arg.slice(0, eq).trim();
+ const raw = arg.slice(eq + 1).trim();
+ if (!key) return;
+ let value: unknown = raw;
+ try {
+ value = JSON.parse(raw);
+ } catch {
+ /* a bare word is its own value */
+ }
+ bb.set(key, value);
+ });
+ }
+}
+
+export const eventBindingPlugin = new EventBindingPlugin();
diff --git a/sdk/src/ui/core/events.ts b/sdk/src/ui/core/events.ts
index cdf6a9622..cecdb9888 100644
--- a/sdk/src/ui/core/events.ts
+++ b/sdk/src/ui/core/events.ts
@@ -1,8 +1,23 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import { defineResource } from '../../resource';
-import type { Entity } from '../../types';
-import { log } from '../../logger';
+/**
+ * @file ui/core/events.ts
+ * @brief The UI's vocabulary over the engine's entity event channel.
+ *
+ * The queue itself is not UI-specific and lives in `entityEvents.ts` (so the
+ * core binding layer and non-UI producers can speak it without importing
+ * `ui/`); the names below are aliases of those very objects — one queue, one
+ * resource, two spellings. What IS UI-specific is {@link UIEventType}: the set
+ * of type strings the built-in widgets emit.
+ */
+// The queue class and the shared resource, under their UI-facing names — the
+// same objects, so `Res(UIEvents)` and `Res(EntityEvents)` resolve identically.
+export { EntityEventQueue as UIEventQueue, EntityEvents as UIEvents } from '../../entityEvents';
+export type {
+ EntityEvent as UIEvent,
+ EntityEventHandler as UIEventHandler,
+ Unsubscribe,
+} from '../../entityEvents';
/**
* Common UI event types. Event type strings are open — users may emit any
@@ -33,260 +48,3 @@ export const UIEventType = {
* to this type when they only handle built-ins.
*/
export type UIEventType = typeof UIEventType[keyof typeof UIEventType];
-
-export interface UIEvent<TData = unknown> {
- /** Event type string (e.g. `'click'`, `'change'`). */
- readonly type: string;
- /** The entity where the event originated. */
- readonly target: Entity;
- /** The entity currently handling the event (differs from target during bubbling). */
- readonly currentTarget: Entity;
- /** User-provided payload (shape depends on `type`). */
- readonly data: TData;
- /** True if any handler called `stopPropagation()`. */
- propagationStopped: boolean;
- /** True if any handler called `preventDefault()`. */
- defaultPrevented: boolean;
- /** Stop the event from bubbling further up the parent chain. */
- stopPropagation(): void;
- /** Signal that the default action (if any) should be skipped. */
- preventDefault(): void;
-}
-
-export type UIEventHandler<TData = unknown> = (event: UIEvent<TData>) => void;
-export type Unsubscribe = () => void;
-
-/**
- * UI event queue: pub/sub with bubbling support.
- *
- * @example
- * ```ts
- * const events = new UIEventQueue();
- * world.onDespawn(e => events.removeAll(e)); // one-time wiring
- *
- * events.on(buttonEntity, 'click', e => console.log('clicked'));
- * events.emit(buttonEntity, 'click');
- * ```
- */
-export class UIEventQueue {
- private readonly entityHandlers_ = new Map<
- Entity,
- Map<string, Set<UIEventHandler>>
- >();
- private readonly globalHandlers_ = new Map<string, Set<UIEventHandler>>();
- private pending_: UIEvent[] = [];
- private readonly activeKeys_ = new Set<string>();
-
- /**
- * Subscribe to an entity-specific event.
- * Returns an unsubscribe function.
- */
- on(entity: Entity, type: string, handler: UIEventHandler): Unsubscribe;
- /**
- * Subscribe to all events of a type, from any entity.
- */
- on(type: string, handler: UIEventHandler): Unsubscribe;
- on(
- arg1: Entity | string,
- arg2: string | UIEventHandler,
- arg3?: UIEventHandler,
- ): Unsubscribe {
- // Entity-specific: on(entity, type, handler)
- if (typeof arg1 === 'number' && typeof arg2 === 'string' && typeof arg3 === 'function') {
- const entity = arg1 as Entity;
- const type = arg2;
- const handler = arg3;
-
- let typeMap = this.entityHandlers_.get(entity);
- if (!typeMap) {
- typeMap = new Map();
- this.entityHandlers_.set(entity, typeMap);
- }
- let set = typeMap.get(type);
- if (!set) {
- set = new Set();
- typeMap.set(type, set);
- }
- set.add(handler);
-
- return () => {
- const tm = this.entityHandlers_.get(entity);
- const s = tm?.get(type);
- if (s) {
- s.delete(handler);
- if (s.size === 0) tm!.delete(type);
- if (tm && tm.size === 0) this.entityHandlers_.delete(entity);
- }
- };
- }
-
- // Global: on(type, handler)
- const type = arg1 as string;
- const handler = arg2 as UIEventHandler;
-
- let set = this.globalHandlers_.get(type);
- if (!set) {
- set = new Set();
- this.globalHandlers_.set(type, set);
- }
- set.add(handler);
-
- return () => {
- const s = this.globalHandlers_.get(type);
- if (s) {
- s.delete(handler);
- if (s.size === 0) this.globalHandlers_.delete(type);
- }
- };
- }
-
- /**
- * Remove all entity-specific handlers for `entity`.
- * Wire this to `world.onDespawn` for automatic cleanup.
- */
- removeAll(entity: Entity): void {
- this.entityHandlers_.delete(entity);
- }
-
- /**
- * Emit an event for `entity`. Synchronously dispatches to registered
- * handlers and queues the event for `drain()` / `query()`. Returns the
- * event so callers can inspect propagationStopped / defaultPrevented
- * (e.g. to drive bubbling to parents).
- */
- emit<TData = unknown>(
- entity: Entity,
- type: string,
- data?: TData,
- ): UIEvent<TData> {
- const event: UIEvent<TData> = {
- type,
- target: entity,
- currentTarget: entity,
- data: data as TData,
- propagationStopped: false,
- defaultPrevented: false,
- stopPropagation() {
- this.propagationStopped = true;
- },
- preventDefault() {
- this.defaultPrevented = true;
- },
- };
- this.pending_.push(event);
- this.dispatch_(entity, event);
- return event;
- }
-
- /**
- * Emit a bubbled event to an ancestor. Shares propagation state with
- * the root event: calling stopPropagation on the bubbled event marks
- * the root as stopped so callers can halt the bubbling walk.
- *
- * Callers are responsible for walking the parent chain; this queue
- * does not know about hierarchy.
- */
- emitBubbled(ancestor: Entity, rootEvent: UIEvent): UIEvent {
- if (rootEvent.propagationStopped) return rootEvent;
-
- const bubbled: UIEvent = {
- type: rootEvent.type,
- target: rootEvent.target,
- currentTarget: ancestor,
- data: rootEvent.data,
- propagationStopped: false,
- defaultPrevented: rootEvent.defaultPrevented,
- stopPropagation() {
- this.propagationStopped = true;
- rootEvent.propagationStopped = true;
- },
- preventDefault() {
- this.defaultPrevented = true;
- (rootEvent as { defaultPrevented: boolean }).defaultPrevented = true;
- },
- };
- this.pending_.push(bubbled);
- this.dispatch_(ancestor, bubbled);
- return bubbled;
- }
-
- /**
- * Return all events queued since the last drain and clear the queue.
- * Typically called once per frame by a UI system.
- */
- drain(): readonly UIEvent[] {
- const events = this.pending_;
- this.pending_ = [];
- return events;
- }
-
- /** Non-destructively inspect currently-pending events of a type. */
- query(type: string): readonly UIEvent[] {
- return this.pending_.filter((e) => e.type === type);
- }
-
- /** Remove all handlers and pending events. */
- clear(): void {
- this.entityHandlers_.clear();
- this.globalHandlers_.clear();
- this.pending_ = [];
- this.activeKeys_.clear();
- }
-
- private dispatch_(entity: Entity, event: UIEvent): void {
- // Re-entry guard: a handler that emits the same event on the same
- // entity would recurse forever. Block recursion for (entity, type).
- const key = `${entity as number}:${event.type}`;
- if (this.activeKeys_.has(key)) return;
- this.activeKeys_.add(key);
-
- try {
- const typeMap = this.entityHandlers_.get(entity);
- if (typeMap) {
- const set = typeMap.get(event.type);
- if (set) {
- // Snapshot so handler-side unsubscribe doesn't skip peers
- for (const h of Array.from(set)) {
- try {
- h(event);
- } catch (err) {
- log.error(
- 'ui',
- `UIEventQueue handler error [${event.type}]`,
- err,
- );
- }
- }
- }
- }
-
- const global = this.globalHandlers_.get(event.type);
- if (global) {
- for (const h of Array.from(global)) {
- try {
- h(event);
- } catch (err) {
- log.error(
- 'ui',
- `UIEventQueue handler error [${event.type}]`,
- err,
- );
- }
- }
- }
- } finally {
- this.activeKeys_.delete(key);
- }
- }
-}
-
-/**
- * Shared UIEventQueue resource. A plugin inserts the authoritative
- * instance on startup; systems access it via `Res(UIEvents)`.
- *
- * The default value exists only so the resource is well-typed before
- * the owning plugin constructs the real queue. Consumers should never
- * see the placeholder at runtime — UIInteractionPlugin inserts its
- * queue during `build()`.
- */
-export const UIEvents = defineResource<UIEventQueue>(new UIEventQueue(), 'UIEvents');
diff --git a/sdk/src/webAppFactory.ts b/sdk/src/webAppFactory.ts
index 5791e3491..3f266d2c2 100644
--- a/sdk/src/webAppFactory.ts
+++ b/sdk/src/webAppFactory.ts
@@ -20,6 +20,7 @@ import { timerPlugin } from './timer';
import { velocityPlugin } from './velocity';
import { lifecyclePlugin } from './lifecycle';
import { navPlugin, fsmPlugin, btPlugin, perceptionPlugin } from './ai';
+import { eventBindingPlugin } from './eventBinding';
import { replicationPlugin } from './net/replication';
import { SpinePlugin } from './spine';
import { createFetchSideModuleHost, type SideModuleHost } from './sideModules';
@@ -36,7 +37,7 @@ export interface CreateWebAppOptions extends WebAppOptions {
wasmBaseUrl?: string;
}
-const basePlugins = [timerPlugin, velocityPlugin, lifecyclePlugin, animationPlugin, audioPlugin, videoPlugin, particlePlugin, trailPlugin, mesh2dPlugin, tilemapPlugin, postProcessPlugin, timelinePlugin, perceptionPlugin, fsmPlugin, btPlugin, navPlugin, replicationPlugin];
+const basePlugins = [timerPlugin, velocityPlugin, lifecyclePlugin, animationPlugin, audioPlugin, videoPlugin, particlePlugin, trailPlugin, mesh2dPlugin, tilemapPlugin, postProcessPlugin, timelinePlugin, perceptionPlugin, fsmPlugin, btPlugin, navPlugin, eventBindingPlugin, replicationPlugin];
export function createWebApp(module: ESEngineModule, options?: CreateWebAppOptions): App {
const sideModules: SideModuleHost | undefined = options?.sideModules
@@ -61,7 +62,7 @@ export interface HeadlessAppOptions {
* native factories, so neither drifts into its own plugin list. */
export const headlessBasePlugins = (): Plugin[] => [
timerPlugin, velocityPlugin, lifecyclePlugin, audioPlugin,
- perceptionPlugin, fsmPlugin, btPlugin, navPlugin, replicationPlugin,
+ perceptionPlugin, fsmPlugin, btPlugin, navPlugin, eventBindingPlugin, replicationPlugin,
];
/**
diff --git a/sdk/tests/event-binding.test.ts b/sdk/tests/event-binding.test.ts
new file mode 100644
index 000000000..1ed2cb127
--- /dev/null
+++ b/sdk/tests/event-binding.test.ts
@@ -0,0 +1,324 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file event-binding.test.ts
+ * @brief Authored event → action wiring: target resolution (nearest-name),
+ * dispatch through the shared aiRegistry, guards/once/enabled, and
+ * bubbling from a child into an ancestor's rows.
+ */
+import { beforeEach, describe, expect, it } from 'vitest';
+import { EntityEventQueue } from '../src/entityEvents';
+import {
+ EventBinding,
+ createEventBindingRuntime,
+ ensureEventBindingActions,
+ resolveBindingTarget,
+ type EventBindingRow,
+} from '../src/eventBinding';
+import { Blackboard } from '../src/ai/fsm/Blackboard';
+import { aiRegistry } from '../src/ai/fsm/AiContext';
+import { Children, Name, Parent } from '../src/component';
+import type { AnyComponentDef } from '../src/component';
+import type { Entity } from '../src/types';
+
+/** A world stub with just the slice EventBinding touches (+ hierarchy helpers). */
+function makeWorld() {
+ const storage = new Map<AnyComponentDef, Map<Entity, unknown>>();
+ const alive = new Set<Entity>();
+ let next = 1;
+ const storeFor = (c: AnyComponentDef) => {
+ let s = storage.get(c);
+ if (!s) storage.set(c, (s = new Map()));
+ return s;
+ };
+ const world = {
+ spawn: (name?: string) => {
+ const e = next++ as Entity;
+ alive.add(e);
+ if (name !== undefined) storeFor(Name).set(e, { value: name });
+ return e;
+ },
+ despawn: (e: Entity) => alive.delete(e),
+ valid: (e: Entity) => alive.has(e),
+ has: (e: Entity, c: AnyComponentDef) => storeFor(c).has(e),
+ get: (e: Entity, c: AnyComponentDef) => storeFor(c).get(e),
+ set: (e: Entity, c: AnyComponentDef, d: unknown) => storeFor(c).set(e, d),
+ insert: (e: Entity, c: AnyComponentDef, d: unknown) => storeFor(c).set(e, d),
+ getEntitiesWithComponents: (comps: readonly AnyComponentDef[]) =>
+ [...storeFor(comps[0]).keys()].filter((e) => alive.has(e)),
+ findEntityByName: (name: string) => {
+ for (const [e, d] of storeFor(Name)) {
+ if ((d as { value: string }).value === name && alive.has(e)) return e;
+ }
+ return null;
+ },
+ /** Test helper: attach `child` under `parent`, maintaining both sides. */
+ parent: (child: Entity, parent: Entity) => {
+ storeFor(Parent).set(child, { entity: parent });
+ const kids = (storeFor(Children).get(parent) as { entities: Entity[] } | undefined) ?? { entities: [] };
+ kids.entities.push(child);
+ storeFor(Children).set(parent, kids);
+ },
+ };
+ return world;
+}
+type TestWorld = ReturnType<typeof makeWorld>;
+
+function bind(world: TestWorld, entity: Entity, ...rows: EventBindingRow[]): void {
+ world.insert(entity, EventBinding, { rows });
+}
+
+/** Runtime over a fresh queue, wired to per-entity throwaway blackboards. */
+function makeRuntime(world: TestWorld) {
+ const events = new EntityEventQueue();
+ const boards = new Map<Entity, Blackboard>();
+ const runtime = createEventBindingRuntime({
+ world: world as never,
+ events,
+ blackboardOf: (e) => {
+ let bb = boards.get(e);
+ if (!bb) boards.set(e, (bb = new Blackboard()));
+ return bb;
+ },
+ commands: () => null,
+ dt: () => 1 / 60,
+ });
+ return { events, runtime, boards };
+}
+
+/** Records (entity, arg) for every invocation of the test action. */
+let calls: Array<{ entity: Entity; arg?: string }> = [];
+
+beforeEach(() => {
+ calls = [];
+ aiRegistry.registerAction('test.record', (ctx, _bb, arg) => {
+ calls.push({ entity: ctx.entity, arg });
+ });
+ aiRegistry.registerCondition('test.never', () => false);
+ aiRegistry.registerCondition('test.always', () => true);
+});
+
+describe('resolveBindingTarget — nearest name wins', () => {
+ it('empty target is the entity that carries the binding', () => {
+ const world = makeWorld();
+ const self = world.spawn('Button');
+ expect(resolveBindingTarget(world as never, self, '')).toBe(self);
+ });
+
+ it('finds a sibling through the shared parent', () => {
+ const world = makeWorld();
+ const root = world.spawn('Root');
+ const button = world.spawn('Button');
+ const panel = world.spawn('Panel');
+ world.parent(button, root);
+ world.parent(panel, root);
+ expect(resolveBindingTarget(world as never, button, 'Panel')).toBe(panel);
+ });
+
+ it('prefers the match inside its own subtree over an outer one', () => {
+ // Two prefab instances, each with a "Panel": a binding inside instance A
+ // must not reach into instance B.
+ const world = makeWorld();
+ const root = world.spawn('Root');
+ const instA = world.spawn('Dialog');
+ const instB = world.spawn('Dialog');
+ world.parent(instA, root);
+ world.parent(instB, root);
+ const panelA = world.spawn('Panel');
+ const panelB = world.spawn('Panel');
+ world.parent(panelA, instA);
+ world.parent(panelB, instB);
+ const buttonA = world.spawn('Close');
+ world.parent(buttonA, instA);
+
+ expect(resolveBindingTarget(world as never, buttonA, 'Panel')).toBe(panelA);
+ });
+
+ it('falls back to the world name index for an unrelated root', () => {
+ const world = makeWorld();
+ const button = world.spawn('Button');
+ const hud = world.spawn('HUD'); // no shared ancestor
+ expect(resolveBindingTarget(world as never, button, 'HUD')).toBe(hud);
+ });
+
+ it('returns null when nothing is named that', () => {
+ const world = makeWorld();
+ const button = world.spawn('Button');
+ expect(resolveBindingTarget(world as never, button, 'Nope')).toBeNull();
+ });
+});
+
+describe('dispatch', () => {
+ it('runs the row action on click, with the row arg', () => {
+ const world = makeWorld();
+ const button = world.spawn('Button');
+ bind(world, button, { event: 'click', action: 'test.record', arg: 'tabs:settings' });
+
+ const { events, runtime } = makeRuntime(world);
+ runtime.sync();
+ events.emit(button, 'click');
+
+ expect(calls).toEqual([{ entity: button, arg: 'tabs:settings' }]);
+ });
+
+ it('runs the action on the NAMED target, not on the emitter', () => {
+ const world = makeWorld();
+ const root = world.spawn('Root');
+ const button = world.spawn('Button');
+ const dialog = world.spawn('Dialog');
+ world.parent(button, root);
+ world.parent(dialog, root);
+ bind(world, button, { event: 'click', action: 'test.record', target: 'Dialog' });
+
+ const { events, runtime } = makeRuntime(world);
+ runtime.sync();
+ events.emit(button, 'click');
+
+ expect(calls).toEqual([{ entity: dialog, arg: undefined }]);
+ });
+
+ it('ignores events of other types and rows that are disabled', () => {
+ const world = makeWorld();
+ const button = world.spawn('Button');
+ bind(
+ world,
+ button,
+ { event: 'click', action: 'test.record', arg: 'on' },
+ { event: 'click', action: 'test.record', arg: 'off', enabled: false },
+ );
+
+ const { events, runtime } = makeRuntime(world);
+ runtime.sync();
+ events.emit(button, 'hover_enter');
+ events.emit(button, 'click');
+
+ expect(calls.map((c) => c.arg)).toEqual(['on']);
+ });
+
+ it('honours a guard condition', () => {
+ const world = makeWorld();
+ const button = world.spawn('Button');
+ bind(
+ world,
+ button,
+ { event: 'click', action: 'test.record', arg: 'blocked', guard: 'test.never' },
+ { event: 'click', action: 'test.record', arg: 'allowed', guard: 'test.always' },
+ );
+
+ const { events, runtime } = makeRuntime(world);
+ runtime.sync();
+ events.emit(button, 'click');
+
+ expect(calls.map((c) => c.arg)).toEqual(['allowed']);
+ });
+
+ it('a `once` row fires exactly once', () => {
+ const world = makeWorld();
+ const button = world.spawn('Button');
+ bind(world, button, { event: 'click', action: 'test.record', once: true });
+
+ const { events, runtime } = makeRuntime(world);
+ runtime.sync();
+ events.emit(button, 'click');
+ events.emit(button, 'click');
+
+ expect(calls).toHaveLength(1);
+ });
+
+ it('an ancestor row hears a bubbled child event', () => {
+ const world = makeWorld();
+ const panel = world.spawn('Panel');
+ const button = world.spawn('Button');
+ world.parent(button, panel);
+ bind(world, panel, { event: 'click', action: 'test.record', arg: 'from-panel' });
+
+ const { events, runtime } = makeRuntime(world);
+ runtime.sync();
+ const root = events.emit(button, 'click'); // the child has no rows
+ events.emitBubbled(panel, root); // the interaction layer bubbles
+
+ expect(calls.map((c) => c.arg)).toEqual(['from-panel']);
+ });
+
+ it('picks up rows authored after the last sync only once re-synced', () => {
+ const world = makeWorld();
+ const button = world.spawn('Button');
+ const { events, runtime } = makeRuntime(world);
+ runtime.sync(); // nothing authored yet
+
+ bind(world, button, { event: 'click', action: 'test.record' });
+ events.emit(button, 'click');
+ expect(calls).toHaveLength(0);
+
+ runtime.sync(); // the per-frame pass the plugin runs
+ events.emit(button, 'click');
+ expect(calls).toHaveLength(1);
+ });
+
+ it('stops dispatching after dispose', () => {
+ const world = makeWorld();
+ const button = world.spawn('Button');
+ bind(world, button, { event: 'click', action: 'test.record' });
+
+ const { events, runtime } = makeRuntime(world);
+ runtime.sync();
+ runtime.dispose();
+ events.emit(button, 'click');
+
+ expect(calls).toHaveLength(0);
+ });
+
+ it('survives an unknown action / missing target without throwing', () => {
+ const world = makeWorld();
+ const button = world.spawn('Button');
+ bind(
+ world,
+ button,
+ { event: 'click', action: 'no.such.action' },
+ { event: 'click', action: 'test.record', target: 'Ghost' },
+ );
+
+ const { events, runtime } = makeRuntime(world);
+ runtime.sync();
+ expect(() => events.emit(button, 'click')).not.toThrow();
+ expect(calls).toHaveLength(0);
+ });
+});
+
+describe('the actions events unlock', () => {
+ it('fsm.fire raises a trigger on the target blackboard', () => {
+ ensureEventBindingActions();
+ const world = makeWorld();
+ const root = world.spawn('Root');
+ const button = world.spawn('Button');
+ const hero = world.spawn('Hero');
+ world.parent(button, root);
+ world.parent(hero, root);
+ bind(world, button, { event: 'click', action: 'fsm.fire', arg: 'start', target: 'Hero' });
+
+ const { events, runtime, boards } = makeRuntime(world);
+ runtime.sync();
+ events.emit(button, 'click');
+
+ expect(boards.get(hero)?.isFired('start')).toBe(true);
+ });
+
+ it('blackboard.set parses JSON values, keeps bare words', () => {
+ ensureEventBindingActions();
+ const world = makeWorld();
+ const button = world.spawn('Button');
+ bind(
+ world,
+ button,
+ { event: 'click', action: 'blackboard.set', arg: 'lives=3' },
+ { event: 'click', action: 'blackboard.set', arg: 'mode=hard' },
+ );
+
+ const { events, runtime, boards } = makeRuntime(world);
+ runtime.sync();
+ events.emit(button, 'click');
+
+ expect(boards.get(button)?.get('lives')).toBe(3);
+ expect(boards.get(button)?.get('mode')).toBe('hard');
+ });
+});