接入宿主生命周期暂停背景音乐

useBackgroundMusic 订阅 app.lifecycle 统一事件

宿主进后台或桌面失焦时暂停音频循环并 suspend WebAudio

宿主恢复 active 后按用户原音乐状态继续播放

更新测试和原生壳架构文档
This commit is contained in:
2026-06-18 03:39:00 +08:00
parent d261cc8d0b
commit 8d30cf65bb
5 changed files with 220 additions and 15 deletions

View File

@@ -36,6 +36,7 @@
- 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 移动图片导入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 H5 图片上传接入宿主导入:`CreativeImageInputPanel``native_app` 且声明 `file.importImage` 时,主图上传和描述参考图上传优先调用 `importHostImageFile()`,并把宿主返回的 base64 图片转换为现有 `File` 回调;浏览器、小程序和未声明能力的裁剪壳继续走原生 `<input type="file">` 路径,不新增玩法侧上传分叉。
- 2026-06-18 桌面图片拖入接入主图槽位:`CreativeImageInputPanel` 在桌面壳声明 `file.imageDropped` 时订阅宿主拖入事件,只在拖入坐标命中当前主图卡片且未被上层元素遮挡时消费事件,避免窗口级拖入被多个创作面板同时接收;成功后仍转换为现有 `File` 上传回调。 - 2026-06-18 桌面图片拖入接入主图槽位:`CreativeImageInputPanel` 在桌面壳声明 `file.imageDropped` 时订阅宿主拖入事件,只在拖入坐标命中当前主图卡片且未被上层元素遮挡时消费事件,避免窗口级拖入被多个创作面板同时接收;成功后仍转换为现有 `File` 上传回调。
- 2026-06-18 H5 背景音乐接入宿主生命周期:`useBackgroundMusic` 订阅 `subscribeHostAppLifecycle()`宿主进入后台、inactive 或桌面窗口失焦时降低音量并暂停音频循环,同时 `suspend` WebAudio context回到 `active + focused` 且用户原本开启音乐时再恢复播放,不改变用户音量设置。
- 影响范围:`src/services/host-bridge/`、未来 `apps/mobile-shell/`、未来 `apps/desktop-shell/`、移动端支付 / 分享 / 深链 / 推送、桌面端系统能力、AI H5 sandbox 的 GameBridge 边界。 - 影响范围:`src/services/host-bridge/`、未来 `apps/mobile-shell/`、未来 `apps/desktop-shell/`、移动端支付 / 分享 / 深链 / 推送、桌面端系统能力、AI H5 sandbox 的 GameBridge 边界。
- 验证方式普通浏览器、小程序、Expo 壳、Tauri 壳都能返回正确 `getHostRuntime()`;未支持能力能回退 H5固定玩法在各宿主中读取同一作品数据和运行态 snapshotAI sandbox 无法直接调用 HostBridgeTauri release 不允许任意远端页面调用桌面命令。 - 验证方式普通浏览器、小程序、Expo 壳、Tauri 壳都能返回正确 `getHostRuntime()`;未支持能力能回退 H5固定玩法在各宿主中读取同一作品数据和运行态 snapshotAI sandbox 无法直接调用 HostBridgeTauri release 不允许任意远端页面调用桌面命令。
- 关联文档:`docs/【前端架构】ExpoReactNative与Tauri宿主壳方案-2026-06-17.md``docs/【前端架构】宿主壳能力统一协议-2026-06-17.md` - 关联文档:`docs/【前端架构】ExpoReactNative与Tauri宿主壳方案-2026-06-17.md``docs/【前端架构】宿主壳能力统一协议-2026-06-17.md`

View File

@@ -249,7 +249,7 @@ GameBridge 禁止:
- iOS / Android 深链打开作品详情、创作页和邀请码。 - iOS / Android 深链打开作品详情、创作页和邀请码。
- 登录和支付先 fallback 到 H5只把能力边界跑通。 - 登录和支付先 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 游戏循环、音频和轮询做真实暂停 / 恢复判断;`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 导航状态变化实时注入 H5WebView 自身拦截到外域导航时只会把 `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 背景音乐 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 导航状态变化实时注入 H5WebView 自身拦截到外域导航时只会把 `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 3Tauri 桌面壳 MVP ### Phase 3Tauri 桌面壳 MVP
@@ -260,7 +260,7 @@ GameBridge 禁止:
- 实现 runtime、openExternalUrl、clipboard、share fallback、窗口标题同步。 - 实现 runtime、openExternalUrl、clipboard、share fallback、窗口标题同步。
- 验证 macOS / Windows / Linux 至少一条本地 smoke。 - 验证 macOS / Windows / Linux 至少一条本地 smoke。
当前状态:已新增 `apps/desktop-shell/`Tauri dev 直接加载本地主站 Viterelease 打包根 `dist` 主站资产。Rust 侧只把 `host_bridge_request` command 授给主窗口,`appearance.getColorScheme` 由 Rust 内部读取主窗口 `theme()` 并返回 `light` / `dark` / `unknown`,不设置或覆盖系统主题;`app.lifecycle` 由主窗口 focus / blur 事件注入 `active` / `inactive` 统一状态,不开放 Tauri event 插件给前端;`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 直接加载本地主站 Viterelease 打包根 `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 成功。
### Phase 4宿主能力扩展 ### Phase 4宿主能力扩展

View File

@@ -41,7 +41,7 @@ AI H5 sandbox
- `getHostRuntime()`:识别 `browser``wechat_mini_program``native_app`,并解析 `hostCapabilities` 能力声明;进入 `native_app` 后会通过真实 `host.getRuntime` 回读宿主 runtime 并缓存能力清单未知能力会被丢弃。H5 业务只根据已声明或已回读的能力展示入口、发起宿主请求或走 fallback。 - `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 主题,也不覆盖用户或系统偏好。 - `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` 用于排障,不作为业务分支依据。 - `subscribeHostAppLifecycle()`:原生 App 宿主的受控生命周期事件入口。Expo 移动壳通过 React Native `AppState` 派发 `app.lifecycle`Tauri 桌面壳通过主窗口 focus / blur 事件派发同名事件H5 只依赖统一的 `active` / `inactive` / `background` 状态和 `focused` 布尔值,原生细分状态只放在 `nativeState` 用于排障,不作为业务分支依据。当前 H5 背景音乐 hook 已订阅该事件,宿主进入后台或窗口失焦时会暂停音频循环,回到 active 且用户原本开启音乐时再恢复播放。
- `getHostNetworkStatus()` / `subscribeHostNetworkStatusChange()`:原生 App 宿主的受控网络状态入口。Expo 移动壳通过 `expo-network` 查询并订阅真实系统网络状态Tauri 桌面壳通过短超时连接 `app.genarrative.world:443` 查询主站可达性,并在主 WebView 内监听 `online` / `offline` 注入变化事件。H5 只依赖统一的 `isConnected``isInternetReachable` 和连接类型,不直接读取平台私有网络 API。 - `getHostNetworkStatus()` / `subscribeHostNetworkStatusChange()`:原生 App 宿主的受控网络状态入口。Expo 移动壳通过 `expo-network` 查询并订阅真实系统网络状态Tauri 桌面壳通过短超时连接 `app.genarrative.world:443` 查询主站可达性,并在主 WebView 内监听 `online` / `offline` 注入变化事件。H5 只依赖统一的 `isConnected``isInternetReachable` 和连接类型,不直接读取平台私有网络 API。
- `requestHostLogin()`:微信小程序跳转原生登录页;浏览器返回 `false`,由 H5 登录弹窗承接。 - `requestHostLogin()`:微信小程序跳转原生登录页;浏览器返回 `false`,由 H5 登录弹窗承接。
- `requestHostPayment()`:微信小程序支付跳转原生支付页;其它渠道返回 `false`,继续走 H5 / Native 二维码。 - `requestHostPayment()`:微信小程序支付跳转原生支付页;其它渠道返回 `false`,继续走 H5 / Native 二维码。

View File

@@ -0,0 +1,142 @@
/* @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 { useBackgroundMusic } from './useBackgroundMusic';
vi.mock('../services/host-bridge/hostBridge', () => ({
subscribeHostAppLifecycle: vi.fn(() => () => undefined),
}));
const subscribeHostAppLifecycleMock = vi.mocked(subscribeHostAppLifecycle);
class MockAudioParam {
value = 0;
setValueAtTime = vi.fn((value: number) => {
this.value = value;
});
linearRampToValueAtTime = vi.fn((value: number) => {
this.value = value;
});
exponentialRampToValueAtTime = vi.fn((value: number) => {
this.value = value;
});
cancelScheduledValues = vi.fn();
}
class MockGainNode {
gain = new MockAudioParam();
connect = vi.fn();
}
class MockOscillatorNode {
frequency = new MockAudioParam();
detune = new MockAudioParam();
type: OscillatorType = 'sine';
connect = vi.fn();
start = vi.fn();
stop = vi.fn();
}
const audioContextInstances: MockAudioContext[] = [];
class MockAudioContext {
currentTime = 0;
destination = {};
state: AudioContextState = 'suspended';
resume = vi.fn(async () => {
this.state = 'running';
});
suspend = vi.fn(async () => {
this.state = 'suspended';
});
close = vi.fn(async () => {
this.state = 'closed';
});
createGain = vi.fn(() => new MockGainNode());
createOscillator = vi.fn(() => new MockOscillatorNode());
constructor() {
audioContextInstances.push(this);
}
}
afterEach(() => {
vi.useRealTimers();
vi.clearAllMocks();
audioContextInstances.length = 0;
Reflect.deleteProperty(window, 'AudioContext');
Reflect.deleteProperty(window, 'webkitAudioContext');
});
function installAudioContextMock() {
Object.defineProperty(window, 'AudioContext', {
configurable: true,
value: MockAudioContext,
});
}
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;
});
renderHook(() => useBackgroundMusic({ active: true, volume: 0.6 }));
await act(async () => {
window.dispatchEvent(new KeyboardEvent('keydown'));
await Promise.resolve();
});
const context = audioContextInstances[0];
expect(context).toBeTruthy();
expect(context?.resume).toHaveBeenCalledTimes(1);
await act(async () => {
lifecycleListener?.({
state: 'background',
focused: false,
nativeState: 'background',
});
await Promise.resolve();
});
expect(context?.suspend).toHaveBeenCalledTimes(1);
await act(async () => {
lifecycleListener?.({
state: 'active',
focused: true,
nativeState: 'active',
});
await Promise.resolve();
});
expect(context?.resume).toHaveBeenCalledTimes(2);
});
test('background music keeps browser fallback behavior when native lifecycle is unsupported', async () => {
installAudioContextMock();
renderHook(() => useBackgroundMusic({ active: true, volume: 0.6 }));
await act(async () => {
window.dispatchEvent(new Event('pointerdown'));
await Promise.resolve();
});
const context = audioContextInstances[0];
expect(subscribeHostAppLifecycleMock).toHaveBeenCalledTimes(1);
expect(context?.resume).toHaveBeenCalledTimes(1);
expect(context?.suspend).not.toHaveBeenCalled();
});

View File

@@ -1,5 +1,7 @@
import { useCallback, useEffect, useRef } from 'react'; import { useCallback, useEffect, useRef } from 'react';
import { subscribeHostAppLifecycle } from '../services/host-bridge/hostBridge';
type AudioWindow = Window & { type AudioWindow = Window & {
webkitAudioContext?: typeof AudioContext; webkitAudioContext?: typeof AudioContext;
}; };
@@ -88,6 +90,7 @@ export function useBackgroundMusic({
const stepRef = useRef(0); const stepRef = useRef(0);
const activeRef = useRef(active); const activeRef = useRef(active);
const volumeRef = useRef(volume); const volumeRef = useRef(volume);
const hostLifecycleActiveRef = useRef(true);
const stopLoop = useCallback(() => { const stopLoop = useCallback(() => {
if (loopTimerRef.current !== null) { if (loopTimerRef.current !== null) {
@@ -126,7 +129,12 @@ export function useBackgroundMusic({
const scheduleLoop = useCallback(() => { const scheduleLoop = useCallback(() => {
const graph = ensureAudioGraph(); const graph = ensureAudioGraph();
if (!graph || !activeRef.current || volumeRef.current <= 0) { if (
!graph ||
!activeRef.current ||
!hostLifecycleActiveRef.current ||
volumeRef.current <= 0
) {
stopLoop(); stopLoop();
return; return;
} }
@@ -162,21 +170,46 @@ export function useBackgroundMusic({
loopTimerRef.current = window.setTimeout(scheduleLoop, 2200); loopTimerRef.current = window.setTimeout(scheduleLoop, 2200);
}, [ensureAudioGraph, stopLoop]); }, [ensureAudioGraph, stopLoop]);
const updateMasterVolume = useCallback((graph?: { context: AudioContext; masterGain: GainNode } | null) => { const updateMasterVolume = useCallback(
const audioGraph = graph ?? ensureAudioGraph(); (graph?: { context: AudioContext; masterGain: GainNode } | null) => {
if (!audioGraph) return; const audioGraph =
graph ??
(contextRef.current && masterGainRef.current
? {
context: contextRef.current,
masterGain: masterGainRef.current,
}
: null);
if (!audioGraph) return;
const targetGain = activeRef.current && volumeRef.current > 0 const targetGain =
? Math.max(0.0001, volumeRef.current * 0.18) activeRef.current &&
: 0.0001; hostLifecycleActiveRef.current &&
volumeRef.current > 0
? Math.max(0.0001, volumeRef.current * 0.18)
: 0.0001;
audioGraph.masterGain.gain.cancelScheduledValues(audioGraph.context.currentTime); audioGraph.masterGain.gain.cancelScheduledValues(
audioGraph.masterGain.gain.linearRampToValueAtTime(targetGain, audioGraph.context.currentTime + 0.24); audioGraph.context.currentTime,
}, [ensureAudioGraph]); );
audioGraph.masterGain.gain.linearRampToValueAtTime(
targetGain,
audioGraph.context.currentTime + 0.24,
);
},
[],
);
const startPlayback = useCallback(async () => { const startPlayback = useCallback(async () => {
const graph = ensureAudioGraph(); const graph = ensureAudioGraph();
if (!graph || !activeRef.current || volumeRef.current <= 0) return; if (
!graph ||
!activeRef.current ||
!hostLifecycleActiveRef.current ||
volumeRef.current <= 0
) {
return;
}
if (graph.context.state === 'suspended') { if (graph.context.state === 'suspended') {
await graph.context.resume(); await graph.context.resume();
@@ -189,11 +222,21 @@ export function useBackgroundMusic({
} }
}, [ensureAudioGraph, scheduleLoop, updateMasterVolume]); }, [ensureAudioGraph, scheduleLoop, updateMasterVolume]);
const suspendPlaybackForHostLifecycle = useCallback(() => {
updateMasterVolume();
stopLoop();
const context = contextRef.current;
if (context?.state === 'running') {
void context.suspend().catch(() => undefined);
}
}, [stopLoop, updateMasterVolume]);
useEffect(() => { useEffect(() => {
activeRef.current = active; activeRef.current = active;
volumeRef.current = volume; volumeRef.current = volume;
if (!active || volume <= 0) { if (!active || !hostLifecycleActiveRef.current || volume <= 0) {
updateMasterVolume(); updateMasterVolume();
stopLoop(); stopLoop();
return; return;
@@ -214,6 +257,25 @@ export function useBackgroundMusic({
}; };
}, [active, startPlayback, stopLoop, updateMasterVolume, volume]); }, [active, startPlayback, stopLoop, updateMasterVolume, volume]);
useEffect(
() =>
subscribeHostAppLifecycle((payload) => {
const isHostActive = payload.state === 'active' && payload.focused;
if (hostLifecycleActiveRef.current === isHostActive) {
return;
}
hostLifecycleActiveRef.current = isHostActive;
if (!isHostActive) {
suspendPlaybackForHostLifecycle();
return;
}
void startPlayback();
}),
[startPlayback, suspendPlaybackForHostLifecycle],
);
useEffect(() => () => { useEffect(() => () => {
stopLoop(); stopLoop();