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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(ui): cancel pointer events invalidated by callbacks
yhh712f1795351d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b5a61fc9f..e43168181 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Fixed+- **Pointer callbacks cancel invalid UI interactions immediately.** Disabling or deleting a control during hover, press or release stops later events from the same batch. Invalidated captures and interaction edges clear in the same frame, so re-enabling a button does not complete an old press.+- **UI focus transitions recheck callback changes.** Removing or disabling a control and opening a modal during blur cannot focus a stale or excluded target. Focus callbacks that remove their control clear the manager in the same update. Blur handlers observe the cleared state, and single-target keyboard eligibility avoids sorting the entire Tab ring.- **Sprite callbacks cannot recursively advance the same animation update.** Nested updates are ignored and exceptions release the update guard. Clearing, replacing or shortening a clip's frame list inside a callback stops stale dispatch and reapplies a valid pose on a later update instead of reading a removed frame.diff --git a/sdk/src/ui/input/interaction.ts b/sdk/src/ui/input/interaction.tsindex 57e0620d8..6502e2463 100644--- a/sdk/src/ui/input/interaction.ts+++ b/sdk/src/ui/input/interaction.ts@@ -37,6 +37,7 @@ function emitWithBubbling(type: string,): void {const event = events.emit(entity, type);+ if (!world.valid(entity)) return;walkParentChain(world, entity, (ancestor) => {if (event.propagationStopped) return true;@@ -102,7 +103,7 @@ export class UIInteractionPlugin implements Plugin {if (interaction.justPressed || interaction.justReleased) {interaction.justPressed = false;interaction.justReleased = false;- world.insert(entity, UIInteraction, interaction);+ world.set(entity, UIInteraction, interaction);}}@@ -167,8 +168,11 @@ export class UIInteractionPlugin implements Plugin {const wasPressed = new Set(book.pressed);const wasHovered = new Set(book.hovered);- for (const event of book.step(pointers, hit,- e => eligible(e) && (camera.valid || overlay.active))) {+ const active = (entity: Entity): boolean => eligible(entity) && (camera.valid || overlay.active);+ const pointerEvents = book.step(pointers, hit, active);+ for (const event of pointerEvents) {+ // Earlier events in this batch can disable or remove a later target.+ if (!active(event.entity)) continue;switch (event.kind) {case 'hoverEnter':ensureComponent(world, event.entity, UIInteraction);@@ -181,12 +185,12 @@ export class UIInteractionPlugin implements Plugin {ensureComponent(world, event.entity, UIInteraction);// A complete click may arrive between frames. Preserve its// edge even when the final held-state is already false.- world.insert(event.entity, UIInteraction, { ...world.get(event.entity, UIInteraction), justPressed: true });+ world.set(event.entity, UIInteraction, { ...world.get(event.entity, UIInteraction), justPressed: true });emitWithBubbling(world, events, event.entity, UIEventType.Press);break;case 'release':if (world.has(event.entity, UIInteraction))- world.insert(event.entity, UIInteraction, { ...world.get(event.entity, UIInteraction), justReleased: true });+ world.set(event.entity, UIInteraction, { ...world.get(event.entity, UIInteraction), justReleased: true });emitWithBubbling(world, events, event.entity, UIEventType.Release);break;case 'click':@@ -194,31 +198,36 @@ export class UIInteractionPlugin implements Plugin {break;}}+ book.prune(active);// `hovered` and `pressed` are facts about the ENTITY: true while// any pointer is over or holding it, false once none is.const hovered = book.hovered;const pressed = book.pressed;const touched = new Set<Entity>([...interactionEntities, ...hovered, ...pressed, ...wasPressed, ...wasHovered]);+ for (const event of pointerEvents) touched.add(event.entity);for (const entity of touched) {if (!world.valid(entity) || !world.has(entity, UIInteraction)) continue;const data = world.get(entity, UIInteraction) as UIInteractionData;- const isHovered = hovered.has(entity);- const isPressed = pressed.has(entity);- const active = eligible(entity) && (camera.valid || overlay.active);- const justPressed = active && (data.justPressed || (isPressed && !wasPressed.has(entity)));- const justReleased = active && (data.justReleased || (!isPressed && wasPressed.has(entity)));+ const isActive = active(entity);+ const isHovered = isActive && hovered.has(entity);+ const isPressed = isActive && pressed.has(entity);+ const justPressed = isActive && (data.justPressed || (isPressed && !wasPressed.has(entity)));+ const justReleased = isActive && (data.justReleased || (!isPressed && wasPressed.has(entity)));if (data.hovered === isHovered && data.pressed === isPressed&& data.justPressed === justPressed && data.justReleased === justReleased) continue;data.hovered = isHovered;data.pressed = isPressed;data.justPressed = justPressed;data.justReleased = justReleased;- world.insert(entity, UIInteraction, data);+ world.set(entity, UIInteraction, data);}// Gameplay reads this (Update) to skip input the UI claimed.- input.pointerOverUI = overUI;+ input.pointerOverUI = overUI && pointers.some(pointer => {+ const entity = lastHit.get(pointer.id)?.entity;+ return entity != null && active(entity);+ });},{ name: 'UIInteractionSystem' }), { runAfter: [SystemLabel.UILayout], runIf: playModeOnly });diff --git a/sdk/src/ui/input/pointerBook.ts b/sdk/src/ui/input/pointerBook.tsindex d0784bca5..824b099fd 100644--- a/sdk/src/ui/input/pointerBook.ts+++ b/sdk/src/ui/input/pointerBook.ts@@ -161,12 +161,17 @@ export class UiPointerBook {}// A control that died under a pointer stops being held, silently.- for (const [id, entity] of [...this.hoveredBy_]) if (!alive(entity)) this.hoveredBy_.delete(id);- for (const [id, entity] of [...this.pressedBy_]) if (!alive(entity)) this.pressedBy_.delete(id);+ this.prune(alive);return out;}+ /** Drop captures invalidated by synchronous event callbacks, without new events. */+ prune(alive: (entity: Entity) => boolean): void {+ for (const [id, entity] of this.hoveredBy_) if (!alive(entity)) this.hoveredBy_.delete(id);+ for (const [id, entity] of this.pressedBy_) if (!alive(entity)) this.pressedBy_.delete(id);+ }+/** Forget every pointer — a realm tearing its UI down owes no events. */clear(): void {this.hoveredBy_.clear();diff --git a/sdk/tests/ui-pointer-callback-wasm.test.ts b/sdk/tests/ui-pointer-callback-wasm.test.tsnew file mode 100644index 000000000..5c804df9d--- /dev/null+++ b/sdk/tests/ui-pointer-callback-wasm.test.ts@@ -0,0 +1,66 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { App, flushPendingRegistrations } from '../src/app/app';+import { AppContext, setDefaultContext } from '../src/ecs/context';+import { setEditorMode, setPlayMode } from '../src/ecs/env';+import { Input, InputState } from '../src/input/input';+import { UICameraInfo } from '../src/ui/core/ui-camera-info';+import { ScreenOverlay } from '../src/ui/core/screen-overlay';+import { UILayoutGeneration } from '../src/ui/layout/ui-layout-generation';+import { Interactable, UIInteraction } from '../src/ui/input/interactable';+import { uiInteractionPlugin } from '../src/ui/input/interaction';+import { UIEvents } from '../src/ui/core/events';+import type { CppRegistry, ESEngineModule } from '../src/wasm';+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';+const hit = vi.hoisted(() => ({ entity: null as number | null }));+// Deterministic picking isolates event dispatch over the actual WASM Registry.+vi.mock('../src/ui/util/ui-pick', () => ({+ screenToUiWorld: () => ({ x: 0, y: 0 }), screenToUiLayout: () => ({ x: 0, y: 0 }),+ uiPointerRay: () => ({}), uiLayoutRay: () => ({}), uiHitTestWorld: () => hit.entity,+}));++describe.skipIf(!HAS_WASM)('pointer callback lifecycle on real WASM', () => {+ let engine: ESEngineModule;+ let registry: CppRegistry;+ let app: App;+ beforeAll(async () => { engine = await loadWasmModule(); });+ beforeEach(() => {+ setDefaultContext(new AppContext()); setEditorMode(false); setPlayMode(false);+ registry = new engine.Registry(); app = App.new(); app.connectCpp(registry, engine);+ app.insertResource(Input, new InputState());+ app.insertResource(UICameraInfo, { valid: false } as any);+ app.insertResource(ScreenOverlay, { active: true, surfaceH: 600 } as any);+ app.insertResource(UILayoutGeneration, { generation: 0 });+ uiInteractionPlugin.build(app); flushPendingRegistrations(app);+ });+ afterEach(() => {+ for (const entity of app.world.getAllEntities()) app.world.despawn(entity);+ app.world.disconnectCpp(); registry.delete();+ });+ for (const mutation of ['disable', 'despawn'] as const) {+ it.each(['hover_enter', 'press', 'release'])(`${mutation} during %s stops later events`, async phase => {+ const entity = app.world.spawn(); hit.entity = entity;+ app.world.insert(entity, Interactable, { enabled: true });+ const kinds: string[] = [];+ for (const kind of ['hover_enter', 'press', 'release', 'click']) {+ app.getResource(UIEvents).on(entity, kind, () => {+ kinds.push(kind);+ if (kind !== phase) return;+ if (mutation === 'despawn') app.world.despawn(entity);+ else app.world.update(entity, Interactable, data => { data.enabled = false; });+ });+ }+ const input = app.getResource(Input);+ input.noteMouseDown(0); input.noteMouseUp(0);+ await app.tick(1 / 60);+ const order = ['hover_enter', 'press', 'release'];+ expect(kinds).toEqual(order.slice(0, order.indexOf(phase) + 1));+ expect(input.pointerOverUI).toBe(false);+ if (mutation === 'despawn') expect(app.world.valid(entity)).toBe(false);+ else expect(app.world.get(entity, UIInteraction)).toMatchObject({+ hovered: false, pressed: false, justPressed: false, justReleased: false,+ });+ });+ }+});diff --git a/sdk/tests/ui-quick-click-focus.test.ts b/sdk/tests/ui-quick-click-focus.test.tsindex 1dc019d3c..9a3c033fe 100644--- a/sdk/tests/ui-quick-click-focus.test.ts+++ b/sdk/tests/ui-quick-click-focus.test.ts@@ -24,6 +24,47 @@ vi.mock('../src/ui/util/ui-pick', () => ({}));describe('quick pointer focus through real interaction projection', () => {+ it.each(['hover_enter', 'press', 'release'])('stops a queued click when %s disables the control', async phase => {+ const { app } = bootMockApp(); const input = new InputState();+ app.insertResource(Input, input);+ app.insertResource(UICameraInfo, { valid: false } as any);+ app.insertResource(ScreenOverlay, { active: true, surfaceH: 600 } as any);+ app.insertResource(UILayoutGeneration, { generation: 0 });+ uiInteractionPlugin.build(app); flushPendingRegistrations(app);+ const entity = app.world.spawn();+ app.world.insert(entity, Interactable, { enabled: true }); hit.entity = entity;+ const kinds: string[] = [];+ for (const kind of ['hover_enter', 'press', 'release', 'click']) {+ app.getResource(UIEvents).on(entity, kind, () => {+ kinds.push(kind);+ if (kind === phase) app.world.update(entity, Interactable, data => { data.enabled = false; });+ });+ }+ input.noteMouseDown(0); input.noteMouseUp(0);+ await app.tick(1 / 60);+ const order = ['hover_enter', 'press', 'release'];+ expect(kinds).toEqual(order.slice(0, order.indexOf(phase) + 1));+ expect(app.world.get(entity, UIInteraction)).toMatchObject({ hovered: false, pressed: false, justPressed: false, justReleased: false });+ expect(input.pointerOverUI).toBe(false);+ });+ it('cancels a held press disabled by its press handler without restoring capture', async () => {+ const { app } = bootMockApp(); const input = new InputState();+ app.insertResource(Input, input);+ app.insertResource(UICameraInfo, { valid: false } as any);+ app.insertResource(ScreenOverlay, { active: true, surfaceH: 600 } as any);+ app.insertResource(UILayoutGeneration, { generation: 0 });+ uiInteractionPlugin.build(app); flushPendingRegistrations(app);+ const entity = app.world.spawn();+ app.world.insert(entity, Interactable, { enabled: true }); hit.entity = entity;+ app.getResource(UIEvents).on(entity, 'press', () => app.world.update(entity, Interactable, data => { data.enabled = false; }));+ const click = vi.fn(); app.getResource(UIEvents).on(entity, 'click', click);+ input.noteMouseDown(0); await app.tick(1 / 60);+ expect(app.world.get(entity, UIInteraction).pressed).toBe(false);+ input.clearFrameState();+ app.world.update(entity, Interactable, data => { data.enabled = true; });+ input.noteMouseUp(0); await app.tick(1 / 60);+ expect(click).not.toHaveBeenCalled();+ });it.each(['control', 'surface'])('clears capture when the %s is switched off', async (reason) => {const { app } = bootMockApp(); const input = new InputState();const overlay = { active: true, surfaceH: 600 } as any;diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 9acf82b5f..e1ff3c753 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'fix(ui): cancel pointer events invalidated by callbacks':+ { note: 'Pointer callbacks cancel invalid UI interactions immediately.' },'fix(ui): revalidate focus targets after synchronous callbacks':{ note: 'UI focus transitions recheck callback changes.' },'fix(animation): guard reentrant updates and frame-list changes':