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): clear focus when live navigation eligibility changes (#79)

YHH550569282df3
diff --git a/examples/ui-localization-debug/README.md b/examples/ui-localization-debug/README.md
index 972bc55b8..6ca3974da 100644
--- a/examples/ui-localization-debug/README.md
+++ b/examples/ui-localization-debug/README.md
@@ -94,3 +94,10 @@ Use Focus, click Inside, then cycle Tab and Shift+Tab; Enter/Space trigger its
actual project handler. Check both the live FocusManager row and browser focus.
Host buttons/forms retain browser navigation. Keep device IME/accessibility
acceptance separate from these Web input and DOM guard checks.
+
+
+For live modal checks, first click Inside to create Runtime button. Game key M
+marks the runtime button as a UIDialog; the Focus view should mark Inside and
+Partial outside the dialog and clear their old game focus. Tab then Enter
+confirms the dialog. D disables the current focus; E restores those controls;
+R removes the test dialog. These keys run normal project systems in Play.
diff --git a/examples/ui-localization-debug/VALIDATION.md b/examples/ui-localization-debug/VALIDATION.md
index c17751d75..b2b6e607b 100644
--- a/examples/ui-localization-debug/VALIDATION.md
+++ b/examples/ui-localization-debug/VALIDATION.md
@@ -232,3 +232,29 @@ snapshot; live-game-only dialogs and scripts need runtime acceptance separately.
- No Electron/native runner launched. Desktop custom-scheme, device keyboard,
real IME/assistive technology, shaping and performance acceptance remain
open. RM-009 remains In Progress.
+
+
+## Dynamic dialog and focus eligibility — 2026-10-09
+
+- Engine #78 merged after the current-head Android API 29–36, packaging and
+ report checks all passed. Emulator boot coverage is separate from device
+ keyboard/IME acceptance.
+- FocusSystem now clears focus and its visibility when an entity becomes
+ disabled, hidden, outside an open dialog, invalid or loses Focusable. Pointer
+ focus uses the same live eligibility rule. Enter/Space rechecks after
+ synchronous focus handlers so opening a modal cannot activate the old
+ background control in the same frame.
+- Built-in browser using the production Play host and real game key input:
+ Inside creates Runtime button; M adds an actual UIDialog to that entity.
+ Focus shows 1 eligible/2 outside-dialog entries and no current focus. Enter
+ leaves background Text at Clicks 1 and the dialog present. Tab focuses the
+ dialog button; Enter confirms and removes UIDialog, restoring 3 entries.
+ D disables the focused button: 2 eligible/1 disabled and no focus. E restores
+ it; Shift+Tab can focus it again. No injected event queue or world mutation
+ from browser evaluation was used.
+- 37 targeted SDK tests pass, including stale disabled/removed-component focus,
+ modal background activation, pointer focus eligibility and a synchronous
+ focus-handler modal change. SDK build and 16 API/built declaration checks pass.
+- No Electron/native runner launched. Multiple/nested modal arbitration,
+ real devices, IME/assistive technology, desktop custom-scheme, complex text
+ shaping and layout-cache performance remain open. RM-009 is In Progress.
diff --git a/sdk/src/ui/input/focus.ts b/sdk/src/ui/input/focus.ts
index 7f448ad97..bcd592485 100644
--- a/sdk/src/ui/input/focus.ts
+++ b/sdk/src/ui/input/focus.ts
@@ -9,8 +9,6 @@ import type { InputState } from '../../input/input';
import type { Entity } from '../../types';
import { Focusable, FocusManager, FocusManagerState } from './focusable';
import type { FocusableData } from './focusable';
-import { Interactable } from './interactable';
-import type { InteractableData } from './interactable';
import { UIInteraction } from './interactable';
import type { UIInteractionData } from './interactable';
import { TextInput } from '../text/text-input';
@@ -19,8 +17,6 @@ import { inspectFocusTraversal } from './focus-inspection';
import { playModeOnly } from '../../ecs/env';
import { UIEvents, UIEventQueue, UIEventType } from '../core/events';
import { PluginName } from '../../ecs/systemLabels';
-import type { CppRegistry } from '../../wasm';
-import { engineApi } from '../../ecs/bridge/engineApi';
export class FocusPlugin implements Plugin {
name = PluginName.Focus;
@@ -38,8 +34,6 @@ export class FocusPlugin implements Plugin {
registerComponent('Focusable', Focusable);
const world = app.world;
- const engine = engineApi(app);
- const registry = engine ? (world.getCppRegistry() as CppRegistry) : undefined;
const focusManager = new FocusManagerState();
app.insertResource(FocusManager, focusManager);
this.keyDefaults_.get(app)?.();
@@ -53,24 +47,16 @@ export class FocusPlugin implements Plugin {
&& entries.some(entry => entry.entity === focused && entry.skipped === null);
}));
-
- // display:none removes an entity from rendering + hit-testing; the Tab
- // ring must skip it too or focus lands on invisible controls.
- const hiddenInTree = (e: Entity): boolean =>
- !!(engine?.getUINodeHiddenInTree && registry
- && engine.getUINodeHiddenInTree(registry, e));
-
app.addSystemToSchedule(Schedule.Update, defineSystem(
[Res(Input), Res(UIEvents)],
(input: InputState, events: UIEventQueue) => {
- if (focusManager.focusedEntity !== null && !world.valid(focusManager.focusedEntity)) {
- focusManager.focusedEntity = null;
- } else if (focusManager.focusedEntity !== null && hiddenInTree(focusManager.focusedEntity)) {
- // A focused control hidden out from under us (e.g. a dialog closed
- // by its own Confirm button) must lose focus, or a later Enter/Space
- // would re-fire Click on the now-invisible control.
- clearFocus();
- }
+ // Live eligibility also governs stale focus and pointer focus, so
+ // opening a dialog cannot leave activation on a background control.
+ const eligible = inspectFocusTraversal(world).entries
+ .filter(entry => entry.skipped === null).map(entry => entry.entity);
+ const eligibleSet = new Set(eligible);
+ if (focusManager.focusedEntity !== null
+ && !eligibleSet.has(focusManager.focusedEntity)) clearFocus();
const focusableEntities = world.getEntitiesWithComponents([Focusable]);
@@ -78,7 +64,7 @@ export class FocusPlugin implements Plugin {
for (const entity of focusableEntities) {
if (!world.has(entity, UIInteraction)) continue;
const interaction = world.get(entity, UIInteraction) as UIInteractionData;
- if (interaction.justPressed) {
+ if (interaction.justPressed && eligibleSet.has(entity)) {
pressedFocusable = true;
// Focus, but NOT visibly: a pointer press moves focus so
// Enter/Space act on what you clicked, while the control
@@ -99,13 +85,17 @@ export class FocusPlugin implements Plugin {
const focused = focusManager.focusedEntity;
if (focused !== null && world.valid(focused) && !world.has(focused, TextInput)
&& (input.isKeyPressed('Enter') || input.isKeyPressed('Space'))) {
- const enabled = !world.has(focused, Interactable)
- || (world.get(focused, Interactable) as InteractableData).enabled;
- if (enabled) events.emit(focused, UIEventType.Click);
+ // Focus/blur handlers can change dialog or enabled state synchronously.
+ if (inspectFocusTraversal(world).entries.some(entry => entry.entity === focused && entry.skipped === null)) {
+ events.emit(focused, UIEventType.Click);
+ } else {
+ clearFocus();
+ }
}
if (input.isKeyPressed('Tab')) {
- const sorted = getSortedFocusables();
+ const sorted = inspectFocusTraversal(world).entries
+ .filter(entry => entry.skipped === null).map(entry => entry.entity);
if (sorted.length === 0) return;
const currentIdx = focusManager.focusedEntity !== null
@@ -127,11 +117,6 @@ export class FocusPlugin implements Plugin {
setFocus(sorted[nextIdx], true);
}
- function getSortedFocusables(): Entity[] {
- return inspectFocusTraversal(world).entries
- .filter(entry => entry.skipped === null).map(entry => entry.entity);
- }
-
function setFocus(entity: Entity, visible: boolean): void {
const prev = focusManager.focusedEntity;
// Re-focusing what is already focused still updates HOW: tabbing
diff --git a/sdk/tests/ui-focus-plugin.test.ts b/sdk/tests/ui-focus-plugin.test.ts
index e20db2b66..0b958a263 100644
--- a/sdk/tests/ui-focus-plugin.test.ts
+++ b/sdk/tests/ui-focus-plugin.test.ts
@@ -17,6 +17,8 @@ import { Focusable, FocusManager } from '../src/ui/input/focusable';
import { Interactable, UIInteraction } from '../src/ui/input/interactable';
import { focusPlugin } from '../src/ui/input/focus';
import { setEditorMode } from '../src/ecs/env';
+import { UIDialog } from '../src/ui/behavior/dialog';
+import { UINode } from '../src/ui/core/ui-node';
import { TextInput } from '../src/ui/text/text-input';
import { bootMockApp } from './helpers/mockApp';
import type { Entity } from '../src/types';
@@ -266,3 +268,77 @@ it('does not reuse a released Shift for the next frame Tab', async () => {
await app.tick(1 / 60);
expect(focused()).toBe(first);
});
+
+
+describe('dynamic focus eligibility', () => {
+ it('blurs a newly disabled focused control and cannot activate it', async () => {
+ const entity = addFocusable(0);
+ await tab();
+ const events = app.getResource(UIEvents);
+ let clicks = 0, blurs = 0;
+ events.on(entity, 'click', () => clicks++);
+ events.on(entity, 'blur', () => blurs++);
+ app.world.insert(entity, Interactable, { enabled: false });
+ app.getResource(Input).keysPressed.add('Enter');
+ await app.tick(1 / 60);
+ expect(focused()).toBe(null);
+ expect(isFocused(entity)).toBe(false);
+ expect(blurs).toBe(1);
+ expect(clicks).toBe(0);
+ });
+
+ it('opening a dialog clears background focus before keyboard activation', async () => {
+ const background = addFocusable(0);
+ await tab();
+ const dialog = app.world.spawn();
+ app.world.insert(dialog, UINode, {});
+ app.world.insert(dialog, UIDialog, {});
+ const confirm = addFocusable(1);
+ app.world.setParent(confirm, dialog);
+ const events = app.getResource(UIEvents);
+ let clicks = 0;
+ events.on(background, 'click', () => clicks++);
+ app.getResource(Input).keysPressed.add('Space');
+ await app.tick(1 / 60);
+ expect(focused()).toBe(null);
+ expect(isFocused(background)).toBe(false);
+ expect(clicks).toBe(0);
+ app.getResource(Input).clearFrameState();
+ await tab();
+ expect(focused()).toBe(confirm);
+ });
+
+ it('cannot move pointer focus to a background entity outside a dialog', async () => {
+ const background = addFocusable(0);
+ const dialog = app.world.spawn();
+ app.world.insert(dialog, UINode, {});
+ app.world.insert(dialog, UIDialog, {});
+ app.world.insert(background, UIInteraction, { justPressed: true });
+ await app.tick(1 / 60);
+ expect(focused()).toBe(null);
+ });
+
+ it('clears focus when the Focusable component is removed', async () => {
+ const entity = addFocusable(0);
+ await tab();
+ app.world.remove(entity, Focusable);
+ await app.tick(1 / 60);
+ expect(focused()).toBe(null);
+ expect(app.getResource(FocusManager).focusVisible).toBe(false);
+ });
+});
+
+
+it('rechecks eligibility after a synchronous focus handler opens a dialog', async () => {
+ const background = addFocusable(0);
+ const dialog = app.world.spawn();
+ app.world.insert(dialog, UINode, {});
+ let clicks = 0;
+ app.getResource(UIEvents).on(background, 'focus', () => app.world.insert(dialog, UIDialog, {}));
+ app.getResource(UIEvents).on(background, 'click', () => clicks++);
+ app.world.insert(background, UIInteraction, { justPressed: true });
+ app.getResource(Input).keysPressed.add('Enter');
+ await app.tick(1 / 60);
+ expect(focused()).toBe(null);
+ expect(clicks).toBe(0);
+});
diff --git a/tools/ui-events-play-browser.tsx b/tools/ui-events-play-browser.tsx
index 48bfbe2f4..6c0d77def 100644
--- a/tools/ui-events-play-browser.tsx
+++ b/tools/ui-events-play-browser.tsx
@@ -41,6 +41,7 @@ function Fixture() {
return <main style={{ padding: 16, height: '100vh', display: 'flex', flexDirection: 'column', gap: 12 }}>
<h2>UI Events · production Play realm browser verification</h2>
<div><button onClick={() => void start()}>Start Play</button> <button onClick={() => { PlayInspect.stop(); PlayRealm.stop(); }}>Stop Play</button> <button onClick={() => setMounted(value => !value)}>Toggle panel</button> <button onClick={() => void inspect()}>Read runtime snapshot</button> <button onClick={() => setView('events')}>Events</button> <button onClick={() => setView('focus')}>Focus</button> <button onClick={() => setView('elements')}>Elements</button></div>
+ <small>Game keys: M opens the runtime button as a dialog; R closes it; D disables current focus; E restores disabled controls.</small>
<p role="status">{realm.playing ? 'Playing' : 'Stopped'} · {realm.ready ? 'Ready' : 'Not ready'} · {realm.error ?? ''}</p>
<div style={{ display: 'flex', gap: 16, flex: 1, minHeight: 0 }}>
<div style={{ width: 800, height: 600, flexShrink: 0 }} ref={attach} />
diff --git a/tools/ui-events-play-project.ts b/tools/ui-events-play-project.ts
index 54bd1deb0..da9f9b2da 100644
--- a/tools/ui-events-play-project.ts
+++ b/tools/ui-events-play-project.ts
@@ -1,15 +1,36 @@
// SPDX-License-Identifier: Apache-2.0
// Disposable browser game script: reactions are driven by real UI clicks.
-import { addSystemToSchedule, defineSystem, Schedule, Res, GetWorld, UIEvents, Text, UINode, Transform, UIVisual, Interactable, Focusable, px, type Entity, type UIEventQueue, type World } from 'esengine';
-const installed = new WeakSet<World>();
-addSystemToSchedule(Schedule.Update, defineSystem([Res(UIEvents), GetWorld()], (events: UIEventQueue, world: World) => {
- if (installed.has(world)) return;
+import { addSystemToSchedule, defineSystem, Schedule, Res, GetWorld, UIEvents, Text, UINode, Transform, UIVisual, Interactable, Focusable, px, Input, FocusManager, UIDialog, type InputState, type FocusManagerState, type Entity, type UIEventQueue, type World } from 'esengine';
+const installed = new WeakMap<World, () => void>();
+addSystemToSchedule(Schedule.Update, defineSystem([Res(UIEvents), GetWorld(), Res(Input), Res(FocusManager)], (events: UIEventQueue, world: World, input: InputState, focus: FocusManagerState) => {
+ const update = installed.get(world);
+ if (update) { update(); return; }
const inside = world.findEntityByName('Inside');
if (inside === null) return;
- installed.add(world);
const partial = world.findEntityByName('Partial')!;
const inner = world.findEntityByName('InnerMask')!;
let count = 0, dynamic: Entity | null = null;
+ const restore = new Set<Entity>();
+ installed.set(world, () => {
+ if (input.isKeyPressed('KeyM') && dynamic !== null && world.valid(dynamic)) {
+ world.insert(dynamic, UIDialog, { closeOnEscape: false, closeOnBackdrop: false });
+ world.insert(dynamic, Text, { ...world.get(dynamic, Text), content: 'Dialog confirm' });
+ }
+ if (input.isKeyPressed('KeyR') && dynamic !== null && world.valid(dynamic)) {
+ world.remove(dynamic, UIDialog);
+ world.insert(dynamic, Text, { ...world.get(dynamic, Text), content: 'Runtime button' });
+ }
+ if (input.isKeyPressed('KeyD') && focus.focusedEntity !== null) {
+ const entity = focus.focusedEntity;
+ world.insert(entity, Interactable, { ...world.get(entity, Interactable), enabled: false });
+ restore.add(entity);
+ }
+ if (input.isKeyPressed('KeyE')) {
+ for (const entity of restore) if (world.valid(entity))
+ world.insert(entity, Interactable, { ...world.get(entity, Interactable), enabled: true });
+ restore.clear();
+ }
+ });
events.on(inside, 'click', () => {
count++;
world.insert(inside, Text, { ...world.get(inside, Text), content: `Clicks ${count}` });
@@ -24,6 +45,12 @@ addSystemToSchedule(Schedule.Update, defineSystem([Res(UIEvents), GetWorld()], (
world.insert(dynamic, Interactable, { enabled: true, raycastTarget: true, blockRaycast: true });
world.insert(dynamic, Focusable, { tabIndex: 2 });
world.setParent(dynamic, inner);
+ const button = dynamic;
+ events.on(button, 'click', () => {
+ if (!world.valid(button) || !world.has(button, UIDialog)) return;
+ world.remove(button, UIDialog);
+ world.insert(button, Text, { ...world.get(button, Text), content: 'Dialog confirmed' });
+ });
}
});
events.on(inner, 'click', event => {