Skip to content

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

fix(ui): revalidate focus targets after synchronous callbacks

yhhc63577f15a16
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2a9150c16..b5a61fc9f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,8 @@ published separately; it ships inside the editor.
### Fixed
+- **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.
- **Sprite playback catches up without replaying a time backlog.** Complete loop crossings deliver events in playback order, zero-time updates do not repeat the initial event, and single-frame completion does not fire it again. Long updates restore the correct phase while coalescing each declared event to one notification per update. Stopped frame/label seeks update the pose, and changed frames write existing component values without rebuilding defaults.
diff --git a/sdk/src/ui/input/focus-inspection.ts b/sdk/src/ui/input/focus-inspection.ts
index 5c0b6047f..bb94356c3 100644
--- a/sdk/src/ui/input/focus-inspection.ts
+++ b/sdk/src/ui/input/focus-inspection.ts
@@ -9,7 +9,8 @@ import { UIDialog, isDialogOpen } from '../behavior/dialog';
import { walkParentChain } from '../util/helpers';
/** Read-only scene queries needed to inspect focus. @experimental */
-export type FocusInspectionWorld = Pick<World, 'getWasmModule' | 'getCppRegistry' | 'getEntitiesWithComponents' | 'valid' | 'has' | 'get'>;
+export type FocusInspectionWorld = Pick<World, 'getWasmModule' | 'getCppRegistry' | 'getEntitiesWithComponents' | 'valid' | 'has' | 'get'>
+ & Partial<Pick<World, 'isEntityActive'>>;
/** Why a focusable is absent from the current Tab ring. @experimental */
export type FocusSkipReason = 'disabled' | 'hidden' | 'outside-dialog';
@@ -26,8 +27,7 @@ export interface FocusTraversalInspection {
visibilityResolved: boolean;
}
-/** Inspect Tab order without moving focus or emitting events. @experimental */
-export function inspectFocusTraversal(world: FocusInspectionWorld): FocusTraversalInspection {
+function focusContext(world: FocusInspectionWorld) {
const engine = worldEngineApi(world);
const registry = world.getCppRegistry();
const visibilityResolved = !!(registry && engine?.getUINodeHiddenInTree);
@@ -42,24 +42,45 @@ export function inspectFocusTraversal(world: FocusInspectionWorld): FocusTravers
return false;
});
}
+ return { engine, registry, visibilityResolved, roots };
+}
+
+function skipReason(world: FocusInspectionWorld, entity: Entity,
+ { engine, registry, visibilityResolved, roots }: ReturnType<typeof focusContext>): FocusSkipReason | null {
+ let skipped: FocusSkipReason | null = null;
+ if (world.has(entity, Interactable) && !world.get(entity, Interactable).enabled) {
+ skipped = 'disabled';
+ } else if (visibilityResolved && engine!.getUINodeHiddenInTree!(registry!, entity)) {
+ skipped = 'hidden';
+ } else if (roots.size > 0 && !roots.has(entity)) {
+ let inside = false;
+ walkParentChain(world, entity, ancestor => {
+ inside = roots.has(ancestor);
+ return inside;
+ });
+ if (!inside) skipped = 'outside-dialog';
+ }
+ return skipped;
+}
+
+/** Check a single target without sorting the entire Tab ring. */
+export function isFocusEligible(world: FocusInspectionWorld, entity: Entity): boolean {
+ if (!world.valid(entity) || !world.has(entity, Focusable)) return false;
+ const active = world.isEntityActive
+ ? world.isEntityActive(entity)
+ : world.getEntitiesWithComponents([Focusable]).includes(entity);
+ return active && skipReason(world, entity, focusContext(world)) === null;
+}
+
+/** Inspect Tab order without moving focus or emitting events. @experimental */
+export function inspectFocusTraversal(world: FocusInspectionWorld): FocusTraversalInspection {
+ const context = focusContext(world);
const entries: FocusTraversalEntry[] = [];
for (const entity of world.getEntitiesWithComponents([Focusable])) {
if (!world.valid(entity)) continue;
- let skipped: FocusSkipReason | null = null;
- if (world.has(entity, Interactable) && !world.get(entity, Interactable).enabled) {
- skipped = 'disabled';
- } else if (visibilityResolved && engine!.getUINodeHiddenInTree!(registry!, entity)) {
- skipped = 'hidden';
- } else if (roots.size > 0 && !roots.has(entity)) {
- let inside = false;
- walkParentChain(world, entity, ancestor => {
- inside = roots.has(ancestor);
- return inside;
- });
- if (!inside) skipped = 'outside-dialog';
- }
- entries.push({ entity, tabIndex: world.get(entity, Focusable).tabIndex, skipped });
+ entries.push({ entity, tabIndex: world.get(entity, Focusable).tabIndex,
+ skipped: skipReason(world, entity, context) });
}
entries.sort((a, b) => a.tabIndex - b.tabIndex);
- return { entries, visibilityResolved };
+ return { entries, visibilityResolved: context.visibilityResolved };
}
diff --git a/sdk/src/ui/input/focus.ts b/sdk/src/ui/input/focus.ts
index bcd592485..498853a29 100644
--- a/sdk/src/ui/input/focus.ts
+++ b/sdk/src/ui/input/focus.ts
@@ -13,7 +13,7 @@ import { UIInteraction } from './interactable';
import type { UIInteractionData } from './interactable';
import { TextInput } from '../text/text-input';
import { setKeyDefaultPolicy, tabWasShifted } from '../../input/keyDefaultPolicy';
-import { inspectFocusTraversal } from './focus-inspection';
+import { inspectFocusTraversal, isFocusEligible } from './focus-inspection';
import { playModeOnly } from '../../ecs/env';
import { UIEvents, UIEventQueue, UIEventType } from '../core/events';
import { PluginName } from '../../ecs/systemLabels';
@@ -40,11 +40,10 @@ export class FocusPlugin implements Plugin {
this.keyDefaults_.set(app, setKeyDefaultPolicy(app.getResource(Input), code => {
if (!playModeOnly() || app.isPaused()) return false;
if (code !== 'Tab' && code !== 'Enter' && code !== 'Space') return false;
- const entries = inspectFocusTraversal(world).entries;
- if (code === 'Tab') return entries.some(entry => entry.skipped === null);
+ if (code === 'Tab') return inspectFocusTraversal(world).entries.some(entry => entry.skipped === null);
const focused = focusManager.focusedEntity;
return focused !== null && world.valid(focused) && !world.has(focused, TextInput)
- && entries.some(entry => entry.entity === focused && entry.skipped === null);
+ && isFocusEligible(world, focused);
}));
app.addSystemToSchedule(Schedule.Update, defineSystem(
@@ -86,7 +85,7 @@ export class FocusPlugin implements Plugin {
if (focused !== null && world.valid(focused) && !world.has(focused, TextInput)
&& (input.isKeyPressed('Enter') || input.isKeyPressed('Space'))) {
// Focus/blur handlers can change dialog or enabled state synchronously.
- if (inspectFocusTraversal(world).entries.some(entry => entry.entity === focused && entry.skipped === null)) {
+ if (isFocusEligible(world, focused)) {
events.emit(focused, UIEventType.Click);
} else {
clearFocus();
@@ -118,6 +117,7 @@ export class FocusPlugin implements Plugin {
}
function setFocus(entity: Entity, visible: boolean): void {
+ if (!isFocusEligible(world, entity)) return;
const prev = focusManager.focusedEntity;
// Re-focusing what is already focused still updates HOW: tabbing
// to a control you had clicked must start drawing the highlight.
@@ -126,24 +126,27 @@ export class FocusPlugin implements Plugin {
return;
}
- blurEntity(prev);
+ clearFocus();
+ // A blur handler can remove the target, open a modal, or redirect focus.
+ if (focusManager.focusedEntity !== null || !isFocusEligible(world, entity)) return;
focusManager.focus(entity, visible);
const f = world.get(entity, Focusable) as FocusableData;
f.isFocused = true;
- world.insert(entity, Focusable, f);
+ world.set(entity, Focusable, f);
events.emit(entity, UIEventType.Focus);
+ if (focusManager.focusedEntity === entity && !isFocusEligible(world, entity)) clearFocus();
}
function clearFocus(): void {
- blurEntity(focusManager.focusedEntity);
- focusManager.blur();
+ const previous = focusManager.blur();
+ blurEntity(previous);
}
function blurEntity(entity: Entity | null): void {
if (entity === null || !world.valid(entity) || !world.has(entity, Focusable)) return;
const f = world.get(entity, Focusable) as FocusableData;
f.isFocused = false;
- world.insert(entity, Focusable, f);
+ world.set(entity, Focusable, f);
events.emit(entity, UIEventType.Blur);
}
},
diff --git a/sdk/tests/ui-focus-plugin.test.ts b/sdk/tests/ui-focus-plugin.test.ts
index 0b958a263..e625cf6e0 100644
--- a/sdk/tests/ui-focus-plugin.test.ts
+++ b/sdk/tests/ui-focus-plugin.test.ts
@@ -342,3 +342,38 @@ it('rechecks eligibility after a synchronous focus handler opens a dialog', asyn
expect(focused()).toBe(null);
expect(clicks).toBe(0);
});
+
+it('does not focus a target deleted by the previous control blur callback', async () => {
+ const first = addFocusable(0), next = addFocusable(1);
+ await tab();
+ app.getResource(UIEvents).on(first, 'blur', () => app.world.despawn(next));
+ await tab();
+ expect(focused()).toBe(null);
+});
+
+it('rechecks modal eligibility after the previous control blur callback', async () => {
+ const first = addFocusable(0), next = addFocusable(1);
+ const dialog = app.world.spawn(); app.world.insert(dialog, UINode, {});
+ await tab();
+ app.getResource(UIEvents).on(first, 'blur', () => app.world.insert(dialog, UIDialog, {}));
+ await tab();
+ expect(focused()).toBe(null);
+ expect(isFocused(next)).toBe(false);
+});
+
+it('clears focus immediately when the focus callback destroys its control', async () => {
+ const entity = addFocusable(0);
+ app.getResource(UIEvents).on(entity, 'focus', () => app.world.despawn(entity));
+ await tab();
+ expect(focused()).toBe(null);
+});
+
+it('reports cleared manager state to blur callbacks before focusing the next control', async () => {
+ const first = addFocusable(0), next = addFocusable(1);
+ await tab();
+ const observed: (Entity | null)[] = [];
+ app.getResource(UIEvents).on(first, 'blur', () => observed.push(focused()));
+ await tab();
+ expect(observed).toEqual([null]);
+ expect(focused()).toBe(next);
+});
diff --git a/sdk/tests/ui-focus-transition-wasm.test.ts b/sdk/tests/ui-focus-transition-wasm.test.ts
new file mode 100644
index 000000000..e750b063f
--- /dev/null
+++ b/sdk/tests/ui-focus-transition-wasm.test.ts
@@ -0,0 +1,83 @@
+// 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 { Disabled, Parent } from '../src/ecs/component';
+import { setEditorMode, setPlayMode } from '../src/ecs/env';
+import { Input, InputState } from '../src/input/input';
+import { UIEvents, UIEventQueue } from '../src/ui/core/events';
+import { UIDialog } from '../src/ui/behavior/dialog';
+import { UINode } from '../src/ui/core/ui-node';
+import { Focusable, FocusManager } from '../src/ui/input/focusable';
+import { focusPlugin } from '../src/ui/input/focus';
+import { inspectFocusTraversal, isFocusEligible } from '../src/ui/input/focus-inspection';
+import type { CppRegistry, ESEngineModule } from '../src/wasm';
+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';
+
+describe.skipIf(!HAS_WASM)('focus transitions 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(UIEvents, new UIEventQueue());
+ focusPlugin.build(app); flushPendingRegistrations(app);
+ });
+ afterEach(() => {
+ focusPlugin.cleanup(app);
+ for (const entity of app.world.getAllEntities()) app.world.despawn(entity);
+ app.world.disconnectCpp(); registry.delete();
+ });
+ const control = (tabIndex: number) => {
+ const entity = app.world.spawn();
+ app.world.insert(entity, Focusable, { tabIndex });
+ return entity;
+ };
+ const tab = async () => {
+ app.getResource(Input).keysPressed.add('Tab');
+ await app.tick(1 / 60);
+ app.getResource(Input).keysPressed.clear();
+ };
+ it.each(['despawn', 'remove', 'modal', 'disable'] as const)(
+ 'rejects a next target invalidated by blur: %s', async mutation => {
+ const first = control(0), next = control(1);
+ const modal = app.world.spawn(); app.world.insert(modal, UINode);
+ await tab();
+ app.getResource(UIEvents).on(first, 'blur', () => {
+ if (mutation === 'despawn') app.world.despawn(next);
+ if (mutation === 'remove') app.world.remove(next, Focusable);
+ if (mutation === 'modal') app.world.insert(modal, UIDialog);
+ if (mutation === 'disable') app.world.insert(next, Disabled);
+ });
+ await tab();
+ expect(app.getResource(FocusManager).focusedEntity).toBeNull();
+ if (app.world.valid(next) && app.world.has(next, Focusable)) {
+ expect(app.world.get(next, Focusable).isFocused).toBe(false);
+ }
+ });
+ it('clears a target deleted by its focus callback in the same tick', async () => {
+ const entity = control(0);
+ app.getResource(UIEvents).on(entity, 'focus', () => app.world.despawn(entity));
+ await tab();
+ expect(app.getResource(FocusManager).focusedEntity).toBeNull();
+ });
+ it('checks inherited inactivity without enumerating other focusables', () => {
+ const parent = app.world.spawn(), entity = control(0);
+ app.world.insert(entity, Parent, { entity: parent });
+ expect(isFocusEligible(app.world, entity)).toBe(true);
+ app.world.insert(parent, Disabled);
+ expect(inspectFocusTraversal(app.world).entries).toEqual([]);
+ expect(isFocusEligible(app.world, entity)).toBe(false);
+ app.world.remove(parent, Disabled);
+ const queries = vi.spyOn(app.world, 'getEntitiesWithComponents');
+ expect(isFocusEligible(app.world, entity)).toBe(true);
+ expect(queries.mock.calls.every(([components]) => !components.includes(Focusable))).toBe(true);
+ queries.mockRestore();
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index a0c0fbd36..9acf82b5f 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): revalidate focus targets after synchronous callbacks':
+ { note: 'UI focus transitions recheck callback changes.' },
'fix(animation): guard reentrant updates and frame-list changes':
{ note: 'Sprite callbacks cannot recursively advance the same animation update.' },
'fix(build): link context tests with WebGL 2 symbols':