Files
Genarrative/apps/mobile-shell/App.tsx
kdletters 51dcff6d16 接入原生壳页面刷新能力
新增 app.reloadWebView HostBridge 契约和 H5 facade

移动端通过 react-native-webview reload 刷新当前 WebView

桌面端通过 Tauri WebviewWindow reload 刷新主窗口

更新壳能力检查、测试、方案文档和共享决策记录
2026-06-18 05:07:01 +08:00

203 lines
5.3 KiB
TypeScript

import { StatusBar } from 'expo-status-bar';
import { useEffect, useMemo, useRef, useState } from 'react';
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';
import {
configureMobileHostBridgeNavigation,
handleMobileHostBridgeMessage,
resolveMobileHostCapabilities,
} from './src/mobileHostBridge';
import { buildMobileShellUrlFromDeepLink } from './src/mobileShellDeepLink';
import { lifecyclePayloadFromAppState } from './src/mobileShellLifecycle';
import {
resolveMobileShellExternalUrl,
shouldOpenInMobileShellWebView,
} from './src/mobileShellNavigation';
import { subscribeMobileNetworkStatus } from './src/mobileShellNetwork';
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<WebView>(null);
const [canGoBack, setCanGoBack] = useState(false);
const baseWebUrl = process.env.EXPO_PUBLIC_GENARRATIVE_WEB_URL || defaultWebUrl;
const mobileShellUrlOptions = useMemo(
() => ({
platform: Platform.OS === 'ios' ? 'ios' as const : 'android' as const,
hostVersion,
capabilities: resolveMobileHostCapabilities(),
}),
[],
);
const [webUrl, setWebUrl] = useState(() =>
buildMobileShellUrl(baseWebUrl, mobileShellUrlOptions),
);
const allowedWebOrigin = useMemo(() => new URL(webUrl).origin, [webUrl]);
useEffect(() => {
configureMobileHostBridgeNavigation({
allowedOrigin: allowedWebOrigin,
openWebViewUrl(url) {
setWebUrl(url);
},
reloadWebView() {
webViewRef.current?.reload();
},
});
return () => configureMobileHostBridgeNavigation(null);
}, [allowedWebOrigin]);
useEffect(() => {
let disposed = false;
const openDeepLink = (url: string | null | undefined) => {
const nextUrl = buildMobileShellUrlFromDeepLink(
url,
baseWebUrl,
mobileShellUrlOptions,
);
setWebUrl(nextUrl);
};
void Linking.getInitialURL().then((url) => {
if (!disposed) {
openDeepLink(url);
}
});
const subscription = Linking.addEventListener('url', (event) => {
openDeepLink(event.url);
});
return () => {
disposed = true;
subscription.remove();
};
}, [baseWebUrl, mobileShellUrlOptions]);
useEffect(() => {
const subscription = BackHandler.addEventListener(
'hardwareBackPress',
() => {
if (!canGoBack) {
return false;
}
webViewRef.current?.goBack();
return true;
},
);
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();
}, []);
useEffect(() => {
return subscribeMobileNetworkStatus((payload) => {
webViewRef.current?.injectJavaScript(
buildHostBridgeMessageScript({
bridge: 'GenarrativeHostBridge',
version: 1,
event: 'network.statusChanged',
payload,
}),
);
});
}, []);
const handleMessage = (event: WebViewMessageEvent) => {
void handleMobileHostBridgeMessage(event.nativeEvent.data, (response) => {
webViewRef.current?.injectJavaScript(
buildHostBridgeMessageScript(response),
);
});
};
const handleShouldStartLoad = (request: { url: string }) => {
if (shouldOpenInMobileShellWebView(request.url, allowedWebOrigin)) {
return true;
}
const externalUrl = resolveMobileShellExternalUrl(request.url);
if (externalUrl) {
void Linking.openURL(externalUrl).catch(() => undefined);
}
return false;
};
return (
<View style={styles.root}>
<StatusBar style="auto" />
<WebView
ref={webViewRef}
source={{ uri: webUrl }}
javaScriptEnabled
domStorageEnabled
originWhitelist={[allowedWebOrigin]}
onMessage={handleMessage}
onShouldStartLoadWithRequest={handleShouldStartLoad}
onNavigationStateChange={(event) => {
setCanGoBack(event.canGoBack);
webViewRef.current?.injectJavaScript(
buildHostBridgeMessageScript({
bridge: 'GenarrativeHostBridge',
version: 1,
event: 'navigation.canGoBack',
payload: {
canGoBack: event.canGoBack,
},
}),
);
}}
setSupportMultipleWindows={false}
/>
</View>
);
}
const styles = StyleSheet.create({
root: {
flex: 1,
backgroundColor: '#fffdf9',
},
});