接入固定玩法宿主生命周期音频暂停
新增 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`。
|
||||
|
||||
@@ -249,7 +249,7 @@ GameBridge 禁止:
|
||||
- iOS / Android 深链打开作品详情、创作页和邀请码。
|
||||
- 登录和支付先 fallback 到 H5;只把能力边界跑通。
|
||||
|
||||
当前状态:已新增 `apps/mobile-shell/`,通过 Expo development build 运行,`react-native-webview` 加载 H5 URL 并附加 `native_app` 宿主 query。移动壳使用真实品牌图标资产,已接入 `genarrative://` scheme、iOS associated domain 和 Android app link filter,启动和运行时 deep link 只会映射到同源 H5 路径并继续附加 HostBridge 上下文,外域和危险协议回退到默认主站入口。首轮真实能力包括 `host.getRuntime`、`appearance.getColorScheme`、`host.events`、`app.lifecycle`、`network.status`、`network.statusChanged`、`share.open`、`share.setTarget`、`navigation.openNativePage`、`navigation.canGoBack`、`app.openExternalUrl`、`clipboard.writeText`、`file.exportText`、`file.exportImage`、`file.importImage`、`haptics.impact` 和 Android 返回键回退;其中 `appearance.getColorScheme` 只读系统配色偏好,不强改 H5 或系统主题;`app.lifecycle` 通过 React Native `AppState` 注入 `active` / `inactive` / `background` 统一状态,供 H5 游戏循环、音频和轮询做真实暂停 / 恢复判断,当前 H5 背景音乐 hook 已通过该统一事件在宿主进后台时暂停、回到前台时按用户原本音乐状态恢复;`network.status` / `network.statusChanged` 通过 `expo-network` 查询并订阅真实系统网络状态,供 H5 游戏运行态和生成页识别离线 / 弱网回退;iOS 额外声明 `app.setBadgeCount`,通过 React Native `PushNotificationIOS` 设置应用图标角标,Android 不声明该能力。H5 会解析并过滤 `hostCapabilities`,也会在主 App 启动时通过真实 `host.getRuntime` 回读并缓存能力,只对声明或回读到的能力展示入口或调用宿主能力;其中 `share.setTarget` / `share.open` 会解析统一分享目标里的 `title`、`message`、`url`、`work`、`path` 或 `targetPath` 并调用 React Native 系统分享面板;发布分享弹窗只有在宿主声明 `share.open` 时才提供“系统分享”动作,失败时保留复制链接回退路径;`navigation.openNativePage` 在 Expo 壳内只接受同源 H5 route 并切换 WebView URL,不伪造尚未存在的登录、支付或其它原生页面,`navigation.canGoBack` 由 WebView 导航状态变化实时注入 H5,WebView 自身拦截到外域导航时只会把 `http:`、`https:`、`mailto:`、`tel:` 交给系统,危险协议直接阻断;`app.openExternalUrl` 也只允许同一协议白名单,ICP备案号和资产调试原图等 H5 外链入口在 `native_app` 中优先通过该能力离开 WebView 并交给系统浏览器;`clipboard.writeText` 由 H5 复制服务优先调用并写入系统剪贴板;`file.exportText` 通过 Expo 文件系统写入缓存文本文件,再交给系统分享 / 保存面板,文件名必须清洗,单次文本不超过 5 MiB,成功只返回文件名和字节数;`file.exportImage` 通过 Expo 文件系统写入缓存图片,再交给系统分享 / 保存面板,H5 只传允许 MIME 的 base64 图片数据,单次不超过 5 MiB,分享卡下载会优先走该能力;`file.importImage` 通过 Expo ImagePicker 请求相册权限并打开系统相册选择器,只接受 `image/png` / `image/jpeg` / `image/webp`、单次不超过 10 MiB,成功只返回清洗后的文件名、MIME、base64 内容和字节数,不把设备本地 URI 暴露给 H5,用户取消返回 `cancelled` 并由 H5 视作无选择;通用创作图片输入面板 `CreativeImageInputPanel` 在原生壳声明 `file.importImage` 时会优先调用该宿主能力,并把导入结果转换为现有 `File` 上传回调,拼图、拼消消、敲木鱼等复用该面板的主图和描述参考图选择无需新增玩法分叉;`haptics.impact` 通过 Expo Haptics 承接运行时轻触反馈,H5 在宿主不支持时回退到浏览器 vibration。登录和支付尚未接入渠道 SDK / 原生页面时明确返回 unsupported,让 H5 fallback 承接。
|
||||
当前状态:已新增 `apps/mobile-shell/`,通过 Expo development build 运行,`react-native-webview` 加载 H5 URL 并附加 `native_app` 宿主 query。移动壳使用真实品牌图标资产,已接入 `genarrative://` scheme、iOS associated domain 和 Android app link filter,启动和运行时 deep link 只会映射到同源 H5 路径并继续附加 HostBridge 上下文,外域和危险协议回退到默认主站入口。首轮真实能力包括 `host.getRuntime`、`appearance.getColorScheme`、`host.events`、`app.lifecycle`、`network.status`、`network.statusChanged`、`share.open`、`share.setTarget`、`navigation.openNativePage`、`navigation.canGoBack`、`app.openExternalUrl`、`clipboard.writeText`、`file.exportText`、`file.exportImage`、`file.importImage`、`haptics.impact` 和 Android 返回键回退;其中 `appearance.getColorScheme` 只读系统配色偏好,不强改 H5 或系统主题;`app.lifecycle` 通过 React Native `AppState` 注入 `active` / `inactive` / `background` 统一状态,供 H5 游戏循环、音频和轮询做真实暂停 / 恢复判断,H5 的 `useHostLifecycleActive()` 会把该事件归一成运行态可播放状态,WebAudio 背景音乐和拼图、抓大鹅等固定玩法 `<audio>` 背景音乐都按该状态在宿主进后台时暂停、回到前台且原播放条件仍满足时恢复;`network.status` / `network.statusChanged` 通过 `expo-network` 查询并订阅真实系统网络状态,供 H5 游戏运行态和生成页识别离线 / 弱网回退;iOS 额外声明 `app.setBadgeCount`,通过 React Native `PushNotificationIOS` 设置应用图标角标,Android 不声明该能力。H5 会解析并过滤 `hostCapabilities`,也会在主 App 启动时通过真实 `host.getRuntime` 回读并缓存能力,只对声明或回读到的能力展示入口或调用宿主能力;其中 `share.setTarget` / `share.open` 会解析统一分享目标里的 `title`、`message`、`url`、`work`、`path` 或 `targetPath` 并调用 React Native 系统分享面板;发布分享弹窗只有在宿主声明 `share.open` 时才提供“系统分享”动作,失败时保留复制链接回退路径;`navigation.openNativePage` 在 Expo 壳内只接受同源 H5 route 并切换 WebView URL,不伪造尚未存在的登录、支付或其它原生页面,`navigation.canGoBack` 由 WebView 导航状态变化实时注入 H5,WebView 自身拦截到外域导航时只会把 `http:`、`https:`、`mailto:`、`tel:` 交给系统,危险协议直接阻断;`app.openExternalUrl` 也只允许同一协议白名单,ICP备案号和资产调试原图等 H5 外链入口在 `native_app` 中优先通过该能力离开 WebView 并交给系统浏览器;`clipboard.writeText` 由 H5 复制服务优先调用并写入系统剪贴板;`file.exportText` 通过 Expo 文件系统写入缓存文本文件,再交给系统分享 / 保存面板,文件名必须清洗,单次文本不超过 5 MiB,成功只返回文件名和字节数;`file.exportImage` 通过 Expo 文件系统写入缓存图片,再交给系统分享 / 保存面板,H5 只传允许 MIME 的 base64 图片数据,单次不超过 5 MiB,分享卡下载会优先走该能力;`file.importImage` 通过 Expo ImagePicker 请求相册权限并打开系统相册选择器,只接受 `image/png` / `image/jpeg` / `image/webp`、单次不超过 10 MiB,成功只返回清洗后的文件名、MIME、base64 内容和字节数,不把设备本地 URI 暴露给 H5,用户取消返回 `cancelled` 并由 H5 视作无选择;通用创作图片输入面板 `CreativeImageInputPanel` 在原生壳声明 `file.importImage` 时会优先调用该宿主能力,并把导入结果转换为现有 `File` 上传回调,拼图、拼消消、敲木鱼等复用该面板的主图和描述参考图选择无需新增玩法分叉;`haptics.impact` 通过 Expo Haptics 承接运行时轻触反馈,H5 在宿主不支持时回退到浏览器 vibration。登录和支付尚未接入渠道 SDK / 原生页面时明确返回 unsupported,让 H5 fallback 承接。
|
||||
|
||||
### Phase 3:Tauri 桌面壳 MVP
|
||||
|
||||
@@ -260,7 +260,7 @@ GameBridge 禁止:
|
||||
- 实现 runtime、openExternalUrl、clipboard、share fallback、窗口标题同步。
|
||||
- 验证 macOS / Windows / Linux 至少一条本地 smoke。
|
||||
|
||||
当前状态:已新增 `apps/desktop-shell/`,Tauri dev 直接加载本地主站 Vite,release 打包根 `dist` 主站资产。Rust 侧只把 `host_bridge_request` command 授给主窗口,`appearance.getColorScheme` 由 Rust 内部读取主窗口 `theme()` 并返回 `light` / `dark` / `unknown`,不设置或覆盖系统主题;`app.lifecycle` 由主窗口 focus / blur 事件注入 `active` / `inactive` 统一状态,不开放 Tauri event 插件给前端,H5 背景音乐 hook 已通过该统一事件在窗口失焦时暂停、恢复焦点后按用户原本音乐状态恢复;`network.status` 由 Rust 对 `app.genarrative.world:443` 做短超时 TCP 可达性查询,`network.statusChanged` 由主 WebView 的 `online` / `offline` 事件注入,不开放任意网络探测给 H5;`app.openExternalUrl` 由 Rust 内部通过 opener 插件执行且只允许 `http:`、`https:`、`mailto:`、`tel:` 外链协议,ICP备案号和资产调试原图等 H5 外链入口在 `native_app` 中优先通过该能力离开主窗口并交给系统浏览器;`navigation.openNativePage` 只接受 `https://app.genarrative.world` 同源 H5 route 并在主窗口内受控跳转,`clipboard.writeText` 由 Rust 内部通过 clipboard-manager 插件写入系统剪贴板并由 H5 复制服务优先调用,`app.setTitle` 通过 Tauri 主窗口 API 同步窗口标题并拒绝空标题 / 控制字符,`app.setBadgeCount` 通过主窗口 `set_badge_count` 设置任务栏角标,数量只接受 `0-99999` 整数且 `0` 表示清除;H5 主站会按当前平台阶段先更新 `document.title`,再通过 `app.setTitle` 把同一标题同步给 Tauri 窗口,Expo 移动壳不声明该能力时静默忽略;不把 opener、clipboard 或 dialog 插件命令直接暴露给前端。当前真实能力为 `host.getRuntime`、`appearance.getColorScheme`、`app.lifecycle`、`network.status`、`network.statusChanged`、`share.setTarget`、`share.open`、`navigation.openNativePage`、`app.openExternalUrl`、`app.setTitle`、`app.setBadgeCount`、`clipboard.writeText`、`file.exportText`、`file.exportImage`、`file.importImage` 和 `file.imageDropped`;H5 会在主 App 启动时通过真实 `host.getRuntime` 回读并缓存这些能力,即使入口 URL 缺少 `hostCapabilities`,也只按宿主真实回包开启能力入口;其中 `share.open` 会把直接传入的分享 payload 或 `share.setTarget` 缓存的作品目标整理成非空分享文本并写入系统剪贴板,返回 `copied_to_clipboard`,发布分享弹窗在桌面壳中也通过该能力提供“系统分享”动作;`file.exportText` 通过系统保存对话框让用户选择本地路径,清洗文件名、限制单次文本导出不超过 5 MiB,写入成功后只返回文件名和字节数,不把本机绝对路径暴露给 H5,用户取消返回 `cancelled`;`file.exportImage` 同样通过系统保存对话框写入 H5 生成的图片字节,只接受 `image/png` / `image/jpeg` / `image/webp` base64 数据,单次不超过 5 MiB,分享卡下载会优先走该能力,用户取消返回 `cancelled`;`file.importImage` 通过系统选择框读取用户选择的图片,`file.imageDropped` 通过主窗口拖拽事件读取用户拖入的图片,二者都只接受 `image/png` / `image/jpeg` / `image/webp`、单次不超过 10 MiB,成功只返回文件名、MIME、base64 内容和字节数,不把本机绝对路径暴露给 H5,也不开放通用文件系统;通用创作图片输入面板 `CreativeImageInputPanel` 在桌面壳声明 `file.importImage` 时会优先打开系统图片选择框,在同时声明 `file.imageDropped` 时会按宿主拖入坐标把图片交给命中的主图槽位,并把结果转换为现有 `File` 上传回调,普通浏览器、小程序和未声明能力的壳继续保留原文件输入路径。原生系统分享面板、登录和支付未接入真实插件 / 渠道前不声明支持,不返回 mock 成功。
|
||||
当前状态:已新增 `apps/desktop-shell/`,Tauri dev 直接加载本地主站 Vite,release 打包根 `dist` 主站资产。Rust 侧只把 `host_bridge_request` command 授给主窗口,`appearance.getColorScheme` 由 Rust 内部读取主窗口 `theme()` 并返回 `light` / `dark` / `unknown`,不设置或覆盖系统主题;`app.lifecycle` 由主窗口 focus / blur 事件注入 `active` / `inactive` 统一状态,不开放 Tauri event 插件给前端,H5 通过 `useHostLifecycleActive()` 统一归一窗口焦点状态,WebAudio 背景音乐和拼图、抓大鹅等固定玩法 `<audio>` 背景音乐都会在窗口失焦时暂停、恢复焦点且原播放条件仍满足时恢复;`network.status` 由 Rust 对 `app.genarrative.world:443` 做短超时 TCP 可达性查询,`network.statusChanged` 由主 WebView 的 `online` / `offline` 事件注入,不开放任意网络探测给 H5;`app.openExternalUrl` 由 Rust 内部通过 opener 插件执行且只允许 `http:`、`https:`、`mailto:`、`tel:` 外链协议,ICP备案号和资产调试原图等 H5 外链入口在 `native_app` 中优先通过该能力离开主窗口并交给系统浏览器;`navigation.openNativePage` 只接受 `https://app.genarrative.world` 同源 H5 route 并在主窗口内受控跳转,`clipboard.writeText` 由 Rust 内部通过 clipboard-manager 插件写入系统剪贴板并由 H5 复制服务优先调用,`app.setTitle` 通过 Tauri 主窗口 API 同步窗口标题并拒绝空标题 / 控制字符,`app.setBadgeCount` 通过主窗口 `set_badge_count` 设置任务栏角标,数量只接受 `0-99999` 整数且 `0` 表示清除;H5 主站会按当前平台阶段先更新 `document.title`,再通过 `app.setTitle` 把同一标题同步给 Tauri 窗口,Expo 移动壳不声明该能力时静默忽略;不把 opener、clipboard 或 dialog 插件命令直接暴露给前端。当前真实能力为 `host.getRuntime`、`appearance.getColorScheme`、`app.lifecycle`、`network.status`、`network.statusChanged`、`share.setTarget`、`share.open`、`navigation.openNativePage`、`app.openExternalUrl`、`app.setTitle`、`app.setBadgeCount`、`clipboard.writeText`、`file.exportText`、`file.exportImage`、`file.importImage` 和 `file.imageDropped`;H5 会在主 App 启动时通过真实 `host.getRuntime` 回读并缓存这些能力,即使入口 URL 缺少 `hostCapabilities`,也只按宿主真实回包开启能力入口;其中 `share.open` 会把直接传入的分享 payload 或 `share.setTarget` 缓存的作品目标整理成非空分享文本并写入系统剪贴板,返回 `copied_to_clipboard`,发布分享弹窗在桌面壳中也通过该能力提供“系统分享”动作;`file.exportText` 通过系统保存对话框让用户选择本地路径,清洗文件名、限制单次文本导出不超过 5 MiB,写入成功后只返回文件名和字节数,不把本机绝对路径暴露给 H5,用户取消返回 `cancelled`;`file.exportImage` 同样通过系统保存对话框写入 H5 生成的图片字节,只接受 `image/png` / `image/jpeg` / `image/webp` base64 数据,单次不超过 5 MiB,分享卡下载会优先走该能力,用户取消返回 `cancelled`;`file.importImage` 通过系统选择框读取用户选择的图片,`file.imageDropped` 通过主窗口拖拽事件读取用户拖入的图片,二者都只接受 `image/png` / `image/jpeg` / `image/webp`、单次不超过 10 MiB,成功只返回文件名、MIME、base64 内容和字节数,不把本机绝对路径暴露给 H5,也不开放通用文件系统;通用创作图片输入面板 `CreativeImageInputPanel` 在桌面壳声明 `file.importImage` 时会优先打开系统图片选择框,在同时声明 `file.imageDropped` 时会按宿主拖入坐标把图片交给命中的主图槽位,并把结果转换为现有 `File` 上传回调,普通浏览器、小程序和未声明能力的壳继续保留原文件输入路径。原生系统分享面板、登录和支付未接入真实插件 / 渠道前不声明支持,不返回 mock 成功。
|
||||
|
||||
### Phase 4:宿主能力扩展
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
68
src/hooks/useHostLifecycleActive.test.tsx
Normal file
68
src/hooks/useHostLifecycleActive.test.tsx
Normal file
@@ -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);
|
||||
});
|
||||
19
src/hooks/useHostLifecycleActive.ts
Normal file
19
src/hooks/useHostLifecycleActive.ts
Normal file
@@ -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