Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

refactor(sdk): one verb per concept — widget values, open/close, subscriptions

esengine51998483509d
diff --git a/docs/astro/src/content/docs/core-concepts/screen.mdx b/docs/astro/src/content/docs/core-concepts/screen.mdx
index c11e2abfb..6659a7d57 100644
--- a/docs/astro/src/content/docs/core-concepts/screen.mdx
+++ b/docs/astro/src/content/docs/core-concepts/screen.mdx
@@ -210,18 +210,17 @@ construct it, feed it sizes, and it derives orientation and fires callbacks.
| `height` | number | `0` | Last reported screen height in px. |
| `dpr` | number | `1` | Device pixel ratio. |
| `orientation` | `ScreenOrientation` | `Portrait` | `Landscape` when `width > height`, else `Portrait`. |
-| `onResize` | `((w, h) => void) \| null` | `null` | Called on every `update()`. |
-| `onOrientationChange` | `((o) => void) \| null` | `null` | Called when the derived orientation flips (never on the first `update()`). |
-| `update(width, height, dpr = 1)` | method | — | Feed the current size; recomputes orientation and fires the callbacks. |
+| `on(event, fn)` | method | — | Subscribe to `'resize'` (every `update()`) or `'orientationchange'` (when the derived orientation flips; never on the first `update()`). Returns an unsubscribe function. |
+| `update(width, height, dpr = 1)` | method | — | Feed the current size; recomputes orientation and fires the listeners. |
```typescript
import { ScreenInfo, ScreenOrientation } from 'esengine';
const screen = new ScreenInfo();
-screen.onResize = (w, h) => { /* re-position off-canvas HUD, etc. */ };
-screen.onOrientationChange = (o) => {
+screen.on('resize', (w, h) => { /* re-position off-canvas HUD, etc. */ });
+screen.on('orientationchange', (o) => {
if (o === ScreenOrientation.Portrait) { /* show the "rotate device" hint */ }
-};
+});
const feed = () =>
screen.update(window.innerWidth, window.innerHeight, window.devicePixelRatio);
diff --git a/docs/astro/src/content/docs/guides/networking.mdx b/docs/astro/src/content/docs/guides/networking.mdx
index 7e9123709..f0600284a 100644
--- a/docs/astro/src/content/docs/guides/networking.mdx
+++ b/docs/astro/src/content/docs/guides/networking.mdx
@@ -17,14 +17,14 @@ import { createSocket } from 'esengine';
const socket = createSocket({ url: 'wss://example.com/game' });
-socket.onOpen = () => {
+socket.on('open', () => {
socket.send(JSON.stringify({ type: 'join', room: 'lobby' }));
-};
-socket.onMessage = (data) => {
+});
+socket.on('message', (data) => {
const msg = JSON.parse(data as string); // a message from the server
-};
-socket.onClose = (code, reason) => { /* reconnect? */ };
-socket.onError = (err) => { /* … */ };
+});
+socket.on('close', (code, reason) => { /* reconnect? */ });
+socket.on('error', (err) => { /* … */ });
socket.connect();
```
@@ -35,7 +35,7 @@ socket.connect();
| `send(data)` | Send a `string` or `ArrayBuffer`; data sent before `open` is queued and flushed on connect. |
| `close(code?, reason?)` | Disconnect. |
| `readyState` | `'connecting' \| 'open' \| 'closing' \| 'closed'`. |
-| `onOpen` / `onMessage` / `onClose` / `onError` | Lifecycle callbacks. |
+| `on(event, fn)` | Subscribe to `'open'` / `'message'` / `'close'` / `'error'`; returns an unsubscribe function. |
## Typed messages & RPC — `NetChannel`
@@ -197,7 +197,7 @@ never re-sends snap back. Owned entities bypass snapshot interpolation.
## Best practices
- **Use `NetChannel`** for anything beyond a trivial socket — routed types and RPC
- beat a giant `onMessage` switch.
+ beat a giant `'message'` handler switch.
- **Set an RPC timeout** so a lost reply rejects instead of hanging forever.
- **Push received state into components** via `Commands` so gameplay stays in ECS.
- **Queue-before-open is automatic** — you can `send` right after `connect()`.
diff --git a/docs/astro/src/content/docs/guides/ui-components.mdx b/docs/astro/src/content/docs/guides/ui-components.mdx
index 82e6ba77d..c704f30e1 100644
--- a/docs/astro/src/content/docs/guides/ui-components.mdx
+++ b/docs/astro/src/content/docs/guides/ui-components.mdx
@@ -89,7 +89,7 @@ const toggle = createToggle({
onChange: (isOn, entity) => { /* … */ },
});
-toggle.setIsOn(false); // programmatic change (fires onChange)
+toggle.setValue(false); // programmatic change (fires onChange)
```
| Option | Default | Description |
@@ -102,11 +102,11 @@ toggle.setIsOn(false); // programmatic change (fires onChange)
| `focusable` / `tabIndex` | `true` / `0` | Keyboard reachability. |
| `onChange(isOn, entity)` | — | Fires on toggle. |
-**Handle:** `isOn()`, `setIsOn(value)`, `setDisabled(disabled)`, `entity`, `dispose()`.
+**Handle:** `getValue()`, `setValue(value)`, `setDisabled(disabled)`, `entity`, `dispose()`.
<Aside type="note">
State lives in a **`UIToggle` component**; the behavior system flips it on click
- and is the single writer of the check visual — `setIsOn`, a binding, or the
+ and is the single writer of the check visual — `setValue`, a binding, or the
editor inspector on a placed prefab all flip the indicator and fire `change`
identically.
</Aside>
@@ -181,7 +181,7 @@ const ring = createProgress({ world, parent, radial: true, value: 0.75 });
| `background` | theme `track` | Track visual (a `UIVisualInit`). |
| `fill` | theme `primary` | The filled bar: `{ color?, sprite? }`. |
-**Handle:** `value()`, `setValue(v)`, `dispose()`, plus `entity` / `fillEntity`.
+**Handle:** `getValue()`, `setValue(v)`, `dispose()`, plus `entity` / `fillEntity`.
<Aside type="note">
**One fill primitive.** A progress bar is a single [`UIVisual`](/docs/guides/ui/) in
diff --git a/docs/astro/src/content/docs/zh-cn/core-concepts/screen.mdx b/docs/astro/src/content/docs/zh-cn/core-concepts/screen.mdx
index ea7a28998..bc2d6eb24 100644
--- a/docs/astro/src/content/docs/zh-cn/core-concepts/screen.mdx
+++ b/docs/astro/src/content/docs/zh-cn/core-concepts/screen.mdx
@@ -186,18 +186,17 @@ UI 在一个世界空间矩形(`uiLayoutRect`)内布局,对场景相机而言,
| `height` | number | `0` | 最后上报的屏幕高度,像素。 |
| `dpr` | number | `1` | 设备像素比。 |
| `orientation` | `ScreenOrientation` | `Portrait` | `width > height` 时为 `Landscape`,否则 `Portrait`。 |
-| `onResize` | `((w, h) => void) \| null` | `null` | 每次 `update()` 都调用。 |
-| `onOrientationChange` | `((o) => void) \| null` | `null` | 推导出的方向翻转时调用(首次 `update()` 从不触发)。 |
-| `update(width, height, dpr = 1)` | 方法 | — | 喂入当前尺寸;重算方向并触发回调。 |
+| `on(event, fn)` | method | — | 订阅 `'resize'`(每次 `update()`)或 `'orientationchange'`(推导出的方向翻转时;首次 `update()` 从不触发)。返回退订函数。 |
+| `update(width, height, dpr = 1)` | 方法 | — | 喂入当前尺寸;重算方向并触发监听器。 |
```typescript
import { ScreenInfo, ScreenOrientation } from 'esengine';
const screen = new ScreenInfo();
-screen.onResize = (w, h) => { /* re-position off-canvas HUD, etc. */ };
-screen.onOrientationChange = (o) => {
+screen.on('resize', (w, h) => { /* re-position off-canvas HUD, etc. */ });
+screen.on('orientationchange', (o) => {
if (o === ScreenOrientation.Portrait) { /* show the "rotate device" hint */ }
-};
+});
const feed = () =>
screen.update(window.innerWidth, window.innerHeight, window.devicePixelRatio);
diff --git a/docs/astro/src/content/docs/zh-cn/guides/networking.mdx b/docs/astro/src/content/docs/zh-cn/guides/networking.mdx
index 9bb24247d..86c776e6a 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/networking.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/networking.mdx
@@ -16,14 +16,14 @@ import { createSocket } from 'esengine';
const socket = createSocket({ url: 'wss://example.com/game' });
-socket.onOpen = () => {
+socket.on('open', () => {
socket.send(JSON.stringify({ type: 'join', room: 'lobby' }));
-};
-socket.onMessage = (data) => {
+});
+socket.on('message', (data) => {
const msg = JSON.parse(data as string); // a message from the server
-};
-socket.onClose = (code, reason) => { /* reconnect? */ };
-socket.onError = (err) => { /* … */ };
+});
+socket.on('close', (code, reason) => { /* reconnect? */ });
+socket.on('error', (err) => { /* … */ });
socket.connect();
```
@@ -34,7 +34,7 @@ socket.connect();
| `send(data)` | 发送 `string` 或 `ArrayBuffer`;`open` 之前发送的数据会排队并在连接时冲刷。 |
| `close(code?, reason?)` | 断开连接。 |
| `readyState` | `'connecting' \| 'open' \| 'closing' \| 'closed'`。 |
-| `onOpen` / `onMessage` / `onClose` / `onError` | 生命周期回调。 |
+| `on(event, fn)` | 订阅 `'open'` / `'message'` / `'close'` / `'error'`;返回退订函数。 |
## 类型化消息与 RPC —— `NetChannel`
@@ -180,7 +180,7 @@ clientNet.client.sendInput({ move: { x: 1, y: 0 } }); // pawn 立刻动
## 最佳实践
-- 超出简单套接字的场景**用 `NetChannel`**——按类型路由和 RPC 胜过一个巨大的 `onMessage` switch。
+- 超出简单套接字的场景**用 `NetChannel`**——按类型路由和 RPC 胜过一个巨大的 `'message'` 处理器 switch。
- **设置 RPC 超时**,让丢失的回复 reject 而不是永远挂起。
- **把收到的状态推入组件**(用 `Commands`),让玩法留在 ECS。
- **连接前排队是自动的**——`connect()` 之后就能立即 `send`。
diff --git a/docs/astro/src/content/docs/zh-cn/guides/ui-components.mdx b/docs/astro/src/content/docs/zh-cn/guides/ui-components.mdx
index 70cdb6970..bcdfd4f03 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/ui-components.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/ui-components.mdx
@@ -82,7 +82,7 @@ const toggle = createToggle({
onChange: (isOn, entity) => { /* … */ },
});
-toggle.setIsOn(false); // programmatic change (fires onChange)
+toggle.setValue(false); // programmatic change (fires onChange)
```
| 选项 | 默认 | 说明 |
@@ -95,11 +95,11 @@ toggle.setIsOn(false); // programmatic change (fires onChange)
| `focusable` / `tabIndex` | `true` / `0` | 键盘可达性。 |
| `onChange(isOn, entity)` | — | 切换时触发。 |
-**句柄:** `isOn()`、`setIsOn(value)`、`setDisabled(disabled)`、`entity`、`dispose()`。
+**句柄:** `getValue()`、`setValue(value)`、`setDisabled(disabled)`、`entity`、`dispose()`。
<Aside type="note">
状态活在 **`UIToggle` 组件**里;行为系统在点击时翻转它,并且是勾选视觉的唯一写入者——
- `setIsOn`、绑定、或编辑器里已摆放预制体的 inspector,翻转指示器和发 `change` 的方式
+ `setValue`、绑定、或编辑器里已摆放预制体的 inspector,翻转指示器和发 `change` 的方式
完全一致。
</Aside>
@@ -171,7 +171,7 @@ const ring = createProgress({ world, parent, radial: true, value: 0.75 });
| `background` | 主题 `track` | 轨道视觉(`UIVisualInit`)。 |
| `fill` | 主题 `primary` | 填充条:`{ color?, sprite? }`。 |
-**句柄:** `value()`、`setValue(v)`、`dispose()`,外加 `entity` / `fillEntity`。
+**句柄:** `getValue()`、`setValue(v)`、`dispose()`,外加 `entity` / `fillEntity`。
<Aside type="note">
**同一个填充原语。** 进度条就是一个 **`Filled`** 模式的
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 0157bfb36..ad6e3489b 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: 1255 stable · 17 beta · 0 deprecated
+Symbols: 1260 stable · 17 beta · 0 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -2739,10 +2739,7 @@ trigger: string | undefined
```
close: (code?: number, reason?: string) => void
connect: () => void
-onClose: ((code: number, reason: string) => void) | null
-onError: ((error: unknown) => void) | null
-onMessage: ((data: string | ArrayBuffer) => void) | null
-onOpen: (() => void) | null
+on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
static new (options: GameSocketOptions): GameSocket
@@ -3668,7 +3665,7 @@ static prototype: MeasuredLinearLayoutProvider
```
dropPending: () => void
flush: (limit?: number) => void
-onMessage: ((data: string | ArrayBuffer) => void) | null
+on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
pendingCount: number
send: (data: string | ArrayBuffer) => void
static new (options?: MemoryTransportOptions): MemoryTransport
@@ -3738,7 +3735,7 @@ postMessage: (data: unknown) => void
## MessagePortTransport — class
```
close: () => void
-onMessage: ((data: string | ArrayBuffer) => void) | null
+on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
send: (data: string | ArrayBuffer) => void
static new (port: MessagePortLike | MessagePort): MessagePortTransport
static prototype: MessagePortTransport
@@ -3929,7 +3926,7 @@ static prototype: NetSession
## NetTransport — interface
```
-onMessage: ((data: string | ArrayBuffer) => void) | null
+on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
send: (data: string | ArrayBuffer) => void
```
@@ -4359,14 +4356,19 @@ text: () => Promise<string>
```
close: (code?: number, reason?: string) => void
connect: () => void
-onClose: ((code: number, reason: string) => void) | null
-onError: ((error: unknown) => void) | null
-onMessage: ((data: string | ArrayBuffer) => void) | null
-onOpen: (() => void) | null
+on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
```
+## PlatformSocketEvents — interface
+```
+close: [code: number, reason: string]
+error: [error: unknown]
+message: [data: string | ArrayBuffer]
+open: []
+```
+
## PlatformSocketOptions — interface
```
protocols: string | string[] | undefined
@@ -4717,8 +4719,8 @@ visible: boolean
dispose: () => void
entity: number
fillEntity: number
+getValue: () => number
setValue: (v: number) => void
-value: () => number
```
## ProgressOptions — interface
@@ -5476,8 +5478,7 @@ Update = 3
```
dpr: number
height: number
-onOrientationChange: ((orientation: ScreenOrientation) => void) | null
-onResize: ((width: number, height: number) => void) | null
+on: <K extends keyof ScreenInfoEvents>(event: K, handler: (...args: ScreenInfoEvents[K]) => void) => () => void
orientation: ScreenOrientation
update: (width: number, height: number, dpr?: number) => void
width: number
@@ -5485,6 +5486,12 @@ static new (): ScreenInfo
static prototype: ScreenInfo
```
+## ScreenInfoEvents — interface
+```
+orientationchange: [orientation: ScreenOrientation]
+resize: [width: number, height: number]
+```
+
## ScreenOrientation — enum
```
Landscape = "landscape"
@@ -6769,9 +6776,9 @@ ResourceDef<TimerManager>
```
dispose: () => void
entity: number
-isOn: () => boolean
+getValue: () => boolean
setDisabled: (disabled: boolean) => void
-setIsOn: (value: boolean) => void
+setValue: (value: boolean) => void
```
## ToggleOptions — interface
@@ -7503,10 +7510,7 @@ Partial<Record<SideModuleId, EmscriptenFactory>>
```
close: (code?: number, reason?: string) => void
connect: () => void
-onClose: ((code: number, reason: string) => void) | null
-onError: ((error: unknown) => void) | null
-onMessage: ((data: string | ArrayBuffer) => void) | null
-onOpen: (() => void) | null
+on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
static new (options: GameSocketOptions): WeChatSocket
@@ -7914,6 +7918,11 @@ BtPlugin
(metadata: Record<string, unknown>): Record<string, unknown>
```
+## closeDialog — function
+```
+(world: World, events: UIEventQueue, root: Entity): void
+```
+
## closeDropdown — function
```
(world: World, e: Entity): void
@@ -8859,6 +8868,11 @@ NavPlugin
(mask: number): number
```
+## openDialog — function
+```
+(world: World, events: UIEventQueue, root: Entity): void
+```
+
## openDropdown — function
```
(world: World, events: UIEventQueue, e: Entity): void
@@ -9334,11 +9348,6 @@ Plugin
(ctx: AppContext): void
```
-## setDialogOpen — function
-```
-(world: World, events: UIEventQueue, root: Entity, open: boolean): void
-```
-
## setEditorMode — function
```
(active: boolean): void
@@ -9719,6 +9728,16 @@ UIRenderOrderPlugin
(x?: number, y?: number, z?: number, w?: number) => Vec4
```
+## velocityPlugin — const
+```
+Plugin
+```
+
+## velocitySystem — const
+```
+SystemDef
+```
+
## videoPlugin — const
```
VideoPlugin
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 127f5916c..b07bffcd2 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: 1254 stable · 19 beta · 0 deprecated
+Symbols: 1259 stable · 19 beta · 0 deprecated
## ANCHOR_AXES — const
```
@@ -2734,10 +2734,7 @@ trigger: string | undefined
```
close: (code?: number, reason?: string) => void
connect: () => void
-onClose: ((code: number, reason: string) => void) | null
-onError: ((error: unknown) => void) | null
-onMessage: ((data: string | ArrayBuffer) => void) | null
-onOpen: (() => void) | null
+on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
static new (options: GameSocketOptions): GameSocket
@@ -3663,7 +3660,7 @@ static prototype: MeasuredLinearLayoutProvider
```
dropPending: () => void
flush: (limit?: number) => void
-onMessage: ((data: string | ArrayBuffer) => void) | null
+on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
pendingCount: number
send: (data: string | ArrayBuffer) => void
static new (options?: MemoryTransportOptions): MemoryTransport
@@ -3733,7 +3730,7 @@ postMessage: (data: unknown) => void
## MessagePortTransport — class
```
close: () => void
-onMessage: ((data: string | ArrayBuffer) => void) | null
+on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
send: (data: string | ArrayBuffer) => void
static new (port: MessagePortLike | MessagePort): MessagePortTransport
static prototype: MessagePortTransport
@@ -3924,7 +3921,7 @@ static prototype: NetSession
## NetTransport — interface
```
-onMessage: ((data: string | ArrayBuffer) => void) | null
+on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
send: (data: string | ArrayBuffer) => void
```
@@ -4354,14 +4351,19 @@ text: () => Promise<string>
```
close: (code?: number, reason?: string) => void
connect: () => void
-onClose: ((code: number, reason: string) => void) | null
-onError: ((error: unknown) => void) | null
-onMessage: ((data: string | ArrayBuffer) => void) | null
-onOpen: (() => void) | null
+on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
```
+## PlatformSocketEvents — interface
+```
+close: [code: number, reason: string]
+error: [error: unknown]
+message: [data: string | ArrayBuffer]
+open: []
+```
+
## PlatformSocketOptions — interface
```
protocols: string | string[] | undefined
@@ -4712,8 +4714,8 @@ visible: boolean
dispose: () => void
entity: number
fillEntity: number
+getValue: () => number
setValue: (v: number) => void
-value: () => number
```
## ProgressOptions — interface
@@ -5471,8 +5473,7 @@ Update = 3
```
dpr: number
height: number
-onOrientationChange: ((orientation: ScreenOrientation) => void) | null
-onResize: ((width: number, height: number) => void) | null
+on: <K extends keyof ScreenInfoEvents>(event: K, handler: (...args: ScreenInfoEvents[K]) => void) => () => void
orientation: ScreenOrientation
update: (width: number, height: number, dpr?: number) => void
width: number
@@ -5480,6 +5481,12 @@ static new (): ScreenInfo
static prototype: ScreenInfo
```
+## ScreenInfoEvents — interface
+```
+orientationchange: [orientation: ScreenOrientation]
+resize: [width: number, height: number]
+```
+
## ScreenOrientation — enum
```
Landscape = "landscape"
@@ -6764,9 +6771,9 @@ ResourceDef<TimerManager>
```
dispose: () => void
entity: number
-isOn: () => boolean
+getValue: () => boolean
setDisabled: (disabled: boolean) => void
-setIsOn: (value: boolean) => void
+setValue: (value: boolean) => void
```
## ToggleOptions — interface
@@ -7498,10 +7505,7 @@ Partial<Record<SideModuleId, EmscriptenFactory>>
```
close: (code?: number, reason?: string) => void
connect: () => void
-onClose: ((code: number, reason: string) => void) | null
-onError: ((error: unknown) => void) | null
-onMessage: ((data: string | ArrayBuffer) => void) | null
-onOpen: (() => void) | null
+on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
static new (options: GameSocketOptions): WeChatSocket
@@ -7909,6 +7913,11 @@ BtPlugin
(metadata: Record<string, unknown>): Record<string, unknown>
```
+## closeDialog — function
+```
+(world: World, events: UIEventQueue, root: Entity): void
+```
+
## closeDropdown — function
```
(world: World, e: Entity): void
@@ -8864,6 +8873,11 @@ NodePlatformAdapter
(mask: number): number
```
+## openDialog — function
+```
+(world: World, events: UIEventQueue, root: Entity): void
+```
+
## openDropdown — function
```
(world: World, events: UIEventQueue, e: Entity): void
@@ -9339,11 +9353,6 @@ Plugin
(ctx: AppContext): void
```
-## setDialogOpen — function
-```
-(world: World, events: UIEventQueue, root: Entity, open: boolean): void
-```
-
## setEditorMode — function
```
(active: boolean): void
@@ -9724,6 +9733,16 @@ UIRenderOrderPlugin
(x?: number, y?: number, z?: number, w?: number) => Vec4
```
+## velocityPlugin — const
+```
+Plugin
+```
+
+## velocitySystem — const
+```
+SystemDef
+```
+
## videoPlugin — const
```
VideoPlugin
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 3a5a43ec9..d57cda710 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: 1265 stable · 17 beta · 0 deprecated
+Symbols: 1270 stable · 17 beta · 0 deprecated
## ANCHOR_AXES — const
```
@@ -2734,10 +2734,7 @@ trigger: string | undefined
```
close: (code?: number, reason?: string) => void
connect: () => void
-onClose: ((code: number, reason: string) => void) | null
-onError: ((error: unknown) => void) | null
-onMessage: ((data: string | ArrayBuffer) => void) | null
-onOpen: (() => void) | null
+on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
static new (options: GameSocketOptions): GameSocket
@@ -3670,7 +3667,7 @@ static prototype: MeasuredLinearLayoutProvider
```
dropPending: () => void
flush: (limit?: number) => void
-onMessage: ((data: string | ArrayBuffer) => void) | null
+on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
pendingCount: number
send: (data: string | ArrayBuffer) => void
static new (options?: MemoryTransportOptions): MemoryTransport
@@ -3740,7 +3737,7 @@ postMessage: (data: unknown) => void
## MessagePortTransport — class
```
close: () => void
-onMessage: ((data: string | ArrayBuffer) => void) | null
+on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
send: (data: string | ArrayBuffer) => void
static new (port: MessagePortLike | MessagePort): MessagePortTransport
static prototype: MessagePortTransport
@@ -3931,7 +3928,7 @@ static prototype: NetSession
## NetTransport — interface
```
-onMessage: ((data: string | ArrayBuffer) => void) | null
+on: (event: "message", handler: (data: string | ArrayBuffer) => void) => () => void
send: (data: string | ArrayBuffer) => void
```
@@ -4361,14 +4358,19 @@ text: () => Promise<string>
```
close: (code?: number, reason?: string) => void
connect: () => void
-onClose: ((code: number, reason: string) => void) | null
-onError: ((error: unknown) => void) | null
-onMessage: ((data: string | ArrayBuffer) => void) | null
-onOpen: (() => void) | null
+on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
```
+## PlatformSocketEvents — interface
+```
+close: [code: number, reason: string]
+error: [error: unknown]
+message: [data: string | ArrayBuffer]
+open: []
+```
+
## PlatformSocketOptions — interface
```
protocols: string | string[] | undefined
@@ -4719,8 +4721,8 @@ visible: boolean
dispose: () => void
entity: number
fillEntity: number
+getValue: () => number
setValue: (v: number) => void
-value: () => number
```
## ProgressOptions — interface
@@ -5478,8 +5480,7 @@ Update = 3
```
dpr: number
height: number
-onOrientationChange: ((orientation: ScreenOrientation) => void) | null
-onResize: ((width: number, height: number) => void) | null
+on: <K extends keyof ScreenInfoEvents>(event: K, handler: (...args: ScreenInfoEvents[K]) => void) => () => void
orientation: ScreenOrientation
update: (width: number, height: number, dpr?: number) => void
width: number
@@ -5487,6 +5488,12 @@ static new (): ScreenInfo
static prototype: ScreenInfo
```
+## ScreenInfoEvents — interface
+```
+orientationchange: [orientation: ScreenOrientation]
+resize: [width: number, height: number]
+```
+
## ScreenOrientation — enum
```
Landscape = "landscape"
@@ -6771,9 +6778,9 @@ ResourceDef<TimerManager>
```
dispose: () => void
entity: number
-isOn: () => boolean
+getValue: () => boolean
setDisabled: (disabled: boolean) => void
-setIsOn: (value: boolean) => void
+setValue: (value: boolean) => void
```
## ToggleOptions — interface
@@ -7522,10 +7529,7 @@ Partial<Record<SideModuleId, EmscriptenFactory>>
```
close: (code?: number, reason?: string) => void
connect: () => void
-onClose: ((code: number, reason: string) => void) | null
-onError: ((error: unknown) => void) | null
-onMessage: ((data: string | ArrayBuffer) => void) | null
-onOpen: (() => void) | null
+on: <K extends keyof PlatformSocketEvents>(event: K, handler: (...args: PlatformSocketEvents[K]) => void) => () => void
readyState: PlatformSocketReadyState
send: (data: string | ArrayBuffer) => void
static new (options: GameSocketOptions): WeChatSocket
@@ -7933,6 +7937,11 @@ BtPlugin
(metadata: Record<string, unknown>): Record<string, unknown>
```
+## closeDialog — function
+```
+(world: World, events: UIEventQueue, root: Entity): void
+```
+
## closeDropdown — function
```
(world: World, e: Entity): void
@@ -8883,6 +8892,11 @@ NavPlugin
(mask: number): number
```
+## openDialog — function
+```
+(world: World, events: UIEventQueue, root: Entity): void
+```
+
## openDropdown — function
```
(world: World, events: UIEventQueue, e: Entity): void
@@ -9358,11 +9372,6 @@ Plugin
(ctx: AppContext): void
```
-## setDialogOpen — function
-```
-(world: World, events: UIEventQueue, root: Entity, open: boolean): void
-```
-
## setEditorMode — function
```
(active: boolean): void
@@ -9743,6 +9752,16 @@ UIRenderOrderPlugin
(x?: number, y?: number, z?: number, w?: number) => Vec4
```
+## velocityPlugin — const
+```
+Plugin
+```
+
+## velocitySystem — const
+```
+SystemDef
+```
+
## videoPlugin — const
```
VideoPlugin
diff --git a/sdk/src/asset/imageDecode.ts b/sdk/src/asset/imageDecode.ts
index 3bcb5d093..83fe71a32 100644
--- a/sdk/src/asset/imageDecode.ts
+++ b/sdk/src/asset/imageDecode.ts
@@ -10,7 +10,7 @@
* NEVER `UNPACK_FLIP_Y_WEBGL`, which Chromium/ANGLE silently ignore for
* `ImageBitmap` sources (uploads every texture upside-down otherwise).
*/
-import { platformCreateCanvas } from '../platform';
+import { platformCreateCanvas } from '../platform/base';
/**
* Canonical `createImageBitmap` options. premultiply + colorspace conversion are
diff --git a/sdk/src/asset/loaders/TextureLoader.ts b/sdk/src/asset/loaders/TextureLoader.ts
index ec795d88c..75d016b89 100644
--- a/sdk/src/asset/loaders/TextureLoader.ts
+++ b/sdk/src/asset/loaders/TextureLoader.ts
@@ -2,7 +2,7 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { AssetLoader, LoadContext, TextureResult } from '../AssetLoader';
import { linearColorSpace } from '../../env';
-import { platformCreateCanvas, platformCreateImage } from '../../platform';
+import { platformCreateCanvas, platformCreateImage } from '../../platform/base';
import { decodeImageBitmap } from '../imageDecode';
import { requireResourceManager } from '../../resourceManager';
import type { ESEngineModule } from '../../wasm';
diff --git a/sdk/src/asset/loaders/TimelineAssetLoader.ts b/sdk/src/asset/loaders/TimelineAssetLoader.ts
index 2757b7145..96fcc5517 100644
--- a/sdk/src/asset/loaders/TimelineAssetLoader.ts
+++ b/sdk/src/asset/loaders/TimelineAssetLoader.ts
@@ -2,7 +2,7 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import type { AssetLoader, LoadContext, TimelineResult } from '../AssetLoader';
import { parseTimelineAsset, extractTimelineAssetPaths } from '../../timeline/TimelineLoader';
-import { registerTimelineAsset, registerTimelineTextureHandles } from '../../timeline/TimelinePlugin';
+import { registerTimelineAsset, registerTimelineTextureHandles } from '../../timeline/TimelineAssetRegistry';
import { log } from '../../logger';
export class TimelineAssetLoader implements AssetLoader<TimelineResult> {
diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.ts
index 3b0ec33fb..24e71589d 100644
--- a/sdk/src/core-sys.ts
+++ b/sdk/src/core-sys.ts
@@ -75,7 +75,7 @@ export { pointInHitArea, type HitAreaShape } from './hitArea';
// Screen
// =============================================================================
-export { ScreenInfo, ScreenOrientation } from './screen';
+export { ScreenInfo, ScreenOrientation, type ScreenInfoEvents } from './screen';
// =============================================================================
// Network
@@ -87,8 +87,8 @@ export {
MessagePortTransport, type MessagePortLike,
type GameSocketOptions, type SocketReadyState, type NetTransport,
type NetChannelOptions, type MessageHandler, type RequestHandler,
- type BinaryHandler, type PlatformSocket, type PlatformSocketOptions,
- type PlatformSocketReadyState,
+ type BinaryHandler, type PlatformSocket, type PlatformSocketEvents,
+ type PlatformSocketOptions, type PlatformSocketReadyState,
} from './net';
export {
@@ -184,6 +184,8 @@ export {
timerPlugin,
} from './timer';
+export { velocityPlugin, velocitySystem } from './velocity';
+
// =============================================================================
// Lifecycle
// =============================================================================
diff --git a/sdk/src/core-ui.ts b/sdk/src/core-ui.ts
index c10c57b4c..efb05abef 100644
--- a/sdk/src/core-ui.ts
+++ b/sdk/src/core-ui.ts
@@ -206,7 +206,8 @@ export {
createDialog,
UIDialog,
isDialogOpen,
- setDialogOpen,
+ openDialog,
+ closeDialog,
type UIDialogData,
type DialogOptions,
type DialogHandle,
diff --git a/sdk/src/emitter.ts b/sdk/src/emitter.ts
new file mode 100644
index 000000000..f852fb832
--- /dev/null
+++ b/sdk/src/emitter.ts
@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file emitter.ts
+ * @brief Minimal typed multicast backing the `on(event, fn)` → unsubscribe
+ * surfaces (sockets, transports, ScreenInfo).
+ */
+
+type AnyHandler = (...args: unknown[]) => void;
+
+export class Emitter<E extends Record<keyof E, unknown[]>> {
+ private handlers_ = new Map<keyof E, Set<AnyHandler>>();
+
+ on<K extends keyof E>(event: K, handler: (...args: E[K]) => void): () => void {
+ let set = this.handlers_.get(event);
+ if (!set) {
+ set = new Set();
+ this.handlers_.set(event, set);
+ }
+ set.add(handler as AnyHandler);
+ return () => {
+ set.delete(handler as AnyHandler);
+ };
+ }
+
+ emit<K extends keyof E>(event: K, ...args: E[K]): void {
+ const set = this.handlers_.get(event);
+ if (!set) return;
+ // Copy: a handler may (un)subscribe during dispatch.
+ for (const h of [...set]) h(...args);
+ }
+
+ clear(): void {
+ this.handlers_.clear();
+ }
+}
diff --git a/sdk/src/lifecycle.ts b/sdk/src/lifecycle.ts
index d6afdf309..91a06b36a 100644
--- a/sdk/src/lifecycle.ts
+++ b/sdk/src/lifecycle.ts
@@ -111,7 +111,7 @@ export class LifecyclePlugin implements Plugin {
const platformType = getPlatformType();
if (platformType === 'wechat') {
- setupWeChatLifecycle_(manager, app);
+ this.cleanupFn_ = setupWeChatLifecycle_(manager, app);
} else if (typeof document !== 'undefined' && typeof window !== 'undefined') {
this.cleanupFn_ = setupWebLifecycle_(manager, app);
}
@@ -175,12 +175,12 @@ function setupWebLifecycle_(manager: LifecycleManager, app: AppLike): () => void
// WeChat Platform
// =============================================================================
-function setupWeChatLifecycle_(manager: LifecycleManager, app: AppLike): void {
+function setupWeChatLifecycle_(manager: LifecycleManager, app: AppLike): (() => void) | null {
let pausedByLifecycle = false;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const wx = (globalThis as any).wx;
- if (!wx) return;
+ if (!wx) return null;
const onShow = (): void => {
manager.setVisible_(true);
@@ -202,4 +202,10 @@ function setupWeChatLifecycle_(manager: LifecycleManager, app: AppLike): void {
wx.onShow(onShow);
wx.onHide(onHide);
+
+ return (): void => {
+ wx.offShow?.(onShow);
+ wx.offHide?.(onHide);
+ manager.removeAllListeners();
+ };
}
diff --git a/sdk/src/net/GameSocket.ts b/sdk/src/net/GameSocket.ts
index 0234b0e56..5fea21f4c 100644
--- a/sdk/src/net/GameSocket.ts
+++ b/sdk/src/net/GameSocket.ts
@@ -4,7 +4,13 @@
* @file GameSocket.ts
* @brief Raw browser-WebSocket wrapper behind the platform socket seam.
*/
-import type { PlatformSocket, PlatformSocketOptions, PlatformSocketReadyState } from '../platform/types';
+import { Emitter } from '../emitter';
+import type {
+ PlatformSocket,
+ PlatformSocketEvents,
+ PlatformSocketOptions,
+ PlatformSocketReadyState,
+} from '../platform/types';
export type SocketReadyState = PlatformSocketReadyState;
@@ -15,19 +21,22 @@ export class GameSocket implements PlatformSocket {
private protocols_?: string | string[];
private ws_: WebSocket | null = null;
private sendQueue_: (string | ArrayBuffer)[] = [];
+ private events_ = new Emitter<PlatformSocketEvents>();
readyState: SocketReadyState = 'closed';
- onOpen: (() => void) | null = null;
- onMessage: ((data: string | ArrayBuffer) => void) | null = null;
- onClose: ((code: number, reason: string) => void) | null = null;
- onError: ((error: unknown) => void) | null = null;
-
constructor(options: GameSocketOptions) {
this.url_ = options.url;
this.protocols_ = options.protocols;
}
+ on<K extends keyof PlatformSocketEvents>(
+ event: K,
+ handler: (...args: PlatformSocketEvents[K]) => void,
+ ): () => void {
+ return this.events_.on(event, handler);
+ }
+
connect(): void {
if (this.ws_) return;
@@ -43,25 +52,25 @@ export class GameSocket implements PlatformSocket {
this.ws_!.send(msg);
}
this.sendQueue_ = [];
- this.onOpen?.();
+ this.events_.emit('open');
};
this.ws_.onmessage = (e) => {
- this.onMessage?.(e.data);
+ this.events_.emit('message', e.data);
};
this.ws_.onclose = (e) => {
this.readyState = 'closed';
this.ws_ = null;
- this.onClose?.(e.code, e.reason);
+ this.events_.emit('close', e.code, e.reason);
};
this.ws_.onerror = (e) => {
- this.onError?.(e);
+ this.events_.emit('error', e);
};
} catch (e) {
this.readyState = 'closed';
- this.onError?.(e);
+ this.events_.emit('error', e);
}
}
diff --git a/sdk/src/net/MemoryTransport.ts b/sdk/src/net/MemoryTransport.ts
index 1815b2f08..9ec5cb430 100644
--- a/sdk/src/net/MemoryTransport.ts
+++ b/sdk/src/net/MemoryTransport.ts
@@ -9,6 +9,7 @@
* pumps them, which is how delivery order, latency and packet
* interleaving are simulated.
*/
+import { Emitter } from '../emitter';
import type { NetTransport } from './NetChannel';
export interface MemoryTransportOptions {
@@ -17,8 +18,7 @@ export interface MemoryTransportOptions {
}
export class MemoryTransport implements NetTransport {
- onMessage: ((data: string | ArrayBuffer) => void) | null = null;
-
+ private events_ = new Emitter<{ message: [data: string | ArrayBuffer] }>();
private peer_: MemoryTransport | null = null;
private readonly manualFlush_: boolean;
private outbox_: (string | ArrayBuffer)[] = [];
@@ -32,12 +32,16 @@ export class MemoryTransport implements NetTransport {
return this.outbox_.length;
}
+ on(event: 'message', handler: (data: string | ArrayBuffer) => void): () => void {
+ return this.events_.on(event, handler);
+ }
+
send(data: string | ArrayBuffer): void {
if (!this.peer_) return;
if (this.manualFlush_) {
this.outbox_.push(data);
} else {
- this.peer_.onMessage?.(data);
+ this.peer_.events_.emit('message', data);
}
}
@@ -47,7 +51,7 @@ export class MemoryTransport implements NetTransport {
let n = 0;
while (this.outbox_.length > 0 && n < limit) {
const frame = this.outbox_.shift()!;
- this.peer_.onMessage?.(frame);
+ this.peer_.events_.emit('message', frame);
n++;
}
}
diff --git a/sdk/src/net/MessagePortTransport.ts b/sdk/src/net/MessagePortTransport.ts
index f15455718..27ed5ca9e 100644
--- a/sdk/src/net/MessagePortTransport.ts
+++ b/sdk/src/net/MessagePortTransport.ts
@@ -8,6 +8,7 @@
* (JSON strings and ArrayBuffer frames) natively, and a port queues
* messages until the other end attaches, so wiring order is free.
*/
+import { Emitter } from '../emitter';
import type { NetTransport } from './NetChannel';
/** The minimal MessagePort surface (structural — works for window and worker
@@ -21,8 +22,7 @@ export interface MessagePortLike {
}
export class MessagePortTransport implements NetTransport {
- onMessage: ((data: string | ArrayBuffer) => void) | null = null;
-
+ private events_ = new Emitter<{ message: [data: string | ArrayBuffer] }>();
private readonly port_: MessagePortLike;
constructor(port: MessagePortLike | MessagePort) {
@@ -31,11 +31,15 @@ export class MessagePortTransport implements NetTransport {
this.port_.onmessage = (e) => {
const d = e.data;
if (typeof d === 'string' || d instanceof ArrayBuffer) {
- this.onMessage?.(d);
+ this.events_.emit('message', d);
}
};
}
+ on(event: 'message', handler: (data: string | ArrayBuffer) => void): () => void {
+ return this.events_.on(event, handler);
+ }
+
send(data: string | ArrayBuffer): void {
this.port_.postMessage(data);
}
diff --git a/sdk/src/net/NetChannel.ts b/sdk/src/net/NetChannel.ts
index 3bfcc5d4b..d8528d8e1 100644
--- a/sdk/src/net/NetChannel.ts
+++ b/sdk/src/net/NetChannel.ts
@@ -6,13 +6,14 @@
* GameSocket / WeChatSocket only move string|ArrayBuffer frames; this
* is the single channel that gives them typed events (`on`/`send`) and
* RPC (`handle`/`request`) with a small JSON envelope. Transport-
- * agnostic — anything that can `send` and surface `onMessage` works.
+ * agnostic — anything that can `send` and surface `message` events works.
*/
/** The minimal socket surface NetChannel drives (GameSocket / WeChatSocket fit). */
export interface NetTransport {
send(data: string | ArrayBuffer): void;
- onMessage: ((data: string | ArrayBuffer) => void) | null;
+ /** Subscribe to incoming frames. Returns an unsubscribe function. */
+ on(event: 'message', handler: (data: string | ArrayBuffer) => void): () => void;
}
export type MessageHandler<T = unknown> = (payload: T) => void;
@@ -36,9 +37,10 @@ interface Pending {
}
/**
- * Typed messaging over a {@link NetTransport}. Claims the transport's
- * `onMessage` (it is the message router). Events are fire-and-forget; requests
- * await a matching response by id (or reject on timeout / remote error).
+ * Typed messaging over a {@link NetTransport}. Subscribes to the transport's
+ * `message` events (it is the message router). Events are fire-and-forget;
+ * requests await a matching response by id (or reject on timeout / remote
+ * error).
*
* Two planes share the one transport: string frames carry the JSON control
* envelope; binary frames carry a 1-byte channel id + payload for high-rate
@@ -52,12 +54,13 @@ export class NetChannel {
private readonly binaryHandlers = new Map<number, BinaryHandler>();
private readonly pending = new Map<number, Pending>();
private readonly defaultTimeout: number;
+ private readonly offMessage_: () => void;
private nextId = 1;
constructor(transport: NetTransport, opts: NetChannelOptions = {}) {
this.transport = transport;
this.defaultTimeout = opts.requestTimeoutMs ?? 10000;
- transport.onMessage = (data) => this.handleIncoming_(data);
+ this.offMessage_ = transport.on('message', (data) => this.handleIncoming_(data));
}
/** Subscribe to a typed event. Returns an unsubscribe function. */
@@ -124,6 +127,7 @@ export class NetChannel {
/** Reject all in-flight requests and drop handlers (call on disconnect). */
dispose(reason = 'net channel closed'): void {
+ this.offMessage_();
for (const [, p] of this.pending) {
if (p.timer) clearTimeout(p.timer);
p.reject(new Error(reason));
diff --git a/sdk/src/net/WeChatSocket.ts b/sdk/src/net/WeChatSocket.ts
index 11c3be162..5f83250fe 100644
--- a/sdk/src/net/WeChatSocket.ts
+++ b/sdk/src/net/WeChatSocket.ts
@@ -4,7 +4,8 @@
* @file WeChatSocket.ts
* @brief Raw wx.connectSocket wrapper behind the platform socket seam.
*/
-import type { PlatformSocket } from '../platform/types';
+import { Emitter } from '../emitter';
+import type { PlatformSocket, PlatformSocketEvents } from '../platform/types';
import type { GameSocketOptions, SocketReadyState } from './GameSocket';
export class WeChatSocket implements PlatformSocket {
@@ -12,25 +13,28 @@ export class WeChatSocket implements PlatformSocket {
private protocols_?: string | string[];
private task_: any = null;
private sendQueue_: (string | ArrayBuffer)[] = [];
+ private events_ = new Emitter<PlatformSocketEvents>();
readyState: SocketReadyState = 'closed';
- onOpen: (() => void) | null = null;
- onMessage: ((data: string | ArrayBuffer) => void) | null = null;
- onClose: ((code: number, reason: string) => void) | null = null;
- onError: ((error: unknown) => void) | null = null;
-
constructor(options: GameSocketOptions) {
this.url_ = options.url;
this.protocols_ = options.protocols;
}
+ on<K extends keyof PlatformSocketEvents>(
+ event: K,
+ handler: (...args: PlatformSocketEvents[K]) => void,
+ ): () => void {
+ return this.events_.on(event, handler);
+ }
+
connect(): void {
if (this.task_) return;
const wx = (globalThis as any).wx;
if (!wx?.connectSocket) {
- this.onError?.('wx.connectSocket not available');
+ this.events_.emit('error', 'wx.connectSocket not available');
return;
}
@@ -47,21 +51,21 @@ export class WeChatSocket implements PlatformSocket {
this.task_.send({ data: msg });
}
this.sendQueue_ = [];
- this.onOpen?.();
+ this.events_.emit('open');
});
this.task_.onMessage((res: { data: string | ArrayBuffer }) => {
- this.onMessage?.(res.data);
+ this.events_.emit('message', res.data);
});
this.task_.onClose((res: { code: number; reason: string }) => {
this.readyState = 'closed';
this.task_ = null;
- this.onClose?.(res.code, res.reason);
+ this.events_.emit('close', res.code, res.reason);
});
this.task_.onError((err: unknown) => {
- this.onError?.(err);
+ this.events_.emit('error', err);
});
}
diff --git a/sdk/src/net/index.ts b/sdk/src/net/index.ts
index 8aa2da0e3..19b88658c 100644
--- a/sdk/src/net/index.ts
+++ b/sdk/src/net/index.ts
@@ -16,7 +16,12 @@ export {
} from './NetChannel';
export { MemoryTransport, createMemoryTransportPair } from './MemoryTransport';
export { MessagePortTransport, type MessagePortLike } from './MessagePortTransport';
-export type { PlatformSocket, PlatformSocketOptions, PlatformSocketReadyState } from '../platform/types';
+export type {
+ PlatformSocket,
+ PlatformSocketEvents,
+ PlatformSocketOptions,
+ PlatformSocketReadyState,
+} from '../platform/types';
export * from './replication';
import { GameSocket, type GameSocketOptions } from './GameSocket';
diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.ts
index 57425a2bd..d3ea79c43 100644
--- a/sdk/src/platform/types.ts
+++ b/sdk/src/platform/types.ts
@@ -93,17 +93,25 @@ export interface PlatformSocketOptions {
protocols?: string | string[];
}
+/** Event payloads for {@link PlatformSocket.on}. */
+export interface PlatformSocketEvents {
+ open: [];
+ message: [data: string | ArrayBuffer];
+ close: [code: number, reason: string];
+ error: [error: unknown];
+}
+
/**
* The platform-neutral socket surface (GameSocket / WeChatSocket / a Node ws
- * wrapper all fit): callback-based, queues sends until open, moves
- * string|ArrayBuffer frames.
+ * wrapper all fit): multicast `on(event, fn)` → unsubscribe, queues sends
+ * until open, moves string|ArrayBuffer frames.
*/
export interface PlatformSocket {
readyState: PlatformSocketReadyState;
- onOpen: (() => void) | null;
- onMessage: ((data: string | ArrayBuffer) => void) | null;
- onClose: ((code: number, reason: string) => void) | null;
- onError: ((error: unknown) => void) | null;
+ on<K extends keyof PlatformSocketEvents>(
+ event: K,
+ handler: (...args: PlatformSocketEvents[K]) => void,
+ ): () => void;
connect(): void;
send(data: string | ArrayBuffer): void;
close(code?: number, reason?: string): void;
diff --git a/sdk/src/screen.ts b/sdk/src/screen.ts
index 92037cc1c..32abb29f0 100644
--- a/sdk/src/screen.ts
+++ b/sdk/src/screen.ts
@@ -1,21 +1,34 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { Emitter } from './emitter';
+
export enum ScreenOrientation {
Portrait = 'portrait',
Landscape = 'landscape',
}
+/** Event payloads for {@link ScreenInfo.on}. */
+export interface ScreenInfoEvents {
+ resize: [width: number, height: number];
+ orientationchange: [orientation: ScreenOrientation];
+}
+
export class ScreenInfo {
width = 0;
height = 0;
dpr = 1;
orientation: ScreenOrientation = ScreenOrientation.Portrait;
- onOrientationChange: ((orientation: ScreenOrientation) => void) | null = null;
- onResize: ((width: number, height: number) => void) | null = null;
-
+ private events_ = new Emitter<ScreenInfoEvents>();
private initialized_ = false;
+ on<K extends keyof ScreenInfoEvents>(
+ event: K,
+ handler: (...args: ScreenInfoEvents[K]) => void,
+ ): () => void {
+ return this.events_.on(event, handler);
+ }
+
update(width: number, height: number, dpr: number = 1): void {
const newOrientation = width > height ? ScreenOrientation.Landscape : ScreenOrientation.Portrait;
const orientationChanged = this.initialized_ && newOrientation !== this.orientation;
@@ -26,10 +39,10 @@ export class ScreenInfo {
this.orientation = newOrientation;
this.initialized_ = true;
- this.onResize?.(width, height);
+ this.events_.emit('resize', width, height);
if (orientationChanged) {
- this.onOrientationChange?.(this.orientation);
+ this.events_.emit('orientationchange', this.orientation);
}
}
}
diff --git a/sdk/src/timeline/TimelineAssetRegistry.ts b/sdk/src/timeline/TimelineAssetRegistry.ts
new file mode 100644
index 000000000..5e418eab9
--- /dev/null
+++ b/sdk/src/timeline/TimelineAssetRegistry.ts
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file TimelineAssetRegistry.ts
+ * @brief Leaf seam between the timeline asset loader and TimelinePlugin.
+ *
+ * The loader writes parsed assets through these free functions without
+ * importing TimelinePlugin — importing it would close a module cycle through
+ * AssetPlugin/Assets. TimelinePlugin implements the registry and binds itself
+ * active on build.
+ */
+import type { TimelineAsset } from './TimelineTypes';
+
+export interface TimelineAssetRegistry {
+ registerAsset(path: string, asset: TimelineAsset): void;
+ getAsset(path: string): TimelineAsset | undefined;
+ registerTextureHandles(path: string, handles: Map<string, number>): void;
+ getTextureHandle(timelinePath: string, textureUuid: string): number;
+}
+
+let active: TimelineAssetRegistry | null = null;
+
+/** @internal TimelinePlugin binds itself on build and unbinds on cleanup. */
+export function setActiveTimelineAssetRegistry(registry: TimelineAssetRegistry | null): void {
+ active = registry;
+}
+
+export function registerTimelineAsset(path: string, asset: TimelineAsset): void {
+ active?.registerAsset(path, asset);
+}
+
+export function getTimelineAsset(path: string): TimelineAsset | undefined {
+ return active?.getAsset(path);
+}
+
+export function registerTimelineTextureHandles(path: string, handles: Map<string, number>): void {
+ active?.registerTextureHandles(path, handles);
+}
+
+export function getTimelineTextureHandle(timelinePath: string, textureUuid: string): number {
+ return active?.getTextureHandle(timelinePath, textureUuid) ?? 0;
+}
diff --git a/sdk/src/timeline/TimelinePlugin.ts b/sdk/src/timeline/TimelinePlugin.ts
index aa48387ee..53d808c4d 100644
--- a/sdk/src/timeline/TimelinePlugin.ts
+++ b/sdk/src/timeline/TimelinePlugin.ts
@@ -14,6 +14,11 @@ import { Timeline, TimelineAPI } from './TimelineControl';
import { resolveChildEntity } from './TimelineRuntime';
import { advanceTimelineTS, applyPlayerFlags, latchPlayerFinish } from './TimelineDrive';
import type { SampleDeps } from './TimelineEvaluator';
+import {
+ setActiveTimelineAssetRegistry,
+ getTimelineTextureHandle,
+ type TimelineAssetRegistry,
+} from './TimelineAssetRegistry';
import type { Entity } from '../types';
export { setNestedProperty } from './TimelineRuntime';
@@ -43,30 +48,12 @@ export const TimelinePlayer = defineComponent<TimelinePlayerData>('TimelinePlaye
},
});
-let activeTimelinePlugin: TimelinePlugin | null = null;
-
-export function registerTimelineAsset(path: string, asset: TimelineAsset): void {
- activeTimelinePlugin?.registerAsset(path, asset);
-}
-
-export function getTimelineAsset(path: string): TimelineAsset | undefined {
- return activeTimelinePlugin?.getAsset(path);
-}
-
-export function registerTimelineTextureHandles(path: string, handles: Map<string, number>): void {
- activeTimelinePlugin?.registerTextureHandles(path, handles);
-}
-
-export function getTimelineTextureHandle(timelinePath: string, textureUuid: string): number {
- return activeTimelinePlugin?.getTextureHandle(timelinePath, textureUuid) ?? 0;
-}
-
interface AnimFramesState {
tracks: AnimFramesTrack[];
lastFrameIndices: number[];
}
-export class TimelinePlugin implements Plugin {
+export class TimelinePlugin implements Plugin, TimelineAssetRegistry {
name = 'timeline';
private loadedAssets_ = new Map<string, TimelineAsset>();
@@ -90,7 +77,7 @@ export class TimelinePlugin implements Plugin {
}
build(app: App): void {
- activeTimelinePlugin = this;
+ setActiveTimelineAssetRegistry(this);
const world = app.world;
// The api's play/pause/stop write through to the component flags (the
@@ -167,7 +154,7 @@ export class TimelinePlugin implements Plugin {
this.animFramesStates_.clear();
this.loadedAssets_.clear();
this.textureHandles_.clear();
- activeTimelinePlugin = null;
+ setActiveTimelineAssetRegistry(null);
}
private ensureAnimFrames(entity: Entity, asset: TimelineAsset): void {
diff --git a/sdk/src/timeline/index.ts b/sdk/src/timeline/index.ts
index 7859946ff..166ac71e9 100644
--- a/sdk/src/timeline/index.ts
+++ b/sdk/src/timeline/index.ts
@@ -79,8 +79,12 @@ export {
timelinePlugin,
TimelinePlayer,
type TimelinePlayerData,
+} from './TimelinePlugin';
+
+export {
registerTimelineAsset,
getTimelineAsset,
registerTimelineTextureHandles,
getTimelineTextureHandle,
-} from './TimelinePlugin';
+ type TimelineAssetRegistry,
+} from './TimelineAssetRegistry';
diff --git a/sdk/src/ui/behavior/dialog.ts b/sdk/src/ui/behavior/dialog.ts
index 3e537b5bd..140db919e 100644
--- a/sdk/src/ui/behavior/dialog.ts
+++ b/sdk/src/ui/behavior/dialog.ts
@@ -39,8 +39,17 @@ export function isDialogOpen(world: World, root: Entity): boolean {
return (world.get(root, UINode) as UINodeData).display !== UIDisplay.None;
}
-/** Show/hide the dialog subtree and emit `change` with the new open state. */
-export function setDialogOpen(
+/** Show the dialog subtree and emit `change` with the new open state. */
+export function openDialog(world: World, events: UIEventQueue, root: Entity): void {
+ setOpen_(world, events, root, true);
+}
+
+/** Hide the dialog subtree and emit `change` with the new open state. */
+export function closeDialog(world: World, events: UIEventQueue, root: Entity): void {
+ setOpen_(world, events, root, false);
+}
+
+function setOpen_(
world: World, events: UIEventQueue, root: Entity, open: boolean,
): void {
if (!world.has(root, UINode) || isDialogOpen(world, root) === open) return;
@@ -63,7 +72,7 @@ export function createDialogSystem(world: World, events: UIEventQueue): SystemDe
&& (world.get(e, UIInteraction) as UIInteractionData).justPressed;
if ((d.closeOnEscape && escape) || scrimClicked) {
- setDialogOpen(world, events, e, false);
+ closeDialog(world, events, e);
}
}
}, { name: 'UIDialogSystem' });
diff --git a/sdk/src/ui/behavior/toggle.ts b/sdk/src/ui/behavior/toggle.ts
index ec114e22e..0f31f6169 100644
--- a/sdk/src/ui/behavior/toggle.ts
+++ b/sdk/src/ui/behavior/toggle.ts
@@ -6,7 +6,7 @@
*
* The component IS the state (`isOn` + the check-indicator entity ref); the
* system flips it on click and is the single writer of the check visual. Any
- * writer — the pointer, `setIsOn`, a binding, the editor inspector — shows
+ * writer — the pointer, `setValue`, a binding, the editor inspector — shows
* the indicator and fires `change` identically, so a prefab-placed toggle
* works without code.
*/
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index 3739a8b66..54fc93b20 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -116,7 +116,8 @@ export { UIBehaviorPlugin, uiBehaviorPlugin } from './behavior/plugin';
export {
UIDialog,
isDialogOpen,
- setDialogOpen,
+ openDialog,
+ closeDialog,
createDialogSystem,
type UIDialogData,
} from './behavior/dialog';
diff --git a/sdk/src/ui/widgets/dialog.ts b/sdk/src/ui/widgets/dialog.ts
index 2348679f1..c9ca7aec9 100644
--- a/sdk/src/ui/widgets/dialog.ts
+++ b/sdk/src/ui/widgets/dialog.ts
@@ -9,7 +9,7 @@ import { UINode, UIDisplay, type UINodeData } from '../core/ui-node';
import { px, percent } from '../core/dimension';
import { themeColors } from '../theme/tokens';
import { markThemed } from '../theme/theme-style';
-import { UIDialog, isDialogOpen, setDialogOpen } from '../behavior/dialog';
+import { UIDialog, isDialogOpen, openDialog, closeDialog } from '../behavior/dialog';
import type { UIEventQueue } from '../core/events';
export interface DialogOptions {
@@ -107,8 +107,8 @@ export function createDialog(opts: DialogOptions): DialogHandle {
entity: backdrop,
panelEntity: panel,
isOpen: () => isDialogOpen(world, backdrop),
- open: () => setDialogOpen(world, events, backdrop, true),
- close: () => setDialogOpen(world, events, backdrop, false),
+ open: () => openDialog(world, events, backdrop),
+ close: () => closeDialog(world, events, backdrop),
dispose: () => {
offChange?.();
if (world.valid(backdrop)) world.despawn(backdrop);
diff --git a/sdk/src/ui/widgets/progress.ts b/sdk/src/ui/widgets/progress.ts
index 03ebe9d70..c0e5c2761 100644
--- a/sdk/src/ui/widgets/progress.ts
+++ b/sdk/src/ui/widgets/progress.ts
@@ -34,7 +34,7 @@ export interface ProgressOptions {
export interface ProgressHandle {
readonly entity: Entity;
readonly fillEntity: Entity;
- value(): number;
+ getValue(): number;
setValue(v: number): void;
dispose(): void;
}
@@ -90,7 +90,7 @@ export function createProgress(opts: ProgressOptions): ProgressHandle {
return {
entity: track,
fillEntity: fill,
- value: () => value,
+ getValue: () => value,
setValue,
dispose: () => {
if (world.valid(track)) world.despawn(track);
diff --git a/sdk/src/ui/widgets/toggle.ts b/sdk/src/ui/widgets/toggle.ts
index c49c3d484..75c4a3dd0 100644
--- a/sdk/src/ui/widgets/toggle.ts
+++ b/sdk/src/ui/widgets/toggle.ts
@@ -49,8 +49,8 @@ export interface ToggleOptions {
export interface ToggleHandle {
readonly entity: Entity;
- isOn(): boolean;
- setIsOn(value: boolean): void;
+ getValue(): boolean;
+ setValue(value: boolean): void;
setDisabled(disabled: boolean): void;
dispose(): void;
}
@@ -59,7 +59,7 @@ export interface ToggleHandle {
* Compose a Toggle from a Button (interaction + visual states) plus a
* separate child entity driven by `isOn` for the check-mark visual.
* State + flipping live in the {@link UIToggle} component and its behavior
- * system — click, `setIsOn`, a binding, or the editor inspector all flip the
+ * system — click, `setValue`, a binding, or the editor inspector all flip the
* indicator and emit `change` identically.
*/
export function createToggle(opts: ToggleOptions): ToggleHandle {
@@ -104,8 +104,8 @@ export function createToggle(opts: ToggleOptions): ToggleHandle {
return {
entity: button,
- isOn: () => (world.get(button, UIToggle) as UIToggleData).isOn,
- setIsOn: (value: boolean) => {
+ getValue: () => (world.get(button, UIToggle) as UIToggleData).isOn,
+ setValue: (value: boolean) => {
const d = world.get(button, UIToggle) as UIToggleData;
if (d.isOn === value) return;
d.isOn = value;
diff --git a/sdk/tests/assets-preload.test.ts b/sdk/tests/assets-preload.test.ts
index fe2500dcf..a64641e4b 100644
--- a/sdk/tests/assets-preload.test.ts
+++ b/sdk/tests/assets-preload.test.ts
@@ -27,7 +27,9 @@ vi.mock('../src/resourceManager', () => ({
evictTextureDimensions: vi.fn(),
}));
-vi.mock('../src/platform', () => ({
+// TextureLoader/imageDecode import the concrete base module (cycle-free); the
+// rest go through the barrel — mock both ids with one factory.
+const platformFactory = vi.hoisted(() => () => ({
platformCreateCanvas: () => ({
width: 256, height: 256,
getContext: () => ({
@@ -46,6 +48,8 @@ vi.mock('../src/platform', () => ({
platformReadTextFile: vi.fn(),
platformFileExists: vi.fn(),
}));
+vi.mock('../src/platform', platformFactory);
+vi.mock('../src/platform/base', platformFactory);
const mockModule = {
_malloc: vi.fn(() => 0),
diff --git a/sdk/tests/net-binary.test.ts b/sdk/tests/net-binary.test.ts
index 381b81e51..32af6225d 100644
--- a/sdk/tests/net-binary.test.ts
+++ b/sdk/tests/net-binary.test.ts
@@ -76,7 +76,7 @@ describe('MemoryTransport manual flush', () => {
it('holds frames until flushed, delivers in send order with a limit', () => {
const [ta, tb] = MemoryTransport.pair({ manualFlush: true });
const got: string[] = [];
- tb.onMessage = (d) => got.push(d as string);
+ tb.on('message', (d) => got.push(d as string));
ta.send('1'); ta.send('2'); ta.send('3');
expect(got).toEqual([]);
expect(ta.pendingCount).toBe(3);
@@ -89,7 +89,7 @@ describe('MemoryTransport manual flush', () => {
it('dropPending simulates packet loss', () => {
const [ta, tb] = MemoryTransport.pair({ manualFlush: true });
const got: string[] = [];
- tb.onMessage = (d) => got.push(d as string);
+ tb.on('message', (d) => got.push(d as string));
ta.send('lost');
ta.dropPending();
ta.flush();
diff --git a/sdk/tests/net-channel.test.ts b/sdk/tests/net-channel.test.ts
index 5fede0367..c50e0c751 100644
--- a/sdk/tests/net-channel.test.ts
+++ b/sdk/tests/net-channel.test.ts
@@ -3,23 +3,36 @@
import { describe, it, expect, vi } from 'vitest';
import { NetChannel, type NetTransport } from '../src/net/NetChannel';
-/** A pair of in-memory transports wired to each other (a.send → b.onMessage). */
-function loopback(): [NetTransport, NetTransport] {
- const a: NetTransport = { onMessage: null, send: (d) => { b.onMessage?.(d); } };
- const b: NetTransport = { onMessage: null, send: (d) => { a.onMessage?.(d); } };
+type Frame = string | ArrayBuffer;
+
+function stubTransport(sendTo?: (d: Frame) => void): NetTransport & {
+ handlers: Set<(d: Frame) => void>;
+ receive(d: Frame): void;
+} {
+ const handlers = new Set<(d: Frame) => void>();
+ return {
+ handlers,
+ send: (d: Frame) => sendTo?.(d),
+ on: (_event, handler) => {
+ handlers.add(handler);
+ return () => handlers.delete(handler);
+ },
+ receive: (d: Frame) => { for (const h of [...handlers]) h(d); },
+ };
+}
+
+/** A pair of in-memory transports wired to each other (a.send → b's handlers). */
+function loopback(): [ReturnType<typeof stubTransport>, ReturnType<typeof stubTransport>] {
+ const a = stubTransport((d) => b.receive(d));
+ const b = stubTransport((d) => a.receive(d));
return [a, b];
}
/** A transport that captures sent frames and lets the test inject incoming ones. */
-function spyTransport(): NetTransport & { sent: string[]; receive(s: string | ArrayBuffer): void } {
+function spyTransport(): ReturnType<typeof stubTransport> & { sent: string[] } {
const sent: string[] = [];
- const t: any = {
- onMessage: null,
- sent,
- send: (d: string | ArrayBuffer) => { if (typeof d === 'string') sent.push(d); },
- receive: (s: string | ArrayBuffer) => t.onMessage?.(s),
- };
- return t;
+ const t = stubTransport((d) => { if (typeof d === 'string') sent.push(d); });
+ return Object.assign(t, { sent });
}
describe('NetChannel events', () => {
diff --git a/sdk/tests/replication-e2e-ws.test.ts b/sdk/tests/replication-e2e-ws.test.ts
index 12d5a6d23..e727534be 100644
--- a/sdk/tests/replication-e2e-ws.test.ts
+++ b/sdk/tests/replication-e2e-ws.test.ts
@@ -29,19 +29,23 @@ const delay = (ms: number) => new Promise((r) => setTimeout(r, ms));
/** Server-side end of one accepted `ws` connection as a NetTransport. */
function wsServerTransport(conn: WsSocket): NetTransport {
- const t: NetTransport = {
- onMessage: null,
- send: (d) => conn.send(d),
- };
+ const handlers = new Set<(d: string | ArrayBuffer) => void>();
conn.on('message', (data, isBinary) => {
- if (isBinary) {
- const buf = data as Buffer;
- t.onMessage?.(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) as ArrayBuffer);
- } else {
- t.onMessage?.(data.toString());
- }
+ const frame = isBinary
+ ? (() => {
+ const buf = data as Buffer;
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) as ArrayBuffer;
+ })()
+ : data.toString();
+ for (const h of [...handlers]) h(frame);
});
- return t;
+ return {
+ send: (d) => conn.send(d),
+ on: (_event, handler) => {
+ handlers.add(handler);
+ return () => handlers.delete(handler);
+ },
+ };
}
describe.skipIf(!HAS_WASM)('replication e2e over real WebSocket', () => {
diff --git a/sdk/tests/screen.test.ts b/sdk/tests/screen.test.ts
index 4dc1e5629..9849ba38b 100644
--- a/sdk/tests/screen.test.ts
+++ b/sdk/tests/screen.test.ts
@@ -24,10 +24,10 @@ describe('ScreenInfo', () => {
expect(screen.dpr).toBe(2);
});
- it('should fire orientation change callback', () => {
+ it('should fire orientation change listeners', () => {
const screen = new ScreenInfo();
const onChange = vi.fn();
- screen.onOrientationChange = onChange;
+ screen.on('orientationchange', onChange);
screen.update(750, 1334, 2);
expect(onChange).not.toHaveBeenCalled();
@@ -41,19 +41,23 @@ describe('ScreenInfo', () => {
const onChange = vi.fn();
screen.update(800, 600, 1);
- screen.onOrientationChange = onChange;
+ screen.on('orientationchange', onChange);
screen.update(1024, 768, 1);
expect(onChange).not.toHaveBeenCalled();
});
- it('should fire resize callback', () => {
+ it('should fire resize listeners until unsubscribed', () => {
const screen = new ScreenInfo();
const onResize = vi.fn();
- screen.onResize = onResize;
+ const off = screen.on('resize', onResize);
screen.update(800, 600, 1);
expect(onResize).toHaveBeenCalledWith(800, 600);
+
+ off();
+ screen.update(1024, 768, 1);
+ expect(onResize).toHaveBeenCalledTimes(1);
});
it('should treat square as portrait', () => {
diff --git a/sdk/tests/texture-residency.test.ts b/sdk/tests/texture-residency.test.ts
index c9086d6f9..7dbbb58cd 100644
--- a/sdk/tests/texture-residency.test.ts
+++ b/sdk/tests/texture-residency.test.ts
@@ -100,7 +100,9 @@ vi.mock('../src/resourceManager', () => ({
evictTextureDimensions: vi.fn(),
}));
-vi.mock('../src/platform', () => ({
+// TextureLoader/imageDecode import the concrete base module (cycle-free); the
+// rest go through the barrel — mock both ids with one factory.
+const platformFactory = vi.hoisted(() => () => ({
platformCreateCanvas: () => ({
width: 256, height: 256,
getContext: () => ({
@@ -119,6 +121,8 @@ vi.mock('../src/platform', () => ({
platformReadTextFile: vi.fn(),
platformFileExists: vi.fn(),
}));
+vi.mock('../src/platform', platformFactory);
+vi.mock('../src/platform/base', platformFactory);
const mockModule = {
_malloc: vi.fn(() => 0),
diff --git a/sdk/tests/ui-two-way-binding.test.ts b/sdk/tests/ui-two-way-binding.test.ts
index 109f49ad2..8d04e4c67 100644
--- a/sdk/tests/ui-two-way-binding.test.ts
+++ b/sdk/tests/ui-two-way-binding.test.ts
@@ -133,7 +133,7 @@ describe('bindWidgetValue', () => {
const muted = signal(true);
bindWidgetValue(
world as unknown as World, events, toggle.entity, UIToggle, 'isOn', muted);
- expect(toggle.isOn()).toBe(true);
+ expect(toggle.getValue()).toBe(true);
tick();
// Up: a click flips the component; change writes the signal.
diff --git a/sdk/tests/ui-widgets.test.ts b/sdk/tests/ui-widgets.test.ts
index e53c7073d..c03481c72 100644
--- a/sdk/tests/ui-widgets.test.ts
+++ b/sdk/tests/ui-widgets.test.ts
@@ -281,7 +281,7 @@ describe('createToggle', () => {
interactionStates: { normal: {}, hover: {}, pressed: {} },
isOn: true,
});
- expect(on.isOn()).toBe(true);
+ expect(on.getValue()).toBe(true);
expect((world.get(on.entity, UIToggle) as { isOn: boolean }).isOn).toBe(true);
});
@@ -297,13 +297,13 @@ describe('createToggle', () => {
tick(); // initial paint — no change event
events.emit(toggle.entity, UIEventType.Click);
- expect(toggle.isOn()).toBe(true);
+ expect(toggle.getValue()).toBe(true);
tick();
expect(onChange).toHaveBeenCalledWith(true, toggle.entity);
});
- it('setIsOn writes the component; the system emits one change per transition', () => {
+ it('setValue writes the component; the system emits one change per transition', () => {
const onChange = vi.fn();
const toggle = createToggle({
world: world as unknown as World,
@@ -313,14 +313,14 @@ describe('createToggle', () => {
});
tick();
- toggle.setIsOn(true);
+ toggle.setValue(true);
tick();
expect(onChange).toHaveBeenCalledTimes(1);
- toggle.setIsOn(true); // no-op
+ toggle.setValue(true); // no-op
tick();
expect(onChange).toHaveBeenCalledTimes(1);
- expect(toggle.isOn()).toBe(true);
+ expect(toggle.getValue()).toBe(true);
});
it('ignores clicks while disabled', () => {
@@ -332,7 +332,7 @@ describe('createToggle', () => {
});
tick();
events.emit(toggle.entity, UIEventType.Click);
- expect(toggle.isOn()).toBe(false);
+ expect(toggle.getValue()).toBe(false);
});
it('dispose despawns the root entity', () => {
@@ -360,13 +360,13 @@ describe('createProgress', () => {
world: world as unknown as World,
value: 1.5,
});
- expect(p.value()).toBe(1);
+ expect(p.getValue()).toBe(1);
const q = createProgress({
world: world as unknown as World,
value: -0.2,
});
- expect(q.value()).toBe(0);
+ expect(q.getValue()).toBe(0);
});
it('setValue writes fillAmount (default "right" = Filled from the left)', () => {
diff --git a/sdk/tests/websocket.test.ts b/sdk/tests/websocket.test.ts
index 810854d09..d1e7c316a 100644
--- a/sdk/tests/websocket.test.ts
+++ b/sdk/tests/websocket.test.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, it, expect, vi } from 'vitest';
-import { GameSocket, type GameSocketOptions } from '../src/net/GameSocket';
+import { GameSocket } from '../src/net/GameSocket';
describe('GameSocket', () => {
it('should create instance with url', () => {
@@ -10,22 +10,18 @@ describe('GameSocket', () => {
expect(socket.readyState).toBe('closed');
});
- it('should register callbacks', () => {
+ it('on() registers handlers and returns an unsubscribe', () => {
const socket = new GameSocket({ url: 'ws://test' });
const onOpen = vi.fn();
const onMessage = vi.fn();
- const onClose = vi.fn();
- const onError = vi.fn();
- socket.onOpen = onOpen;
- socket.onMessage = onMessage;
- socket.onClose = onClose;
- socket.onError = onError;
+ const offOpen = socket.on('open', onOpen);
+ const offMessage = socket.on('message', onMessage);
- expect(socket.onOpen).toBe(onOpen);
- expect(socket.onMessage).toBe(onMessage);
- expect(socket.onClose).toBe(onClose);
- expect(socket.onError).toBe(onError);
+ expect(typeof offOpen).toBe('function');
+ expect(typeof offMessage).toBe('function');
+ offOpen();
+ offMessage();
});
it('should have send and close methods', () => {