接入原生壳生命周期事件
新增 app.lifecycle HostBridge 能力与 H5 订阅入口 Expo 壳通过 React Native AppState 注入真实前后台状态 Tauri 壳通过主窗口 focus 和 blur 注入真实激活状态 更新壳能力漂移检查、测试和架构文档
This commit is contained in:
@@ -134,6 +134,7 @@ const requiredBuildCommands = ['host_bridge_request'];
|
||||
const requiredMainSnippets = [
|
||||
'tauri_plugin_clipboard_manager::init()',
|
||||
'"appearance.getColorScheme"',
|
||||
'"app.lifecycle"',
|
||||
'"share.open"',
|
||||
'"share.setTarget"',
|
||||
'"navigation.openNativePage"',
|
||||
@@ -149,6 +150,8 @@ const requiredMainSnippets = [
|
||||
'set_title',
|
||||
'set_badge_count',
|
||||
'window.theme()',
|
||||
'WindowEvent::Focused',
|
||||
'host_bridge_event_script',
|
||||
];
|
||||
|
||||
for (const permission of requiredPermissions) {
|
||||
|
||||
@@ -7,6 +7,8 @@ use std::sync::Mutex;
|
||||
use tauri::Manager;
|
||||
use tauri::Theme;
|
||||
use tauri::Url;
|
||||
use tauri::WebviewWindow;
|
||||
use tauri::WindowEvent;
|
||||
use tauri_plugin_clipboard_manager::ClipboardExt;
|
||||
use tauri_plugin_dialog::DialogExt;
|
||||
use tauri_plugin_opener::OpenerExt;
|
||||
@@ -81,6 +83,7 @@ fn capabilities() -> Vec<&'static str> {
|
||||
vec![
|
||||
"host.getRuntime",
|
||||
"appearance.getColorScheme",
|
||||
"app.lifecycle",
|
||||
"share.open",
|
||||
"share.setTarget",
|
||||
"navigation.openNativePage",
|
||||
@@ -403,6 +406,55 @@ fn write_export_bytes_file(path: PathBuf, bytes: Vec<u8>) -> Result<usize, Strin
|
||||
Ok(byte_count)
|
||||
}
|
||||
|
||||
fn host_bridge_event_script(event: &str, payload: Value) -> Result<String, serde_json::Error> {
|
||||
let message = json!({
|
||||
"bridge": HOST_BRIDGE_PROTOCOL,
|
||||
"version": HOST_BRIDGE_VERSION,
|
||||
"event": event,
|
||||
"payload": payload,
|
||||
});
|
||||
let data = serde_json::to_string(&message)?;
|
||||
let data_literal = serde_json::to_string(&data)?;
|
||||
|
||||
Ok(format!(
|
||||
"window.dispatchEvent(new MessageEvent('message', {{ data: {} }})); true;",
|
||||
data_literal
|
||||
))
|
||||
}
|
||||
|
||||
fn emit_desktop_lifecycle_event(
|
||||
window: &WebviewWindow,
|
||||
state: &'static str,
|
||||
focused: bool,
|
||||
native_state: &'static str,
|
||||
) -> tauri::Result<()> {
|
||||
let script = host_bridge_event_script(
|
||||
"app.lifecycle",
|
||||
json!({
|
||||
"state": state,
|
||||
"focused": focused,
|
||||
"nativeState": native_state,
|
||||
}),
|
||||
)
|
||||
.map_err(tauri::Error::Json)?;
|
||||
|
||||
window.eval(script)
|
||||
}
|
||||
|
||||
fn register_desktop_lifecycle_events(window: &WebviewWindow) {
|
||||
let lifecycle_window = window.clone();
|
||||
window.on_window_event(move |event| {
|
||||
if let WindowEvent::Focused(focused) = event {
|
||||
let (state, native_state) = if *focused {
|
||||
("active", "focused")
|
||||
} else {
|
||||
("inactive", "blurred")
|
||||
};
|
||||
let _ = emit_desktop_lifecycle_event(&lifecycle_window, state, *focused, native_state);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn payload_string<'a>(value: &'a Value, field: &str) -> Option<&'a str> {
|
||||
value
|
||||
.get(field)
|
||||
@@ -727,7 +779,10 @@ fn main() {
|
||||
.setup(|app| {
|
||||
let window_config = app.config().app.windows.get(0).cloned();
|
||||
if let Some(config) = window_config {
|
||||
tauri::WebviewWindowBuilder::from_config(app.handle(), &config)?.build()?;
|
||||
let window =
|
||||
tauri::WebviewWindowBuilder::from_config(app.handle(), &config)?.build()?;
|
||||
register_desktop_lifecycle_events(&window);
|
||||
let _ = emit_desktop_lifecycle_event(&window, "active", true, "created");
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
@@ -763,6 +818,10 @@ mod tests {
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!("appearance.getColorScheme")));
|
||||
assert!(result["capabilities"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!("app.lifecycle")));
|
||||
assert!(result["capabilities"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
@@ -833,6 +892,25 @@ mod tests {
|
||||
assert_eq!(color_scheme_from_theme(Theme::Dark), "dark");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_bridge_event_script_dispatches_lifecycle_message() {
|
||||
let script = host_bridge_event_script(
|
||||
"app.lifecycle",
|
||||
json!({
|
||||
"state": "active",
|
||||
"focused": true,
|
||||
"nativeState": "focused",
|
||||
}),
|
||||
)
|
||||
.expect("event script");
|
||||
|
||||
assert!(script.contains("MessageEvent('message'"));
|
||||
assert!(script.contains("GenarrativeHostBridge"));
|
||||
assert!(script.contains("app.lifecycle"));
|
||||
assert!(script.contains("\\\"state\\\":\\\"active\\\""));
|
||||
assert!(script.contains("\\\"focused\\\":true"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_url_normalization_allows_only_safe_protocols() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"build": {
|
||||
"beforeDevCommand": "npm --prefix ../.. run dev:web",
|
||||
"beforeBuildCommand": "npm --prefix ../.. run build:raw && npm run typecheck",
|
||||
"devUrl": "http://127.0.0.1:3000/?clientRuntime=native_app&clientType=native_app&hostShell=tauri_desktop&hostPlatform=unknown&hostVersion=0.1.0&bridgeVersion=1&hostCapabilities=host.getRuntime,appearance.getColorScheme,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,app.setBadgeCount,clipboard.writeText,file.exportText,file.exportImage",
|
||||
"devUrl": "http://127.0.0.1:3000/?clientRuntime=native_app&clientType=native_app&hostShell=tauri_desktop&hostPlatform=unknown&hostVersion=0.1.0&bridgeVersion=1&hostCapabilities=host.getRuntime,appearance.getColorScheme,app.lifecycle,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,app.setBadgeCount,clipboard.writeText,file.exportText,file.exportImage",
|
||||
"frontendDist": "../../../dist"
|
||||
},
|
||||
"app": {
|
||||
@@ -14,7 +14,7 @@
|
||||
{
|
||||
"create": false,
|
||||
"label": "main",
|
||||
"url": "index.html?clientRuntime=native_app&clientType=native_app&hostShell=tauri_desktop&hostPlatform=unknown&hostVersion=0.1.0&bridgeVersion=1&hostCapabilities=host.getRuntime,appearance.getColorScheme,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,app.setBadgeCount,clipboard.writeText,file.exportText,file.exportImage",
|
||||
"url": "index.html?clientRuntime=native_app&clientType=native_app&hostShell=tauri_desktop&hostPlatform=unknown&hostVersion=0.1.0&bridgeVersion=1&hostCapabilities=host.getRuntime,appearance.getColorScheme,app.lifecycle,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,app.setBadgeCount,clipboard.writeText,file.exportText,file.exportImage",
|
||||
"title": "Genarrative",
|
||||
"width": 1280,
|
||||
"height": 820,
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
import { StatusBar } from 'expo-status-bar';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { BackHandler, Linking, Platform, StyleSheet, View } from 'react-native';
|
||||
import {
|
||||
AppState,
|
||||
type AppStateStatus,
|
||||
BackHandler,
|
||||
Linking,
|
||||
Platform,
|
||||
StyleSheet,
|
||||
View,
|
||||
} from 'react-native';
|
||||
import type { WebViewMessageEvent } from 'react-native-webview';
|
||||
import { WebView } from 'react-native-webview';
|
||||
|
||||
@@ -10,6 +18,7 @@ import {
|
||||
resolveMobileHostCapabilities,
|
||||
} from './src/mobileHostBridge';
|
||||
import { buildMobileShellUrlFromDeepLink } from './src/mobileShellDeepLink';
|
||||
import { lifecyclePayloadFromAppState } from './src/mobileShellLifecycle';
|
||||
import {
|
||||
resolveMobileShellExternalUrl,
|
||||
shouldOpenInMobileShellWebView,
|
||||
@@ -97,6 +106,27 @@ export default function App() {
|
||||
return () => subscription.remove();
|
||||
}, [canGoBack]);
|
||||
|
||||
useEffect(() => {
|
||||
const sendLifecycleEvent = (state: AppStateStatus) => {
|
||||
webViewRef.current?.injectJavaScript(
|
||||
buildHostBridgeMessageScript({
|
||||
bridge: 'GenarrativeHostBridge',
|
||||
version: 1,
|
||||
event: 'app.lifecycle',
|
||||
payload: lifecyclePayloadFromAppState(state),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const subscription = AppState.addEventListener(
|
||||
'change',
|
||||
sendLifecycleEvent,
|
||||
);
|
||||
sendLifecycleEvent(AppState.currentState);
|
||||
|
||||
return () => subscription.remove();
|
||||
}, []);
|
||||
|
||||
const handleMessage = (event: WebViewMessageEvent) => {
|
||||
void handleMobileHostBridgeMessage(event.nativeEvent.data, (response) => {
|
||||
webViewRef.current?.injectJavaScript(
|
||||
|
||||
@@ -75,6 +75,7 @@ for (const capability of iosMobileCapabilities) {
|
||||
const switchCase = `case '${capability}':`;
|
||||
if (
|
||||
capability !== 'host.events' &&
|
||||
capability !== 'app.lifecycle' &&
|
||||
capability !== 'navigation.canGoBack' &&
|
||||
!bridgeSource.includes(switchCase)
|
||||
) {
|
||||
@@ -116,6 +117,8 @@ for (const snippet of [
|
||||
"Linking.addEventListener('url'",
|
||||
'buildMobileShellUrlFromDeepLink',
|
||||
'configureMobileHostBridgeNavigation',
|
||||
'AppState.addEventListener',
|
||||
'app.lifecycle',
|
||||
'navigation.canGoBack',
|
||||
'buildHostBridgeMessageScript',
|
||||
]) {
|
||||
@@ -156,6 +159,7 @@ for (const capability of [
|
||||
'appearance.getColorScheme',
|
||||
'share.open',
|
||||
'share.setTarget',
|
||||
'app.lifecycle',
|
||||
'navigation.openNativePage',
|
||||
'navigation.canGoBack',
|
||||
'app.openExternalUrl',
|
||||
|
||||
@@ -174,6 +174,7 @@ describe('handleMobileHostBridgeMessage', () => {
|
||||
expect.arrayContaining([
|
||||
'appearance.getColorScheme',
|
||||
'host.events',
|
||||
'app.lifecycle',
|
||||
'navigation.canGoBack',
|
||||
'app.setBadgeCount',
|
||||
]),
|
||||
|
||||
@@ -48,6 +48,7 @@ export const MOBILE_HOST_CAPABILITIES: HostBridgeCapability[] = [
|
||||
'host.getRuntime',
|
||||
'appearance.getColorScheme',
|
||||
'host.events',
|
||||
'app.lifecycle',
|
||||
'share.open',
|
||||
'share.setTarget',
|
||||
'navigation.openNativePage',
|
||||
|
||||
28
apps/mobile-shell/src/mobileShellLifecycle.test.ts
Normal file
28
apps/mobile-shell/src/mobileShellLifecycle.test.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, test } from 'vitest';
|
||||
|
||||
import { lifecyclePayloadFromAppState } from './mobileShellLifecycle';
|
||||
|
||||
describe('mobileShellLifecycle', () => {
|
||||
test('把 React Native AppState 映射为统一 HostBridge 生命周期状态', () => {
|
||||
expect(lifecyclePayloadFromAppState('active')).toEqual({
|
||||
state: 'active',
|
||||
focused: true,
|
||||
nativeState: 'active',
|
||||
});
|
||||
expect(lifecyclePayloadFromAppState('background')).toEqual({
|
||||
state: 'background',
|
||||
focused: false,
|
||||
nativeState: 'background',
|
||||
});
|
||||
expect(lifecyclePayloadFromAppState('inactive')).toEqual({
|
||||
state: 'inactive',
|
||||
focused: false,
|
||||
nativeState: 'inactive',
|
||||
});
|
||||
expect(lifecyclePayloadFromAppState('unknown')).toEqual({
|
||||
state: 'inactive',
|
||||
focused: false,
|
||||
nativeState: 'unknown',
|
||||
});
|
||||
});
|
||||
});
|
||||
13
apps/mobile-shell/src/mobileShellLifecycle.ts
Normal file
13
apps/mobile-shell/src/mobileShellLifecycle.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import type { AppStateStatus } from 'react-native';
|
||||
|
||||
export function lifecyclePayloadFromAppState(state: AppStateStatus) {
|
||||
return {
|
||||
state: state === 'active'
|
||||
? 'active'
|
||||
: state === 'background'
|
||||
? 'background'
|
||||
: 'inactive',
|
||||
focused: state === 'active',
|
||||
nativeState: state,
|
||||
};
|
||||
}
|
||||
@@ -30,6 +30,7 @@
|
||||
- 2026-06-18 分享卡图片导出:新增 `file.exportImage` HostBridge capability,H5 分享卡下载在 native app 中优先把 canvas 生成的 base64 图片交给宿主导出;Expo 壳写缓存图片后交给系统分享 / 保存面板,Tauri 壳通过系统保存对话框写入图片字节。该能力只接受 `image/png` / `image/jpeg` / `image/webp`、单次 5 MiB 内图片数据,成功只返回文件名和字节数,不暴露本机绝对路径;宿主未声明时保留浏览器下载。
|
||||
- 2026-06-18 应用角标能力:新增 `app.setBadgeCount` HostBridge capability,H5 只传 `0-99999` 整数并在宿主未声明时静默 fallback;Expo 壳只在 iOS 声明并通过 React Native `PushNotificationIOS` 设置应用图标角标,Android 不声明、不伪造成功;Tauri 壳通过主窗口 `set_badge_count` 设置任务栏角标,底层平台不支持时返回真实错误。
|
||||
- 2026-06-18 宿主外观只读查询:新增 `appearance.getColorScheme` HostBridge capability,Expo 壳通过 React Native `Appearance.getColorScheme()` 读取系统配色,Tauri 壳通过主窗口 `theme()` 读取窗口主题;该能力只返回 `light` / `dark` / `unknown`,不设置 H5 主题、不覆盖系统主题,也不作为强制 UI 样式入口。
|
||||
- 2026-06-18 原生壳生命周期事件:新增 `app.lifecycle` HostBridge capability,Expo 壳通过 React Native `AppState` 派发 `active` / `inactive` / `background`,Tauri 壳通过主窗口 focus / blur 派发 `active` / `inactive`;H5 只通过 `subscribeHostAppLifecycle()` 订阅统一状态,后续游戏循环、音频和轮询暂停 / 恢复不得直接依赖 Expo / Tauri 平台细节。
|
||||
- 影响范围:`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`。
|
||||
|
||||
@@ -117,6 +117,7 @@ type HostBridgeEvent = {
|
||||
| `share.setTarget` | 同步当前作品分享目标 | 支持 | 支持 |
|
||||
| `share.open` | 打开分享动作 | 支持系统分享面板 | 复制分享文本到剪贴板 |
|
||||
| `navigation.openNativePage` | 打开受控宿主页 | 支持同源 H5 route | 支持同源 H5 route |
|
||||
| `app.lifecycle` | 通知 H5 宿主前后台 / 焦点状态 | 支持 AppState 事件 | 支持窗口 focus / blur 事件 |
|
||||
| `navigation.canGoBack` | 通知 H5 宿主返回栈状态 | 支持事件 | 不声明 |
|
||||
| `app.openExternalUrl` | 用系统浏览器打开外链 | 支持白名单协议 | 支持白名单协议 |
|
||||
| `app.setTitle` | 同步宿主窗口标题 | 不声明 | 支持 |
|
||||
@@ -244,7 +245,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`、`share.open`、`share.setTarget`、`navigation.openNativePage`、`navigation.canGoBack`、`app.openExternalUrl`、`clipboard.writeText`、`file.exportText`、`file.exportImage`、`haptics.impact` 和 Android 返回键回退;其中 `appearance.getColorScheme` 只读系统配色偏好,不强改 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,分享卡下载会优先走该能力;`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`、`share.open`、`share.setTarget`、`navigation.openNativePage`、`navigation.canGoBack`、`app.openExternalUrl`、`clipboard.writeText`、`file.exportText`、`file.exportImage`、`haptics.impact` 和 Android 返回键回退;其中 `appearance.getColorScheme` 只读系统配色偏好,不强改 H5 或系统主题;`app.lifecycle` 通过 React Native `AppState` 注入 `active` / `inactive` / `background` 统一状态,供 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,分享卡下载会优先走该能力;`haptics.impact` 通过 Expo Haptics 承接运行时轻触反馈,H5 在宿主不支持时回退到浏览器 vibration。登录和支付尚未接入渠道 SDK / 原生页面时明确返回 unsupported,让 H5 fallback 承接。
|
||||
|
||||
### Phase 3:Tauri 桌面壳 MVP
|
||||
|
||||
@@ -255,7 +256,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.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`、`share.setTarget`、`share.open`、`navigation.openNativePage`、`app.openExternalUrl`、`app.setTitle`、`app.setBadgeCount`、`clipboard.writeText`、`file.exportText` 和 `file.exportImage`;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`。原生系统分享面板、登录和支付未接入真实插件 / 渠道前不声明支持,不返回 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 插件给前端;`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`、`share.setTarget`、`share.open`、`navigation.openNativePage`、`app.openExternalUrl`、`app.setTitle`、`app.setBadgeCount`、`clipboard.writeText`、`file.exportText` 和 `file.exportImage`;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`。原生系统分享面板、登录和支付未接入真实插件 / 渠道前不声明支持,不返回 mock 成功。
|
||||
|
||||
### Phase 4:宿主能力扩展
|
||||
|
||||
|
||||
@@ -41,6 +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` 用于排障,不作为业务分支依据。
|
||||
- `requestHostLogin()`:微信小程序跳转原生登录页;浏览器返回 `false`,由 H5 登录弹窗承接。
|
||||
- `requestHostPayment()`:微信小程序支付跳转原生支付页;其它渠道返回 `false`,继续走 H5 / Native 二维码。
|
||||
- `setHostShareTarget()`:把当前公开作品分享目标同步给宿主。
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
normalizeHostBridgeColorScheme,
|
||||
normalizeHostBridgeExportFileName,
|
||||
normalizeHostBridgeExternalUrl,
|
||||
normalizeHostBridgeLifecycleState,
|
||||
} from './hostBridge';
|
||||
|
||||
describe('HostBridge shared contract helpers', () => {
|
||||
@@ -49,6 +50,7 @@ describe('HostBridge shared contract helpers', () => {
|
||||
test('识别 HostBridge 能力白名单', () => {
|
||||
expect(isHostBridgeCapability('appearance.getColorScheme')).toBe(true);
|
||||
expect(isHostBridgeCapability('share.open')).toBe(true);
|
||||
expect(isHostBridgeCapability('app.lifecycle')).toBe(true);
|
||||
expect(isHostBridgeCapability('app.setBadgeCount')).toBe(true);
|
||||
expect(isHostBridgeCapability('navigation.canGoBack')).toBe(true);
|
||||
expect(isHostBridgeCapability('unknown.capability')).toBe(false);
|
||||
@@ -71,4 +73,11 @@ describe('HostBridge shared contract helpers', () => {
|
||||
expect(normalizeHostBridgeColorScheme('unspecified')).toBe('unknown');
|
||||
expect(normalizeHostBridgeColorScheme(null)).toBe('unknown');
|
||||
});
|
||||
|
||||
test('归一化宿主生命周期状态', () => {
|
||||
expect(normalizeHostBridgeLifecycleState('active')).toBe('active');
|
||||
expect(normalizeHostBridgeLifecycleState('background')).toBe('background');
|
||||
expect(normalizeHostBridgeLifecycleState('extension')).toBe('inactive');
|
||||
expect(normalizeHostBridgeLifecycleState(null)).toBe('inactive');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -35,6 +35,7 @@ export type HostBridgeMethod = (typeof HOST_BRIDGE_METHODS)[number];
|
||||
export const HOST_BRIDGE_CAPABILITIES = [
|
||||
...HOST_BRIDGE_METHODS,
|
||||
'host.events',
|
||||
'app.lifecycle',
|
||||
'navigation.canGoBack',
|
||||
] as const;
|
||||
|
||||
@@ -103,6 +104,22 @@ export type NavigationCanGoBackEventPayload = {
|
||||
canGoBack: boolean;
|
||||
};
|
||||
|
||||
export type HostAppLifecycleState = 'active' | 'inactive' | 'background';
|
||||
|
||||
export type AppLifecycleEventPayload = {
|
||||
state: HostAppLifecycleState;
|
||||
focused: boolean;
|
||||
nativeState?: string;
|
||||
};
|
||||
|
||||
export function normalizeHostBridgeLifecycleState(
|
||||
rawState: unknown,
|
||||
): HostAppLifecycleState {
|
||||
return rawState === 'active' || rawState === 'background'
|
||||
? rawState
|
||||
: 'inactive';
|
||||
}
|
||||
|
||||
export type HostAppearanceColorScheme = 'light' | 'dark' | 'unknown';
|
||||
|
||||
export type AppearanceColorSchemeResult = {
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
setHostAppBadgeCount,
|
||||
setHostAppTitle,
|
||||
setHostShareTarget,
|
||||
subscribeHostAppLifecycle,
|
||||
subscribeHostRuntimeChange,
|
||||
writeHostClipboardText,
|
||||
} from './hostBridge';
|
||||
@@ -140,6 +141,82 @@ describe('hostBridge', () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test('订阅原生 App 生命周期事件并归一化 payload', () => {
|
||||
const listener = vi.fn();
|
||||
window.history.replaceState(
|
||||
null,
|
||||
'',
|
||||
nativeAppPath(['app.lifecycle']),
|
||||
);
|
||||
window.ReactNativeWebView = {
|
||||
postMessage: vi.fn(),
|
||||
};
|
||||
|
||||
const unsubscribe = subscribeHostAppLifecycle(listener);
|
||||
window.dispatchEvent(
|
||||
new MessageEvent('message', {
|
||||
data: JSON.stringify({
|
||||
bridge: 'GenarrativeHostBridge',
|
||||
version: 1,
|
||||
event: 'app.lifecycle',
|
||||
payload: {
|
||||
state: 'extension',
|
||||
focused: true,
|
||||
nativeState: 'extension',
|
||||
},
|
||||
}),
|
||||
}),
|
||||
);
|
||||
unsubscribe();
|
||||
window.dispatchEvent(
|
||||
new MessageEvent('message', {
|
||||
data: JSON.stringify({
|
||||
bridge: 'GenarrativeHostBridge',
|
||||
version: 1,
|
||||
event: 'app.lifecycle',
|
||||
payload: {
|
||||
state: 'active',
|
||||
focused: true,
|
||||
nativeState: 'active',
|
||||
},
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
expect(listener).toHaveBeenCalledWith({
|
||||
state: 'inactive',
|
||||
focused: true,
|
||||
nativeState: 'extension',
|
||||
});
|
||||
});
|
||||
|
||||
test('未声明生命周期能力时不订阅原生事件', () => {
|
||||
const listener = vi.fn();
|
||||
window.history.replaceState(null, '', nativeAppPath());
|
||||
window.ReactNativeWebView = {
|
||||
postMessage: vi.fn(),
|
||||
};
|
||||
|
||||
const unsubscribe = subscribeHostAppLifecycle(listener);
|
||||
window.dispatchEvent(
|
||||
new MessageEvent('message', {
|
||||
data: JSON.stringify({
|
||||
bridge: 'GenarrativeHostBridge',
|
||||
version: 1,
|
||||
event: 'app.lifecycle',
|
||||
payload: {
|
||||
state: 'active',
|
||||
focused: true,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
);
|
||||
unsubscribe();
|
||||
|
||||
expect(listener).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('从真实宿主 runtime 回读能力并通知订阅者', async () => {
|
||||
const listener = vi.fn();
|
||||
const unsubscribe = subscribeHostRuntimeChange(listener);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type {
|
||||
AppearanceColorSchemeResult,
|
||||
AppLifecycleEventPayload,
|
||||
FileExportImagePayload,
|
||||
FileExportImageResult,
|
||||
FileExportTextPayload,
|
||||
@@ -17,6 +18,7 @@ import {
|
||||
normalizeHostBridgeBadgeCount,
|
||||
normalizeHostBridgeColorScheme,
|
||||
normalizeHostBridgeExternalUrl,
|
||||
normalizeHostBridgeLifecycleState,
|
||||
} from '../../../packages/shared/src/contracts/hostBridge';
|
||||
import type {
|
||||
WechatMiniProgramPayParams,
|
||||
@@ -25,6 +27,7 @@ import type {
|
||||
import {
|
||||
canUseNativeAppHostBridge,
|
||||
requestNativeAppHostBridge,
|
||||
subscribeNativeAppHostBridgeEvent,
|
||||
} from './nativeAppHostBridge';
|
||||
|
||||
const WECHAT_JS_SDK_URL = 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js';
|
||||
@@ -99,6 +102,8 @@ export type HostExternalUrlRequest = OpenExternalUrlPayload;
|
||||
|
||||
export type HostAppearanceColorSchemeSnapshot = AppearanceColorSchemeResult;
|
||||
|
||||
export type HostAppLifecycleSnapshot = AppLifecycleEventPayload;
|
||||
|
||||
const HOST_RUNTIME_REFRESH_TIMEOUT_MS = 3000;
|
||||
|
||||
let cachedNativeHostRuntime: HostBridgeRuntimeResult | null = null;
|
||||
@@ -786,3 +791,27 @@ export async function getHostAppearanceColorScheme() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function subscribeHostAppLifecycle(
|
||||
listener: (payload: HostAppLifecycleSnapshot) => void,
|
||||
) {
|
||||
if (!canUseNativeHostCapability('app.lifecycle')) {
|
||||
return () => undefined;
|
||||
}
|
||||
|
||||
return subscribeNativeAppHostBridgeEvent<AppLifecycleEventPayload>(
|
||||
'app.lifecycle',
|
||||
(payload) => {
|
||||
const state = normalizeHostBridgeLifecycleState(payload?.state);
|
||||
listener({
|
||||
state,
|
||||
focused: typeof payload?.focused === 'boolean'
|
||||
? payload.focused
|
||||
: state === 'active',
|
||||
...(typeof payload?.nativeState === 'string'
|
||||
? { nativeState: payload.nativeState }
|
||||
: {}),
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user