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(ui): data-driven bridges into controllers — ui.setPage + bindControllerPage

yhh330aaebef4fb
diff --git a/examples/ui-controller/src/systems/build.ts b/examples/ui-controller/src/systems/build.ts
index 528168c1d..c54093aa4 100644
--- a/examples/ui-controller/src/systems/build.ts
+++ b/examples/ui-controller/src/systems/build.ts
@@ -17,8 +17,8 @@ import {
Transform, UIVisual, Interactable, UIInteraction,
spawnUIEntity, px, percent, UIPositionType,
UIController, UIGear, interactionController, controllerState,
- setControllerPage, getControllerPage, gearBinding,
- EasingType,
+ setControllerPage, getControllerPage, gearBinding, bindControllerPage,
+ signal, EasingType,
} from 'esengine';
import type { Entity, World, Color, UIEventQueue } from 'esengine';
@@ -80,6 +80,12 @@ export const buildSystem = defineSystem(
// ── 1. Tab bar ───────────────────────────────────────────────────────────────
function buildTabBar(world: World, events: UIEventQueue, canvas: Entity): void {
+ // Data-driven: a signal names the active tab, bound to the 'tab' controller.
+ // Clicks set the signal (the data model); the controller follows and every
+ // geared element reflows — the same shape as binding UI to any game state.
+ const activeTab = signal<string>('overview');
+ bindControllerPage(world, canvas, 'tab', activeTab);
+
TAB_PAGES.forEach((page, i) => {
const btn = panel(world, canvas, {
width: 150, height: 40, top: 96, centerOffsetX: (i - 1) * 160,
@@ -96,7 +102,7 @@ function buildTabBar(world: World, events: UIEventQueue, canvas: Entity): void {
{ easing: EasingType.EaseOutCubic, duration: 0.12 })],
});
- events.on(btn, 'click', () => setControllerPage(world, canvas, 'tab', page));
+ events.on(btn, 'click', () => activeTab.set(page));
});
}
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 50334e225..76bd04694 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: 1203 stable · 17 beta · 1 deprecated
+Symbols: 1204 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -7531,6 +7531,11 @@ AudioPlugin
<C extends object, K extends keyof C>(world: World, entity: Entity, component: ComponentDef<C>, field: K, source: ReadonlySignal<C[K]>): () => void
```
+## bindControllerPage — function
+```
+(world: World, entity: Entity, controller: string, source: ReadonlySignal<string>): () => void
+```
+
## btEdges — function
```
(def: BtDefinition): BtEdge[]
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index c4f6e14d2..f850b1f46 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: 1202 stable · 19 beta · 1 deprecated
+Symbols: 1203 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -7526,6 +7526,11 @@ AudioPlugin
<C extends object, K extends keyof C>(world: World, entity: Entity, component: ComponentDef<C>, field: K, source: ReadonlySignal<C[K]>): () => void
```
+## bindControllerPage — function
+```
+(world: World, entity: Entity, controller: string, source: ReadonlySignal<string>): () => void
+```
+
## btEdges — function
```
(def: BtDefinition): BtEdge[]
diff --git a/sdk/src/core-ui.ts b/sdk/src/core-ui.ts
index 585f32ce4..a292f0adb 100644
--- a/sdk/src/core-ui.ts
+++ b/sdk/src/core-ui.ts
@@ -122,6 +122,7 @@ export {
setControllerPage,
getControllerPage,
findControllerOwner,
+ bindControllerPage,
type UIControllerData,
type ControllerState,
type UIGearData,
diff --git a/sdk/src/ui/controller/ai-builtins.ts b/sdk/src/ui/controller/ai-builtins.ts
new file mode 100644
index 000000000..b2d681a25
--- /dev/null
+++ b/sdk/src/ui/controller/ai-builtins.ts
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui/controller/ai-builtins.ts
+ * @brief The .esfsm / .esbt → UIController bridge.
+ *
+ * Registers `ui.setPage` on the shared AI registry so data-driven behavior can
+ * switch a controller's page with no code — the logic-layer half of the layering
+ * `.esfsm (logic) → UIController (state) → UIGear (presentation)`, exactly the
+ * shape of the built-in `timeline.play` / `spriteAnim.play` glue. Registered from
+ * the UI side (ui → ai, one direction) so the `ai` module never learns about UI;
+ * idempotent and namespaced, so game-registered names always win.
+ */
+import { aiRegistry } from '../../ai/fsm/AiContext';
+import { setControllerPage } from './ui-controller';
+
+/**
+ * Idempotently register the UI AI glue. `ui.setPage` takes an arg `"controller:page"`
+ * and switches the nearest controller of that name (self → ancestors) to the page,
+ * guarding unknown controllers/pages (a no-op, same as {@link setControllerPage}).
+ * Called when the controller plugin builds (and re-called after an aiRegistry clear).
+ */
+export function ensureControllerAiRegistrations(): void {
+ if (aiRegistry.hasAction('ui.setPage')) return;
+ aiRegistry.registerAction('ui.setPage', (ctx, _bb, arg) => {
+ if (!arg) return;
+ const sep = arg.indexOf(':');
+ if (sep < 0) return;
+ setControllerPage(ctx.world, ctx.entity, arg.slice(0, sep), arg.slice(sep + 1));
+ });
+}
diff --git a/sdk/src/ui/controller/bind-page.ts b/sdk/src/ui/controller/bind-page.ts
new file mode 100644
index 000000000..3b753122a
--- /dev/null
+++ b/sdk/src/ui/controller/bind-page.ts
@@ -0,0 +1,53 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui/controller/bind-page.ts
+ * @brief bindControllerPage — drive a controller's page from a Signal.
+ *
+ * The data-layer bridge into a controller: a reactive value (see binding/signal)
+ * that names the current page, applied now and on every change. This is the
+ * declarative path to a data-driven tab bar / view switcher — set the signal, the
+ * controller switches page, and every geared element reflows. Mirrors `bind`
+ * (seed + subscribe + auto-dispose on despawn); the target is a controller's
+ * `current` rather than a plain component field, so it goes through
+ * {@link setControllerPage} instead of a raw insert.
+ */
+import type { World } from '../../world';
+import type { Entity } from '../../types';
+import type { ReadonlySignal } from '../binding/signal';
+import { setControllerPage } from './ui-controller';
+
+/**
+ * Bind `source` (a page name) to the nearest controller named `controller`
+ * (self → ancestors from `entity`): applied now and on every change. Unknown
+ * pages/controllers are ignored (see {@link setControllerPage}); the binding tears
+ * itself down when `entity` despawns. Returns a dispose to unbind early.
+ */
+export function bindControllerPage(
+ world: World,
+ entity: Entity,
+ controller: string,
+ source: ReadonlySignal<string>,
+): () => void {
+ let disposed = false;
+
+ const apply = (page: string): void => {
+ if (disposed || !world.valid(entity)) return;
+ setControllerPage(world, entity, controller, page);
+ };
+
+ apply(source.get()); // seed the controller with the current page
+
+ const unsub = source.subscribe(apply);
+ const dispose = (): void => {
+ if (disposed) return;
+ disposed = true;
+ unsub();
+ offDespawn();
+ };
+ const offDespawn = world.onDespawn((e) => {
+ if (e === entity) dispose();
+ });
+
+ return dispose;
+}
diff --git a/sdk/src/ui/controller/index.ts b/sdk/src/ui/controller/index.ts
index 8559feadd..71dcee8b0 100644
--- a/sdk/src/ui/controller/index.ts
+++ b/sdk/src/ui/controller/index.ts
@@ -35,4 +35,7 @@ export {
lerpGearValue,
} from './gear-apply';
+export { bindControllerPage } from './bind-page';
+export { ensureControllerAiRegistrations } from './ai-builtins';
+
export { UIControllerPlugin, uiControllerPlugin } from './plugin';
diff --git a/sdk/src/ui/controller/plugin.ts b/sdk/src/ui/controller/plugin.ts
index cdf3092f6..8ecd39a92 100644
--- a/sdk/src/ui/controller/plugin.ts
+++ b/sdk/src/ui/controller/plugin.ts
@@ -14,11 +14,16 @@ import type { App, Plugin } from '../../app';
import { Schedule } from '../../system';
import { SystemLabel } from '../../systemLabels';
import { createGearApplySystem, createInteractionControllerDriverSystem } from './gear-apply';
+import { ensureControllerAiRegistrations } from './ai-builtins';
export class UIControllerPlugin implements Plugin {
name = 'uiController';
build(app: App): void {
+ // Register the `.esfsm`/`.esbt` → controller glue (idempotent) so a
+ // data-driven state machine can drive `ui.setPage`.
+ ensureControllerAiRegistrations();
+
app.addSystemToSchedule(
Schedule.Update,
createInteractionControllerDriverSystem(app.world),
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index 0176a1a0b..c1859ca57 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -182,6 +182,9 @@ export {
lerpGearValue,
} from './controller/gear-apply';
+export { bindControllerPage } from './controller/bind-page';
+export { ensureControllerAiRegistrations } from './controller/ai-builtins';
+
export { UIControllerPlugin, uiControllerPlugin } from './controller/plugin';
// ─── Collection ─────────────────────────────────────────────────────────────
diff --git a/sdk/tests/ui-controller-bridges.test.ts b/sdk/tests/ui-controller-bridges.test.ts
new file mode 100644
index 000000000..c7e942535
--- /dev/null
+++ b/sdk/tests/ui-controller-bridges.test.ts
@@ -0,0 +1,105 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui-controller-bridges.test.ts
+ * @brief The data-driven bridges into a controller: the `ui.setPage` .esfsm
+ * action and the reactive bindControllerPage(signal) binding.
+ */
+import { describe, expect, it } from 'vitest';
+import { aiRegistry } from '../src/ai/fsm/AiContext';
+import { UIController, controllerState, getControllerPage } from '../src/ui/controller/ui-controller';
+import { ensureControllerAiRegistrations } from '../src/ui/controller/ai-builtins';
+import { bindControllerPage } from '../src/ui/controller/bind-page';
+import { signal } from '../src/ui/binding/signal';
+import type { Entity } from '../src/types';
+import type { AnyComponentDef } from '../src/component';
+
+function makeMockWorld() {
+ const storage = new Map<AnyComponentDef, Map<Entity, unknown>>();
+ const alive = new Set<Entity>();
+ const despawnSubs = new Set<(e: Entity) => void>();
+ let next = 1;
+ const storeFor = (c: AnyComponentDef) => {
+ let s = storage.get(c);
+ if (!s) { s = new Map(); storage.set(c, s); }
+ return s;
+ };
+ return {
+ spawn: () => { const e = next++ as Entity; alive.add(e); return e; },
+ despawn: (e: Entity) => { alive.delete(e); for (const fn of [...despawnSubs]) fn(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),
+ insert: (e: Entity, c: AnyComponentDef, d: unknown) => { storeFor(c).set(e, d); },
+ onDespawn: (fn: (e: Entity) => void) => { despawnSubs.add(fn); return () => despawnSubs.delete(fn); },
+ };
+}
+type MockWorld = ReturnType<typeof makeMockWorld>;
+
+function withController(world: MockWorld, current = 'home'): Entity {
+ const e = world.spawn();
+ world.insert(e, UIController, { controllers: [controllerState('tab', ['home', 'shop', 'info'], current)] });
+ return e;
+}
+
+describe('ui.setPage — the .esfsm/.esbt bridge', () => {
+ it('registers on the shared AI registry (idempotent)', () => {
+ ensureControllerAiRegistrations();
+ ensureControllerAiRegistrations(); // second call is a no-op
+ expect(aiRegistry.hasAction('ui.setPage')).toBe(true);
+ });
+
+ it('switches the nearest controller to "controller:page"', () => {
+ ensureControllerAiRegistrations();
+ const action = aiRegistry.getAction('ui.setPage')!;
+ const world = makeMockWorld();
+ const e = withController(world);
+ action({ world, entity: e } as never, {} as never, 'tab:shop');
+ expect(getControllerPage(world as never, e, 'tab')).toBe('shop');
+ });
+
+ it('ignores an unknown page, unknown controller, or malformed arg', () => {
+ ensureControllerAiRegistrations();
+ const action = aiRegistry.getAction('ui.setPage')!;
+ const world = makeMockWorld();
+ const e = withController(world, 'shop');
+ action({ world, entity: e } as never, {} as never, 'tab:zzz'); // unknown page
+ action({ world, entity: e } as never, {} as never, 'nope:home'); // unknown controller
+ action({ world, entity: e } as never, {} as never, 'noSeparator');
+ action({ world, entity: e } as never, {} as never, undefined);
+ expect(getControllerPage(world as never, e, 'tab')).toBe('shop');
+ });
+});
+
+describe('bindControllerPage — the reactive (signal) bridge', () => {
+ it('seeds the controller from the signal, then tracks changes', () => {
+ const world = makeMockWorld();
+ const e = withController(world, 'home');
+ const page = signal('shop');
+ bindControllerPage(world as never, e, 'tab', page);
+ expect(getControllerPage(world as never, e, 'tab')).toBe('shop'); // seeded
+
+ page.set('info');
+ expect(getControllerPage(world as never, e, 'tab')).toBe('info');
+ });
+
+ it('stops tracking after dispose', () => {
+ const world = makeMockWorld();
+ const e = withController(world, 'home');
+ const page = signal('shop');
+ const dispose = bindControllerPage(world as never, e, 'tab', page);
+ dispose();
+ page.set('info');
+ expect(getControllerPage(world as never, e, 'tab')).toBe('shop'); // frozen at dispose-time value
+ });
+
+ it('auto-disposes when the entity despawns', () => {
+ const world = makeMockWorld();
+ const e = withController(world, 'home');
+ const page = signal('shop');
+ bindControllerPage(world as never, e, 'tab', page);
+ world.despawn(e);
+ page.set('info'); // entity gone → guarded, no throw
+ expect(world.valid(e)).toBe(false);
+ });
+});