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): keep Web keyboard traversal in the game (#78)
YHH8b9efc88e645
diff --git a/desktop b/desktopindex 82cfeb7c1..fb81b2352 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 82cfeb7c12882d3a635ccef5338a97545d80e339+Subproject commit fb81b2352095f05429b3940ccda0dc020081439ediff --git a/examples/ui-localization-debug/README.md b/examples/ui-localization-debug/README.mdindex 17c591c20..972bc55b8 100644--- a/examples/ui-localization-debug/README.md+++ b/examples/ui-localization-debug/README.md@@ -86,3 +86,11 @@ components, and a second activation deletes it. Start Play, open Focus, clickInside, press Tab and then Enter to exercise real keyboard activation andauto-updating traversal. Continuous Tab may move browser focus out of thegame iframe; this remains an input follow-up, not a passed keyboard gate.+++Web keyboard verification uses `node tools/ui-events-play-browser.mjs` and+`http://127.0.0.1:5195/__events-play` with the built production Play host and SDK.+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.diff --git a/examples/ui-localization-debug/VALIDATION.md b/examples/ui-localization-debug/VALIDATION.mdindex e9b75a588..c17751d75 100644--- a/examples/ui-localization-debug/VALIDATION.md+++ b/examples/ui-localization-debug/VALIDATION.md@@ -204,3 +204,31 @@ snapshot; live-game-only dialogs and scripts need runtime acceptance separately.read-only policy/manager capture, request coalescing and late-responserejection. Typecheck, production build and CSS-variable gate pass.- No local Electron/native test runner launched. RM-009 remains In Progress.+++## Web keyboard handoff — 2026-10-09++- Engine #77 and editor #14 are merged. Editor Typecheck + tests passed at+ their current head; the tool/docs/gitlink-only engine increment did not+ trigger Android CI. This does not establish device acceptance.+- Web key callbacks can explicitly claim the host default. FocusPlugin claims+ Tab only with eligible controls, and Enter/Space only with eligible game+ focus outside TextInput. Paused/edit mode do not claim these defaults.+ Ordinary host form/button/link/contenteditable controls and browser shortcut+ chords keep their DOM behavior. Input-router consumption also claims defaults.+- The parked engine textarea has tabIndex=-1. Composition confirmation/cancel+ keys do not activate gameplay or submit/cancel the text editor mid-composition.+ This guard is covered by DOM tests; real device IME acceptance remains open.+- ShiftLeft/ShiftRight are recognized. Tab captures Shift at its keydown edge+ so releasing the complete chord before the next frame still reverses order.+ Blur/unbind releases held keys; cleared frame state cannot retain old Shift.+- Built-in browser, production Play host/SDK/WASM, actual key input: Tab cycles+ Inside → Partial → Runtime button → Inside; Shift+Tab reverses through the+ three entries. Browser focus stays in the game iframe. Enter on Inside+ removes the dynamic control (3→2); Space recreates it (2→3). Clicking the+ host Focus button then Tab moves to the host Elements button normally.+- 89 targeted SDK tests and editor typecheck pass; SDK build, 16 API surface+ and built-declaration checks, and stability inventory checks pass.+- 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.diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex d46c29b1c..dc0c46f52 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -3749,6 +3749,7 @@ static prototype: FocusManagerState## FocusPlugin — class @experimental```build: (app: App) => void+cleanup: (app?: App) => voiddependencies: "uiInteraction"[]name: "focus"static new (): FocusPlugindiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 9542c8fe1..6a25b55ce 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -3757,6 +3757,7 @@ static prototype: FocusManagerState## FocusPlugin — class @experimental```build: (app: App) => void+cleanup: (app?: App) => voiddependencies: "uiInteraction"[]name: "focus"static new (): FocusPlugindiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex b9e4c9906..5bc846b98 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -3744,6 +3744,7 @@ static prototype: FocusManagerState## FocusPlugin — class @experimental```build: (app: App) => void+cleanup: (app?: App) => voiddependencies: "uiInteraction"[]name: "focus"static new (): FocusPlugindiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 7b4f49dc6..48ff6d749 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -3744,6 +3744,7 @@ static prototype: FocusManagerState## FocusPlugin — class @experimental```build: (app: App) => void+cleanup: (app?: App) => voiddependencies: "uiInteraction"[]name: "focus"static new (): FocusPlugindiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 9f46a56c9..49796187b 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -3744,6 +3744,7 @@ static prototype: FocusManagerState## FocusPlugin — class @experimental```build: (app: App) => void+cleanup: (app?: App) => voiddependencies: "uiInteraction"[]name: "focus"static new (): FocusPlugindiff --git a/sdk/src/input/input.ts b/sdk/src/input/input.tsindex 505ff32b6..9af0d2c17 100644--- a/sdk/src/input/input.ts+++ b/sdk/src/input/input.ts@@ -3,6 +3,7 @@import { defineResource } from '../ecs/resource';import { defineSystem, Schedule } from '../ecs/system';import type { App, Plugin } from '../app/app';+import { claimsKeyDefault, recordTabModifiers, clearTabModifiers } from './keyDefaultPolicy';import { getPlatform, platformUnbindInputEvents } from '../platform';import type { GamepadSnapshot, InputEventCallbacks } from '../platform/types';import { inputRouter } from './inputRouter';@@ -145,6 +146,7 @@ export class InputState {/** Record a key-down. The pressed edge only fires on the transition, so a* browser's auto-repeat keydown for a held key doesn't re-trigger it. */noteKeyDown(code: string): void {+ recordTabModifiers(this, code);if (!this.keysDown.has(code)) {this.keysPressed.add(code);this.keysPressedFixed.add(code);@@ -344,6 +346,7 @@ export class InputState {clearFrameState(): void {this.keysPressed.clear();+ clearTabModifiers(this);this.keysReleased.clear();this.mouseButtonsPressed.clear();this.mouseButtonsReleased.clear();@@ -397,8 +400,9 @@ export const Input = defineResource<InputState>(new InputState(), 'Input');export function inputEventCallbacks(state: InputState): InputEventCallbacks {return {onKeyDown(code) {- if (inputRouter.dispatchKeyDown(code)) return;+ if (inputRouter.dispatchKeyDown(code)) return true;state.noteKeyDown(code);+ return claimsKeyDefault(state, code);},onKeyUp(code) {if (inputRouter.dispatchKeyUp(code)) return;diff --git a/sdk/src/input/keyDefaultPolicy.ts b/sdk/src/input/keyDefaultPolicy.tsnew file mode 100644index 000000000..8ab39542f--- /dev/null+++ b/sdk/src/input/keyDefaultPolicy.ts@@ -0,0 +1,24 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import type { InputState } from './input';+const policies = new WeakMap<InputState, (code: string) => boolean>();+/** Internal app-scoped policy; claiming the browser default does not consume game input. */+export function setKeyDefaultPolicy(state: InputState, policy: (code: string) => boolean): () => void {+ policies.set(state, policy);+ return () => { if (policies.get(state) === policy) policies.delete(state); };+}+export function claimsKeyDefault(state: InputState, code: string): boolean {+ return policies.get(state)?.(code) ?? false;+}++// Preserve the modifier at the Tab edge even if keyup arrives before the next frame.+const tabShift = new WeakMap<InputState, boolean>();+export function recordTabModifiers(state: InputState, code: string): void {+ if (code === 'Tab' && !state.keysDown.has(code)) {+ tabShift.set(state, ['Shift', 'ShiftLeft', 'ShiftRight'].some(key => state.isKeyDown(key)));+ }+}+export function tabWasShifted(state: InputState): boolean {+ return tabShift.get(state) ?? ['Shift', 'ShiftLeft', 'ShiftRight'].some(key => state.isKeyDown(key));+}+export function clearTabModifiers(state: InputState): void { tabShift.delete(state); }diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.tsindex ad15a671d..2f57284e7 100644--- a/sdk/src/platform/types.ts+++ b/sdk/src/platform/types.ts@@ -48,7 +48,8 @@ export interface WasmInstantiateResult {// =============================================================================export interface InputEventCallbacks {- onKeyDown(code: string): void;+ /** Return true to cancel the host default (e.g. browser Tab traversal). */+ onKeyDown(code: string): boolean | void;onKeyUp(code: string): void;onPointerMove(x: number, y: number): void;onPointerDown(button: number, x: number, y: number): void;diff --git a/sdk/src/platform/web.ts b/sdk/src/platform/web.tsindex e05068f32..67eff0e41 100644--- a/sdk/src/platform/web.ts+++ b/sdk/src/platform/web.ts@@ -181,8 +181,26 @@ class WebPlatformAdapter implements PlatformAdapter {const el = (target as HTMLElement) ?? document.querySelector('canvas') ?? document.body;- const onKeyDown = (e: Event) => callbacks.onKeyDown((e as KeyboardEvent).code);- const onKeyUp = (e: Event) => callbacks.onKeyUp((e as KeyboardEvent).code);+ const heldKeys = new Set<string>();+ const onKeyDown = (e: Event) => {+ const key = e as KeyboardEvent;+ const target = key.target instanceof HTMLElement ? key.target : null;+ // Host forms keep typing/Tab; the engine's own hidden editor still routes Tab.+ if (target?.closest('input, textarea, select, button, a[href], [contenteditable]')+ && target.dataset.estellaTextEditor !== 'true') return;+ if (key.isComposing || key.keyCode === 229) return;+ if ((key.ctrlKey || key.metaKey || key.altKey) && ['Tab', 'Enter', 'Space'].includes(key.code)) return;+ heldKeys.add(key.code);+ if (callbacks.onKeyDown(key.code) === true) key.preventDefault();+ };+ const onKeyUp = (e: Event) => {+ const code = (e as KeyboardEvent).code;+ if (heldKeys.delete(code)) callbacks.onKeyUp(code);+ };+ const onBlur = () => {+ for (const code of heldKeys) callbacks.onKeyUp(code);+ heldKeys.clear();+ };const onMouseMove = (e: Event) => {const me = e as MouseEvent;callbacks.onPointerMove(me.offsetX, me.offsetY);@@ -241,6 +259,7 @@ class WebPlatformAdapter implements PlatformAdapter {callbacks.onWheel(dx, dy);};+ window.addEventListener('blur', onBlur);document.addEventListener('keydown', onKeyDown);document.addEventListener('keyup', onKeyUp);el.addEventListener('mousemove', onMouseMove);@@ -253,6 +272,8 @@ class WebPlatformAdapter implements PlatformAdapter {el.addEventListener('wheel', onWheel);this.inputCleanup_ = () => {+ window.removeEventListener('blur', onBlur);+ onBlur();document.removeEventListener('keydown', onKeyDown);document.removeEventListener('keyup', onKeyUp);el.removeEventListener('mousemove', onMouseMove);diff --git a/sdk/src/platform/webTextEditor.ts b/sdk/src/platform/webTextEditor.tsindex 1ee5fc2c7..8eea1483d 100644--- a/sdk/src/platform/webTextEditor.ts+++ b/sdk/src/platform/webTextEditor.ts@@ -34,6 +34,8 @@ function createHiddenTextarea(): HTMLTextAreaElement | null {textarea.style.pointerEvents = 'none';textarea.style.border = '0';textarea.style.padding = '0';+ textarea.tabIndex = -1;+ textarea.dataset.estellaTextEditor = 'true';textarea.autocomplete = 'off';textarea.setAttribute('autocorrect', 'off');textarea.setAttribute('autocapitalize', 'off');@@ -68,6 +70,7 @@ export function createWebTextEditor(): PlatformTextEditor | null {emit({ kind: 'change' });};const onKeyDown = (e: KeyboardEvent): void => {+ if (composing || e.isComposing || e.keyCode === 229) return;if (e.key === 'Escape') {emit({ kind: 'cancel' });return;diff --git a/sdk/src/ui/input/focus.ts b/sdk/src/ui/input/focus.tsindex 0e70c16e8..7f448ad97 100644--- a/sdk/src/ui/input/focus.ts+++ b/sdk/src/ui/input/focus.ts@@ -14,6 +14,7 @@ import type { InteractableData } from './interactable';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 { playModeOnly } from '../../ecs/env';import { UIEvents, UIEventQueue, UIEventType } from '../core/events';@@ -25,6 +26,14 @@ export class FocusPlugin implements Plugin {name = PluginName.Focus;dependencies = [PluginName.UIInteraction];+ private readonly keyDefaults_ = new WeakMap<App, () => void>();++ cleanup(app?: App): void {+ if (!app) return;+ this.keyDefaults_.get(app)?.();+ this.keyDefaults_.delete(app);+ }+build(app: App): void {registerComponent('Focusable', Focusable);@@ -33,6 +42,17 @@ export class FocusPlugin implements Plugin {const registry = engine ? (world.getCppRegistry() as CppRegistry) : undefined;const focusManager = new FocusManagerState();app.insertResource(FocusManager, focusManager);+ this.keyDefaults_.get(app)?.();+ 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);+ const focused = focusManager.focusedEntity;+ return focused !== null && world.valid(focused) && !world.has(focused, TextInput)+ && 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.@@ -92,7 +112,7 @@ export class FocusPlugin implements Plugin {? sorted.findIndex(e => e === focusManager.focusedEntity): -1;- const reverse = input.isKeyDown('Shift');+ const reverse = tabWasShifted(input);let nextIdx: number;if (currentIdx === -1) {nextIdx = reverse ? sorted.length - 1 : 0;diff --git a/sdk/tests/ui-focus-plugin.test.ts b/sdk/tests/ui-focus-plugin.test.tsindex b2a19bc85..e20db2b66 100644--- a/sdk/tests/ui-focus-plugin.test.ts+++ b/sdk/tests/ui-focus-plugin.test.ts@@ -11,11 +11,13 @@import { describe, it, expect, beforeEach } from 'vitest';import { flushPendingRegistrations } from '../src/app/app';import type { App } from '../src/app/app';-import { Input, InputState } from '../src/input/input';+import { Input, InputState, inputEventCallbacks } from '../src/input/input';import { UIEvents, UIEventQueue } from '../src/ui/core/events';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 { TextInput } from '../src/ui/text/text-input';import { bootMockApp } from './helpers/mockApp';import type { Entity } from '../src/types';@@ -182,3 +184,85 @@ describe('focus visibility', () => {expect(visible()).toBe(false);});});+++describe('FocusPlugin browser default policy', () => {+ it.each(['ShiftLeft', 'ShiftRight'])('reverses using the real DOM %s code', async (code) => {+ const a = addFocusable(0);+ const b = addFocusable(1);+ const input = app.getResource(Input);+ input.keysDown.add(code);+ await tab();+ expect(focused()).toBe(b);+ await tab();+ expect(focused()).toBe(a);+ });++ it('claims Tab only with eligible controls and releases the policy on cleanup', () => {+ const callbacks = inputEventCallbacks(app.getResource(Input));+ expect(callbacks.onKeyDown('Tab')).toBe(false);+ addFocusable(0, false);+ expect(callbacks.onKeyDown('Tab')).toBe(false);+ addFocusable(1);+ expect(callbacks.onKeyDown('Tab')).toBe(true);+ expect(app.getResource(Input).keysPressed.has('Tab')).toBe(true);+ app.setPaused(true);+ expect(callbacks.onKeyDown('Tab')).toBe(false);+ app.setPaused(false);+ focusPlugin.cleanup(app);+ expect(callbacks.onKeyDown('Tab')).toBe(false);+ });++ it('claims activation only for a valid eligible focus', async () => {+ const callbacks = inputEventCallbacks(app.getResource(Input));+ const entity = addFocusable(0);+ expect(callbacks.onKeyDown('Enter')).toBe(false);+ await tab();+ expect(callbacks.onKeyDown('Enter')).toBe(true);+ expect(callbacks.onKeyDown('Space')).toBe(true);+ app.world.despawn(entity);+ expect(callbacks.onKeyDown('Enter')).toBe(false);+ });+});+++it('retains Shift at the Tab edge when the whole chord ends before a frame', async () => {+ addFocusable(0);+ const last = addFocusable(1);+ const input = app.getResource(Input);+ input.noteKeyDown('ShiftLeft');+ input.noteKeyDown('Tab');+ input.noteKeyUp('Tab');+ input.noteKeyUp('ShiftLeft');+ await app.tick(1 / 60);+ expect(focused()).toBe(last);+});+++it('does not claim keys in edit mode or activation for a text field', async () => {+ const entity = addFocusable(0);+ const callbacks = inputEventCallbacks(app.getResource(Input));+ setEditorMode(true);+ expect(callbacks.onKeyDown('Tab')).toBe(false);+ setEditorMode(false);+ await tab();+ app.world.insert(entity, TextInput, {});+ expect(callbacks.onKeyDown('Enter')).toBe(false);+ expect(callbacks.onKeyDown('Space')).toBe(false);+ expect(callbacks.onKeyDown('Tab')).toBe(true);+});++it('does not reuse a released Shift for the next frame Tab', async () => {+ const first = addFocusable(0);+ addFocusable(1);+ const input = app.getResource(Input);+ input.noteKeyDown('ShiftRight');+ input.noteKeyDown('Tab');+ input.noteKeyUp('Tab');+ input.noteKeyUp('ShiftRight');+ await app.tick(1 / 60);+ input.clearFrameState();+ input.noteKeyDown('Tab');+ await app.tick(1 / 60);+ expect(focused()).toBe(first);+});diff --git a/sdk/tests/web-keyboard-handoff.test.ts b/sdk/tests/web-keyboard-handoff.test.tsnew file mode 100644index 000000000..021a4bf56--- /dev/null+++ b/sdk/tests/web-keyboard-handoff.test.ts@@ -0,0 +1,87 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { afterEach, describe, expect, it, vi } from 'vitest';+import { webAdapter } from '../src/platform/web';+import { createWebTextEditor } from '../src/platform/webTextEditor';++function bind() {+ const canvas = document.createElement('canvas');+ document.body.appendChild(canvas);+ const callbacks = {+ onKeyDown: vi.fn(() => true), onKeyUp: vi.fn(),+ onPointerDown: vi.fn(), onPointerUp: vi.fn(), onPointerMove: vi.fn(), onWheel: vi.fn(),+ };+ webAdapter.bindInputEvents(callbacks, canvas);+ return callbacks;+}+function key(target: EventTarget, code: string, options: KeyboardEventInit = {}) {+ const event = new KeyboardEvent('keydown', { code, bubbles: true, cancelable: true, ...options });+ target.dispatchEvent(event);+ return event;+}+afterEach(() => {+ webAdapter.unbindInputEvents();+ document.body.replaceChildren();+});++describe('Web keyboard handoff', () => {+ it('cancels defaults only when the callback claims the key', () => {+ const callbacks = bind();+ expect(key(document.body, 'Tab').defaultPrevented).toBe(true);+ callbacks.onKeyDown.mockReturnValue(false);+ expect(key(document.body, 'Tab').defaultPrevented).toBe(false);+ });+ it.each(['input', 'textarea', 'select', 'button', 'a', 'div'])('leaves host %s controls alone', tag => {+ const callbacks = bind();+ const control = document.createElement(tag);+ if (tag === 'a') control.setAttribute('href', '#');+ if (tag === 'div') control.setAttribute('contenteditable', 'true');+ document.body.appendChild(control);+ expect(key(control, 'Tab').defaultPrevented).toBe(false);+ expect(key(control, 'Enter').defaultPrevented).toBe(false);+ expect(callbacks.onKeyDown).not.toHaveBeenCalled();+ });+ it('keeps IME confirmation and browser shortcuts out of game activation', () => {+ const callbacks = bind();+ for (const options of [{ isComposing: true }, { keyCode: 229 }, { ctrlKey: true }, { metaKey: true }, { altKey: true }]) {+ expect(key(document.body, 'Enter', options).defaultPrevented).toBe(false);+ }+ expect(callbacks.onKeyDown).not.toHaveBeenCalled();+ });+ it('routes the engine editor while keeping the parked textarea out of Tab order', () => {+ const callbacks = bind();+ const editor = createWebTextEditor()!;+ const textarea = document.querySelector('textarea')!;+ expect(textarea.tabIndex).toBe(-1);+ expect(key(textarea, 'Tab').defaultPrevented).toBe(true);+ expect(callbacks.onKeyDown).toHaveBeenCalledWith('Tab');+ editor.dispose();+ });+ it('releases held modifiers on blur and removes handlers on unbind', () => {+ const callbacks = bind();+ key(document.body, 'ShiftLeft');+ key(document.body, 'Tab');+ window.dispatchEvent(new Event('blur'));+ expect(callbacks.onKeyUp.mock.calls).toEqual([['ShiftLeft'], ['Tab']]);+ webAdapter.unbindInputEvents();+ expect(key(document.body, 'Tab').defaultPrevented).toBe(false);+ expect(callbacks.onKeyDown).toHaveBeenCalledTimes(2);+ });+});+++it('does not submit or cancel the engine textarea during composition', () => {+ bind();+ const editor = createWebTextEditor()!;+ const events: string[] = [];+ editor.subscribe(event => events.push(event.kind));+ const textarea = document.querySelector('textarea')!;+ textarea.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true }));+ key(textarea, 'Enter', { key: 'Enter' });+ key(textarea, 'Escape', { key: 'Escape' });+ expect(events).toEqual(['composition']);+ textarea.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true }));+ key(textarea, 'Enter', { key: 'Enter' });+ expect(events.at(-1)).toBe('submit');+ editor.dispose();+});