接入原生壳网络状态能力
新增 network.status 与 network.statusChanged HostBridge 能力 Expo 壳通过 expo-network 查询并订阅真实网络状态 Tauri 壳通过主站可达性查询和 WebView online/offline 事件同步网络状态 更新壳能力检查、测试和架构文档
This commit is contained in:
@@ -135,6 +135,8 @@ const requiredMainSnippets = [
|
|||||||
'tauri_plugin_clipboard_manager::init()',
|
'tauri_plugin_clipboard_manager::init()',
|
||||||
'"appearance.getColorScheme"',
|
'"appearance.getColorScheme"',
|
||||||
'"app.lifecycle"',
|
'"app.lifecycle"',
|
||||||
|
'"network.status"',
|
||||||
|
'"network.statusChanged"',
|
||||||
'"share.open"',
|
'"share.open"',
|
||||||
'"share.setTarget"',
|
'"share.setTarget"',
|
||||||
'"navigation.openNativePage"',
|
'"navigation.openNativePage"',
|
||||||
@@ -152,6 +154,8 @@ const requiredMainSnippets = [
|
|||||||
'window.theme()',
|
'window.theme()',
|
||||||
'WindowEvent::Focused',
|
'WindowEvent::Focused',
|
||||||
'host_bridge_event_script',
|
'host_bridge_event_script',
|
||||||
|
'resolve_desktop_network_status',
|
||||||
|
'network.statusChanged',
|
||||||
];
|
];
|
||||||
|
|
||||||
for (const permission of requiredPermissions) {
|
for (const permission of requiredPermissions) {
|
||||||
|
|||||||
@@ -2,8 +2,10 @@ use base64::{engine::general_purpose::STANDARD as BASE64_STANDARD, Engine as _};
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::{json, Value};
|
use serde_json::{json, Value};
|
||||||
use std::fs;
|
use std::fs;
|
||||||
|
use std::net::{TcpStream, ToSocketAddrs};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
|
use std::time::Duration;
|
||||||
use tauri::Manager;
|
use tauri::Manager;
|
||||||
use tauri::Theme;
|
use tauri::Theme;
|
||||||
use tauri::Url;
|
use tauri::Url;
|
||||||
@@ -22,6 +24,7 @@ const EXPORT_IMAGE_MAX_BYTES: usize = 5 * 1024 * 1024;
|
|||||||
const EXPORT_FILE_NAME_FALLBACK: &str = "genarrative-export.txt";
|
const EXPORT_FILE_NAME_FALLBACK: &str = "genarrative-export.txt";
|
||||||
const EXPORT_FILE_NAME_MAX_LENGTH: usize = 120;
|
const EXPORT_FILE_NAME_MAX_LENGTH: usize = 120;
|
||||||
const BADGE_COUNT_MAX: i64 = 99999;
|
const BADGE_COUNT_MAX: i64 = 99999;
|
||||||
|
const DESKTOP_NETWORK_CHECK_TIMEOUT_MS: u64 = 1200;
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
@@ -90,6 +93,8 @@ fn capabilities() -> Vec<&'static str> {
|
|||||||
"app.openExternalUrl",
|
"app.openExternalUrl",
|
||||||
"app.setTitle",
|
"app.setTitle",
|
||||||
"app.setBadgeCount",
|
"app.setBadgeCount",
|
||||||
|
"network.status",
|
||||||
|
"network.statusChanged",
|
||||||
"clipboard.writeText",
|
"clipboard.writeText",
|
||||||
"file.exportText",
|
"file.exportText",
|
||||||
"file.exportImage",
|
"file.exportImage",
|
||||||
@@ -441,6 +446,34 @@ fn emit_desktop_lifecycle_event(
|
|||||||
window.eval(script)
|
window.eval(script)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn desktop_network_status_payload(is_online: bool) -> Value {
|
||||||
|
json!({
|
||||||
|
"isConnected": is_online,
|
||||||
|
"isInternetReachable": is_online,
|
||||||
|
"connectionType": if is_online { "unknown" } else { "none" },
|
||||||
|
"nativeType": if is_online { "online" } else { "offline" },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolve_desktop_network_status() -> Value {
|
||||||
|
let timeout = Duration::from_millis(DESKTOP_NETWORK_CHECK_TIMEOUT_MS);
|
||||||
|
let is_reachable = ("app.genarrative.world", 443)
|
||||||
|
.to_socket_addrs()
|
||||||
|
.map(|addresses| {
|
||||||
|
addresses.into_iter().any(|address| {
|
||||||
|
TcpStream::connect_timeout(&address, timeout)
|
||||||
|
.map(|stream| {
|
||||||
|
drop(stream);
|
||||||
|
true
|
||||||
|
})
|
||||||
|
.unwrap_or(false)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.unwrap_or(false);
|
||||||
|
|
||||||
|
desktop_network_status_payload(is_reachable)
|
||||||
|
}
|
||||||
|
|
||||||
fn register_desktop_lifecycle_events(window: &WebviewWindow) {
|
fn register_desktop_lifecycle_events(window: &WebviewWindow) {
|
||||||
let lifecycle_window = window.clone();
|
let lifecycle_window = window.clone();
|
||||||
window.on_window_event(move |event| {
|
window.on_window_event(move |event| {
|
||||||
@@ -455,6 +488,56 @@ fn register_desktop_lifecycle_events(window: &WebviewWindow) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn register_desktop_network_events(window: &WebviewWindow) -> tauri::Result<()> {
|
||||||
|
let online_script = host_bridge_event_script(
|
||||||
|
"network.statusChanged",
|
||||||
|
desktop_network_status_payload(true),
|
||||||
|
)
|
||||||
|
.map_err(tauri::Error::Json)?;
|
||||||
|
let offline_script = host_bridge_event_script(
|
||||||
|
"network.statusChanged",
|
||||||
|
desktop_network_status_payload(false),
|
||||||
|
)
|
||||||
|
.map_err(tauri::Error::Json)?;
|
||||||
|
let current_status_script = host_bridge_event_script(
|
||||||
|
"network.statusChanged",
|
||||||
|
json!({
|
||||||
|
"isConnected": "__GENARRATIVE_DESKTOP_ONLINE__",
|
||||||
|
"isInternetReachable": "__GENARRATIVE_DESKTOP_ONLINE__",
|
||||||
|
"connectionType": "__GENARRATIVE_DESKTOP_CONNECTION_TYPE__",
|
||||||
|
"nativeType": "__GENARRATIVE_DESKTOP_NATIVE_TYPE__",
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.map_err(tauri::Error::Json)?
|
||||||
|
.replace("\"__GENARRATIVE_DESKTOP_ONLINE__\"", "navigator.onLine")
|
||||||
|
.replace(
|
||||||
|
"\"__GENARRATIVE_DESKTOP_CONNECTION_TYPE__\"",
|
||||||
|
"(navigator.onLine ? 'unknown' : 'none')",
|
||||||
|
)
|
||||||
|
.replace(
|
||||||
|
"\"__GENARRATIVE_DESKTOP_NATIVE_TYPE__\"",
|
||||||
|
"(navigator.onLine ? 'online' : 'offline')",
|
||||||
|
);
|
||||||
|
|
||||||
|
let script = format!(
|
||||||
|
"(() => {{
|
||||||
|
if (window.__GENARRATIVE_DESKTOP_NETWORK_LISTENER_INSTALLED__) {{
|
||||||
|
return true;
|
||||||
|
}}
|
||||||
|
window.__GENARRATIVE_DESKTOP_NETWORK_LISTENER_INSTALLED__ = true;
|
||||||
|
const emitOnline = () => {{ {} }};
|
||||||
|
const emitOffline = () => {{ {} }};
|
||||||
|
window.addEventListener('online', emitOnline);
|
||||||
|
window.addEventListener('offline', emitOffline);
|
||||||
|
{}
|
||||||
|
return true;
|
||||||
|
}})();",
|
||||||
|
online_script, offline_script, current_status_script
|
||||||
|
);
|
||||||
|
|
||||||
|
window.eval(script)
|
||||||
|
}
|
||||||
|
|
||||||
fn payload_string<'a>(value: &'a Value, field: &str) -> Option<&'a str> {
|
fn payload_string<'a>(value: &'a Value, field: &str) -> Option<&'a str> {
|
||||||
value
|
value
|
||||||
.get(field)
|
.get(field)
|
||||||
@@ -730,6 +813,14 @@ async fn host_bridge_request(
|
|||||||
None => failed(request.id, "host_error", "main window not found"),
|
None => failed(request.id, "host_error", "main window not found"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
"network.status" => {
|
||||||
|
let network_status =
|
||||||
|
tauri::async_runtime::spawn_blocking(resolve_desktop_network_status).await;
|
||||||
|
match network_status {
|
||||||
|
Ok(status) => ok(request.id, status),
|
||||||
|
Err(error) => failed(request.id, "host_error", error.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
"share.setTarget" => {
|
"share.setTarget" => {
|
||||||
let target = request
|
let target = request
|
||||||
.payload
|
.payload
|
||||||
@@ -783,6 +874,7 @@ fn main() {
|
|||||||
tauri::WebviewWindowBuilder::from_config(app.handle(), &config)?.build()?;
|
tauri::WebviewWindowBuilder::from_config(app.handle(), &config)?.build()?;
|
||||||
register_desktop_lifecycle_events(&window);
|
register_desktop_lifecycle_events(&window);
|
||||||
let _ = emit_desktop_lifecycle_event(&window, "active", true, "created");
|
let _ = emit_desktop_lifecycle_event(&window, "active", true, "created");
|
||||||
|
let _ = register_desktop_network_events(&window);
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
@@ -822,6 +914,14 @@ mod tests {
|
|||||||
.as_array()
|
.as_array()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.contains(&json!("app.lifecycle")));
|
.contains(&json!("app.lifecycle")));
|
||||||
|
assert!(result["capabilities"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.contains(&json!("network.status")));
|
||||||
|
assert!(result["capabilities"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.contains(&json!("network.statusChanged")));
|
||||||
assert!(result["capabilities"]
|
assert!(result["capabilities"]
|
||||||
.as_array()
|
.as_array()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
@@ -911,6 +1011,28 @@ mod tests {
|
|||||||
assert!(script.contains("\\\"focused\\\":true"));
|
assert!(script.contains("\\\"focused\\\":true"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn desktop_network_status_payload_reports_reachability() {
|
||||||
|
assert_eq!(
|
||||||
|
desktop_network_status_payload(true),
|
||||||
|
json!({
|
||||||
|
"isConnected": true,
|
||||||
|
"isInternetReachable": true,
|
||||||
|
"connectionType": "unknown",
|
||||||
|
"nativeType": "online",
|
||||||
|
})
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
desktop_network_status_payload(false),
|
||||||
|
json!({
|
||||||
|
"isConnected": false,
|
||||||
|
"isInternetReachable": false,
|
||||||
|
"connectionType": "none",
|
||||||
|
"nativeType": "offline",
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn external_url_normalization_allows_only_safe_protocols() {
|
fn external_url_normalization_allows_only_safe_protocols() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "npm --prefix ../.. run dev:web",
|
"beforeDevCommand": "npm --prefix ../.. run dev:web",
|
||||||
"beforeBuildCommand": "npm --prefix ../.. run build:raw && npm run typecheck",
|
"beforeBuildCommand": "npm --prefix ../.. run build:raw && npm run typecheck",
|
||||||
"devUrl": "http://127.0.0.1:3000/?clientRuntime=native_app&clientType=native_app&hostShell=tauri_desktop&hostPlatform=unknown&hostVersion=0.1.0&bridgeVersion=1&hostCapabilities=host.getRuntime,appearance.getColorScheme,app.lifecycle,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,app.setBadgeCount,clipboard.writeText,file.exportText,file.exportImage",
|
"devUrl": "http://127.0.0.1:3000/?clientRuntime=native_app&clientType=native_app&hostShell=tauri_desktop&hostPlatform=unknown&hostVersion=0.1.0&bridgeVersion=1&hostCapabilities=host.getRuntime,appearance.getColorScheme,app.lifecycle,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,app.setBadgeCount,network.status,network.statusChanged,clipboard.writeText,file.exportText,file.exportImage",
|
||||||
"frontendDist": "../../../dist"
|
"frontendDist": "../../../dist"
|
||||||
},
|
},
|
||||||
"app": {
|
"app": {
|
||||||
@@ -14,7 +14,7 @@
|
|||||||
{
|
{
|
||||||
"create": false,
|
"create": false,
|
||||||
"label": "main",
|
"label": "main",
|
||||||
"url": "index.html?clientRuntime=native_app&clientType=native_app&hostShell=tauri_desktop&hostPlatform=unknown&hostVersion=0.1.0&bridgeVersion=1&hostCapabilities=host.getRuntime,appearance.getColorScheme,app.lifecycle,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,app.setBadgeCount,clipboard.writeText,file.exportText,file.exportImage",
|
"url": "index.html?clientRuntime=native_app&clientType=native_app&hostShell=tauri_desktop&hostPlatform=unknown&hostVersion=0.1.0&bridgeVersion=1&hostCapabilities=host.getRuntime,appearance.getColorScheme,app.lifecycle,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,app.setBadgeCount,network.status,network.statusChanged,clipboard.writeText,file.exportText,file.exportImage",
|
||||||
"title": "Genarrative",
|
"title": "Genarrative",
|
||||||
"width": 1280,
|
"width": 1280,
|
||||||
"height": 820,
|
"height": 820,
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ import {
|
|||||||
resolveMobileShellExternalUrl,
|
resolveMobileShellExternalUrl,
|
||||||
shouldOpenInMobileShellWebView,
|
shouldOpenInMobileShellWebView,
|
||||||
} from './src/mobileShellNavigation';
|
} from './src/mobileShellNavigation';
|
||||||
|
import { subscribeMobileNetworkStatus } from './src/mobileShellNetwork';
|
||||||
import { buildMobileShellUrl } from './src/mobileShellUrl';
|
import { buildMobileShellUrl } from './src/mobileShellUrl';
|
||||||
|
|
||||||
const defaultWebUrl = 'http://127.0.0.1:3000/';
|
const defaultWebUrl = 'http://127.0.0.1:3000/';
|
||||||
@@ -127,6 +128,19 @@ export default function App() {
|
|||||||
return () => subscription.remove();
|
return () => subscription.remove();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
return subscribeMobileNetworkStatus((payload) => {
|
||||||
|
webViewRef.current?.injectJavaScript(
|
||||||
|
buildHostBridgeMessageScript({
|
||||||
|
bridge: 'GenarrativeHostBridge',
|
||||||
|
version: 1,
|
||||||
|
event: 'network.statusChanged',
|
||||||
|
payload,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
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(
|
||||||
|
|||||||
@@ -18,6 +18,7 @@
|
|||||||
"expo-file-system": "^56.0.8",
|
"expo-file-system": "^56.0.8",
|
||||||
"expo-haptics": "^56.0.3",
|
"expo-haptics": "^56.0.3",
|
||||||
"expo-linking": "^56.0.14",
|
"expo-linking": "^56.0.14",
|
||||||
|
"expo-network": "^56.0.5",
|
||||||
"expo-sharing": "^56.0.18",
|
"expo-sharing": "^56.0.18",
|
||||||
"expo-status-bar": "^56.0.4",
|
"expo-status-bar": "^56.0.4",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
|
|||||||
@@ -119,6 +119,8 @@ for (const snippet of [
|
|||||||
'configureMobileHostBridgeNavigation',
|
'configureMobileHostBridgeNavigation',
|
||||||
'AppState.addEventListener',
|
'AppState.addEventListener',
|
||||||
'app.lifecycle',
|
'app.lifecycle',
|
||||||
|
'network.statusChanged',
|
||||||
|
'subscribeMobileNetworkStatus',
|
||||||
'navigation.canGoBack',
|
'navigation.canGoBack',
|
||||||
'buildHostBridgeMessageScript',
|
'buildHostBridgeMessageScript',
|
||||||
]) {
|
]) {
|
||||||
@@ -127,7 +129,7 @@ for (const snippet of [
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const dependency of ['expo-file-system', 'expo-sharing']) {
|
for (const dependency of ['expo-file-system', 'expo-network', 'expo-sharing']) {
|
||||||
if (!packageConfig.dependencies?.[dependency]) {
|
if (!packageConfig.dependencies?.[dependency]) {
|
||||||
throw new Error(`mobile shell package missing ${dependency}`);
|
throw new Error(`mobile shell package missing ${dependency}`);
|
||||||
}
|
}
|
||||||
@@ -136,6 +138,8 @@ for (const dependency of ['expo-file-system', 'expo-sharing']) {
|
|||||||
for (const snippet of [
|
for (const snippet of [
|
||||||
'file.exportText',
|
'file.exportText',
|
||||||
'file.exportImage',
|
'file.exportImage',
|
||||||
|
'network.status',
|
||||||
|
'getMobileNetworkStatus',
|
||||||
'Sharing.shareAsync',
|
'Sharing.shareAsync',
|
||||||
'normalizeHostBridgeExportFileName',
|
'normalizeHostBridgeExportFileName',
|
||||||
'base64Data',
|
'base64Data',
|
||||||
@@ -160,6 +164,8 @@ for (const capability of [
|
|||||||
'share.open',
|
'share.open',
|
||||||
'share.setTarget',
|
'share.setTarget',
|
||||||
'app.lifecycle',
|
'app.lifecycle',
|
||||||
|
'network.status',
|
||||||
|
'network.statusChanged',
|
||||||
'navigation.openNativePage',
|
'navigation.openNativePage',
|
||||||
'navigation.canGoBack',
|
'navigation.canGoBack',
|
||||||
'app.openExternalUrl',
|
'app.openExternalUrl',
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import * as Haptics from 'expo-haptics';
|
import * as Haptics from 'expo-haptics';
|
||||||
import * as Linking from 'expo-linking';
|
import * as Linking from 'expo-linking';
|
||||||
|
import * as Network from 'expo-network';
|
||||||
import * as Sharing from 'expo-sharing';
|
import * as Sharing from 'expo-sharing';
|
||||||
import {
|
import {
|
||||||
Appearance,
|
Appearance,
|
||||||
@@ -69,6 +70,20 @@ vi.mock('expo-linking', () => ({
|
|||||||
openURL: vi.fn(),
|
openURL: vi.fn(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
vi.mock('expo-network', () => ({
|
||||||
|
getNetworkStateAsync: vi.fn(async () => ({
|
||||||
|
type: 'WIFI',
|
||||||
|
isConnected: true,
|
||||||
|
isInternetReachable: true,
|
||||||
|
})),
|
||||||
|
NetworkStateType: {
|
||||||
|
CELLULAR: 'CELLULAR',
|
||||||
|
ETHERNET: 'ETHERNET',
|
||||||
|
NONE: 'NONE',
|
||||||
|
WIFI: 'WIFI',
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
vi.mock('expo-sharing', () => ({
|
vi.mock('expo-sharing', () => ({
|
||||||
isAvailableAsync: vi.fn(async () => true),
|
isAvailableAsync: vi.fn(async () => true),
|
||||||
shareAsync: vi.fn(),
|
shareAsync: vi.fn(),
|
||||||
@@ -142,6 +157,12 @@ afterEach(() => {
|
|||||||
vi.mocked(Appearance.getColorScheme).mockReturnValue('light');
|
vi.mocked(Appearance.getColorScheme).mockReturnValue('light');
|
||||||
vi.mocked(Haptics.impactAsync).mockReset();
|
vi.mocked(Haptics.impactAsync).mockReset();
|
||||||
vi.mocked(Linking.openURL).mockReset();
|
vi.mocked(Linking.openURL).mockReset();
|
||||||
|
vi.mocked(Network.getNetworkStateAsync).mockReset();
|
||||||
|
vi.mocked(Network.getNetworkStateAsync).mockResolvedValue({
|
||||||
|
type: Network.NetworkStateType.WIFI,
|
||||||
|
isConnected: true,
|
||||||
|
isInternetReachable: true,
|
||||||
|
});
|
||||||
vi.mocked(PushNotificationIOS.setApplicationIconBadgeNumber).mockReset();
|
vi.mocked(PushNotificationIOS.setApplicationIconBadgeNumber).mockReset();
|
||||||
setPlatformOS('ios');
|
setPlatformOS('ios');
|
||||||
vi.mocked(Sharing.isAvailableAsync).mockReset();
|
vi.mocked(Sharing.isAvailableAsync).mockReset();
|
||||||
@@ -175,6 +196,8 @@ describe('handleMobileHostBridgeMessage', () => {
|
|||||||
'appearance.getColorScheme',
|
'appearance.getColorScheme',
|
||||||
'host.events',
|
'host.events',
|
||||||
'app.lifecycle',
|
'app.lifecycle',
|
||||||
|
'network.status',
|
||||||
|
'network.statusChanged',
|
||||||
'navigation.canGoBack',
|
'navigation.canGoBack',
|
||||||
'app.setBadgeCount',
|
'app.setBadgeCount',
|
||||||
]),
|
]),
|
||||||
@@ -288,6 +311,23 @@ describe('handleMobileHostBridgeMessage', () => {
|
|||||||
expect(Linking.openURL).not.toHaveBeenCalled();
|
expect(Linking.openURL).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('network.status 返回 Expo Network 真实状态', async () => {
|
||||||
|
vi.mocked(Network.getNetworkStateAsync).mockResolvedValue({
|
||||||
|
type: Network.NetworkStateType.CELLULAR,
|
||||||
|
isConnected: true,
|
||||||
|
isInternetReachable: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await send(request('network.status'));
|
||||||
|
|
||||||
|
expect(expectOk(response).result).toEqual({
|
||||||
|
isConnected: true,
|
||||||
|
isInternetReachable: false,
|
||||||
|
connectionType: 'cellular',
|
||||||
|
nativeType: 'CELLULAR',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
test('haptics.impact 调起 Expo 触觉反馈', async () => {
|
test('haptics.impact 调起 Expo 触觉反馈', async () => {
|
||||||
const response = await send(
|
const response = await send(
|
||||||
request('haptics.impact', {
|
request('haptics.impact', {
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ import {
|
|||||||
type ShareOpenPayload,
|
type ShareOpenPayload,
|
||||||
} from '../../../packages/shared/src/contracts/hostBridge';
|
} from '../../../packages/shared/src/contracts/hostBridge';
|
||||||
import { resolveMobileShellWebViewUrl } from './mobileShellNavigation';
|
import { resolveMobileShellWebViewUrl } from './mobileShellNavigation';
|
||||||
|
import { getMobileNetworkStatus } from './mobileShellNetwork';
|
||||||
|
|
||||||
const WEB_APP_ORIGIN = 'https://app.genarrative.world';
|
const WEB_APP_ORIGIN = 'https://app.genarrative.world';
|
||||||
const EXPORT_TEXT_MAX_BYTES = 5 * 1024 * 1024;
|
const EXPORT_TEXT_MAX_BYTES = 5 * 1024 * 1024;
|
||||||
@@ -54,6 +55,8 @@ export const MOBILE_HOST_CAPABILITIES: HostBridgeCapability[] = [
|
|||||||
'navigation.openNativePage',
|
'navigation.openNativePage',
|
||||||
'navigation.canGoBack',
|
'navigation.canGoBack',
|
||||||
'app.openExternalUrl',
|
'app.openExternalUrl',
|
||||||
|
'network.status',
|
||||||
|
'network.statusChanged',
|
||||||
'clipboard.writeText',
|
'clipboard.writeText',
|
||||||
'file.exportText',
|
'file.exportText',
|
||||||
'file.exportImage',
|
'file.exportImage',
|
||||||
@@ -437,6 +440,8 @@ async function handleRequest(request: HostBridgeRequest) {
|
|||||||
return ok(request, getColorScheme());
|
return ok(request, getColorScheme());
|
||||||
case 'app.openExternalUrl':
|
case 'app.openExternalUrl':
|
||||||
return ok(request, await openExternalUrl(request.payload));
|
return ok(request, await openExternalUrl(request.payload));
|
||||||
|
case 'network.status':
|
||||||
|
return ok(request, await getMobileNetworkStatus());
|
||||||
case 'clipboard.writeText':
|
case 'clipboard.writeText':
|
||||||
return ok(request, await writeClipboard(request.payload));
|
return ok(request, await writeClipboard(request.payload));
|
||||||
case 'file.exportText':
|
case 'file.exportText':
|
||||||
|
|||||||
84
apps/mobile-shell/src/mobileShellNetwork.test.ts
Normal file
84
apps/mobile-shell/src/mobileShellNetwork.test.ts
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
import { describe, expect, test, vi } from 'vitest';
|
||||||
|
|
||||||
|
import {
|
||||||
|
getMobileNetworkStatus,
|
||||||
|
normalizeMobileNetworkStatus,
|
||||||
|
subscribeMobileNetworkStatus,
|
||||||
|
} from './mobileShellNetwork';
|
||||||
|
|
||||||
|
vi.mock('expo-network', () => ({
|
||||||
|
addNetworkStateListener: vi.fn(),
|
||||||
|
getNetworkStateAsync: vi.fn(),
|
||||||
|
NetworkStateType: {
|
||||||
|
CELLULAR: 'CELLULAR',
|
||||||
|
ETHERNET: 'ETHERNET',
|
||||||
|
NONE: 'NONE',
|
||||||
|
WIFI: 'WIFI',
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('mobileShellNetwork', async () => {
|
||||||
|
const Network = await import('expo-network');
|
||||||
|
|
||||||
|
test('归一化 Expo Network 状态', () => {
|
||||||
|
expect(
|
||||||
|
normalizeMobileNetworkStatus({
|
||||||
|
type: Network.NetworkStateType.WIFI,
|
||||||
|
isConnected: true,
|
||||||
|
isInternetReachable: true,
|
||||||
|
}),
|
||||||
|
).toEqual({
|
||||||
|
isConnected: true,
|
||||||
|
isInternetReachable: true,
|
||||||
|
connectionType: 'wifi',
|
||||||
|
nativeType: 'WIFI',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(
|
||||||
|
normalizeMobileNetworkStatus({
|
||||||
|
type: Network.NetworkStateType.NONE,
|
||||||
|
}),
|
||||||
|
).toEqual({
|
||||||
|
isConnected: false,
|
||||||
|
isInternetReachable: null,
|
||||||
|
connectionType: 'none',
|
||||||
|
nativeType: 'NONE',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('查询和订阅真实 Expo Network API', async () => {
|
||||||
|
vi.mocked(Network.getNetworkStateAsync).mockResolvedValue({
|
||||||
|
type: Network.NetworkStateType.CELLULAR,
|
||||||
|
isConnected: true,
|
||||||
|
isInternetReachable: false,
|
||||||
|
});
|
||||||
|
const remove = vi.fn();
|
||||||
|
vi.mocked(Network.addNetworkStateListener).mockReturnValue({ remove });
|
||||||
|
const listener = vi.fn();
|
||||||
|
|
||||||
|
await expect(getMobileNetworkStatus()).resolves.toEqual({
|
||||||
|
isConnected: true,
|
||||||
|
isInternetReachable: false,
|
||||||
|
connectionType: 'cellular',
|
||||||
|
nativeType: 'CELLULAR',
|
||||||
|
});
|
||||||
|
|
||||||
|
const unsubscribe = subscribeMobileNetworkStatus(listener);
|
||||||
|
const networkListener = vi.mocked(Network.addNetworkStateListener).mock
|
||||||
|
.calls[0]?.[0];
|
||||||
|
networkListener?.({
|
||||||
|
type: Network.NetworkStateType.ETHERNET,
|
||||||
|
isConnected: true,
|
||||||
|
isInternetReachable: true,
|
||||||
|
});
|
||||||
|
unsubscribe();
|
||||||
|
|
||||||
|
expect(listener).toHaveBeenCalledWith({
|
||||||
|
isConnected: true,
|
||||||
|
isInternetReachable: true,
|
||||||
|
connectionType: 'ethernet',
|
||||||
|
nativeType: 'ETHERNET',
|
||||||
|
});
|
||||||
|
expect(remove).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
40
apps/mobile-shell/src/mobileShellNetwork.ts
Normal file
40
apps/mobile-shell/src/mobileShellNetwork.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import * as Network from 'expo-network';
|
||||||
|
|
||||||
|
import {
|
||||||
|
type NetworkStatusResult,
|
||||||
|
normalizeHostBridgeConnectionType,
|
||||||
|
} from '../../../packages/shared/src/contracts/hostBridge';
|
||||||
|
|
||||||
|
export function normalizeMobileNetworkStatus(
|
||||||
|
state: Network.NetworkState,
|
||||||
|
): NetworkStatusResult {
|
||||||
|
const nativeType = state.type;
|
||||||
|
const connectionType = normalizeHostBridgeConnectionType(nativeType);
|
||||||
|
|
||||||
|
return {
|
||||||
|
isConnected:
|
||||||
|
typeof state.isConnected === 'boolean'
|
||||||
|
? state.isConnected
|
||||||
|
: connectionType !== 'none' && connectionType !== 'unknown',
|
||||||
|
isInternetReachable:
|
||||||
|
typeof state.isInternetReachable === 'boolean'
|
||||||
|
? state.isInternetReachable
|
||||||
|
: null,
|
||||||
|
connectionType,
|
||||||
|
...(nativeType ? { nativeType } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getMobileNetworkStatus() {
|
||||||
|
return normalizeMobileNetworkStatus(await Network.getNetworkStateAsync());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function subscribeMobileNetworkStatus(
|
||||||
|
listener: (status: NetworkStatusResult) => void,
|
||||||
|
) {
|
||||||
|
const subscription = Network.addNetworkStateListener((state) => {
|
||||||
|
listener(normalizeMobileNetworkStatus(state));
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => subscription.remove();
|
||||||
|
}
|
||||||
@@ -31,6 +31,7 @@
|
|||||||
- 2026-06-18 应用角标能力:新增 `app.setBadgeCount` HostBridge capability,H5 只传 `0-99999` 整数并在宿主未声明时静默 fallback;Expo 壳只在 iOS 声明并通过 React Native `PushNotificationIOS` 设置应用图标角标,Android 不声明、不伪造成功;Tauri 壳通过主窗口 `set_badge_count` 设置任务栏角标,底层平台不支持时返回真实错误。
|
- 2026-06-18 应用角标能力:新增 `app.setBadgeCount` HostBridge capability,H5 只传 `0-99999` 整数并在宿主未声明时静默 fallback;Expo 壳只在 iOS 声明并通过 React Native `PushNotificationIOS` 设置应用图标角标,Android 不声明、不伪造成功;Tauri 壳通过主窗口 `set_badge_count` 设置任务栏角标,底层平台不支持时返回真实错误。
|
||||||
- 2026-06-18 宿主外观只读查询:新增 `appearance.getColorScheme` HostBridge capability,Expo 壳通过 React Native `Appearance.getColorScheme()` 读取系统配色,Tauri 壳通过主窗口 `theme()` 读取窗口主题;该能力只返回 `light` / `dark` / `unknown`,不设置 H5 主题、不覆盖系统主题,也不作为强制 UI 样式入口。
|
- 2026-06-18 宿主外观只读查询:新增 `appearance.getColorScheme` HostBridge capability,Expo 壳通过 React Native `Appearance.getColorScheme()` 读取系统配色,Tauri 壳通过主窗口 `theme()` 读取窗口主题;该能力只返回 `light` / `dark` / `unknown`,不设置 H5 主题、不覆盖系统主题,也不作为强制 UI 样式入口。
|
||||||
- 2026-06-18 原生壳生命周期事件:新增 `app.lifecycle` HostBridge capability,Expo 壳通过 React Native `AppState` 派发 `active` / `inactive` / `background`,Tauri 壳通过主窗口 focus / blur 派发 `active` / `inactive`;H5 只通过 `subscribeHostAppLifecycle()` 订阅统一状态,后续游戏循环、音频和轮询暂停 / 恢复不得直接依赖 Expo / Tauri 平台细节。
|
- 2026-06-18 原生壳生命周期事件:新增 `app.lifecycle` HostBridge capability,Expo 壳通过 React Native `AppState` 派发 `active` / `inactive` / `background`,Tauri 壳通过主窗口 focus / blur 派发 `active` / `inactive`;H5 只通过 `subscribeHostAppLifecycle()` 订阅统一状态,后续游戏循环、音频和轮询暂停 / 恢复不得直接依赖 Expo / Tauri 平台细节。
|
||||||
|
- 2026-06-18 原生壳网络状态:新增 `network.status` 与 `network.statusChanged` HostBridge capability,Expo 壳通过 `expo-network` 查询和订阅真实系统网络状态,Tauri 壳通过短超时连接 `app.genarrative.world:443` 查询主站可达性,并通过 WebView `online` / `offline` 注入变化事件;H5 统一使用 `getHostNetworkStatus()` / `subscribeHostNetworkStatusChange()`,不得直接读取 Expo / Tauri 私有网络 API。
|
||||||
- 影响范围:`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;固定玩法在各宿主中读取同一作品数据和运行态 snapshot;AI sandbox 无法直接调用 HostBridge;Tauri release 不允许任意远端页面调用桌面命令。
|
- 验证方式:普通浏览器、小程序、Expo 壳、Tauri 壳都能返回正确 `getHostRuntime()`;未支持能力能回退 H5;固定玩法在各宿主中读取同一作品数据和运行态 snapshot;AI sandbox 无法直接调用 HostBridge;Tauri 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`。
|
||||||
|
|||||||
@@ -122,6 +122,8 @@ type HostBridgeEvent = {
|
|||||||
| `app.openExternalUrl` | 用系统浏览器打开外链 | 支持白名单协议 | 支持白名单协议 |
|
| `app.openExternalUrl` | 用系统浏览器打开外链 | 支持白名单协议 | 支持白名单协议 |
|
||||||
| `app.setTitle` | 同步宿主窗口标题 | 不声明 | 支持 |
|
| `app.setTitle` | 同步宿主窗口标题 | 不声明 | 支持 |
|
||||||
| `app.setBadgeCount` | 设置应用 / 任务栏角标 | 仅 iOS 支持,Android 不声明 | 支持;平台底层不支持时返回错误 |
|
| `app.setBadgeCount` | 设置应用 / 任务栏角标 | 仅 iOS 支持,Android 不声明 | 支持;平台底层不支持时返回错误 |
|
||||||
|
| `network.status` | 查询宿主网络状态 | 支持 Expo Network | 支持主站可达性短超时查询 |
|
||||||
|
| `network.statusChanged` | 通知 H5 网络状态变化 | 支持 Expo Network 事件 | 支持 WebView online / offline 事件 |
|
||||||
| `clipboard.writeText` | 写剪贴板 | 支持 | 支持 |
|
| `clipboard.writeText` | 写剪贴板 | 支持 | 支持 |
|
||||||
| `file.exportText` | 导出文本到用户选择的本地文件 | 支持系统分享 / 保存面板 | 支持系统保存对话框 |
|
| `file.exportText` | 导出文本到用户选择的本地文件 | 支持系统分享 / 保存面板 | 支持系统保存对话框 |
|
||||||
| `haptics.impact` | 轻量触感反馈 | 支持 | 不声明 |
|
| `haptics.impact` | 轻量触感反馈 | 支持 | 不声明 |
|
||||||
@@ -245,7 +247,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`、`appearance.getColorScheme`、`host.events`、`app.lifecycle`、`share.open`、`share.setTarget`、`navigation.openNativePage`、`navigation.canGoBack`、`app.openExternalUrl`、`clipboard.writeText`、`file.exportText`、`file.exportImage`、`haptics.impact` 和 Android 返回键回退;其中 `appearance.getColorScheme` 只读系统配色偏好,不强改 H5 或系统主题;`app.lifecycle` 通过 React Native `AppState` 注入 `active` / `inactive` / `background` 统一状态,供 H5 游戏循环、音频和轮询做真实暂停 / 恢复判断;iOS 额外声明 `app.setBadgeCount`,通过 React Native `PushNotificationIOS` 设置应用图标角标,Android 不声明该能力。H5 会解析并过滤 `hostCapabilities`,也会在主 App 启动时通过真实 `host.getRuntime` 回读并缓存能力,只对声明或回读到的能力展示入口或调用宿主能力;其中 `share.setTarget` / `share.open` 会解析统一分享目标里的 `title`、`message`、`url`、`work`、`path` 或 `targetPath` 并调用 React Native 系统分享面板;发布分享弹窗只有在宿主声明 `share.open` 时才提供“系统分享”动作,失败时保留复制链接回退路径;`navigation.openNativePage` 在 Expo 壳内只接受同源 H5 route 并切换 WebView URL,不伪造尚未存在的登录、支付或其它原生页面,`navigation.canGoBack` 由 WebView 导航状态变化实时注入 H5,WebView 自身拦截到外域导航时只会把 `http:`、`https:`、`mailto:`、`tel:` 交给系统,危险协议直接阻断;`app.openExternalUrl` 也只允许同一协议白名单,ICP备案号和资产调试原图等 H5 外链入口在 `native_app` 中优先通过该能力离开 WebView 并交给系统浏览器;`clipboard.writeText` 由 H5 复制服务优先调用并写入系统剪贴板;`file.exportText` 通过 Expo 文件系统写入缓存文本文件,再交给系统分享 / 保存面板,文件名必须清洗,单次文本不超过 5 MiB,成功只返回文件名和字节数;`file.exportImage` 通过 Expo 文件系统写入缓存图片,再交给系统分享 / 保存面板,H5 只传允许 MIME 的 base64 图片数据,单次不超过 5 MiB,分享卡下载会优先走该能力;`haptics.impact` 通过 Expo Haptics 承接运行时轻触反馈,H5 在宿主不支持时回退到浏览器 vibration。登录和支付尚未接入渠道 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`、`appearance.getColorScheme`、`host.events`、`app.lifecycle`、`network.status`、`network.statusChanged`、`share.open`、`share.setTarget`、`navigation.openNativePage`、`navigation.canGoBack`、`app.openExternalUrl`、`clipboard.writeText`、`file.exportText`、`file.exportImage`、`haptics.impact` 和 Android 返回键回退;其中 `appearance.getColorScheme` 只读系统配色偏好,不强改 H5 或系统主题;`app.lifecycle` 通过 React Native `AppState` 注入 `active` / `inactive` / `background` 统一状态,供 H5 游戏循环、音频和轮询做真实暂停 / 恢复判断;`network.status` / `network.statusChanged` 通过 `expo-network` 查询并订阅真实系统网络状态,供 H5 游戏运行态和生成页识别离线 / 弱网回退;iOS 额外声明 `app.setBadgeCount`,通过 React Native `PushNotificationIOS` 设置应用图标角标,Android 不声明该能力。H5 会解析并过滤 `hostCapabilities`,也会在主 App 启动时通过真实 `host.getRuntime` 回读并缓存能力,只对声明或回读到的能力展示入口或调用宿主能力;其中 `share.setTarget` / `share.open` 会解析统一分享目标里的 `title`、`message`、`url`、`work`、`path` 或 `targetPath` 并调用 React Native 系统分享面板;发布分享弹窗只有在宿主声明 `share.open` 时才提供“系统分享”动作,失败时保留复制链接回退路径;`navigation.openNativePage` 在 Expo 壳内只接受同源 H5 route 并切换 WebView URL,不伪造尚未存在的登录、支付或其它原生页面,`navigation.canGoBack` 由 WebView 导航状态变化实时注入 H5,WebView 自身拦截到外域导航时只会把 `http:`、`https:`、`mailto:`、`tel:` 交给系统,危险协议直接阻断;`app.openExternalUrl` 也只允许同一协议白名单,ICP备案号和资产调试原图等 H5 外链入口在 `native_app` 中优先通过该能力离开 WebView 并交给系统浏览器;`clipboard.writeText` 由 H5 复制服务优先调用并写入系统剪贴板;`file.exportText` 通过 Expo 文件系统写入缓存文本文件,再交给系统分享 / 保存面板,文件名必须清洗,单次文本不超过 5 MiB,成功只返回文件名和字节数;`file.exportImage` 通过 Expo 文件系统写入缓存图片,再交给系统分享 / 保存面板,H5 只传允许 MIME 的 base64 图片数据,单次不超过 5 MiB,分享卡下载会优先走该能力;`haptics.impact` 通过 Expo Haptics 承接运行时轻触反馈,H5 在宿主不支持时回退到浏览器 vibration。登录和支付尚未接入渠道 SDK / 原生页面时明确返回 unsupported,让 H5 fallback 承接。
|
||||||
|
|
||||||
### Phase 3:Tauri 桌面壳 MVP
|
### Phase 3:Tauri 桌面壳 MVP
|
||||||
|
|
||||||
@@ -256,7 +258,7 @@ GameBridge 禁止:
|
|||||||
- 实现 runtime、openExternalUrl、clipboard、share fallback、窗口标题同步。
|
- 实现 runtime、openExternalUrl、clipboard、share fallback、窗口标题同步。
|
||||||
- 验证 macOS / Windows / Linux 至少一条本地 smoke。
|
- 验证 macOS / Windows / Linux 至少一条本地 smoke。
|
||||||
|
|
||||||
当前状态:已新增 `apps/desktop-shell/`,Tauri dev 直接加载本地主站 Vite,release 打包根 `dist` 主站资产。Rust 侧只把 `host_bridge_request` command 授给主窗口,`appearance.getColorScheme` 由 Rust 内部读取主窗口 `theme()` 并返回 `light` / `dark` / `unknown`,不设置或覆盖系统主题;`app.lifecycle` 由主窗口 focus / blur 事件注入 `active` / `inactive` 统一状态,不开放 Tauri event 插件给前端;`app.openExternalUrl` 由 Rust 内部通过 opener 插件执行且只允许 `http:`、`https:`、`mailto:`、`tel:` 外链协议,ICP备案号和资产调试原图等 H5 外链入口在 `native_app` 中优先通过该能力离开主窗口并交给系统浏览器;`navigation.openNativePage` 只接受 `https://app.genarrative.world` 同源 H5 route 并在主窗口内受控跳转,`clipboard.writeText` 由 Rust 内部通过 clipboard-manager 插件写入系统剪贴板并由 H5 复制服务优先调用,`app.setTitle` 通过 Tauri 主窗口 API 同步窗口标题并拒绝空标题 / 控制字符,`app.setBadgeCount` 通过主窗口 `set_badge_count` 设置任务栏角标,数量只接受 `0-99999` 整数且 `0` 表示清除;H5 主站会按当前平台阶段先更新 `document.title`,再通过 `app.setTitle` 把同一标题同步给 Tauri 窗口,Expo 移动壳不声明该能力时静默忽略;不把 opener、clipboard 或 dialog 插件命令直接暴露给前端。当前真实能力为 `host.getRuntime`、`appearance.getColorScheme`、`app.lifecycle`、`share.setTarget`、`share.open`、`navigation.openNativePage`、`app.openExternalUrl`、`app.setTitle`、`app.setBadgeCount`、`clipboard.writeText`、`file.exportText` 和 `file.exportImage`;H5 会在主 App 启动时通过真实 `host.getRuntime` 回读并缓存这些能力,即使入口 URL 缺少 `hostCapabilities`,也只按宿主真实回包开启能力入口;其中 `share.open` 会把直接传入的分享 payload 或 `share.setTarget` 缓存的作品目标整理成非空分享文本并写入系统剪贴板,返回 `copied_to_clipboard`,发布分享弹窗在桌面壳中也通过该能力提供“系统分享”动作;`file.exportText` 通过系统保存对话框让用户选择本地路径,清洗文件名、限制单次文本导出不超过 5 MiB,写入成功后只返回文件名和字节数,不把本机绝对路径暴露给 H5,用户取消返回 `cancelled`;`file.exportImage` 同样通过系统保存对话框写入 H5 生成的图片字节,只接受 `image/png` / `image/jpeg` / `image/webp` base64 数据,单次不超过 5 MiB,分享卡下载会优先走该能力,用户取消返回 `cancelled`。原生系统分享面板、登录和支付未接入真实插件 / 渠道前不声明支持,不返回 mock 成功。
|
当前状态:已新增 `apps/desktop-shell/`,Tauri dev 直接加载本地主站 Vite,release 打包根 `dist` 主站资产。Rust 侧只把 `host_bridge_request` command 授给主窗口,`appearance.getColorScheme` 由 Rust 内部读取主窗口 `theme()` 并返回 `light` / `dark` / `unknown`,不设置或覆盖系统主题;`app.lifecycle` 由主窗口 focus / blur 事件注入 `active` / `inactive` 统一状态,不开放 Tauri event 插件给前端;`network.status` 由 Rust 对 `app.genarrative.world:443` 做短超时 TCP 可达性查询,`network.statusChanged` 由主 WebView 的 `online` / `offline` 事件注入,不开放任意网络探测给 H5;`app.openExternalUrl` 由 Rust 内部通过 opener 插件执行且只允许 `http:`、`https:`、`mailto:`、`tel:` 外链协议,ICP备案号和资产调试原图等 H5 外链入口在 `native_app` 中优先通过该能力离开主窗口并交给系统浏览器;`navigation.openNativePage` 只接受 `https://app.genarrative.world` 同源 H5 route 并在主窗口内受控跳转,`clipboard.writeText` 由 Rust 内部通过 clipboard-manager 插件写入系统剪贴板并由 H5 复制服务优先调用,`app.setTitle` 通过 Tauri 主窗口 API 同步窗口标题并拒绝空标题 / 控制字符,`app.setBadgeCount` 通过主窗口 `set_badge_count` 设置任务栏角标,数量只接受 `0-99999` 整数且 `0` 表示清除;H5 主站会按当前平台阶段先更新 `document.title`,再通过 `app.setTitle` 把同一标题同步给 Tauri 窗口,Expo 移动壳不声明该能力时静默忽略;不把 opener、clipboard 或 dialog 插件命令直接暴露给前端。当前真实能力为 `host.getRuntime`、`appearance.getColorScheme`、`app.lifecycle`、`network.status`、`network.statusChanged`、`share.setTarget`、`share.open`、`navigation.openNativePage`、`app.openExternalUrl`、`app.setTitle`、`app.setBadgeCount`、`clipboard.writeText`、`file.exportText` 和 `file.exportImage`;H5 会在主 App 启动时通过真实 `host.getRuntime` 回读并缓存这些能力,即使入口 URL 缺少 `hostCapabilities`,也只按宿主真实回包开启能力入口;其中 `share.open` 会把直接传入的分享 payload 或 `share.setTarget` 缓存的作品目标整理成非空分享文本并写入系统剪贴板,返回 `copied_to_clipboard`,发布分享弹窗在桌面壳中也通过该能力提供“系统分享”动作;`file.exportText` 通过系统保存对话框让用户选择本地路径,清洗文件名、限制单次文本导出不超过 5 MiB,写入成功后只返回文件名和字节数,不把本机绝对路径暴露给 H5,用户取消返回 `cancelled`;`file.exportImage` 同样通过系统保存对话框写入 H5 生成的图片字节,只接受 `image/png` / `image/jpeg` / `image/webp` base64 数据,单次不超过 5 MiB,分享卡下载会优先走该能力,用户取消返回 `cancelled`。原生系统分享面板、登录和支付未接入真实插件 / 渠道前不声明支持,不返回 mock 成功。
|
||||||
|
|
||||||
### Phase 4:宿主能力扩展
|
### Phase 4:宿主能力扩展
|
||||||
|
|
||||||
|
|||||||
@@ -42,6 +42,7 @@ AI H5 sandbox
|
|||||||
- `getHostRuntime()`:识别 `browser`、`wechat_mini_program`、`native_app`,并解析 `hostCapabilities` 能力声明;进入 `native_app` 后会通过真实 `host.getRuntime` 回读宿主 runtime 并缓存能力清单,未知能力会被丢弃。H5 业务只根据已声明或已回读的能力展示入口、发起宿主请求或走 fallback。
|
- `getHostRuntime()`:识别 `browser`、`wechat_mini_program`、`native_app`,并解析 `hostCapabilities` 能力声明;进入 `native_app` 后会通过真实 `host.getRuntime` 回读宿主 runtime 并缓存能力清单,未知能力会被丢弃。H5 业务只根据已声明或已回读的能力展示入口、发起宿主请求或走 fallback。
|
||||||
- `getHostAppearanceColorScheme()`:原生 App 宿主的受控外观查询入口。H5 可通过 `appearance.getColorScheme` 读取宿主当前 `light` / `dark` / `unknown` 配色模式;Expo 移动壳通过 React Native `Appearance.getColorScheme()` 读取系统偏好,Tauri 桌面壳通过主窗口 `theme()` 读取窗口主题。该能力只读,不改变 H5 主题,也不覆盖用户或系统偏好。
|
- `getHostAppearanceColorScheme()`:原生 App 宿主的受控外观查询入口。H5 可通过 `appearance.getColorScheme` 读取宿主当前 `light` / `dark` / `unknown` 配色模式;Expo 移动壳通过 React Native `Appearance.getColorScheme()` 读取系统偏好,Tauri 桌面壳通过主窗口 `theme()` 读取窗口主题。该能力只读,不改变 H5 主题,也不覆盖用户或系统偏好。
|
||||||
- `subscribeHostAppLifecycle()`:原生 App 宿主的受控生命周期事件入口。Expo 移动壳通过 React Native `AppState` 派发 `app.lifecycle`,Tauri 桌面壳通过主窗口 focus / blur 事件派发同名事件;H5 只依赖统一的 `active` / `inactive` / `background` 状态和 `focused` 布尔值,原生细分状态只放在 `nativeState` 用于排障,不作为业务分支依据。
|
- `subscribeHostAppLifecycle()`:原生 App 宿主的受控生命周期事件入口。Expo 移动壳通过 React Native `AppState` 派发 `app.lifecycle`,Tauri 桌面壳通过主窗口 focus / blur 事件派发同名事件;H5 只依赖统一的 `active` / `inactive` / `background` 状态和 `focused` 布尔值,原生细分状态只放在 `nativeState` 用于排障,不作为业务分支依据。
|
||||||
|
- `getHostNetworkStatus()` / `subscribeHostNetworkStatusChange()`:原生 App 宿主的受控网络状态入口。Expo 移动壳通过 `expo-network` 查询并订阅真实系统网络状态;Tauri 桌面壳通过短超时连接 `app.genarrative.world:443` 查询主站可达性,并在主 WebView 内监听 `online` / `offline` 注入变化事件。H5 只依赖统一的 `isConnected`、`isInternetReachable` 和连接类型,不直接读取平台私有网络 API。
|
||||||
- `requestHostLogin()`:微信小程序跳转原生登录页;浏览器返回 `false`,由 H5 登录弹窗承接。
|
- `requestHostLogin()`:微信小程序跳转原生登录页;浏览器返回 `false`,由 H5 登录弹窗承接。
|
||||||
- `requestHostPayment()`:微信小程序支付跳转原生支付页;其它渠道返回 `false`,继续走 H5 / Native 二维码。
|
- `requestHostPayment()`:微信小程序支付跳转原生支付页;其它渠道返回 `false`,继续走 H5 / Native 二维码。
|
||||||
- `setHostShareTarget()`:把当前公开作品分享目标同步给宿主。
|
- `setHostShareTarget()`:把当前公开作品分享目标同步给宿主。
|
||||||
|
|||||||
17
package-lock.json
generated
17
package-lock.json
generated
@@ -20,6 +20,7 @@
|
|||||||
"expo-file-system": "^56.0.8",
|
"expo-file-system": "^56.0.8",
|
||||||
"expo-haptics": "^56.0.3",
|
"expo-haptics": "^56.0.3",
|
||||||
"expo-linking": "^56.0.14",
|
"expo-linking": "^56.0.14",
|
||||||
|
"expo-network": "^56.0.5",
|
||||||
"expo-sharing": "^56.0.18",
|
"expo-sharing": "^56.0.18",
|
||||||
"expo-status-bar": "^56.0.4",
|
"expo-status-bar": "^56.0.4",
|
||||||
"lucide-react": "^0.546.0",
|
"lucide-react": "^0.546.0",
|
||||||
@@ -6444,6 +6445,16 @@
|
|||||||
"react-native": "*"
|
"react-native": "*"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/expo-network": {
|
||||||
|
"version": "56.0.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/expo-network/-/expo-network-56.0.5.tgz",
|
||||||
|
"integrity": "sha512-zmuyO95jayDY9jyUfOAlNp9XXJrJaAOkBXXLy0TS/nh2kppj7CHirRPkQ/tf0rsxhIL3AEd9nsRTiPtNsGT9Lw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"peerDependencies": {
|
||||||
|
"expo": "*",
|
||||||
|
"react": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/expo-server": {
|
"node_modules/expo-server": {
|
||||||
"version": "56.0.5",
|
"version": "56.0.5",
|
||||||
"resolved": "https://registry.npmjs.org/expo-server/-/expo-server-56.0.5.tgz",
|
"resolved": "https://registry.npmjs.org/expo-server/-/expo-server-56.0.5.tgz",
|
||||||
@@ -17320,6 +17331,12 @@
|
|||||||
"integrity": "sha512-fHZcFpYO/o62GYa6fJyAQJZcAShzhoN0iMMDzbr7vD3ewET6e1vAlTonbEakN9F0VHEgBFJ4NREy87uwVcpCuA==",
|
"integrity": "sha512-fHZcFpYO/o62GYa6fJyAQJZcAShzhoN0iMMDzbr7vD3ewET6e1vAlTonbEakN9F0VHEgBFJ4NREy87uwVcpCuA==",
|
||||||
"requires": {}
|
"requires": {}
|
||||||
},
|
},
|
||||||
|
"expo-network": {
|
||||||
|
"version": "56.0.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/expo-network/-/expo-network-56.0.5.tgz",
|
||||||
|
"integrity": "sha512-zmuyO95jayDY9jyUfOAlNp9XXJrJaAOkBXXLy0TS/nh2kppj7CHirRPkQ/tf0rsxhIL3AEd9nsRTiPtNsGT9Lw==",
|
||||||
|
"requires": {}
|
||||||
|
},
|
||||||
"expo-server": {
|
"expo-server": {
|
||||||
"version": "56.0.5",
|
"version": "56.0.5",
|
||||||
"resolved": "https://registry.npmjs.org/expo-server/-/expo-server-56.0.5.tgz",
|
"resolved": "https://registry.npmjs.org/expo-server/-/expo-server-56.0.5.tgz",
|
||||||
|
|||||||
@@ -90,6 +90,7 @@
|
|||||||
"expo-file-system": "^56.0.8",
|
"expo-file-system": "^56.0.8",
|
||||||
"expo-haptics": "^56.0.3",
|
"expo-haptics": "^56.0.3",
|
||||||
"expo-linking": "^56.0.14",
|
"expo-linking": "^56.0.14",
|
||||||
|
"expo-network": "^56.0.5",
|
||||||
"expo-sharing": "^56.0.18",
|
"expo-sharing": "^56.0.18",
|
||||||
"expo-status-bar": "^56.0.4",
|
"expo-status-bar": "^56.0.4",
|
||||||
"lucide-react": "^0.546.0",
|
"lucide-react": "^0.546.0",
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
isHostBridgeCapability,
|
isHostBridgeCapability,
|
||||||
normalizeHostBridgeBadgeCount,
|
normalizeHostBridgeBadgeCount,
|
||||||
normalizeHostBridgeColorScheme,
|
normalizeHostBridgeColorScheme,
|
||||||
|
normalizeHostBridgeConnectionType,
|
||||||
normalizeHostBridgeExportFileName,
|
normalizeHostBridgeExportFileName,
|
||||||
normalizeHostBridgeExternalUrl,
|
normalizeHostBridgeExternalUrl,
|
||||||
normalizeHostBridgeLifecycleState,
|
normalizeHostBridgeLifecycleState,
|
||||||
@@ -51,6 +52,8 @@ describe('HostBridge shared contract helpers', () => {
|
|||||||
expect(isHostBridgeCapability('appearance.getColorScheme')).toBe(true);
|
expect(isHostBridgeCapability('appearance.getColorScheme')).toBe(true);
|
||||||
expect(isHostBridgeCapability('share.open')).toBe(true);
|
expect(isHostBridgeCapability('share.open')).toBe(true);
|
||||||
expect(isHostBridgeCapability('app.lifecycle')).toBe(true);
|
expect(isHostBridgeCapability('app.lifecycle')).toBe(true);
|
||||||
|
expect(isHostBridgeCapability('network.status')).toBe(true);
|
||||||
|
expect(isHostBridgeCapability('network.statusChanged')).toBe(true);
|
||||||
expect(isHostBridgeCapability('app.setBadgeCount')).toBe(true);
|
expect(isHostBridgeCapability('app.setBadgeCount')).toBe(true);
|
||||||
expect(isHostBridgeCapability('navigation.canGoBack')).toBe(true);
|
expect(isHostBridgeCapability('navigation.canGoBack')).toBe(true);
|
||||||
expect(isHostBridgeCapability('unknown.capability')).toBe(false);
|
expect(isHostBridgeCapability('unknown.capability')).toBe(false);
|
||||||
@@ -80,4 +83,13 @@ describe('HostBridge shared contract helpers', () => {
|
|||||||
expect(normalizeHostBridgeLifecycleState('extension')).toBe('inactive');
|
expect(normalizeHostBridgeLifecycleState('extension')).toBe('inactive');
|
||||||
expect(normalizeHostBridgeLifecycleState(null)).toBe('inactive');
|
expect(normalizeHostBridgeLifecycleState(null)).toBe('inactive');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('归一化宿主网络连接类型', () => {
|
||||||
|
expect(normalizeHostBridgeConnectionType('WIFI')).toBe('wifi');
|
||||||
|
expect(normalizeHostBridgeConnectionType('CELLULAR')).toBe('cellular');
|
||||||
|
expect(normalizeHostBridgeConnectionType('ETHERNET')).toBe('ethernet');
|
||||||
|
expect(normalizeHostBridgeConnectionType('NONE')).toBe('none');
|
||||||
|
expect(normalizeHostBridgeConnectionType('satellite')).toBe('unknown');
|
||||||
|
expect(normalizeHostBridgeConnectionType(null)).toBe('unknown');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ export const HOST_BRIDGE_METHODS = [
|
|||||||
'app.openExternalUrl',
|
'app.openExternalUrl',
|
||||||
'app.setTitle',
|
'app.setTitle',
|
||||||
'app.setBadgeCount',
|
'app.setBadgeCount',
|
||||||
|
'network.status',
|
||||||
'clipboard.writeText',
|
'clipboard.writeText',
|
||||||
'file.exportText',
|
'file.exportText',
|
||||||
'file.exportImage',
|
'file.exportImage',
|
||||||
@@ -36,6 +37,7 @@ export const HOST_BRIDGE_CAPABILITIES = [
|
|||||||
...HOST_BRIDGE_METHODS,
|
...HOST_BRIDGE_METHODS,
|
||||||
'host.events',
|
'host.events',
|
||||||
'app.lifecycle',
|
'app.lifecycle',
|
||||||
|
'network.statusChanged',
|
||||||
'navigation.canGoBack',
|
'navigation.canGoBack',
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
@@ -120,6 +122,49 @@ export function normalizeHostBridgeLifecycleState(
|
|||||||
: 'inactive';
|
: 'inactive';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type HostNetworkConnectionType =
|
||||||
|
| 'none'
|
||||||
|
| 'unknown'
|
||||||
|
| 'cellular'
|
||||||
|
| 'wifi'
|
||||||
|
| 'ethernet'
|
||||||
|
| 'bluetooth'
|
||||||
|
| 'vpn'
|
||||||
|
| 'other';
|
||||||
|
|
||||||
|
export type NetworkStatusResult = {
|
||||||
|
isConnected: boolean;
|
||||||
|
isInternetReachable: boolean | null;
|
||||||
|
connectionType: HostNetworkConnectionType;
|
||||||
|
nativeType?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function normalizeHostBridgeConnectionType(
|
||||||
|
rawConnectionType: unknown,
|
||||||
|
): HostNetworkConnectionType {
|
||||||
|
if (typeof rawConnectionType !== 'string') {
|
||||||
|
return 'unknown';
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizedType = rawConnectionType.toLowerCase();
|
||||||
|
if (
|
||||||
|
normalizedType === 'none' ||
|
||||||
|
normalizedType === 'cellular' ||
|
||||||
|
normalizedType === 'wifi' ||
|
||||||
|
normalizedType === 'ethernet' ||
|
||||||
|
normalizedType === 'bluetooth' ||
|
||||||
|
normalizedType === 'vpn'
|
||||||
|
) {
|
||||||
|
return normalizedType;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (normalizedType === 'other') {
|
||||||
|
return 'other';
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'unknown';
|
||||||
|
}
|
||||||
|
|
||||||
export type HostAppearanceColorScheme = 'light' | 'dark' | 'unknown';
|
export type HostAppearanceColorScheme = 'light' | 'dark' | 'unknown';
|
||||||
|
|
||||||
export type AppearanceColorSchemeResult = {
|
export type AppearanceColorSchemeResult = {
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
exportHostImageFile,
|
exportHostImageFile,
|
||||||
exportHostTextFile,
|
exportHostTextFile,
|
||||||
getHostAppearanceColorScheme,
|
getHostAppearanceColorScheme,
|
||||||
|
getHostNetworkStatus,
|
||||||
getHostRuntime,
|
getHostRuntime,
|
||||||
getNativeAppHostRuntime,
|
getNativeAppHostRuntime,
|
||||||
isWechatMiniProgramWebViewRuntime,
|
isWechatMiniProgramWebViewRuntime,
|
||||||
@@ -30,6 +31,7 @@ import {
|
|||||||
setHostAppTitle,
|
setHostAppTitle,
|
||||||
setHostShareTarget,
|
setHostShareTarget,
|
||||||
subscribeHostAppLifecycle,
|
subscribeHostAppLifecycle,
|
||||||
|
subscribeHostNetworkStatusChange,
|
||||||
subscribeHostRuntimeChange,
|
subscribeHostRuntimeChange,
|
||||||
writeHostClipboardText,
|
writeHostClipboardText,
|
||||||
} from './hostBridge';
|
} from './hostBridge';
|
||||||
@@ -217,6 +219,78 @@ describe('hostBridge', () => {
|
|||||||
expect(listener).not.toHaveBeenCalled();
|
expect(listener).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('查询并订阅原生 App 网络状态', async () => {
|
||||||
|
const invoke = vi.fn(
|
||||||
|
async (_command: string, args?: Record<string, unknown>) => {
|
||||||
|
const request = (args as { request: { id: string; method: string } })
|
||||||
|
.request;
|
||||||
|
return {
|
||||||
|
bridge: 'GenarrativeHostBridge',
|
||||||
|
version: 1,
|
||||||
|
id: request.id,
|
||||||
|
ok: true,
|
||||||
|
result: {
|
||||||
|
isConnected: true,
|
||||||
|
isInternetReachable: false,
|
||||||
|
connectionType: 'WIFI',
|
||||||
|
nativeType: 'WIFI',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const listener = vi.fn();
|
||||||
|
window.history.replaceState(
|
||||||
|
null,
|
||||||
|
'',
|
||||||
|
nativeAppPath(['network.status', 'network.statusChanged']),
|
||||||
|
);
|
||||||
|
window.ReactNativeWebView = {
|
||||||
|
postMessage: vi.fn(),
|
||||||
|
};
|
||||||
|
window.__TAURI__ = {
|
||||||
|
core: {
|
||||||
|
invoke: asTauriInvoke(invoke),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
await expect(getHostNetworkStatus()).resolves.toEqual({
|
||||||
|
isConnected: true,
|
||||||
|
isInternetReachable: false,
|
||||||
|
connectionType: 'wifi',
|
||||||
|
nativeType: 'WIFI',
|
||||||
|
});
|
||||||
|
|
||||||
|
const unsubscribe = subscribeHostNetworkStatusChange(listener);
|
||||||
|
window.dispatchEvent(
|
||||||
|
new MessageEvent('message', {
|
||||||
|
data: JSON.stringify({
|
||||||
|
bridge: 'GenarrativeHostBridge',
|
||||||
|
version: 1,
|
||||||
|
event: 'network.statusChanged',
|
||||||
|
payload: {
|
||||||
|
isConnected: false,
|
||||||
|
isInternetReachable: false,
|
||||||
|
connectionType: 'NONE',
|
||||||
|
nativeType: 'NONE',
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
unsubscribe();
|
||||||
|
|
||||||
|
expect(listener).toHaveBeenCalledWith({
|
||||||
|
isConnected: false,
|
||||||
|
isInternetReachable: false,
|
||||||
|
connectionType: 'none',
|
||||||
|
nativeType: 'NONE',
|
||||||
|
});
|
||||||
|
expect(invoke).toHaveBeenCalledWith('host_bridge_request', {
|
||||||
|
request: expect.objectContaining({
|
||||||
|
method: 'network.status',
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
test('从真实宿主 runtime 回读能力并通知订阅者', async () => {
|
test('从真实宿主 runtime 回读能力并通知订阅者', async () => {
|
||||||
const listener = vi.fn();
|
const listener = vi.fn();
|
||||||
const unsubscribe = subscribeHostRuntimeChange(listener);
|
const unsubscribe = subscribeHostRuntimeChange(listener);
|
||||||
@@ -510,6 +584,13 @@ describe('hostBridge', () => {
|
|||||||
}
|
}
|
||||||
: request.method === 'appearance.getColorScheme'
|
: request.method === 'appearance.getColorScheme'
|
||||||
? { colorScheme: 'dark' }
|
? { colorScheme: 'dark' }
|
||||||
|
: request.method === 'network.status'
|
||||||
|
? {
|
||||||
|
isConnected: true,
|
||||||
|
isInternetReachable: true,
|
||||||
|
connectionType: 'ethernet',
|
||||||
|
nativeType: 'online',
|
||||||
|
}
|
||||||
: true,
|
: true,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
@@ -527,6 +608,7 @@ describe('hostBridge', () => {
|
|||||||
'app.openExternalUrl',
|
'app.openExternalUrl',
|
||||||
'app.setTitle',
|
'app.setTitle',
|
||||||
'app.setBadgeCount',
|
'app.setBadgeCount',
|
||||||
|
'network.status',
|
||||||
'share.open',
|
'share.open',
|
||||||
'file.exportImage',
|
'file.exportImage',
|
||||||
]),
|
]),
|
||||||
@@ -565,6 +647,12 @@ describe('hostBridge', () => {
|
|||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
await expect(setHostAppBadgeCount({ count: 7 })).resolves.toBe(true);
|
await expect(setHostAppBadgeCount({ count: 7 })).resolves.toBe(true);
|
||||||
|
await expect(getHostNetworkStatus()).resolves.toEqual({
|
||||||
|
isConnected: true,
|
||||||
|
isInternetReachable: true,
|
||||||
|
connectionType: 'ethernet',
|
||||||
|
nativeType: 'online',
|
||||||
|
});
|
||||||
await expect(
|
await expect(
|
||||||
openHostShare({
|
openHostShare({
|
||||||
title: '暖灯猫街',
|
title: '暖灯猫街',
|
||||||
@@ -645,6 +733,11 @@ describe('hostBridge', () => {
|
|||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
expect(invoke).toHaveBeenCalledWith('host_bridge_request', {
|
||||||
|
request: expect.objectContaining({
|
||||||
|
method: 'network.status',
|
||||||
|
}),
|
||||||
|
});
|
||||||
expect(invoke).toHaveBeenCalledWith('host_bridge_request', {
|
expect(invoke).toHaveBeenCalledWith('host_bridge_request', {
|
||||||
request: expect.objectContaining({
|
request: expect.objectContaining({
|
||||||
method: 'share.open',
|
method: 'share.open',
|
||||||
@@ -716,6 +809,7 @@ describe('hostBridge', () => {
|
|||||||
await expect(setHostAppBadgeCount({ count: 1 })).resolves.toBe(false);
|
await expect(setHostAppBadgeCount({ count: 1 })).resolves.toBe(false);
|
||||||
await expect(setHostAppBadgeCount({ count: -1 })).resolves.toBe(false);
|
await expect(setHostAppBadgeCount({ count: -1 })).resolves.toBe(false);
|
||||||
await expect(setHostAppBadgeCount({ count: 1.5 })).resolves.toBe(false);
|
await expect(setHostAppBadgeCount({ count: 1.5 })).resolves.toBe(false);
|
||||||
|
await expect(getHostNetworkStatus()).resolves.toBe(false);
|
||||||
await expect(
|
await expect(
|
||||||
openHostShare({
|
openHostShare({
|
||||||
title: '暖灯猫街',
|
title: '暖灯猫街',
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import type {
|
|||||||
HostBridgeCapability,
|
HostBridgeCapability,
|
||||||
HostBridgeMethod,
|
HostBridgeMethod,
|
||||||
HostBridgeRuntimeResult,
|
HostBridgeRuntimeResult,
|
||||||
|
NetworkStatusResult,
|
||||||
OpenExternalUrlPayload,
|
OpenExternalUrlPayload,
|
||||||
SetBadgeCountPayload,
|
SetBadgeCountPayload,
|
||||||
ShareOpenPayload,
|
ShareOpenPayload,
|
||||||
@@ -17,6 +18,7 @@ import {
|
|||||||
isHostBridgeCapability,
|
isHostBridgeCapability,
|
||||||
normalizeHostBridgeBadgeCount,
|
normalizeHostBridgeBadgeCount,
|
||||||
normalizeHostBridgeColorScheme,
|
normalizeHostBridgeColorScheme,
|
||||||
|
normalizeHostBridgeConnectionType,
|
||||||
normalizeHostBridgeExternalUrl,
|
normalizeHostBridgeExternalUrl,
|
||||||
normalizeHostBridgeLifecycleState,
|
normalizeHostBridgeLifecycleState,
|
||||||
} from '../../../packages/shared/src/contracts/hostBridge';
|
} from '../../../packages/shared/src/contracts/hostBridge';
|
||||||
@@ -104,6 +106,8 @@ export type HostAppearanceColorSchemeSnapshot = AppearanceColorSchemeResult;
|
|||||||
|
|
||||||
export type HostAppLifecycleSnapshot = AppLifecycleEventPayload;
|
export type HostAppLifecycleSnapshot = AppLifecycleEventPayload;
|
||||||
|
|
||||||
|
export type HostNetworkStatusSnapshot = NetworkStatusResult;
|
||||||
|
|
||||||
const HOST_RUNTIME_REFRESH_TIMEOUT_MS = 3000;
|
const HOST_RUNTIME_REFRESH_TIMEOUT_MS = 3000;
|
||||||
|
|
||||||
let cachedNativeHostRuntime: HostBridgeRuntimeResult | null = null;
|
let cachedNativeHostRuntime: HostBridgeRuntimeResult | null = null;
|
||||||
@@ -815,3 +819,56 @@ export function subscribeHostAppLifecycle(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function normalizeHostNetworkStatus(
|
||||||
|
payload: NetworkStatusResult | null | undefined,
|
||||||
|
): HostNetworkStatusSnapshot {
|
||||||
|
const connectionType = normalizeHostBridgeConnectionType(
|
||||||
|
payload?.connectionType ?? payload?.nativeType,
|
||||||
|
);
|
||||||
|
const isConnected =
|
||||||
|
typeof payload?.isConnected === 'boolean'
|
||||||
|
? payload.isConnected
|
||||||
|
: connectionType !== 'none' && connectionType !== 'unknown';
|
||||||
|
|
||||||
|
return {
|
||||||
|
isConnected,
|
||||||
|
isInternetReachable:
|
||||||
|
typeof payload?.isInternetReachable === 'boolean'
|
||||||
|
? payload.isInternetReachable
|
||||||
|
: null,
|
||||||
|
connectionType,
|
||||||
|
...(typeof payload?.nativeType === 'string'
|
||||||
|
? { nativeType: payload.nativeType }
|
||||||
|
: {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getHostNetworkStatus() {
|
||||||
|
if (!canUseNativeHostCapability('network.status')) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
return normalizeHostNetworkStatus(
|
||||||
|
await requestNativeAppHostBridge<NetworkStatusResult>('network.status'),
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function subscribeHostNetworkStatusChange(
|
||||||
|
listener: (payload: HostNetworkStatusSnapshot) => void,
|
||||||
|
) {
|
||||||
|
if (!canUseNativeHostCapability('network.statusChanged')) {
|
||||||
|
return () => undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
return subscribeNativeAppHostBridgeEvent<NetworkStatusResult>(
|
||||||
|
'network.statusChanged',
|
||||||
|
(payload) => {
|
||||||
|
listener(normalizeHostNetworkStatus(payload));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user