Files
Genarrative/apps/mobile-shell/App.tsx
T
kdletters 00b41b6a29 统一宿主壳目录边界
移动端壳拆分为 host-bridge 与 shell 目录

桌面端 Tauri 拆分为 host_bridge 与 shell Rust 模块

更新三端桥接层结构门禁与配置检查

同步宿主壳方案文档和项目共享决策
2026-06-18 16:02:55 +08:00

258 lines
7.5 KiB
TypeScript

import { StatusBar } from 'expo-status-bar';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
AppState,
type AppStateStatus,
BackHandler,
Linking,
Platform,
StyleSheet,
} from 'react-native';
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
import type { WebViewMessageEvent } from 'react-native-webview';
import { WebView } from 'react-native-webview';
import {
configureMobileHostBridgeNavigation,
handleMobileHostBridgeMessage,
resolveMobileHostCapabilities,
} from './src/host-bridge/mobileHostBridge';
import { buildMobileShellUrlFromDeepLink } from './src/shell/mobileShellDeepLink';
import { lifecyclePayloadFromAppState } from './src/shell/mobileShellLifecycle';
import {
resolveMobileShellExternalUrl,
shouldAcceptMobileShellHostBridgeMessage,
shouldOpenInMobileShellWebView,
} from './src/shell/mobileShellNavigation';
import {
getMobileNetworkStatus,
subscribeMobileNetworkStatus,
} from './src/shell/mobileShellNetwork';
import { MOBILE_SHELL_HOST_VERSION } from './src/shell/mobileShellRuntime';
import { MOBILE_SHELL_SAFE_AREA_EDGES } from './src/shell/mobileShellSafeArea';
import {
buildMobileShellUrl,
resolveMobileShellBaseWebUrl,
} from './src/shell/mobileShellUrl';
import { BLOCK_WEBVIEW_DOWNLOAD_SCRIPT } from './src/shell/mobileShellWebViewPolicy';
function buildHostBridgeMessageScript(message: unknown) {
return `window.dispatchEvent(new MessageEvent('message', { data: ${JSON.stringify(
JSON.stringify(message),
)}, origin: window.location.origin, source: window })); true;`;
}
export default function App() {
const webViewRef = useRef<WebView>(null);
const [canGoBack, setCanGoBack] = useState(false);
const baseWebUrl = resolveMobileShellBaseWebUrl(
process.env.EXPO_PUBLIC_GENARRATIVE_WEB_URL,
);
const mobileShellUrlOptions = useMemo(
() => ({
platform: Platform.OS === 'ios' ? 'ios' as const : 'android' as const,
hostVersion: MOBILE_SHELL_HOST_VERSION,
capabilities: resolveMobileHostCapabilities(),
}),
[],
);
const [webUrl, setWebUrl] = useState(() =>
buildMobileShellUrl(baseWebUrl, mobileShellUrlOptions),
);
const allowedWebOrigin = useMemo(() => new URL(webUrl).origin, [webUrl]);
const reloadCurrentWebView = useCallback(() => {
webViewRef.current?.reload();
}, []);
const injectHostBridgeEvent = useCallback((event: string, payload: unknown) => {
webViewRef.current?.injectJavaScript(
buildHostBridgeMessageScript({
bridge: 'GenarrativeHostBridge',
version: 1,
event,
payload,
}),
);
}, []);
const injectLifecycleEvent = useCallback(
(state: AppStateStatus) => {
injectHostBridgeEvent('app.lifecycle', lifecyclePayloadFromAppState(state));
},
[injectHostBridgeEvent],
);
const injectNetworkStatusEvent = useCallback(
(payload: Awaited<ReturnType<typeof getMobileNetworkStatus>>) => {
injectHostBridgeEvent('network.statusChanged', payload);
},
[injectHostBridgeEvent],
);
useEffect(() => {
configureMobileHostBridgeNavigation({
allowedOrigin: allowedWebOrigin,
openWebViewUrl(url) {
setWebUrl(url);
},
reloadWebView: reloadCurrentWebView,
});
return () => configureMobileHostBridgeNavigation(null);
}, [allowedWebOrigin, reloadCurrentWebView]);
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 subscription = AppState.addEventListener(
'change',
injectLifecycleEvent,
);
injectLifecycleEvent(AppState.currentState);
return () => subscription.remove();
}, [injectLifecycleEvent]);
useEffect(() => {
return subscribeMobileNetworkStatus(injectNetworkStatusEvent);
}, [injectNetworkStatusEvent]);
const handleMessage = (event: WebViewMessageEvent) => {
if (
!shouldAcceptMobileShellHostBridgeMessage(
event.nativeEvent.url,
allowedWebOrigin,
)
) {
return;
}
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;
};
const handleWebViewLoad = (event: { nativeEvent: { url: string } }) => {
if (
!shouldAcceptMobileShellHostBridgeMessage(
event.nativeEvent.url,
allowedWebOrigin,
)
) {
return;
}
injectLifecycleEvent(AppState.currentState);
void getMobileNetworkStatus()
.then(injectNetworkStatusEvent)
.catch(() => undefined);
};
return (
<SafeAreaProvider>
<SafeAreaView style={styles.root} edges={MOBILE_SHELL_SAFE_AREA_EDGES}>
<StatusBar style="auto" />
<WebView
ref={webViewRef}
source={{ uri: webUrl }}
javaScriptEnabled
javaScriptCanOpenWindowsAutomatically={false}
domStorageEnabled
mixedContentMode="never"
originWhitelist={[allowedWebOrigin]}
allowFileAccess={false}
allowFileAccessFromFileURLs={false}
allowUniversalAccessFromFileURLs={false}
allowsFullscreenVideo
allowsInlineMediaPlayback
mediaPlaybackRequiresUserAction
thirdPartyCookiesEnabled={false}
sharedCookiesEnabled={false}
webviewDebuggingEnabled={false}
injectedJavaScriptBeforeContentLoaded={BLOCK_WEBVIEW_DOWNLOAD_SCRIPT}
onFileDownload={() => undefined}
onMessage={handleMessage}
onContentProcessDidTerminate={reloadCurrentWebView}
onRenderProcessGone={reloadCurrentWebView}
onLoad={handleWebViewLoad}
onShouldStartLoadWithRequest={handleShouldStartLoad}
onNavigationStateChange={(event) => {
setCanGoBack(event.canGoBack);
webViewRef.current?.injectJavaScript(
buildHostBridgeMessageScript({
bridge: 'GenarrativeHostBridge',
version: 1,
event: 'navigation.canGoBack',
payload: {
canGoBack: event.canGoBack,
},
}),
);
}}
setSupportMultipleWindows={false}
/>
</SafeAreaView>
</SafeAreaProvider>
);
}
const styles = StyleSheet.create({
root: {
flex: 1,
backgroundColor: '#fffdf9',
},
});