diff --git a/apps/mobile-shell/App.tsx b/apps/mobile-shell/App.tsx index aa33c28e..74ba95bc 100644 --- a/apps/mobile-shell/App.tsx +++ b/apps/mobile-shell/App.tsx @@ -16,6 +16,12 @@ import { buildMobileShellUrl } from './src/mobileShellUrl'; const defaultWebUrl = 'http://127.0.0.1:3000/'; const hostVersion = '0.1.0'; +function buildHostBridgeMessageScript(message: unknown) { + return `window.dispatchEvent(new MessageEvent('message', { data: ${JSON.stringify( + JSON.stringify(message), + )} })); true;`; +} + export default function App() { const webViewRef = useRef(null); const [canGoBack, setCanGoBack] = useState(false); @@ -91,9 +97,7 @@ export default function App() { const handleMessage = (event: WebViewMessageEvent) => { void handleMobileHostBridgeMessage(event.nativeEvent.data, (response) => { webViewRef.current?.injectJavaScript( - `window.dispatchEvent(new MessageEvent('message', { data: ${JSON.stringify( - JSON.stringify(response), - )} })); true;`, + buildHostBridgeMessageScript(response), ); }); }; @@ -118,7 +122,19 @@ export default function App() { originWhitelist={[allowedWebOrigin]} onMessage={handleMessage} onShouldStartLoadWithRequest={handleShouldStartLoad} - onNavigationStateChange={(event) => setCanGoBack(event.canGoBack)} + onNavigationStateChange={(event) => { + setCanGoBack(event.canGoBack); + webViewRef.current?.injectJavaScript( + buildHostBridgeMessageScript({ + bridge: 'GenarrativeHostBridge', + version: 1, + event: 'navigation.canGoBack', + payload: { + canGoBack: event.canGoBack, + }, + }), + ); + }} setSupportMultipleWindows={false} /> diff --git a/apps/mobile-shell/scripts/check-config.mjs b/apps/mobile-shell/scripts/check-config.mjs index 90c1b72c..e874370e 100644 --- a/apps/mobile-shell/scripts/check-config.mjs +++ b/apps/mobile-shell/scripts/check-config.mjs @@ -41,6 +41,8 @@ for (const snippet of [ "Linking.addEventListener('url'", 'buildMobileShellUrlFromDeepLink', 'configureMobileHostBridgeNavigation', + 'navigation.canGoBack', + 'buildHostBridgeMessageScript', ]) { if (!appSource.includes(snippet)) { throw new Error(`mobile shell App missing ${snippet}`); diff --git a/apps/mobile-shell/src/mobileHostBridge.test.ts b/apps/mobile-shell/src/mobileHostBridge.test.ts index 47a889ad..c4383804 100644 --- a/apps/mobile-shell/src/mobileHostBridge.test.ts +++ b/apps/mobile-shell/src/mobileHostBridge.test.ts @@ -101,6 +101,11 @@ describe('handleMobileHostBridgeMessage', () => { expect( (okResponse.result as { capabilities: string[] }).capabilities, ).toContain('navigation.openNativePage'); + expect( + (okResponse.result as { capabilities: string[] }).capabilities, + ).toEqual( + expect.arrayContaining(['host.events', 'navigation.canGoBack']), + ); }); test('navigation.openNativePage 把同源路径切到移动壳 WebView', async () => { diff --git a/apps/mobile-shell/src/mobileHostBridge.ts b/apps/mobile-shell/src/mobileHostBridge.ts index d8c7bd08..43823427 100644 --- a/apps/mobile-shell/src/mobileHostBridge.ts +++ b/apps/mobile-shell/src/mobileHostBridge.ts @@ -22,9 +22,11 @@ import { resolveMobileShellWebViewUrl } from './mobileShellNavigation'; export const MOBILE_HOST_CAPABILITIES: HostBridgeCapability[] = [ 'host.getRuntime', + 'host.events', 'share.open', 'share.setTarget', 'navigation.openNativePage', + 'navigation.canGoBack', 'app.openExternalUrl', 'clipboard.writeText', 'haptics.impact', diff --git a/docs/project-memory/shared-memory/decision-log.md b/docs/project-memory/shared-memory/decision-log.md index 41222c36..d9f96402 100644 --- a/docs/project-memory/shared-memory/decision-log.md +++ b/docs/project-memory/shared-memory/decision-log.md @@ -20,7 +20,7 @@ - 背景:后续需要移动端 App 和桌面端 App,但现有主站、固定玩法 runtime、小程序壳和未来 AI H5 sandbox 已经以 H5 为主线;如果移动端重写 React Native UI、桌面端重写 Rust/Tauri UI,会形成玩法、登录、支付、分享和运行态的多套实现。 - 决策:移动端原生壳采用 `Expo + React Native`,桌面端壳采用 `Tauri`。两者都只作为 `native_app` 宿主壳和 HostBridge adapter,不重写现有 React H5 主站,不把固定内置玩法迁到 React Native / Rust UI,也不让 AI 生成 H5 游戏直接访问完整 HostBridge。Expo 壳通过 `react-native-webview` 承接 H5 与 native 通信,Tauri 壳通过受控 command 和 capabilities 承接桌面能力;新增能力必须先进入 HostBridge 契约和测试。 -- 2026-06-17 首轮落地:新增 `packages/shared/src/contracts/hostBridge.ts`、`src/services/host-bridge/nativeAppHostBridge.ts`、`apps/mobile-shell/` 和 `apps/desktop-shell/`。壳只声明并实现真实可用能力;移动壳使用真实品牌图标资产并支持 `genarrative://`、iOS associated domain、Android app link 到同源 H5 路径,`navigation.openNativePage` 只接受同源 H5 route 并切换 WebView URL,不伪造尚未存在的原生页面;`app.openExternalUrl` 在 Expo 与 Tauri 两端都只允许 `http:`、`https:`、`mailto:`、`tel:` 外链协议;桌面壳已通过 Tauri clipboard-manager 接入 `clipboard.writeText`,并将 `share.setTarget` / `share.open` 实现为复制非空分享文本到系统剪贴板,`app.setTitle` 通过主窗口 API 同步非空窗口标题;登录、支付、原生系统分享面板等未接入真实 SDK / 插件前必须返回 unsupported 并让 H5 fallback,生产代码禁止 mock 成功。 +- 2026-06-17 首轮落地:新增 `packages/shared/src/contracts/hostBridge.ts`、`src/services/host-bridge/nativeAppHostBridge.ts`、`apps/mobile-shell/` 和 `apps/desktop-shell/`。壳只声明并实现真实可用能力;移动壳使用真实品牌图标资产并支持 `genarrative://`、iOS associated domain、Android app link 到同源 H5 路径,`navigation.openNativePage` 只接受同源 H5 route 并切换 WebView URL,不伪造尚未存在的原生页面,且通过 `host.events` 注入 `navigation.canGoBack` 返回栈状态事件;`app.openExternalUrl` 在 Expo 与 Tauri 两端都只允许 `http:`、`https:`、`mailto:`、`tel:` 外链协议;桌面壳已通过 Tauri clipboard-manager 接入 `clipboard.writeText`,并将 `share.setTarget` / `share.open` 实现为复制非空分享文本到系统剪贴板,`app.setTitle` 通过主窗口 API 同步非空窗口标题;登录、支付、原生系统分享面板等未接入真实 SDK / 插件前必须返回 unsupported 并让 H5 fallback,生产代码禁止 mock 成功。 - 影响范围:`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`。 diff --git a/docs/【前端架构】ExpoReactNative与Tauri宿主壳方案-2026-06-17.md b/docs/【前端架构】ExpoReactNative与Tauri宿主壳方案-2026-06-17.md index 8be1ca09..74283c0d 100644 --- a/docs/【前端架构】ExpoReactNative与Tauri宿主壳方案-2026-06-17.md +++ b/docs/【前端架构】ExpoReactNative与Tauri宿主壳方案-2026-06-17.md @@ -116,6 +116,7 @@ type HostBridgeEvent = { | `share.setTarget` | 同步当前作品分享目标 | 支持 | 支持 | | `share.open` | 打开分享动作 | 支持系统分享面板 | 复制分享文本到剪贴板 | | `navigation.openNativePage` | 打开受控宿主页 | 支持同源 H5 route | 支持设置 / 关于等 | +| `navigation.canGoBack` | 通知 H5 宿主返回栈状态 | 支持事件 | 不声明 | | `app.openExternalUrl` | 用系统浏览器打开外链 | 支持白名单协议 | 支持白名单协议 | | `app.setTitle` | 同步宿主窗口标题 | 不声明 | 支持 | | `clipboard.writeText` | 写剪贴板 | 可选 | 可选 | @@ -239,7 +240,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`、`share.open`、`share.setTarget`、`navigation.openNativePage`、`app.openExternalUrl`、`clipboard.writeText`、`haptics.impact` 和 Android 返回键回退;其中 `navigation.openNativePage` 在 Expo 壳内只接受同源 H5 route 并切换 WebView URL,不伪造尚未存在的登录、支付或其它原生页面,`app.openExternalUrl` 只允许 `http:`、`https:`、`mailto:`、`tel:` 外链协议。登录和支付尚未接入渠道 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`、`host.events`、`share.open`、`share.setTarget`、`navigation.openNativePage`、`navigation.canGoBack`、`app.openExternalUrl`、`clipboard.writeText`、`haptics.impact` 和 Android 返回键回退;其中 `navigation.openNativePage` 在 Expo 壳内只接受同源 H5 route 并切换 WebView URL,不伪造尚未存在的登录、支付或其它原生页面,`navigation.canGoBack` 由 WebView 导航状态变化实时注入 H5,`app.openExternalUrl` 只允许 `http:`、`https:`、`mailto:`、`tel:` 外链协议。登录和支付尚未接入渠道 SDK 时明确返回 unsupported,让 H5 fallback 承接。 ### Phase 3:Tauri 桌面壳 MVP diff --git a/packages/shared/src/contracts/hostBridge.ts b/packages/shared/src/contracts/hostBridge.ts index 48fde3d9..64c52d48 100644 --- a/packages/shared/src/contracts/hostBridge.ts +++ b/packages/shared/src/contracts/hostBridge.ts @@ -80,6 +80,10 @@ export type HostBridgeEvent = { payload?: Payload; }; +export type NavigationCanGoBackEventPayload = { + canGoBack: boolean; +}; + export type NavigateNativePagePayload = { url: string; }; diff --git a/src/services/host-bridge/nativeAppHostBridge.test.ts b/src/services/host-bridge/nativeAppHostBridge.test.ts index 39b5d024..05969676 100644 --- a/src/services/host-bridge/nativeAppHostBridge.test.ts +++ b/src/services/host-bridge/nativeAppHostBridge.test.ts @@ -14,6 +14,7 @@ import { canUseTauriHostBridge, requestNativeAppHostBridge, resetNativeAppHostBridgeForTest, + subscribeNativeAppHostBridgeEvent, } from './nativeAppHostBridge'; afterEach(() => { @@ -139,4 +140,43 @@ describe('nativeAppHostBridge', () => { await assertion; }); + + test('订阅 React Native WebView 注入的宿主事件', () => { + window.ReactNativeWebView = { + postMessage: vi.fn(), + }; + const listener = vi.fn(); + const unsubscribe = subscribeNativeAppHostBridgeEvent<{ + canGoBack: boolean; + }>('navigation.canGoBack', listener); + + window.dispatchEvent( + new MessageEvent('message', { + data: JSON.stringify({ + bridge: HOST_BRIDGE_PROTOCOL, + version: HOST_BRIDGE_VERSION, + event: 'navigation.canGoBack', + payload: { + canGoBack: true, + }, + }), + }), + ); + unsubscribe(); + window.dispatchEvent( + new MessageEvent('message', { + data: JSON.stringify({ + bridge: HOST_BRIDGE_PROTOCOL, + version: HOST_BRIDGE_VERSION, + event: 'navigation.canGoBack', + payload: { + canGoBack: false, + }, + }), + }), + ); + + expect(listener).toHaveBeenCalledTimes(1); + expect(listener).toHaveBeenCalledWith({ canGoBack: true }); + }); }); diff --git a/src/services/host-bridge/nativeAppHostBridge.ts b/src/services/host-bridge/nativeAppHostBridge.ts index c4321f58..4705f294 100644 --- a/src/services/host-bridge/nativeAppHostBridge.ts +++ b/src/services/host-bridge/nativeAppHostBridge.ts @@ -2,6 +2,7 @@ import { HOST_BRIDGE_PROTOCOL, HOST_BRIDGE_VERSION, type HostBridgeError, + type HostBridgeEvent, type HostBridgeMethod, type HostBridgeRequest, type HostBridgeResponse, @@ -31,6 +32,7 @@ type PendingNativeRequest = { }; const pendingNativeRequests = new Map(); +const nativeEventListeners = new Map void>>(); let nativeBridgeListenerInstalled = false; let nextNativeRequestSequence = 0; @@ -77,6 +79,19 @@ function isHostBridgeResponse(value: unknown): value is HostBridgeResponse { ); } +function isHostBridgeEvent(value: unknown): value is HostBridgeEvent { + if (!value || typeof value !== 'object') { + return false; + } + + const candidate = value as Partial; + return ( + candidate.bridge === HOST_BRIDGE_PROTOCOL && + candidate.version === HOST_BRIDGE_VERSION && + typeof candidate.event === 'string' + ); +} + function parseNativeMessage(data: unknown) { if (typeof data === 'string') { try { @@ -106,6 +121,17 @@ function settleNativeResponse(response: HostBridgeResponse) { pending.reject(createHostBridgeError(response.error)); } +function dispatchNativeEvent(event: HostBridgeEvent) { + const listeners = nativeEventListeners.get(event.event); + if (!listeners) { + return; + } + + for (const listener of listeners) { + listener(event.payload); + } +} + function ensureNativeBridgeListener() { const nativeWindow = resolveNativeWindow(); if (!nativeWindow || nativeBridgeListenerInstalled) { @@ -116,6 +142,10 @@ function ensureNativeBridgeListener() { const value = parseNativeMessage(event.data); if (isHostBridgeResponse(value)) { settleNativeResponse(value); + return; + } + if (isHostBridgeEvent(value)) { + dispatchNativeEvent(value); } }); @@ -139,6 +169,24 @@ export function canUseNativeAppHostBridge() { return canUseReactNativeHostBridge() || canUseTauriHostBridge(); } +export function subscribeNativeAppHostBridgeEvent( + eventName: string, + listener: (payload: Payload | undefined) => void, +) { + ensureNativeBridgeListener(); + + const listeners = nativeEventListeners.get(eventName) ?? new Set(); + listeners.add(listener as (payload: unknown) => void); + nativeEventListeners.set(eventName, listeners); + + return () => { + listeners.delete(listener as (payload: unknown) => void); + if (listeners.size === 0) { + nativeEventListeners.delete(eventName); + } + }; +} + export async function requestNativeAppHostBridge( method: HostBridgeMethod, payload?: unknown, @@ -213,5 +261,6 @@ export function resetNativeAppHostBridgeForTest() { clearTimeout(pending.timeoutId); } pendingNativeRequests.clear(); + nativeEventListeners.clear(); nextNativeRequestSequence = 0; }