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(runtime): a mini-game host other than WeChat keeps its lifecycle

esengine463fe25c9128
diff --git a/sdk/src/ecs/lifecycle.ts b/sdk/src/ecs/lifecycle.ts
index 37ebd397d..bc79912ab 100644
--- a/sdk/src/ecs/lifecycle.ts
+++ b/sdk/src/ecs/lifecycle.ts
@@ -7,7 +7,7 @@
import { defineResource } from './resource';
import type { App, Plugin } from '../app/app';
-import { getPlatformType, platformOnAppShow, platformOnAppHide } from '../platform';
+import { getPlatformType, isMiniGame, platformOnAppShow, platformOnAppHide } from '../platform';
import { log } from '../util/logger';
// =============================================================================
@@ -110,11 +110,13 @@ export class LifecyclePlugin implements Plugin {
const platformType = getPlatformType();
- if (platformType === 'wechat') {
- this.cleanupFn_ = setupWeChatLifecycle_(manager, app);
- } else if (platformType === 'native') {
- this.cleanupFn_ = setupNativeLifecycle_(manager, app);
- } else if (typeof document !== 'undefined' && typeof window !== 'undefined') {
+ // A mini-game host and the native shell both push foreground/background
+ // through the adapter. Every mini-game runs with a `document` stub that has
+ // no addEventListener, so the web branch must not be reached from one.
+ if (platformType === 'native' || isMiniGame()) {
+ this.cleanupFn_ = setupHostLifecycle_(manager, app);
+ } else if (typeof document !== 'undefined' && typeof document.addEventListener === 'function'
+ && typeof window !== 'undefined') {
this.cleanupFn_ = setupWebLifecycle_(manager, app);
}
// Headless hosts (node server, workers) keep the Lifecycle resource and
@@ -175,56 +177,17 @@ function setupWebLifecycle_(manager: LifecycleManager, app: AppLike): () => void
}
// =============================================================================
-// WeChat Platform
-// =============================================================================
-
-function setupWeChatLifecycle_(manager: LifecycleManager, app: AppLike): (() => void) | null {
- let pausedByLifecycle = false;
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const wx = (globalThis as any).wx;
- if (!wx) return null;
-
- const onShow = (): void => {
- manager.setVisible_(true);
- if (pausedByLifecycle) {
- app.setPaused(false);
- pausedByLifecycle = false;
- manager.emit_('resume');
- }
- };
-
- const onHide = (): void => {
- manager.setVisible_(false);
- if (manager.autoPause && !app.isPaused()) {
- app.setPaused(true);
- pausedByLifecycle = true;
- manager.emit_('pause');
- }
- };
-
- wx.onShow(onShow);
- wx.onHide(onHide);
-
- return (): void => {
- wx.offShow?.(onShow);
- wx.offHide?.(onHide);
- manager.removeAllListeners();
- };
-}
-
-// =============================================================================
-// Native Platform (embedded Dawn + JS engine)
+// Hosts that push foreground/background (mini-game vendors, the native shell)
// =============================================================================
/**
- * Native has no DOM visibility event; the shell pushes foreground/background
- * through the platform adapter (onAppShow/onAppHide, backed by the bridge). Same
- * auto-pause contract as WeChat. The audio device is suspended by the host
- * directly on background — correct even while the JS tick is paused — so this
- * only drives the game tick and the lifecycle events.
+ * No DOM visibility event: the host pushes foreground/background through the
+ * platform adapter (a mini-game's onShow/onHide, the native bridge). On native
+ * the audio device is suspended by the host directly on background — correct
+ * even while the JS tick is paused — so this only drives the game tick and the
+ * lifecycle events.
*/
-function setupNativeLifecycle_(manager: LifecycleManager, app: AppLike): () => void {
+function setupHostLifecycle_(manager: LifecycleManager, app: AppLike): () => void {
let pausedByLifecycle = false;
const offShow = platformOnAppShow(() => {
diff --git a/sdk/src/platform/minigame/adapter.ts b/sdk/src/platform/minigame/adapter.ts
index 6b50b819e..5434fd98b 100644
--- a/sdk/src/platform/minigame/adapter.ts
+++ b/sdk/src/platform/minigame/adapter.ts
@@ -195,6 +195,18 @@ export class MiniGamePlatformAdapter implements PlatformAdapter {
this.g_.shareAppMessage?.call(this.g_, options);
}
+ /** The host's foreground signal. A host without `offShow` cannot unsubscribe,
+ * and the returned function then does nothing. */
+ onAppShow(callback: () => void): () => void {
+ this.g_.onShow?.call(this.g_, callback);
+ return () => { this.g_.offShow?.call(this.g_, callback); };
+ }
+
+ onAppHide(callback: () => void): () => void {
+ this.g_.onHide?.call(this.g_, callback);
+ return () => { this.g_.offHide?.call(this.g_, callback); };
+ }
+
/** Register the passive-share card provider (the host's own share menu). */
onShareRequest(provide: () => PlatformShareOptions): void {
this.g_.onShareAppMessage?.call(this.g_, provide);
diff --git a/sdk/src/platform/minigame/api.ts b/sdk/src/platform/minigame/api.ts
index 70a067c27..4b5e69380 100644
--- a/sdk/src/platform/minigame/api.ts
+++ b/sdk/src/platform/minigame/api.ts
@@ -296,6 +296,8 @@ export interface MiniGameGlobal {
onShow?(cb: () => void): void;
onHide?(cb: () => void): void;
+ offShow?(cb: () => void): void;
+ offHide?(cb: () => void): void;
/** The window changed size — a rotation, a foldable, split screen. Carries
* the new size, which is authoritative: a `getSystemInfoSync` beside it can
* still answer with the old one. */
diff --git a/sdk/tests/minigame-lifecycle.test.ts b/sdk/tests/minigame-lifecycle.test.ts
new file mode 100644
index 000000000..9d8616372
--- /dev/null
+++ b/sdk/tests/minigame-lifecycle.test.ts
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Lifecycle on a mini-game host that is not WeChat.
+ *
+ * Every mini-game runs with a `document` stub (wxgame-pre.js) that has no
+ * addEventListener. The plugin used to branch on the vendor name, so any other
+ * vendor fell through to the web path and threw at boot — which is how a vivo
+ * quick game first died on an emulator. The host's own onShow/onHide drive it.
+ */
+import { describe, it, expect, afterEach } from 'vitest';
+import { App } from '../src/app/app';
+import { LifecyclePlugin } from '../src/ecs/lifecycle';
+import { setPlatform } from '../src/platform/base';
+import { webAdapter } from '../src/platform/web';
+import { MiniGamePlatformAdapter } from '../src/platform/minigame/adapter';
+import type { MiniGameGlobal, MiniGameProfile } from '../src/platform/minigame/api';
+
+function vendorHost() {
+ const shown: Array<() => void> = [];
+ const hidden: Array<() => void> = [];
+ const g = {
+ onShow: (cb: () => void) => { shown.push(cb); },
+ onHide: (cb: () => void) => { hidden.push(cb); },
+ offShow: (cb: () => void) => { shown.splice(shown.indexOf(cb), 1); },
+ offHide: (cb: () => void) => { hidden.splice(hidden.indexOf(cb), 1); },
+ } as unknown as MiniGameGlobal;
+ const profile = { id: 'qg', hostLabel: 'quick game', global: g } as MiniGameProfile;
+ return { adapter: new MiniGamePlatformAdapter(profile), shown, hidden };
+}
+
+const realDocument = (globalThis as { document?: unknown }).document;
+
+afterEach(() => {
+ (globalThis as { document?: unknown }).document = realDocument;
+ setPlatform(webAdapter);
+});
+
+describe('lifecycle on a mini-game host that is not WeChat', () => {
+ it('builds against the document stub and pauses with the host', () => {
+ (globalThis as { document?: unknown }).document = {};
+ const host = vendorHost();
+ setPlatform(host.adapter);
+ const app = App.new();
+ const plugin = new LifecyclePlugin();
+ expect(() => plugin.build(app)).not.toThrow();
+
+ host.hidden.forEach((cb) => cb());
+ expect(app.isPaused()).toBe(true);
+ host.shown.forEach((cb) => cb());
+ expect(app.isPaused()).toBe(false);
+
+ plugin.cleanup();
+ expect(host.shown).toEqual([]);
+ expect(host.hidden).toEqual([]);
+ });
+});