接入固定玩法宿主生命周期音频暂停
新增 useHostLifecycleActive 统一归一宿主生命周期状态 拼图和抓大鹅运行态背景音乐按宿主后台与失焦状态暂停恢复 useBackgroundMusic 复用统一生命周期状态避免重复订阅逻辑 补充生命周期音频测试和宿主壳架构文档
This commit is contained in:
@@ -36,7 +36,8 @@
|
||||
- 2026-06-18 移动图片导入:Expo 壳开始声明并实现 `file.importImage`,通过 `expo-image-picker` 请求相册权限并打开系统相册选择器,只允许 `image/png`、`image/jpeg`、`image/webp` 且单次不超过 10 MiB;成功只回传清洗后的文件名、MIME、base64 内容和字节数,不暴露设备本地 URI,不请求相机或麦克风权限,用户取消返回 `cancelled` 并由 H5 facade 归为 `false`。
|
||||
- 2026-06-18 H5 图片上传接入宿主导入:`CreativeImageInputPanel` 在 `native_app` 且声明 `file.importImage` 时,主图上传和描述参考图上传优先调用 `importHostImageFile()`,并把宿主返回的 base64 图片转换为现有 `File` 回调;浏览器、小程序和未声明能力的裁剪壳继续走原生 `<input type="file">` 路径,不新增玩法侧上传分叉。
|
||||
- 2026-06-18 桌面图片拖入接入主图槽位:`CreativeImageInputPanel` 在桌面壳声明 `file.imageDropped` 时订阅宿主拖入事件,只在拖入坐标命中当前主图卡片且未被上层元素遮挡时消费事件,避免窗口级拖入被多个创作面板同时接收;成功后仍转换为现有 `File` 上传回调。
|
||||
- 2026-06-18 H5 背景音乐接入宿主生命周期:`useBackgroundMusic` 订阅 `subscribeHostAppLifecycle()`,宿主进入后台、inactive 或桌面窗口失焦时降低音量并暂停音频循环,同时 `suspend` WebAudio context;回到 `active + focused` 且用户原本开启音乐时再恢复播放,不改变用户音量设置。
|
||||
- 2026-06-18 H5 背景音乐接入宿主生命周期:`useBackgroundMusic` 通过 `useHostLifecycleActive()` 消费 `subscribeHostAppLifecycle()` 的归一结果,宿主进入后台、inactive 或桌面窗口失焦时降低音量并暂停音频循环,同时 `suspend` WebAudio context;回到 `active + focused` 且用户原本开启音乐时再恢复播放,不改变用户音量设置。
|
||||
- 2026-06-18 固定玩法音频接入宿主生命周期:前端新增 `useHostLifecycleActive()` 统一消费 `subscribeHostAppLifecycle()`,`useBackgroundMusic`、拼图运行态和抓大鹅运行态都只依赖该归一状态判断音频可播放性;宿主 inactive、background 或窗口失焦时暂停 `<audio>` / WebAudio,回到 `active + focused` 后仅在运行态仍在播放、音源存在且用户音乐音量大于 0 时恢复,不改变用户音量设置。
|
||||
- 影响范围:`src/services/host-bridge/`、未来 `apps/mobile-shell/`、未来 `apps/desktop-shell/`、移动端支付 / 分享 / 深链 / 推送、桌面端系统能力、AI H5 sandbox 的 GameBridge 边界。
|
||||
- 验证方式:普通浏览器、小程序、Expo 壳、Tauri 壳都能返回正确 `getHostRuntime()`;未支持能力能回退 H5;固定玩法在各宿主中读取同一作品数据和运行态 snapshot;AI sandbox 无法直接调用 HostBridge;Tauri release 不允许任意远端页面调用桌面命令。
|
||||
- 关联文档:`docs/【前端架构】ExpoReactNative与Tauri宿主壳方案-2026-06-17.md`、`docs/【前端架构】宿主壳能力统一协议-2026-06-17.md`。
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -41,7 +41,7 @@ AI H5 sandbox
|
||||
|
||||
- `getHostRuntime()`:识别 `browser`、`wechat_mini_program`、`native_app`,并解析 `hostCapabilities` 能力声明;进入 `native_app` 后会通过真实 `host.getRuntime` 回读宿主 runtime 并缓存能力清单,未知能力会被丢弃。H5 业务只根据已声明或已回读的能力展示入口、发起宿主请求或走 fallback。
|
||||
- `getHostAppearanceColorScheme()`:原生 App 宿主的受控外观查询入口。H5 可通过 `appearance.getColorScheme` 读取宿主当前 `light` / `dark` / `unknown` 配色模式;Expo 移动壳通过 React Native `Appearance.getColorScheme()` 读取系统偏好,Tauri 桌面壳通过主窗口 `theme()` 读取窗口主题。该能力只读,不改变 H5 主题,也不覆盖用户或系统偏好。
|
||||
- `subscribeHostAppLifecycle()`:原生 App 宿主的受控生命周期事件入口。Expo 移动壳通过 React Native `AppState` 派发 `app.lifecycle`,Tauri 桌面壳通过主窗口 focus / blur 事件派发同名事件;H5 只依赖统一的 `active` / `inactive` / `background` 状态和 `focused` 布尔值,原生细分状态只放在 `nativeState` 用于排障,不作为业务分支依据。当前 H5 背景音乐 hook 已订阅该事件,宿主进入后台或窗口失焦时会暂停音频循环,回到 active 且用户原本开启音乐时再恢复播放。
|
||||
- `subscribeHostAppLifecycle()`:原生 App 宿主的受控生命周期事件入口。Expo 移动壳通过 React Native `AppState` 派发 `app.lifecycle`,Tauri 桌面壳通过主窗口 focus / blur 事件派发同名事件;H5 只依赖统一的 `active` / `inactive` / `background` 状态和 `focused` 布尔值,原生细分状态只放在 `nativeState` 用于排障,不作为业务分支依据。H5 统一通过 `useHostLifecycleActive()` 把宿主状态折算为运行态可播放状态;WebAudio 背景音乐和固定玩法 `<audio>` 背景音乐都必须按该状态暂停 / 恢复,宿主进入后台、inactive 或窗口失焦时暂停,回到 active 且 focused 后只在原运行态、音源和用户音量仍允许时恢复。
|
||||
- `getHostNetworkStatus()` / `subscribeHostNetworkStatusChange()`:原生 App 宿主的受控网络状态入口。Expo 移动壳通过 `expo-network` 查询并订阅真实系统网络状态;Tauri 桌面壳通过短超时连接 `app.genarrative.world:443` 查询主站可达性,并在主 WebView 内监听 `online` / `offline` 注入变化事件。H5 只依赖统一的 `isConnected`、`isInternetReachable` 和连接类型,不直接读取平台私有网络 API。
|
||||
- `requestHostLogin()`:微信小程序跳转原生登录页;浏览器返回 `false`,由 H5 登录弹窗承接。
|
||||
- `requestHostPayment()`:微信小程序支付跳转原生支付页;其它渠道返回 `false`,继续走 H5 / Native 二维码。
|
||||
|
||||
@@ -16,11 +16,13 @@ import type {
|
||||
Match3DRunSnapshot,
|
||||
} from '../../../packages/shared/src/contracts/match3dRuntime';
|
||||
import type { Match3DGeneratedItemAsset } from '../../../packages/shared/src/contracts/match3dWorks';
|
||||
import { useHostLifecycleActive } from '../../hooks/useHostLifecycleActive';
|
||||
import {
|
||||
confirmLocalMatch3DClick,
|
||||
resolveLocalMatch3DItemTypeCount,
|
||||
startLocalMatch3DRun,
|
||||
} from '../../services/match3d-runtime';
|
||||
import { AuthUiContext } from '../auth/AuthUiContext';
|
||||
import {
|
||||
applyMatch3DRendererCanvasLayout,
|
||||
buildMatch3DGeneratedAssetTypeMap,
|
||||
@@ -78,6 +80,10 @@ vi.mock('../../services/match3dSpritesheetParser', async (importOriginal) => {
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('../../hooks/useHostLifecycleActive', () => ({
|
||||
useHostLifecycleActive: vi.fn(() => true),
|
||||
}));
|
||||
|
||||
vi.mock('./Match3DPhysicsBoard', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('./Match3DPhysicsBoard')>();
|
||||
return {
|
||||
@@ -102,6 +108,8 @@ vi.mock('./Match3DPhysicsBoard', async (importOriginal) => {
|
||||
};
|
||||
});
|
||||
|
||||
const useHostLifecycleActiveMock = vi.mocked(useHostLifecycleActive);
|
||||
|
||||
afterEach(() => {
|
||||
delete (
|
||||
globalThis as typeof globalThis & {
|
||||
@@ -110,6 +118,8 @@ afterEach(() => {
|
||||
).__MATCH3D_KEEP_3D_TEST_RENDER__;
|
||||
runtimeAudioFeedback.playRuntimeMergeSound.mockReset();
|
||||
match3dSpritesheetParser.loadMatch3DSpritesheetAssetRegions.mockReset();
|
||||
useHostLifecycleActiveMock.mockReset();
|
||||
useHostLifecycleActiveMock.mockReturnValue(true);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
@@ -212,6 +222,51 @@ function renderRuntime(
|
||||
};
|
||||
}
|
||||
|
||||
function createMatch3DBackgroundMusicAssets(): Match3DGeneratedItemAsset[] {
|
||||
return [
|
||||
{
|
||||
itemId: 'match3d-item-1',
|
||||
itemName: '草莓',
|
||||
imageSrc: '/match3d/strawberry.png',
|
||||
imageObjectKey: null,
|
||||
imageViews: [],
|
||||
status: 'image_ready',
|
||||
modelSrc: null,
|
||||
modelObjectKey: null,
|
||||
backgroundMusic: {
|
||||
taskId: 'music-task-1',
|
||||
provider: 'vector-engine-suno',
|
||||
assetObjectId: 'asset-music-1',
|
||||
assetKind: 'match3d_background_music',
|
||||
audioSrc: '/match3d/music.mp3',
|
||||
prompt: '',
|
||||
title: '果园轻舞',
|
||||
updatedAt: '2026-06-18T00:00:00.000Z',
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function createMatch3DAuthValue(musicVolume: number) {
|
||||
return {
|
||||
user: null,
|
||||
canAccessProtectedData: false,
|
||||
openLoginModal: () => {},
|
||||
requireAuth: (action: () => void) => action(),
|
||||
openSettingsModal: () => {},
|
||||
openAccountModal: () => {},
|
||||
setCurrentUser: vi.fn(),
|
||||
logout: async () => {},
|
||||
musicVolume,
|
||||
setMusicVolume: vi.fn(),
|
||||
platformTheme: 'light' as const,
|
||||
setPlatformTheme: vi.fn(),
|
||||
isHydratingSettings: false,
|
||||
isPersistingSettings: false,
|
||||
settingsError: null,
|
||||
};
|
||||
}
|
||||
|
||||
test('展示圆形空间和 7 格备选栏', () => {
|
||||
renderRuntime(startLocalMatch3DRun(4));
|
||||
|
||||
@@ -1843,6 +1898,84 @@ test('运行态从任意素材读取作品级背景音乐并换签播放', async
|
||||
await waitFor(() => expect(playSpy).toHaveBeenCalled());
|
||||
});
|
||||
|
||||
test('抓大鹅背景音乐跟随宿主生命周期暂停和恢复', async () => {
|
||||
const playSpy = vi
|
||||
.spyOn(HTMLMediaElement.prototype, 'play')
|
||||
.mockResolvedValue(undefined);
|
||||
const pauseSpy = vi
|
||||
.spyOn(HTMLMediaElement.prototype, 'pause')
|
||||
.mockImplementation(() => undefined);
|
||||
const run = startLocalMatch3DRun(3);
|
||||
const generatedItemAssets = createMatch3DBackgroundMusicAssets();
|
||||
useHostLifecycleActiveMock.mockReturnValue(true);
|
||||
|
||||
const { rerender } = render(
|
||||
<Match3DRuntimeShell
|
||||
run={run}
|
||||
generatedItemAssets={generatedItemAssets}
|
||||
onBack={vi.fn()}
|
||||
onRestart={vi.fn()}
|
||||
onOptimisticRunChange={vi.fn()}
|
||||
onClickItem={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => expect(playSpy).toHaveBeenCalledTimes(1));
|
||||
useHostLifecycleActiveMock.mockReturnValue(false);
|
||||
rerender(
|
||||
<Match3DRuntimeShell
|
||||
run={run}
|
||||
generatedItemAssets={generatedItemAssets}
|
||||
onBack={vi.fn()}
|
||||
onRestart={vi.fn()}
|
||||
onOptimisticRunChange={vi.fn()}
|
||||
onClickItem={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => expect(pauseSpy).toHaveBeenCalledTimes(1));
|
||||
expect(playSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
useHostLifecycleActiveMock.mockReturnValue(true);
|
||||
rerender(
|
||||
<Match3DRuntimeShell
|
||||
run={run}
|
||||
generatedItemAssets={generatedItemAssets}
|
||||
onBack={vi.fn()}
|
||||
onRestart={vi.fn()}
|
||||
onOptimisticRunChange={vi.fn()}
|
||||
onClickItem={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => expect(playSpy).toHaveBeenCalledTimes(2));
|
||||
});
|
||||
|
||||
test('抓大鹅背景音乐音量为 0 时不尝试播放', async () => {
|
||||
const playSpy = vi
|
||||
.spyOn(HTMLMediaElement.prototype, 'play')
|
||||
.mockResolvedValue(undefined);
|
||||
const pauseSpy = vi
|
||||
.spyOn(HTMLMediaElement.prototype, 'pause')
|
||||
.mockImplementation(() => undefined);
|
||||
|
||||
render(
|
||||
<AuthUiContext.Provider value={createMatch3DAuthValue(0)}>
|
||||
<Match3DRuntimeShell
|
||||
run={startLocalMatch3DRun(3)}
|
||||
generatedItemAssets={createMatch3DBackgroundMusicAssets()}
|
||||
onBack={vi.fn()}
|
||||
onRestart={vi.fn()}
|
||||
onOptimisticRunChange={vi.fn()}
|
||||
onClickItem={vi.fn()}
|
||||
/>
|
||||
</AuthUiContext.Provider>,
|
||||
);
|
||||
|
||||
await waitFor(() => expect(pauseSpy).toHaveBeenCalledTimes(1));
|
||||
expect(playSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('本地试玩按难度档位生成类型并兼容历史硬核消除数', () => {
|
||||
const smallRun = startLocalMatch3DRun(12);
|
||||
const hardRun = startLocalMatch3DRun(20);
|
||||
|
||||
@@ -28,6 +28,7 @@ import type {
|
||||
Match3DGeneratedBackgroundAsset,
|
||||
Match3DGeneratedItemAsset,
|
||||
} from '../../../packages/shared/src/contracts/match3dWorks';
|
||||
import { useHostLifecycleActive } from '../../hooks/useHostLifecycleActive';
|
||||
import {
|
||||
isGeneratedLegacyPath,
|
||||
readAssetBytes,
|
||||
@@ -1094,6 +1095,7 @@ export function Match3DRuntimeShell({
|
||||
const [resolvedBackgroundImageSrc, setResolvedBackgroundImageSrc] =
|
||||
useState('');
|
||||
const musicVolume = authUi?.musicVolume ?? DEFAULT_MATCH3D_MUSIC_VOLUME;
|
||||
const isHostLifecycleActive = useHostLifecycleActive();
|
||||
const levelAudioConfig = DEFAULT_RUNTIME_LEVEL_AUDIO_CONFIG;
|
||||
const runtimeGeneratedItemAssets = useMemo(
|
||||
() => normalizeMatch3DGeneratedItemAssetsForRuntime(generatedItemAssets),
|
||||
@@ -1476,7 +1478,9 @@ export function Match3DRuntimeShell({
|
||||
!audio ||
|
||||
!resolvedBackgroundMusicSrc ||
|
||||
!run ||
|
||||
!isRunState(run.status, 'running')
|
||||
!isRunState(run.status, 'running') ||
|
||||
!isHostLifecycleActive ||
|
||||
musicVolume <= 0
|
||||
) {
|
||||
if (audio) {
|
||||
audio.pause();
|
||||
@@ -1485,7 +1489,7 @@ export function Match3DRuntimeShell({
|
||||
}
|
||||
audio.volume = Math.max(0, Math.min(1, musicVolume));
|
||||
void audio.play().catch(() => {});
|
||||
}, [musicVolume, resolvedBackgroundMusicSrc, run]);
|
||||
}, [isHostLifecycleActive, musicVolume, resolvedBackgroundMusicSrc, run]);
|
||||
|
||||
useEffect(() => {
|
||||
tryPlayBackgroundMusic();
|
||||
|
||||
@@ -8,9 +8,10 @@ import {
|
||||
waitFor,
|
||||
within,
|
||||
} from '@testing-library/react';
|
||||
import { expect, test, vi } from 'vitest';
|
||||
import { afterEach, expect, test, vi } from 'vitest';
|
||||
|
||||
import type { PuzzleRunSnapshot } from '../../../packages/shared/src/contracts/puzzleRuntimeSession';
|
||||
import { useHostLifecycleActive } from '../../hooks/useHostLifecycleActive';
|
||||
import { loadPuzzleUiSpritesheetLayout } from '../../services/puzzle-runtime/puzzleUiSpritesheetParser';
|
||||
import { AuthUiContext } from '../auth/AuthUiContext';
|
||||
import {
|
||||
@@ -29,6 +30,10 @@ vi.mock('../../hooks/useResolvedAssetReadUrl', () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('../../hooks/useHostLifecycleActive', () => ({
|
||||
useHostLifecycleActive: vi.fn(() => true),
|
||||
}));
|
||||
|
||||
vi.mock('../../services/puzzle-runtime/puzzleUiSpritesheetParser', async () => {
|
||||
const actual = await vi.importActual<
|
||||
typeof import('../../services/puzzle-runtime/puzzleUiSpritesheetParser')
|
||||
@@ -66,6 +71,14 @@ vi.mock('../ResolvedAssetImage', () => ({
|
||||
}) => (src ? <img src={src} alt={alt} className={className} /> : null),
|
||||
}));
|
||||
|
||||
const useHostLifecycleActiveMock = vi.mocked(useHostLifecycleActive);
|
||||
|
||||
afterEach(() => {
|
||||
useHostLifecycleActiveMock.mockReset();
|
||||
useHostLifecycleActiveMock.mockReturnValue(true);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function createAuthValue() {
|
||||
return {
|
||||
user: null,
|
||||
@@ -224,6 +237,136 @@ test('拼图运行态错误提示使用公共运行态 toast', () => {
|
||||
expect(toast.className).toContain('platform-runtime-status-toast');
|
||||
});
|
||||
|
||||
test('拼图背景音乐跟随宿主生命周期暂停和恢复', async () => {
|
||||
const playSpy = vi
|
||||
.spyOn(HTMLMediaElement.prototype, 'play')
|
||||
.mockResolvedValue(undefined);
|
||||
const pauseSpy = vi
|
||||
.spyOn(HTMLMediaElement.prototype, 'pause')
|
||||
.mockImplementation(() => undefined);
|
||||
const playingRun: PuzzleRunSnapshot = {
|
||||
...clearedRun,
|
||||
currentLevel: {
|
||||
...clearedRun.currentLevel!,
|
||||
status: 'playing',
|
||||
startedAtMs: Date.now(),
|
||||
clearedAtMs: null,
|
||||
elapsedMs: null,
|
||||
remainingMs: 300_000,
|
||||
timeLimitMs: 300_000,
|
||||
backgroundMusic: {
|
||||
taskId: 'music-task-1',
|
||||
provider: 'vector-engine-suno',
|
||||
assetObjectId: 'asset-music-1',
|
||||
assetKind: 'puzzle_background_music',
|
||||
audioSrc: '/generated-puzzle-assets/audio/music.mp3',
|
||||
prompt: '',
|
||||
title: '潮雾轻歌',
|
||||
updatedAt: '2026-06-18T00:00:00.000Z',
|
||||
},
|
||||
board: {
|
||||
...clearedRun.currentLevel!.board,
|
||||
allTilesResolved: false,
|
||||
},
|
||||
},
|
||||
};
|
||||
useHostLifecycleActiveMock.mockReturnValue(true);
|
||||
|
||||
const { rerender } = renderPuzzleRuntime(
|
||||
<PuzzleRuntimeShell
|
||||
run={playingRun}
|
||||
onBack={vi.fn()}
|
||||
onSwapPieces={vi.fn()}
|
||||
onDragPiece={vi.fn()}
|
||||
onAdvanceNextLevel={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
await waitFor(() => expect(playSpy).toHaveBeenCalledTimes(1));
|
||||
useHostLifecycleActiveMock.mockReturnValue(false);
|
||||
rerender(
|
||||
<AuthUiContext.Provider value={createAuthValue()}>
|
||||
<PuzzleRuntimeShell
|
||||
run={playingRun}
|
||||
onBack={vi.fn()}
|
||||
onSwapPieces={vi.fn()}
|
||||
onDragPiece={vi.fn()}
|
||||
onAdvanceNextLevel={vi.fn()}
|
||||
/>
|
||||
</AuthUiContext.Provider>,
|
||||
);
|
||||
|
||||
await waitFor(() => expect(pauseSpy).toHaveBeenCalledTimes(1));
|
||||
expect(playSpy).toHaveBeenCalledTimes(1);
|
||||
|
||||
useHostLifecycleActiveMock.mockReturnValue(true);
|
||||
rerender(
|
||||
<AuthUiContext.Provider value={createAuthValue()}>
|
||||
<PuzzleRuntimeShell
|
||||
run={playingRun}
|
||||
onBack={vi.fn()}
|
||||
onSwapPieces={vi.fn()}
|
||||
onDragPiece={vi.fn()}
|
||||
onAdvanceNextLevel={vi.fn()}
|
||||
/>
|
||||
</AuthUiContext.Provider>,
|
||||
);
|
||||
|
||||
await waitFor(() => expect(playSpy).toHaveBeenCalledTimes(2));
|
||||
});
|
||||
|
||||
test('拼图背景音乐音量为 0 时不尝试播放', async () => {
|
||||
const playSpy = vi
|
||||
.spyOn(HTMLMediaElement.prototype, 'play')
|
||||
.mockResolvedValue(undefined);
|
||||
const pauseSpy = vi
|
||||
.spyOn(HTMLMediaElement.prototype, 'pause')
|
||||
.mockImplementation(() => undefined);
|
||||
const playingRun: PuzzleRunSnapshot = {
|
||||
...clearedRun,
|
||||
currentLevel: {
|
||||
...clearedRun.currentLevel!,
|
||||
status: 'playing',
|
||||
startedAtMs: Date.now(),
|
||||
clearedAtMs: null,
|
||||
elapsedMs: null,
|
||||
remainingMs: 300_000,
|
||||
timeLimitMs: 300_000,
|
||||
backgroundMusic: {
|
||||
taskId: 'music-task-1',
|
||||
provider: 'vector-engine-suno',
|
||||
assetObjectId: 'asset-music-1',
|
||||
assetKind: 'puzzle_background_music',
|
||||
audioSrc: '/generated-puzzle-assets/audio/music.mp3',
|
||||
prompt: '',
|
||||
title: '潮雾轻歌',
|
||||
updatedAt: '2026-06-18T00:00:00.000Z',
|
||||
},
|
||||
board: {
|
||||
...clearedRun.currentLevel!.board,
|
||||
allTilesResolved: false,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
renderPuzzleRuntime(
|
||||
<PuzzleRuntimeShell
|
||||
run={playingRun}
|
||||
onBack={vi.fn()}
|
||||
onSwapPieces={vi.fn()}
|
||||
onDragPiece={vi.fn()}
|
||||
onAdvanceNextLevel={vi.fn()}
|
||||
/>,
|
||||
{
|
||||
...createAuthValue(),
|
||||
musicVolume: 0,
|
||||
},
|
||||
);
|
||||
|
||||
await waitFor(() => expect(pauseSpy).toHaveBeenCalledTimes(1));
|
||||
expect(playSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('指针拖拽时会触发拖拽提交并在松开时落子', () => {
|
||||
const originalRequestAnimationFrame = window.requestAnimationFrame;
|
||||
const onDragPiece = vi.fn();
|
||||
|
||||
@@ -30,6 +30,7 @@ import type {
|
||||
PuzzleRuntimePropKind,
|
||||
SwapPuzzlePiecesRequest,
|
||||
} from '../../../packages/shared/src/contracts/puzzleRuntimeSession';
|
||||
import { useHostLifecycleActive } from '../../hooks/useHostLifecycleActive';
|
||||
import { useResolvedAssetReadUrl } from '../../hooks/useResolvedAssetReadUrl';
|
||||
import {
|
||||
createRuntimeDragInputController,
|
||||
@@ -520,6 +521,7 @@ export function PuzzleRuntimeShell({
|
||||
const currentLevelStartedAtMs = currentLevel?.startedAtMs ?? null;
|
||||
const currentLevelStatus = currentLevel?.status ?? null;
|
||||
const musicVolume = authUi?.musicVolume ?? DEFAULT_PUZZLE_MUSIC_VOLUME;
|
||||
const isHostLifecycleActive = useHostLifecycleActive();
|
||||
const backgroundMusicSrc =
|
||||
currentLevel?.backgroundMusic?.audioSrc?.trim() || null;
|
||||
const levelAudioConfig = DEFAULT_RUNTIME_LEVEL_AUDIO_CONFIG;
|
||||
@@ -549,7 +551,13 @@ export function PuzzleRuntimeShell({
|
||||
const hasUiSpritesheet = Boolean(resolvedUiSpritesheetImage);
|
||||
const tryPlayBackgroundMusic = useCallback(() => {
|
||||
const audio = backgroundAudioRef.current;
|
||||
if (!audio || !resolvedBackgroundMusicSrc || runtimeStatus !== 'playing') {
|
||||
if (
|
||||
!audio ||
|
||||
!resolvedBackgroundMusicSrc ||
|
||||
runtimeStatus !== 'playing' ||
|
||||
!isHostLifecycleActive ||
|
||||
musicVolume <= 0
|
||||
) {
|
||||
if (audio) {
|
||||
audio.pause();
|
||||
}
|
||||
@@ -557,7 +565,12 @@ export function PuzzleRuntimeShell({
|
||||
}
|
||||
audio.volume = Math.max(0, Math.min(1, musicVolume));
|
||||
void audio.play().catch(() => {});
|
||||
}, [musicVolume, resolvedBackgroundMusicSrc, runtimeStatus]);
|
||||
}, [
|
||||
isHostLifecycleActive,
|
||||
musicVolume,
|
||||
resolvedBackgroundMusicSrc,
|
||||
runtimeStatus,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!rawUiSpritesheetImage) {
|
||||
|
||||
@@ -3,14 +3,14 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { afterEach, expect, test, vi } from 'vitest';
|
||||
|
||||
import { subscribeHostAppLifecycle } from '../services/host-bridge/hostBridge';
|
||||
import { useBackgroundMusic } from './useBackgroundMusic';
|
||||
import { useHostLifecycleActive } from './useHostLifecycleActive';
|
||||
|
||||
vi.mock('../services/host-bridge/hostBridge', () => ({
|
||||
subscribeHostAppLifecycle: vi.fn(() => () => undefined),
|
||||
vi.mock('./useHostLifecycleActive', () => ({
|
||||
useHostLifecycleActive: vi.fn(() => true),
|
||||
}));
|
||||
|
||||
const subscribeHostAppLifecycleMock = vi.mocked(subscribeHostAppLifecycle);
|
||||
const useHostLifecycleActiveMock = vi.mocked(useHostLifecycleActive);
|
||||
|
||||
class MockAudioParam {
|
||||
value = 0;
|
||||
@@ -72,6 +72,7 @@ class MockAudioContext {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.clearAllMocks();
|
||||
useHostLifecycleActiveMock.mockReturnValue(true);
|
||||
audioContextInstances.length = 0;
|
||||
Reflect.deleteProperty(window, 'AudioContext');
|
||||
Reflect.deleteProperty(window, 'webkitAudioContext');
|
||||
@@ -87,14 +88,11 @@ function installAudioContextMock() {
|
||||
test('background music suspends and resumes with native host lifecycle', async () => {
|
||||
vi.useFakeTimers();
|
||||
installAudioContextMock();
|
||||
let lifecycleListener: Parameters<typeof subscribeHostAppLifecycle>[0] | null =
|
||||
null;
|
||||
subscribeHostAppLifecycleMock.mockImplementation((listener) => {
|
||||
lifecycleListener = listener;
|
||||
return () => undefined;
|
||||
});
|
||||
useHostLifecycleActiveMock.mockReturnValue(true);
|
||||
|
||||
renderHook(() => useBackgroundMusic({ active: true, volume: 0.6 }));
|
||||
const { rerender } = renderHook(() =>
|
||||
useBackgroundMusic({ active: true, volume: 0.6 }),
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
window.dispatchEvent(new KeyboardEvent('keydown'));
|
||||
@@ -105,21 +103,15 @@ test('background music suspends and resumes with native host lifecycle', async (
|
||||
expect(context?.resume).toHaveBeenCalledTimes(1);
|
||||
|
||||
await act(async () => {
|
||||
lifecycleListener?.({
|
||||
state: 'background',
|
||||
focused: false,
|
||||
nativeState: 'background',
|
||||
});
|
||||
useHostLifecycleActiveMock.mockReturnValue(false);
|
||||
rerender();
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(context?.suspend).toHaveBeenCalledTimes(1);
|
||||
|
||||
await act(async () => {
|
||||
lifecycleListener?.({
|
||||
state: 'active',
|
||||
focused: true,
|
||||
nativeState: 'active',
|
||||
});
|
||||
useHostLifecycleActiveMock.mockReturnValue(true);
|
||||
rerender();
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(context?.resume).toHaveBeenCalledTimes(2);
|
||||
@@ -136,7 +128,7 @@ test('background music keeps browser fallback behavior when native lifecycle is
|
||||
});
|
||||
|
||||
const context = audioContextInstances[0];
|
||||
expect(subscribeHostAppLifecycleMock).toHaveBeenCalledTimes(1);
|
||||
expect(useHostLifecycleActiveMock).toHaveBeenCalledTimes(1);
|
||||
expect(context?.resume).toHaveBeenCalledTimes(1);
|
||||
expect(context?.suspend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
|
||||
import { subscribeHostAppLifecycle } from '../services/host-bridge/hostBridge';
|
||||
import { useHostLifecycleActive } from './useHostLifecycleActive';
|
||||
|
||||
type AudioWindow = Window & {
|
||||
webkitAudioContext?: typeof AudioContext;
|
||||
@@ -84,13 +84,14 @@ export function useBackgroundMusic({
|
||||
active: boolean;
|
||||
volume: number;
|
||||
}) {
|
||||
const isHostLifecycleActive = useHostLifecycleActive();
|
||||
const contextRef = useRef<AudioContext | null>(null);
|
||||
const masterGainRef = useRef<GainNode | null>(null);
|
||||
const loopTimerRef = useRef<number | null>(null);
|
||||
const stepRef = useRef(0);
|
||||
const activeRef = useRef(active);
|
||||
const volumeRef = useRef(volume);
|
||||
const hostLifecycleActiveRef = useRef(true);
|
||||
const hostLifecycleActiveRef = useRef(isHostLifecycleActive);
|
||||
|
||||
const stopLoop = useCallback(() => {
|
||||
if (loopTimerRef.current !== null) {
|
||||
@@ -257,24 +258,23 @@ export function useBackgroundMusic({
|
||||
};
|
||||
}, [active, startPlayback, stopLoop, updateMasterVolume, volume]);
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
subscribeHostAppLifecycle((payload) => {
|
||||
const isHostActive = payload.state === 'active' && payload.focused;
|
||||
if (hostLifecycleActiveRef.current === isHostActive) {
|
||||
return;
|
||||
}
|
||||
useEffect(() => {
|
||||
if (hostLifecycleActiveRef.current === isHostLifecycleActive) {
|
||||
return;
|
||||
}
|
||||
|
||||
hostLifecycleActiveRef.current = isHostActive;
|
||||
if (!isHostActive) {
|
||||
suspendPlaybackForHostLifecycle();
|
||||
return;
|
||||
}
|
||||
hostLifecycleActiveRef.current = isHostLifecycleActive;
|
||||
if (!isHostLifecycleActive) {
|
||||
suspendPlaybackForHostLifecycle();
|
||||
return;
|
||||
}
|
||||
|
||||
void startPlayback();
|
||||
}),
|
||||
[startPlayback, suspendPlaybackForHostLifecycle],
|
||||
);
|
||||
void startPlayback();
|
||||
}, [
|
||||
isHostLifecycleActive,
|
||||
startPlayback,
|
||||
suspendPlaybackForHostLifecycle,
|
||||
]);
|
||||
|
||||
useEffect(() => () => {
|
||||
stopLoop();
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
/* @vitest-environment jsdom */
|
||||
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { afterEach, expect, test, vi } from 'vitest';
|
||||
|
||||
import { subscribeHostAppLifecycle } from '../services/host-bridge/hostBridge';
|
||||
import { useHostLifecycleActive } from './useHostLifecycleActive';
|
||||
|
||||
vi.mock('../services/host-bridge/hostBridge', () => ({
|
||||
subscribeHostAppLifecycle: vi.fn(() => () => undefined),
|
||||
}));
|
||||
|
||||
const subscribeHostAppLifecycleMock = vi.mocked(subscribeHostAppLifecycle);
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test('host lifecycle active defaults to active when host lifecycle is unavailable', () => {
|
||||
const { result } = renderHook(() => useHostLifecycleActive());
|
||||
|
||||
expect(result.current).toBe(true);
|
||||
expect(subscribeHostAppLifecycleMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('host lifecycle active follows native app lifecycle events', () => {
|
||||
const unsubscribe = vi.fn();
|
||||
let lifecycleListener:
|
||||
| Parameters<typeof subscribeHostAppLifecycle>[0]
|
||||
| null = null;
|
||||
subscribeHostAppLifecycleMock.mockImplementation((listener) => {
|
||||
lifecycleListener = listener;
|
||||
return unsubscribe;
|
||||
});
|
||||
|
||||
const { result, unmount } = renderHook(() => useHostLifecycleActive());
|
||||
expect(result.current).toBe(true);
|
||||
|
||||
act(() => {
|
||||
lifecycleListener?.({
|
||||
state: 'inactive',
|
||||
focused: false,
|
||||
nativeState: 'blur',
|
||||
});
|
||||
});
|
||||
expect(result.current).toBe(false);
|
||||
|
||||
act(() => {
|
||||
lifecycleListener?.({
|
||||
state: 'active',
|
||||
focused: false,
|
||||
nativeState: 'active',
|
||||
});
|
||||
});
|
||||
expect(result.current).toBe(false);
|
||||
|
||||
act(() => {
|
||||
lifecycleListener?.({
|
||||
state: 'active',
|
||||
focused: true,
|
||||
nativeState: 'active',
|
||||
});
|
||||
});
|
||||
expect(result.current).toBe(true);
|
||||
|
||||
unmount();
|
||||
expect(unsubscribe).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { subscribeHostAppLifecycle } from '../services/host-bridge/hostBridge';
|
||||
|
||||
export function useHostLifecycleActive() {
|
||||
const [isHostLifecycleActive, setIsHostLifecycleActive] = useState(true);
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
subscribeHostAppLifecycle((payload) => {
|
||||
setIsHostLifecycleActive(
|
||||
payload.state === 'active' && payload.focused,
|
||||
);
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
return isHostLifecycleActive;
|
||||
}
|
||||
Reference in New Issue
Block a user