接入移动壳返回栈事件

移动壳声明 host.events 和 navigation.canGoBack 能力

Expo WebView 导航状态变化时向 H5 注入返回栈事件

H5 native_app transport 支持订阅 HostBridge 事件

补充事件订阅测试、移动壳能力测试和配置守卫

更新宿主壳方案和团队共享决策记录
This commit is contained in:
2026-06-17 22:42:44 +08:00
parent a87f3dcc82
commit 6f19e1c3ba
9 changed files with 125 additions and 6 deletions

View File

@@ -16,6 +16,12 @@ import { buildMobileShellUrl } from './src/mobileShellUrl';
const defaultWebUrl = 'http://127.0.0.1:3000/'; const defaultWebUrl = 'http://127.0.0.1:3000/';
const hostVersion = '0.1.0'; 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() { export default function App() {
const webViewRef = useRef<WebView>(null); const webViewRef = useRef<WebView>(null);
const [canGoBack, setCanGoBack] = useState(false); const [canGoBack, setCanGoBack] = useState(false);
@@ -91,9 +97,7 @@ export default function App() {
const handleMessage = (event: WebViewMessageEvent) => { const handleMessage = (event: WebViewMessageEvent) => {
void handleMobileHostBridgeMessage(event.nativeEvent.data, (response) => { void handleMobileHostBridgeMessage(event.nativeEvent.data, (response) => {
webViewRef.current?.injectJavaScript( webViewRef.current?.injectJavaScript(
`window.dispatchEvent(new MessageEvent('message', { data: ${JSON.stringify( buildHostBridgeMessageScript(response),
JSON.stringify(response),
)} })); true;`,
); );
}); });
}; };
@@ -118,7 +122,19 @@ export default function App() {
originWhitelist={[allowedWebOrigin]} originWhitelist={[allowedWebOrigin]}
onMessage={handleMessage} onMessage={handleMessage}
onShouldStartLoadWithRequest={handleShouldStartLoad} 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} setSupportMultipleWindows={false}
/> />
</View> </View>

View File

@@ -41,6 +41,8 @@ for (const snippet of [
"Linking.addEventListener('url'", "Linking.addEventListener('url'",
'buildMobileShellUrlFromDeepLink', 'buildMobileShellUrlFromDeepLink',
'configureMobileHostBridgeNavigation', 'configureMobileHostBridgeNavigation',
'navigation.canGoBack',
'buildHostBridgeMessageScript',
]) { ]) {
if (!appSource.includes(snippet)) { if (!appSource.includes(snippet)) {
throw new Error(`mobile shell App missing ${snippet}`); throw new Error(`mobile shell App missing ${snippet}`);

View File

@@ -101,6 +101,11 @@ describe('handleMobileHostBridgeMessage', () => {
expect( expect(
(okResponse.result as { capabilities: string[] }).capabilities, (okResponse.result as { capabilities: string[] }).capabilities,
).toContain('navigation.openNativePage'); ).toContain('navigation.openNativePage');
expect(
(okResponse.result as { capabilities: string[] }).capabilities,
).toEqual(
expect.arrayContaining(['host.events', 'navigation.canGoBack']),
);
}); });
test('navigation.openNativePage 把同源路径切到移动壳 WebView', async () => { test('navigation.openNativePage 把同源路径切到移动壳 WebView', async () => {

View File

@@ -22,9 +22,11 @@ import { resolveMobileShellWebViewUrl } from './mobileShellNavigation';
export const MOBILE_HOST_CAPABILITIES: HostBridgeCapability[] = [ export const MOBILE_HOST_CAPABILITIES: HostBridgeCapability[] = [
'host.getRuntime', 'host.getRuntime',
'host.events',
'share.open', 'share.open',
'share.setTarget', 'share.setTarget',
'navigation.openNativePage', 'navigation.openNativePage',
'navigation.canGoBack',
'app.openExternalUrl', 'app.openExternalUrl',
'clipboard.writeText', 'clipboard.writeText',
'haptics.impact', 'haptics.impact',

View File

@@ -20,7 +20,7 @@
- 背景:后续需要移动端 App 和桌面端 App但现有主站、固定玩法 runtime、小程序壳和未来 AI H5 sandbox 已经以 H5 为主线;如果移动端重写 React Native UI、桌面端重写 Rust/Tauri UI会形成玩法、登录、支付、分享和运行态的多套实现。 - 背景:后续需要移动端 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 契约和测试。 - 决策:移动端原生壳采用 `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 边界。 - 影响范围:`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

@@ -116,6 +116,7 @@ type HostBridgeEvent = {
| `share.setTarget` | 同步当前作品分享目标 | 支持 | 支持 | | `share.setTarget` | 同步当前作品分享目标 | 支持 | 支持 |
| `share.open` | 打开分享动作 | 支持系统分享面板 | 复制分享文本到剪贴板 | | `share.open` | 打开分享动作 | 支持系统分享面板 | 复制分享文本到剪贴板 |
| `navigation.openNativePage` | 打开受控宿主页 | 支持同源 H5 route | 支持设置 / 关于等 | | `navigation.openNativePage` | 打开受控宿主页 | 支持同源 H5 route | 支持设置 / 关于等 |
| `navigation.canGoBack` | 通知 H5 宿主返回栈状态 | 支持事件 | 不声明 |
| `app.openExternalUrl` | 用系统浏览器打开外链 | 支持白名单协议 | 支持白名单协议 | | `app.openExternalUrl` | 用系统浏览器打开外链 | 支持白名单协议 | 支持白名单协议 |
| `app.setTitle` | 同步宿主窗口标题 | 不声明 | 支持 | | `app.setTitle` | 同步宿主窗口标题 | 不声明 | 支持 |
| `clipboard.writeText` | 写剪贴板 | 可选 | 可选 | | `clipboard.writeText` | 写剪贴板 | 可选 | 可选 |
@@ -239,7 +240,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``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 3Tauri 桌面壳 MVP ### Phase 3Tauri 桌面壳 MVP

View File

@@ -80,6 +80,10 @@ export type HostBridgeEvent<Payload = unknown> = {
payload?: Payload; payload?: Payload;
}; };
export type NavigationCanGoBackEventPayload = {
canGoBack: boolean;
};
export type NavigateNativePagePayload = { export type NavigateNativePagePayload = {
url: string; url: string;
}; };

View File

@@ -14,6 +14,7 @@ import {
canUseTauriHostBridge, canUseTauriHostBridge,
requestNativeAppHostBridge, requestNativeAppHostBridge,
resetNativeAppHostBridgeForTest, resetNativeAppHostBridgeForTest,
subscribeNativeAppHostBridgeEvent,
} from './nativeAppHostBridge'; } from './nativeAppHostBridge';
afterEach(() => { afterEach(() => {
@@ -139,4 +140,43 @@ describe('nativeAppHostBridge', () => {
await assertion; 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 });
});
}); });

View File

@@ -2,6 +2,7 @@ import {
HOST_BRIDGE_PROTOCOL, HOST_BRIDGE_PROTOCOL,
HOST_BRIDGE_VERSION, HOST_BRIDGE_VERSION,
type HostBridgeError, type HostBridgeError,
type HostBridgeEvent,
type HostBridgeMethod, type HostBridgeMethod,
type HostBridgeRequest, type HostBridgeRequest,
type HostBridgeResponse, type HostBridgeResponse,
@@ -31,6 +32,7 @@ type PendingNativeRequest = {
}; };
const pendingNativeRequests = new Map<string, PendingNativeRequest>(); const pendingNativeRequests = new Map<string, PendingNativeRequest>();
const nativeEventListeners = new Map<string, Set<(payload: unknown) => void>>();
let nativeBridgeListenerInstalled = false; let nativeBridgeListenerInstalled = false;
let nextNativeRequestSequence = 0; 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<HostBridgeEvent>;
return (
candidate.bridge === HOST_BRIDGE_PROTOCOL &&
candidate.version === HOST_BRIDGE_VERSION &&
typeof candidate.event === 'string'
);
}
function parseNativeMessage(data: unknown) { function parseNativeMessage(data: unknown) {
if (typeof data === 'string') { if (typeof data === 'string') {
try { try {
@@ -106,6 +121,17 @@ function settleNativeResponse(response: HostBridgeResponse) {
pending.reject(createHostBridgeError(response.error)); 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() { function ensureNativeBridgeListener() {
const nativeWindow = resolveNativeWindow(); const nativeWindow = resolveNativeWindow();
if (!nativeWindow || nativeBridgeListenerInstalled) { if (!nativeWindow || nativeBridgeListenerInstalled) {
@@ -116,6 +142,10 @@ function ensureNativeBridgeListener() {
const value = parseNativeMessage(event.data); const value = parseNativeMessage(event.data);
if (isHostBridgeResponse(value)) { if (isHostBridgeResponse(value)) {
settleNativeResponse(value); settleNativeResponse(value);
return;
}
if (isHostBridgeEvent(value)) {
dispatchNativeEvent(value);
} }
}); });
@@ -139,6 +169,24 @@ export function canUseNativeAppHostBridge() {
return canUseReactNativeHostBridge() || canUseTauriHostBridge(); return canUseReactNativeHostBridge() || canUseTauriHostBridge();
} }
export function subscribeNativeAppHostBridgeEvent<Payload = unknown>(
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<Result = unknown>( export async function requestNativeAppHostBridge<Result = unknown>(
method: HostBridgeMethod, method: HostBridgeMethod,
payload?: unknown, payload?: unknown,
@@ -213,5 +261,6 @@ export function resetNativeAppHostBridgeForTest() {
clearTimeout(pending.timeoutId); clearTimeout(pending.timeoutId);
} }
pendingNativeRequests.clear(); pendingNativeRequests.clear();
nativeEventListeners.clear();
nextNativeRequestSequence = 0; nextNativeRequestSequence = 0;
} }