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(input): cancel touch state when mini-games hide
yhh592581fe8a52
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 379d0ef68..2d1298ecf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,8 @@ published separately; it ships inside the editor.### Fixed+- **Cancelled touch input no longer becomes a click.** Shared touch forwarding distinguishes primary cancellation from normal release, clears cancelled touch and fixed-step edges, and preserves other fingers. Mini-game hide and input teardown cancel held gestures and keys, reset the primary finger, and unregister the hide callback so resumed input starts cleanly.+- **Mini-game storage preserves empty strings.** The adapter distinguishes an explicitly stored empty string from an absent key through the host's key list, matching Web storage and preserving empty text preferences across adapter restarts. Non-empty reads keep their direct path; unavailable host storage remains a safe absent result.- **Audio preferences survive game restart.** Audio-demo saves and restores master, music and SFX volumes through engine storage, validates saved values, and restores the displayed percentages and actual bus gains at startup. Golden verification uses independent browser processes with a stable origin and isolated profile, cycles master volume to mute and verifies that both the label and silent output survive restart.diff --git a/sdk/src/input/input.ts b/sdk/src/input/input.tsindex 755ad5f74..0b8ccc29e 100644--- a/sdk/src/input/input.ts+++ b/sdk/src/input/input.ts@@ -458,8 +458,19 @@ export function inputEventCallbacks(state: InputState): InputEventCallbacks {onTouchEnd(id) {finishTouch(id, inputRouter.dispatchTouchEnd(id));},- onTouchCancel(id) {- finishTouch(id, inputRouter.dispatchTouchCancel(id));+ onTouchCancel(id, primary) {+ inputRouter.dispatchTouchCancel(id);+ state.touches.delete(id);+ state.touchesStarted.delete(id);+ state.touchesEnded.delete(id);+ if (primary === true || (primary === undefined && state.touches.size === 0)) {+ state.mouseButtons.delete(0);+ state.mouseButtonsPressed.delete(0);+ state.mouseButtonsReleased.delete(0);+ state.mouseButtonsPressedFixed.delete(0);+ state.mouseButtonsReleasedFixed.delete(0);+ cancelPrimaryPointer(state);+ }},onInputCancel() {state.keysDown.clear();diff --git a/sdk/src/platform/minigame/adapter.ts b/sdk/src/platform/minigame/adapter.tsindex a932c2cf5..cbe44004a 100644--- a/sdk/src/platform/minigame/adapter.ts+++ b/sdk/src/platform/minigame/adapter.ts@@ -512,8 +512,14 @@ export class MiniGamePlatformAdapter implements PlatformAdapter {const g = this.g_;- const onKeyDown = (res: { code: string }) => callbacks.onKeyDown(res.code);- const onKeyUp = (res: { code: string }) => callbacks.onKeyUp(res.code);+ const heldKeys = new Set<string>();+ const onKeyDown = (res: { code: string }) => {+ heldKeys.add(res.code);+ callbacks.onKeyDown(res.code);+ };+ const onKeyUp = (res: { code: string }) => {+ if (heldKeys.delete(res.code)) callbacks.onKeyUp(res.code);+ };const hasKeyboard = typeof g.onKeyDown === 'function';if (hasKeyboard) {@@ -522,28 +528,42 @@ export class MiniGamePlatformAdapter implements PlatformAdapter {}const pointer = createPrimaryPointer(callbacks);+ const heldTouches = new Set<number>();+ const cancelInput = () => {+ for (const code of heldKeys) callbacks.onKeyUp(code);+ heldKeys.clear();+ for (const id of heldTouches) pointer.cancel(id);+ heldTouches.clear();+ callbacks.onInputCancel?.();+ };// A pointer is read in logical pixels and scaled by pixelRatio to reach the// canvas; a host that reports touches in physical pixels would land every// tap pixelRatio times too far out, past the edge of the screen.const toLogical = this.profile_.windowInPhysicalPixels ? 1 / this.devicePixelRatio() : 1;const onTouchStart = (res: MiniGameTouchEvent) => {- for (const touch of res.changedTouches) pointer.start(touch.identifier, touch.clientX * toLogical, touch.clientY * toLogical);+ for (const touch of res.changedTouches) {+ heldTouches.add(touch.identifier);+ pointer.start(touch.identifier, touch.clientX * toLogical, touch.clientY * toLogical);+ }};const onTouchMove = (res: MiniGameTouchEvent) => {- for (const touch of res.changedTouches) pointer.move(touch.identifier, touch.clientX * toLogical, touch.clientY * toLogical);+ for (const touch of res.changedTouches) {+ if (heldTouches.has(touch.identifier)) pointer.move(touch.identifier, touch.clientX * toLogical, touch.clientY * toLogical);+ }};const onTouchEnd = (res: MiniGameTouchEvent) => {- for (const touch of res.changedTouches) pointer.end(touch.identifier);+ for (const touch of res.changedTouches) if (heldTouches.delete(touch.identifier)) pointer.end(touch.identifier);};const onTouchCancel = (res: MiniGameTouchEvent) => {- for (const touch of res.changedTouches) pointer.cancel(touch.identifier);+ for (const touch of res.changedTouches) if (heldTouches.delete(touch.identifier)) pointer.cancel(touch.identifier);};g.onTouchStart(onTouchStart);g.onTouchMove(onTouchMove);g.onTouchEnd(onTouchEnd);g.onTouchCancel?.(onTouchCancel);+ g.onHide?.(cancelInput);this.inputCleanup_ = () => {if (hasKeyboard) {@@ -554,6 +574,8 @@ export class MiniGamePlatformAdapter implements PlatformAdapter {g.offTouchMove(onTouchMove);g.offTouchEnd(onTouchEnd);g.offTouchCancel?.(onTouchCancel);+ g.offHide?.(cancelInput);+ cancelInput();};}diff --git a/sdk/src/platform/primaryPointer.ts b/sdk/src/platform/primaryPointer.tsindex 88a46ee4c..afa48ab0f 100644--- a/sdk/src/platform/primaryPointer.ts+++ b/sdk/src/platform/primaryPointer.ts@@ -41,7 +41,7 @@ export function createPrimaryPointer(callbacks: InputEventCallbacks): PrimaryPoi}},cancel(id) {- callbacks.onTouchCancel?.(id);+ callbacks.onTouchCancel?.(id, id === primary);if (id === primary) {primary = null;callbacks.onPointerUp(0);diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.tsindex a800be003..aaccc7664 100644--- a/sdk/src/platform/types.ts+++ b/sdk/src/platform/types.ts@@ -58,7 +58,8 @@ export interface InputEventCallbacks {onTouchStart?(id: number, x: number, y: number): void;onTouchMove?(id: number, x: number, y: number): void;onTouchEnd?(id: number): void;- onTouchCancel?(id: number): void;+ /** Primary identifies the synthesized mouse without cancelling another finger. */+ onTouchCancel?(id: number, primary?: boolean): void;/** Cancel held input and pending edges when the host loses focus or unbinds. */onInputCancel?(): void;}diff --git a/sdk/tests/minigame-input-cancellation.test.ts b/sdk/tests/minigame-input-cancellation.test.tsnew file mode 100644index 000000000..b7caf352b--- /dev/null+++ b/sdk/tests/minigame-input-cancellation.test.ts@@ -0,0 +1,64 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { afterEach, expect, it, vi } from 'vitest';+import { MiniGamePlatformAdapter } from '../src/platform/minigame/adapter';+import type { MiniGameGlobal, MiniGameTouchEvent } from '../src/platform/minigame/api';+import { InputState, inputEventCallbacks } from '../src/input/input';+import { UiPointerBook, uiPointersOf } from '../src/ui/input/pointerBook';+import type { Entity } from '../src/types';+import { inputRouter } from '../src/input/inputRouter';+afterEach(() => { inputRouter.setEditorHandler(null); inputRouter.dispatchKeyUp('ShiftLeft'); });++function setup() {+ const handlers = new Map<string, Function>();+ const host: Record<string, unknown> = {};+ for (const name of ['TouchStart', 'TouchMove', 'TouchEnd', 'TouchCancel', 'KeyDown', 'KeyUp', 'Hide']) {+ host['on' + name] = (handler: Function) => handlers.set(name, handler);+ host['off' + name] = vi.fn((handler: Function) => { if (handlers.get(name) === handler) handlers.delete(name); });+ }+ const adapter = new MiniGamePlatformAdapter({ id: 'test', hostLabel: 'Test', global: host as unknown as MiniGameGlobal });+ const input = new InputState(); adapter.bindInputEvents(inputEventCallbacks(input));+ const touch = (kind: string, id: number) => handlers.get(kind)?.({ changedTouches: [{ identifier: id, clientX: 5, clientY: 5 }] } as MiniGameTouchEvent);+ return { adapter, input, handlers, touch };+}+it('cancels hidden input and lets a new finger become primary after showing', () => {+ const { adapter, input, handlers, touch } = setup();+ handlers.get('KeyDown')?.({ code: 'KeyD' }); touch('TouchStart', 1);+ handlers.get('Hide')?.();+ expect(input.keysDown.size).toBe(0); expect(input.touches.size).toBe(0);+ expect(input.isMouseButtonDown(0)).toBe(false);+ input.beginFixedStep();+ expect(input.isKeyPressed('KeyD')).toBe(false); expect(input.isMouseButtonPressed(0)).toBe(false);+ input.endFixedStep();+ touch('TouchStart', 2); expect(input.isMouseButtonDown(0)).toBe(true);+ touch('TouchEnd', 1); expect(input.isMouseButtonDown(0)).toBe(true);+ adapter.unbindInputEvents(); expect(handlers.size).toBe(0);+ expect(input.touches.size).toBe(0);+});+it('does not turn a cancelled quick touch into a UI click', () => {+ const { adapter, input, touch } = setup(), book = new UiPointerBook();+ touch('TouchStart', 1); touch('TouchCancel', 1);+ const events = book.step(uiPointersOf(input), () => 1 as Entity, () => true);+ expect(events.some(event => event.kind === 'click')).toBe(false);+ expect(input.touchesEnded.size).toBe(0);+ input.beginFixedStep(); expect(input.isMouseButtonPressed(0)).toBe(false); input.endFixedStep();+ adapter.unbindInputEvents();+});+it('cancels a secondary finger without releasing the primary finger', () => {+ const { adapter, input, touch } = setup();+ touch('TouchStart', 1); touch('TouchStart', 2); touch('TouchCancel', 2);+ expect(input.isMouseButtonDown(0)).toBe(true);+ expect(input.touches.has(1)).toBe(true); expect(input.touches.has(2)).toBe(false);+ expect(input.touchesEnded.has(2)).toBe(false);+ adapter.unbindInputEvents();+});+it('clears router modifiers on hide as well as the gameplay key state', () => {+ const { adapter, handlers, touch } = setup();+ handlers.get('KeyDown')?.({ code: 'ShiftLeft' });+ handlers.get('Hide')?.();+ let shifted = true;+ inputRouter.setEditorHandler({ onPointerDown: (_button, _x, _y, mods) => { shifted = mods.shift; } });+ touch('TouchStart', 3);+ expect(shifted).toBe(false);+ adapter.unbindInputEvents();+});diff --git a/sdk/tests/web-focus-cancellation.test.ts b/sdk/tests/web-focus-cancellation.test.tsindex b5d9c9b76..a4c2e0752 100644--- a/sdk/tests/web-focus-cancellation.test.ts+++ b/sdk/tests/web-focus-cancellation.test.ts@@ -17,6 +17,13 @@ function touch(canvas: HTMLCanvasElement, type: string, ids: number[]) {Object.defineProperty(event, 'changedTouches', { value: ids.map(identifier => ({ identifier, clientX: 5, clientY: 5 })) });canvas.dispatchEvent(event);}+it('a cancelled quick touch does not create a click through the mouse fallback', () => {+ const { canvas, input } = bind(), book = new UiPointerBook();+ touch(canvas, 'touchstart', [1]); touch(canvas, 'touchcancel', [1]);+ expect(book.step(uiPointersOf(input), () => 1 as Entity, () => true).some(e => e.kind === 'click')).toBe(false);+ expect(input.touchesEnded.size).toBe(0);+ input.beginFixedStep(); expect(input.isMouseButtonPressed(0)).toBe(false); input.endFixedStep();+});it('blur cancels a held mouse without a UI click or stale fixed-step edges', () => {const { canvas, input } = bind(), book = new UiPointerBook(), entity = 1 as Entity;canvas.dispatchEvent(new MouseEvent('mousedown', { button: 0 }));diff --git a/tools/launchers/minigameHost.mjs b/tools/launchers/minigameHost.mjsindex 1bfef9dc2..7eb529439 100644--- a/tools/launchers/minigameHost.mjs+++ b/tools/launchers/minigameHost.mjs@@ -65,6 +65,27 @@ export function miniGameKeyboardBridge(target) {return api;}+/** Forward page visibility with the same callback identity as vendor lifecycle hooks. */+export function miniGameVisibilityBridge(target) {+ const api = {};+ for (const phase of ['Show', 'Hide']) {+ const listeners = new Map();+ api['on' + phase] = callback => {+ if (listeners.has(callback)) return;+ const listener = () => { if (target.hidden === (phase === 'Hide')) callback(); };+ listeners.set(callback, listener);+ target.addEventListener('visibilitychange', listener);+ };+ api['off' + phase] = callback => {+ const listener = listeners.get(callback);+ if (!listener) return;+ target.removeEventListener('visibilitychange', listener);+ listeners.delete(callback);+ };+ }+ return api;+}+/*** The page source; `BASE` is substituted with the served root.*@@ -89,6 +110,7 @@ export const HOST_PAGE = (entry, failSubpackage = null) => `<!doctype html>document.body.appendChild(screenCanvas);const touchBridge = (${miniGameTouchBridge.toString()})(screenCanvas);const keyboardBridge = (${miniGameKeyboardBridge.toString()})(window);+ const visibilityBridge = (${miniGameVisibilityBridge.toString()})(document);let screenTaken = false;const makeCanvas = () => {if (!screenTaken) { screenTaken = true; return screenCanvas; }@@ -185,10 +207,10 @@ export const HOST_PAGE = (entry, failSubpackage = null) => `<!doctype html>},...touchBridge,...keyboardBridge,+ ...visibilityBridge,onMemoryWarning: noop, offMemoryWarning: noop,onError: noop, offError: noop,onUnhandledRejection: noop, offUnhandledRejection: noop,- onShow: noop, onHide: noop, offShow: noop, offHide: noop,onWindowResize: noop, offWindowResize: noop,loadSubpackage: (o) => {if (o && o.name === ${JSON.stringify(failSubpackage)}) {diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 9ffd76235..eb8edea88 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(input): cancel touch state when mini-games hide':+ { note: 'Cancelled touch input no longer becomes a click.' },'fix(storage): preserve empty mini-game values':{ note: 'Mini-game storage preserves empty strings.' },'fix(examples): restore audio preferences across game restarts':diff --git a/tools/tests/minigame-visibility-bridge.test.ts b/tools/tests/minigame-visibility-bridge.test.tsnew file mode 100644index 000000000..6d014d73d--- /dev/null+++ b/tools/tests/minigame-visibility-bridge.test.ts@@ -0,0 +1,19 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { expect, it, vi } from 'vitest';+import { miniGameVisibilityBridge } from '../launchers/minigameHost.mjs';++it('forwards hide and show while removing only the specified subscription', () => {+ const target = Object.assign(new EventTarget(), { hidden: false });+ const api = miniGameVisibilityBridge(target);+ const first = vi.fn(), second = vi.fn(), shown = vi.fn();+ api.onHide(first); api.onHide(first); api.onHide(second); api.onShow(shown);+ target.hidden = true; target.dispatchEvent(new Event('visibilitychange'));+ expect(first).toHaveBeenCalledOnce(); expect(second).toHaveBeenCalledOnce(); expect(shown).not.toHaveBeenCalled();+ api.offHide(first);+ target.dispatchEvent(new Event('visibilitychange'));+ expect(first).toHaveBeenCalledOnce(); expect(second).toHaveBeenCalledTimes(2);+ target.hidden = false; target.dispatchEvent(new Event('visibilitychange'));+ expect(shown).toHaveBeenCalledOnce();+ api.offShow(shown); api.offHide(second);+});