移动壳补齐加载失败兜底

新增同源主页面加载失败归一模型与测试

Expo WebView 接入 onError/onHttpError 原生重试层

更新原生壳门禁与宿主壳方案文档
This commit is contained in:
2026-06-18 20:26:20 +08:00
parent 077c37b67c
commit 8bdfd1c629
7 changed files with 376 additions and 0 deletions
+120
View File
@@ -6,7 +6,10 @@ import {
BackHandler,
Linking,
Platform,
Pressable,
StyleSheet,
Text,
View,
} from 'react-native';
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
import type { WebViewMessageEvent } from 'react-native-webview';
@@ -19,6 +22,10 @@ import {
} from '../host-bridge/bridge';
import { buildMobileShellUrlFromDeepLink } from './deepLink';
import { lifecyclePayloadFromAppState } from './lifecycle';
import {
type MobileShellLoadFailure,
normalizeMobileShellLoadFailure,
} from './loadFailure';
import {
resolveMobileShellExternalUrl,
shouldAcceptMobileShellHostBridgeMessage,
@@ -45,6 +52,22 @@ function buildHostBridgeMessageScript(message: unknown) {
)}, origin: window.location.origin, source: window })); true;`;
}
type MobileWebViewLoadErrorEvent = {
nativeEvent: {
url: string;
code?: number;
description?: string;
};
};
type MobileWebViewHttpErrorEvent = {
nativeEvent: {
url: string;
statusCode?: number;
description?: string;
};
};
export default function ShellApp() {
const webViewRef = useRef<WebView>(null);
const [canGoBack, setCanGoBack] = useState(false);
@@ -62,6 +85,8 @@ export default function ShellApp() {
const [webUrl, setWebUrl] = useState(() =>
buildMobileShellUrl(baseWebUrl, urlOptions),
);
const [loadFailure, setLoadFailure] =
useState<MobileShellLoadFailure | null>(null);
const allowedWebOrigin = useMemo(() => new URL(webUrl).origin, [webUrl]);
const reloadCurrentWebView = useCallback(() => {
webViewRef.current?.reload();
@@ -94,6 +119,7 @@ export default function ShellApp() {
allowedOrigin: allowedWebOrigin,
urlOptions,
openWebViewUrl(url) {
setLoadFailure(null);
setWebUrl(url);
},
reloadWebView: reloadCurrentWebView,
@@ -111,6 +137,7 @@ export default function ShellApp() {
baseWebUrl,
urlOptions,
);
setLoadFailure(null);
setWebUrl(nextUrl);
};
@@ -203,11 +230,44 @@ export default function ShellApp() {
return;
}
setLoadFailure(null);
injectLifecycleEvent(AppState.currentState);
void getMobileNetworkStatus()
.then(injectNetworkStatusEvent)
.catch(() => undefined);
};
const handleWebViewLoadError = (event: MobileWebViewLoadErrorEvent) => {
setLoadFailure(
normalizeMobileShellLoadFailure(
{
type: 'native',
url: event.nativeEvent.url,
code: event.nativeEvent.code,
description: event.nativeEvent.description,
},
allowedWebOrigin,
webUrl,
),
);
};
const handleWebViewHttpError = (event: MobileWebViewHttpErrorEvent) => {
setLoadFailure(
normalizeMobileShellLoadFailure(
{
type: 'http',
url: event.nativeEvent.url,
statusCode: event.nativeEvent.statusCode,
description: event.nativeEvent.description,
},
allowedWebOrigin,
webUrl,
),
);
};
const handleRetryLoadFailure = () => {
setLoadFailure(null);
reloadCurrentWebView();
};
const handleBlockedFileDownload = () => undefined;
return (
@@ -237,6 +297,8 @@ export default function ShellApp() {
onContentProcessDidTerminate={reloadCurrentWebView}
onRenderProcessGone={reloadCurrentWebView}
onLoad={handleWebViewLoad}
onError={handleWebViewLoadError}
onHttpError={handleWebViewHttpError}
onShouldStartLoadWithRequest={handleShouldStartLoad}
onNavigationStateChange={(event) => {
setCanGoBack(event.canGoBack);
@@ -253,6 +315,21 @@ export default function ShellApp() {
}}
setSupportMultipleWindows={false}
/>
{loadFailure ? (
<View style={styles.loadFailurePanel} pointerEvents="auto">
<Text style={styles.loadFailureTitle}>{loadFailure.title}</Text>
<Text style={styles.loadFailureDetail}>{loadFailure.detail}</Text>
<Pressable
accessibilityRole="button"
onPress={handleRetryLoadFailure}
style={styles.loadFailureButton}
>
<Text style={styles.loadFailureButtonText}>
{loadFailure.retryLabel}
</Text>
</Pressable>
</View>
) : null}
</SafeAreaView>
</SafeAreaProvider>
);
@@ -263,4 +340,47 @@ const styles = StyleSheet.create({
flex: 1,
backgroundColor: '#fffdf9',
},
loadFailurePanel: {
position: 'absolute',
top: 0,
right: 0,
bottom: 0,
left: 0,
alignItems: 'center',
justifyContent: 'center',
paddingHorizontal: 28,
backgroundColor: '#fffdf9',
},
loadFailureTitle: {
color: '#211a16',
fontSize: 18,
fontWeight: '700',
lineHeight: 24,
textAlign: 'center',
},
loadFailureDetail: {
maxWidth: 320,
marginTop: 10,
color: '#6a5c52',
fontSize: 14,
lineHeight: 20,
textAlign: 'center',
},
loadFailureButton: {
minWidth: 112,
minHeight: 42,
alignItems: 'center',
justifyContent: 'center',
marginTop: 20,
borderRadius: 8,
backgroundColor: '#211a16',
paddingHorizontal: 22,
},
loadFailureButtonText: {
color: '#fffdf9',
fontSize: 15,
fontWeight: '700',
lineHeight: 20,
textAlign: 'center',
},
});
@@ -0,0 +1,115 @@
import { describe, expect, test } from 'vitest';
import { normalizeMobileShellLoadFailure } from './loadFailure';
const allowedOrigin = 'https://app.genarrative.world';
describe('loadFailure', () => {
test('归一化同源 HTTP 加载失败', () => {
expect(
normalizeMobileShellLoadFailure(
{
type: 'http',
url: 'https://app.genarrative.world/creation/puzzle',
statusCode: 503,
description: 'Service Unavailable',
},
allowedOrigin,
),
).toEqual({
type: 'http',
url: 'https://app.genarrative.world/creation/puzzle',
title: '加载失败 503',
detail: 'Service Unavailable',
retryLabel: '重试',
});
});
test('归一化同源原生加载失败并折叠错误描述', () => {
expect(
normalizeMobileShellLoadFailure(
{
type: 'native',
url: '/works/detail?work=WF-1',
code: -1009,
description: ' The Internet connection appears to be offline. ',
},
allowedOrigin,
),
).toEqual({
type: 'native',
url: 'https://app.genarrative.world/works/detail?work=WF-1',
title: '网络不可用',
detail: 'The Internet connection appears to be offline.',
retryLabel: '重试',
});
});
test('忽略外域和非页面加载失败', () => {
expect(
normalizeMobileShellLoadFailure(
{
type: 'http',
url: 'https://example.com/',
statusCode: 500,
},
allowedOrigin,
),
).toBeNull();
expect(
normalizeMobileShellLoadFailure(
{
type: 'native',
url: 'about:blank',
code: -1,
},
allowedOrigin,
),
).toBeNull();
expect(
normalizeMobileShellLoadFailure(
{
type: 'native',
url: 'javascript:alert(1)',
code: -1,
},
allowedOrigin,
),
).toBeNull();
expect(
normalizeMobileShellLoadFailure(
{
type: 'http',
url: '/favicon.ico',
statusCode: 404,
},
allowedOrigin,
),
).toBeNull();
});
test('只展示当前主页面失败', () => {
expect(
normalizeMobileShellLoadFailure(
{
type: 'http',
url: 'https://app.genarrative.world/assets/main.js',
statusCode: 404,
},
allowedOrigin,
'https://app.genarrative.world/creation/puzzle',
),
).toBeNull();
expect(
normalizeMobileShellLoadFailure(
{
type: 'http',
url: 'https://app.genarrative.world/creation/puzzle',
statusCode: 503,
},
allowedOrigin,
'https://app.genarrative.world/creation/puzzle',
)?.title,
).toBe('加载失败 503');
});
});
+110
View File
@@ -0,0 +1,110 @@
import { shouldOpenInMobileShellWebView } from './navigation';
export type MobileShellLoadFailureInput =
| {
type: 'native';
url: string;
code?: number | null;
description?: string | null;
}
| {
type: 'http';
url: string;
statusCode?: number | null;
description?: string | null;
};
export type MobileShellLoadFailure = {
type: 'native' | 'http';
url: string;
title: string;
detail: string;
retryLabel: string;
};
function normalizeDescription(value: string | null | undefined) {
const normalized = value?.replace(/\s+/g, ' ').trim();
if (!normalized) {
return null;
}
return normalized.length > 96
? `${normalized.slice(0, 96).trim()}...`
: normalized;
}
function sameDocumentUrl(
left: URL,
right: string | null | undefined,
allowedOrigin: string,
) {
if (!right) {
return true;
}
try {
const current = new URL(right, allowedOrigin);
return (
left.origin === current.origin &&
left.pathname === current.pathname &&
left.search === current.search
);
} catch {
return false;
}
}
function shouldShowLoadFailure(
rawUrl: string,
allowedOrigin: string,
currentPageUrl?: string | null,
) {
if (!shouldOpenInMobileShellWebView(rawUrl, allowedOrigin)) {
return false;
}
try {
const url = new URL(rawUrl, allowedOrigin);
return (
url.origin === allowedOrigin &&
url.pathname !== '/favicon.ico' &&
sameDocumentUrl(url, currentPageUrl, allowedOrigin)
);
} catch {
return false;
}
}
export function normalizeMobileShellLoadFailure(
input: MobileShellLoadFailureInput,
allowedOrigin: string,
currentPageUrl?: string | null,
): MobileShellLoadFailure | null {
if (!shouldShowLoadFailure(input.url, allowedOrigin, currentPageUrl)) {
return null;
}
const url = new URL(input.url, allowedOrigin).toString();
const description = normalizeDescription(input.description);
if (input.type === 'http') {
const statusCode =
Number.isInteger(input.statusCode) && input.statusCode
? input.statusCode
: null;
return {
type: 'http',
url,
title: statusCode ? `加载失败 ${statusCode}` : '加载失败',
detail: description ?? '服务器暂时没有返回可用页面',
retryLabel: '重试',
};
}
return {
type: 'native',
url,
title: '网络不可用',
detail: description ?? '当前页面没有加载成功',
retryLabel: '重试',
};
}