接入原生壳分享卡图片导出
新增 file.exportImage 宿主能力契约 分享卡下载在原生壳中优先走宿主图片导出 Expo 壳写入缓存图片并调用系统分享保存 Tauri 壳通过保存对话框写入图片字节 补齐能力漂移检查、测试和架构文档
This commit is contained in:
@@ -139,9 +139,11 @@ const requiredMainSnippets = [
|
||||
'"app.setTitle"',
|
||||
'"clipboard.writeText"',
|
||||
'"file.exportText"',
|
||||
'"file.exportImage"',
|
||||
'tauri_plugin_dialog::init()',
|
||||
'"copied_to_clipboard"',
|
||||
'"file export cancelled"',
|
||||
'BASE64_STANDARD.decode',
|
||||
'set_title',
|
||||
];
|
||||
|
||||
|
||||
1
apps/desktop-shell/src-tauri/Cargo.lock
generated
1
apps/desktop-shell/src-tauri/Cargo.lock
generated
@@ -1277,6 +1277,7 @@ dependencies = [
|
||||
name = "genarrative-desktop-shell"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
|
||||
@@ -8,6 +8,7 @@ publish = false
|
||||
tauri-build = { version = "2.6.2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
base64 = "0.22"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tauri = { version = "2.11.2", features = [] }
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use base64::{engine::general_purpose::STANDARD as BASE64_STANDARD, Engine as _};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use std::fs;
|
||||
@@ -14,6 +15,7 @@ const HOST_BRIDGE_VERSION: u8 = 1;
|
||||
const WEB_APP_ORIGIN: &str = "https://app.genarrative.world";
|
||||
const EXTERNAL_URL_PROTOCOLS: [&str; 4] = ["http:", "https:", "mailto:", "tel:"];
|
||||
const EXPORT_TEXT_MAX_BYTES: usize = 5 * 1024 * 1024;
|
||||
const EXPORT_IMAGE_MAX_BYTES: usize = 5 * 1024 * 1024;
|
||||
const EXPORT_FILE_NAME_FALLBACK: &str = "genarrative-export.txt";
|
||||
const EXPORT_FILE_NAME_MAX_LENGTH: usize = 120;
|
||||
|
||||
@@ -83,6 +85,7 @@ fn capabilities() -> Vec<&'static str> {
|
||||
"app.setTitle",
|
||||
"clipboard.writeText",
|
||||
"file.exportText",
|
||||
"file.exportImage",
|
||||
]
|
||||
}
|
||||
|
||||
@@ -271,6 +274,83 @@ fn write_export_text_file(path: PathBuf, content: String) -> Result<usize, Strin
|
||||
Ok(content.len())
|
||||
}
|
||||
|
||||
fn export_image_extension(mime_type: &str) -> Option<&'static str> {
|
||||
match mime_type {
|
||||
"image/png" => Some("png"),
|
||||
"image/jpeg" => Some("jpg"),
|
||||
"image/webp" => Some("webp"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_export_image_file_name(raw_file_name: &str, mime_type: &str) -> String {
|
||||
let mut file_name = normalize_export_file_name(raw_file_name);
|
||||
let extension = export_image_extension(mime_type).unwrap_or("png");
|
||||
if !file_name.to_ascii_lowercase().ends_with(&format!(".{}", extension)) {
|
||||
file_name.push('.');
|
||||
file_name.push_str(extension);
|
||||
}
|
||||
file_name
|
||||
}
|
||||
|
||||
fn export_image_payload(
|
||||
request: &HostBridgeRequest,
|
||||
) -> Result<(String, Vec<u8>), HostBridgeResponse> {
|
||||
let payload = request.payload.as_ref().ok_or_else(|| {
|
||||
failed(
|
||||
request.id.clone(),
|
||||
"invalid_request",
|
||||
"fileName, mimeType and base64Data are required",
|
||||
)
|
||||
})?;
|
||||
let mime_type = payload
|
||||
.get("mimeType")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| failed(request.id.clone(), "invalid_request", "mimeType is required"))?;
|
||||
if export_image_extension(mime_type).is_none() {
|
||||
return Err(failed(
|
||||
request.id.clone(),
|
||||
"invalid_request",
|
||||
"mimeType must be an allowed image type",
|
||||
));
|
||||
}
|
||||
|
||||
let base64_data = payload
|
||||
.get("base64Data")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.ok_or_else(|| failed(request.id.clone(), "invalid_request", "base64Data is required"))?;
|
||||
let bytes = BASE64_STANDARD.decode(base64_data).map_err(|_| {
|
||||
failed(
|
||||
request.id.clone(),
|
||||
"invalid_request",
|
||||
"base64Data is invalid",
|
||||
)
|
||||
})?;
|
||||
if bytes.len() > EXPORT_IMAGE_MAX_BYTES {
|
||||
return Err(failed(
|
||||
request.id.clone(),
|
||||
"invalid_request",
|
||||
"image exceeds file export size limit",
|
||||
));
|
||||
}
|
||||
|
||||
let file_name = payload
|
||||
.get("fileName")
|
||||
.and_then(Value::as_str)
|
||||
.map(|file_name| normalize_export_image_file_name(file_name, mime_type))
|
||||
.unwrap_or_else(|| normalize_export_image_file_name("genarrative-share-card", mime_type));
|
||||
|
||||
Ok((file_name, bytes))
|
||||
}
|
||||
|
||||
fn write_export_bytes_file(path: PathBuf, bytes: Vec<u8>) -> Result<usize, String> {
|
||||
let byte_count = bytes.len();
|
||||
fs::write(path, bytes).map_err(|error| error.to_string())?;
|
||||
Ok(byte_count)
|
||||
}
|
||||
|
||||
fn payload_string<'a>(value: &'a Value, field: &str) -> Option<&'a str> {
|
||||
value
|
||||
.get(field)
|
||||
@@ -468,6 +548,41 @@ async fn host_bridge_request(
|
||||
}),
|
||||
)
|
||||
}
|
||||
"file.exportImage" => {
|
||||
let (file_name, bytes) = match export_image_payload(&request) {
|
||||
Ok(payload) => payload,
|
||||
Err(response) => return response,
|
||||
};
|
||||
let file_path = app
|
||||
.dialog()
|
||||
.file()
|
||||
.add_filter("Image", &["png", "jpg", "jpeg", "webp"])
|
||||
.set_file_name(file_name.clone())
|
||||
.blocking_save_file();
|
||||
let Some(file_path) = file_path else {
|
||||
return failed(request.id, "cancelled", "file export cancelled");
|
||||
};
|
||||
let path = match file_path.into_path() {
|
||||
Ok(path) => path,
|
||||
Err(error) => return failed(request.id, "host_error", error.to_string()),
|
||||
};
|
||||
let export_result =
|
||||
tauri::async_runtime::spawn_blocking(move || write_export_bytes_file(path, bytes))
|
||||
.await;
|
||||
let byte_count = match export_result {
|
||||
Ok(Ok(byte_count)) => byte_count,
|
||||
Ok(Err(error)) => return failed(request.id, "host_error", error),
|
||||
Err(error) => return failed(request.id, "host_error", error.to_string()),
|
||||
};
|
||||
ok(
|
||||
request.id,
|
||||
json!({
|
||||
"action": "saved",
|
||||
"fileName": file_name,
|
||||
"bytes": byte_count,
|
||||
}),
|
||||
)
|
||||
}
|
||||
"app.setTitle" => {
|
||||
let title = match required_string_payload(&request, "title")
|
||||
.ok()
|
||||
@@ -586,6 +701,10 @@ mod tests {
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!("file.exportText")));
|
||||
assert!(result["capabilities"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!("file.exportImage")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -756,6 +875,71 @@ mod tests {
|
||||
fs::remove_file(path).expect("remove export file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_image_payload_decodes_allowed_image_base64() {
|
||||
let mut valid = request("file.exportImage");
|
||||
valid.payload = Some(json!({
|
||||
"fileName": "分享:卡?.png",
|
||||
"base64Data": "c2hhcmUtY2FyZA==",
|
||||
"mimeType": "image/png"
|
||||
}));
|
||||
|
||||
let (file_name, bytes) = export_image_payload(&valid).expect("image payload");
|
||||
|
||||
assert_eq!(file_name, "分享-卡-.png");
|
||||
assert_eq!(bytes, b"share-card");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_image_payload_rejects_invalid_mime_and_base64() {
|
||||
let mut invalid_mime = request("file.exportImage");
|
||||
invalid_mime.payload = Some(json!({
|
||||
"fileName": "分享卡.txt",
|
||||
"base64Data": "c2hhcmUtY2FyZA==",
|
||||
"mimeType": "text/plain"
|
||||
}));
|
||||
let response = export_image_payload(&invalid_mime).expect_err("invalid mime");
|
||||
assert_eq!(response.error.expect("error").code, "invalid_request");
|
||||
|
||||
let mut invalid_base64 = request("file.exportImage");
|
||||
invalid_base64.payload = Some(json!({
|
||||
"fileName": "分享卡.png",
|
||||
"base64Data": "not base64!",
|
||||
"mimeType": "image/png"
|
||||
}));
|
||||
let response = export_image_payload(&invalid_base64).expect_err("invalid base64");
|
||||
assert_eq!(response.error.expect("error").message, "base64Data is invalid");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_image_payload_rejects_oversized_image() {
|
||||
let mut invalid = request("file.exportImage");
|
||||
invalid.payload = Some(json!({
|
||||
"fileName": "分享卡.png",
|
||||
"base64Data": BASE64_STANDARD.encode(vec![1u8; EXPORT_IMAGE_MAX_BYTES + 1]),
|
||||
"mimeType": "image/png"
|
||||
}));
|
||||
|
||||
let response = export_image_payload(&invalid).expect_err("oversized image");
|
||||
|
||||
assert_eq!(response.error.expect("error").message, "image exceeds file export size limit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_export_bytes_file_persists_binary_content() {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"genarrative-host-bridge-share-card-{}.png",
|
||||
std::process::id()
|
||||
));
|
||||
|
||||
let bytes = write_export_bytes_file(path.clone(), vec![0x89, b'P', b'N', b'G'])
|
||||
.expect("write image file");
|
||||
|
||||
assert_eq!(bytes, 4);
|
||||
assert_eq!(fs::read(&path).expect("read image file"), vec![0x89, b'P', b'N', b'G']);
|
||||
fs::remove_file(path).expect("remove image file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn share_text_uses_direct_share_payload() {
|
||||
let state = DesktopShareState::default();
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"build": {
|
||||
"beforeDevCommand": "npm --prefix ../.. run dev:web",
|
||||
"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,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,clipboard.writeText,file.exportText",
|
||||
"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,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,clipboard.writeText,file.exportText,file.exportImage",
|
||||
"frontendDist": "../../../dist"
|
||||
},
|
||||
"app": {
|
||||
@@ -14,7 +14,7 @@
|
||||
{
|
||||
"create": false,
|
||||
"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,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,clipboard.writeText,file.exportText",
|
||||
"url": "index.html?clientRuntime=native_app&clientType=native_app&hostShell=tauri_desktop&hostPlatform=unknown&hostVersion=0.1.0&bridgeVersion=1&hostCapabilities=host.getRuntime,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,clipboard.writeText,file.exportText,file.exportImage",
|
||||
"title": "Genarrative",
|
||||
"width": 1280,
|
||||
"height": 820,
|
||||
|
||||
@@ -118,8 +118,10 @@ for (const dependency of ['expo-file-system', 'expo-sharing']) {
|
||||
|
||||
for (const snippet of [
|
||||
'file.exportText',
|
||||
'file.exportImage',
|
||||
'Sharing.shareAsync',
|
||||
'normalizeHostBridgeExportFileName',
|
||||
'base64Data',
|
||||
]) {
|
||||
if (!bridgeSource.includes(snippet)) {
|
||||
throw new Error(`mobile shell HostBridge missing ${snippet}`);
|
||||
@@ -140,6 +142,7 @@ for (const capability of [
|
||||
'app.openExternalUrl',
|
||||
'clipboard.writeText',
|
||||
'file.exportText',
|
||||
'file.exportImage',
|
||||
'haptics.impact',
|
||||
]) {
|
||||
if (!mobileCapabilitySet.has(capability)) {
|
||||
|
||||
@@ -22,7 +22,12 @@ vi.mock('expo-clipboard', () => ({
|
||||
}));
|
||||
|
||||
const writtenFiles = vi.hoisted(
|
||||
() => [] as { uri: string; content: string }[],
|
||||
() =>
|
||||
[] as {
|
||||
uri: string;
|
||||
content: string;
|
||||
options?: { encoding?: 'utf8' | 'base64' };
|
||||
}[],
|
||||
);
|
||||
|
||||
vi.mock('expo-file-system', () => ({
|
||||
@@ -36,10 +41,11 @@ vi.mock('expo-file-system', () => ({
|
||||
this.uri = `file:///cache/${fileName}`;
|
||||
}
|
||||
|
||||
write(content: string) {
|
||||
write(content: string, options?: { encoding?: 'utf8' | 'base64' }) {
|
||||
writtenFiles.push({
|
||||
uri: this.uri,
|
||||
content,
|
||||
options,
|
||||
});
|
||||
}
|
||||
},
|
||||
@@ -309,6 +315,7 @@ describe('handleMobileHostBridgeMessage', () => {
|
||||
{
|
||||
uri: 'file:///cache/作品-记录-.txt',
|
||||
content: '暖灯猫街',
|
||||
options: undefined,
|
||||
},
|
||||
]);
|
||||
expect(Sharing.shareAsync).toHaveBeenCalledWith(
|
||||
@@ -352,4 +359,61 @@ describe('handleMobileHostBridgeMessage', () => {
|
||||
expect(writtenFiles).toEqual([]);
|
||||
expect(Sharing.shareAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('file.exportImage 写入缓存图片并调起系统分享', async () => {
|
||||
const response = await send(
|
||||
request('file.exportImage', {
|
||||
fileName: ' ../分享:卡?.png ',
|
||||
base64Data: 'c2hhcmUtY2FyZA==',
|
||||
mimeType: 'image/png',
|
||||
}),
|
||||
);
|
||||
|
||||
const okResponse = expectOk(response);
|
||||
|
||||
expect(okResponse.result).toEqual({
|
||||
action: 'saved',
|
||||
fileName: '分享-卡-.png',
|
||||
bytes: 10,
|
||||
});
|
||||
expect(writtenFiles).toEqual([
|
||||
{
|
||||
uri: 'file:///cache/分享-卡-.png',
|
||||
content: 'c2hhcmUtY2FyZA==',
|
||||
options: { encoding: 'base64' },
|
||||
},
|
||||
]);
|
||||
expect(Sharing.shareAsync).toHaveBeenCalledWith(
|
||||
'file:///cache/分享-卡-.png',
|
||||
{
|
||||
mimeType: 'image/png',
|
||||
UTI: 'public.png',
|
||||
dialogTitle: '分享-卡-.png',
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('file.exportImage 拒绝非图片 MIME 与超限内容', async () => {
|
||||
const unsupportedMime = await send(
|
||||
request('file.exportImage', {
|
||||
fileName: '分享卡.txt',
|
||||
base64Data: 'c2hhcmUtY2FyZA==',
|
||||
mimeType: 'text/plain',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(expectFailed(unsupportedMime).error.code).toBe('invalid_request');
|
||||
|
||||
const oversized = await send(
|
||||
request('file.exportImage', {
|
||||
fileName: '分享卡.png',
|
||||
base64Data: `${'A'.repeat(7 * 1024 * 1024)}`,
|
||||
mimeType: 'image/png',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(expectFailed(oversized).error.code).toBe('invalid_request');
|
||||
expect(writtenFiles).toEqual([]);
|
||||
expect(Sharing.shareAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,6 +7,8 @@ import { Platform, Share } from 'react-native';
|
||||
|
||||
import {
|
||||
type ClipboardWriteTextPayload,
|
||||
type FileExportImagePayload,
|
||||
type FileExportImageResult,
|
||||
type FileExportTextPayload,
|
||||
type FileExportTextResult,
|
||||
type HapticsImpactPayload,
|
||||
@@ -27,6 +29,12 @@ import { resolveMobileShellWebViewUrl } from './mobileShellNavigation';
|
||||
|
||||
const WEB_APP_ORIGIN = 'https://app.genarrative.world';
|
||||
const EXPORT_TEXT_MAX_BYTES = 5 * 1024 * 1024;
|
||||
const EXPORT_IMAGE_MAX_BYTES = 5 * 1024 * 1024;
|
||||
const EXPORT_IMAGE_MIME_TYPES = new Set([
|
||||
'image/png',
|
||||
'image/jpeg',
|
||||
'image/webp',
|
||||
]);
|
||||
|
||||
export const MOBILE_HOST_CAPABILITIES: HostBridgeCapability[] = [
|
||||
'host.getRuntime',
|
||||
@@ -38,6 +46,7 @@ export const MOBILE_HOST_CAPABILITIES: HostBridgeCapability[] = [
|
||||
'app.openExternalUrl',
|
||||
'clipboard.writeText',
|
||||
'file.exportText',
|
||||
'file.exportImage',
|
||||
'haptics.impact',
|
||||
];
|
||||
|
||||
@@ -86,6 +95,28 @@ function utf8ByteLength(value: string) {
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function normalizedBase64Data(value: unknown) {
|
||||
if (typeof value !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalizedValue = value.trim();
|
||||
if (
|
||||
!normalizedValue ||
|
||||
normalizedValue.length % 4 !== 0 ||
|
||||
!/^[A-Za-z0-9+/]+={0,2}$/u.test(normalizedValue)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalizedValue;
|
||||
}
|
||||
|
||||
function base64DecodedByteLength(value: string) {
|
||||
const padding = value.endsWith('==') ? 2 : value.endsWith('=') ? 1 : 0;
|
||||
return Math.floor((value.length * 3) / 4) - padding;
|
||||
}
|
||||
|
||||
function isHostBridgeRequest(value: unknown): value is HostBridgeRequest {
|
||||
if (!value || typeof value !== 'object') {
|
||||
return false;
|
||||
@@ -193,6 +224,46 @@ async function exportTextFile(payload: unknown): Promise<FileExportTextResult> {
|
||||
};
|
||||
}
|
||||
|
||||
async function exportImageFile(payload: unknown): Promise<FileExportImageResult> {
|
||||
const exportPayload = payload as FileExportImagePayload | undefined;
|
||||
const mimeType = exportPayload?.mimeType;
|
||||
if (typeof mimeType !== 'string' || !EXPORT_IMAGE_MIME_TYPES.has(mimeType)) {
|
||||
throw invalidRequest('mimeType must be an allowed image type');
|
||||
}
|
||||
|
||||
const base64Data = normalizedBase64Data(exportPayload?.base64Data);
|
||||
if (!base64Data) {
|
||||
throw invalidRequest('base64Data is required');
|
||||
}
|
||||
const bytes = base64DecodedByteLength(base64Data);
|
||||
if (bytes > EXPORT_IMAGE_MAX_BYTES) {
|
||||
throw invalidRequest('image exceeds file export size limit');
|
||||
}
|
||||
|
||||
const isSharingAvailable = await Sharing.isAvailableAsync();
|
||||
if (!isSharingAvailable) {
|
||||
throw {
|
||||
code: 'unsupported_capability',
|
||||
message: 'file sharing is unavailable in mobile shell',
|
||||
} satisfies HostBridgeError;
|
||||
}
|
||||
|
||||
const fileName = normalizeHostBridgeExportFileName(exportPayload?.fileName);
|
||||
const file = new File(Paths.cache, fileName);
|
||||
file.write(base64Data, { encoding: 'base64' });
|
||||
await Sharing.shareAsync(file.uri, {
|
||||
mimeType,
|
||||
UTI: mimeType === 'image/png' ? 'public.png' : 'public.image',
|
||||
dialogTitle: fileName,
|
||||
});
|
||||
|
||||
return {
|
||||
action: 'saved',
|
||||
fileName,
|
||||
bytes,
|
||||
};
|
||||
}
|
||||
|
||||
async function runHaptics(payload: unknown) {
|
||||
const style = (payload as HapticsImpactPayload | undefined)?.style;
|
||||
const impactStyle =
|
||||
@@ -322,6 +393,8 @@ async function handleRequest(request: HostBridgeRequest) {
|
||||
return ok(request, await writeClipboard(request.payload));
|
||||
case 'file.exportText':
|
||||
return ok(request, await exportTextFile(request.payload));
|
||||
case 'file.exportImage':
|
||||
return ok(request, await exportImageFile(request.payload));
|
||||
case 'haptics.impact':
|
||||
return ok(request, await runHaptics(request.payload));
|
||||
case 'share.open':
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
- 2026-06-18 宿主 runtime 回读:主 App 启动时会通过真实 `host.getRuntime` 回读 Expo / Tauri runtime 并缓存过滤后的能力清单,能力来源为 URL `hostCapabilities` 与宿主真实回包的并集;裁剪壳或旧入口 URL 缺少 `hostCapabilities` 时也能启用真实声明能力,但仍不会仅凭 `native_app` 或 transport 存在推断能力可用。
|
||||
- 2026-06-18 壳能力防漂移:`npm run mobile-shell:typecheck` 与 `npm run desktop-shell:typecheck` 会校验 Expo / Tauri 壳声明的 capability 均来自共享 HostBridge 白名单,并校验壳 runtime 回包、H5 URL `hostCapabilities` 和实现分支保持一致;新增能力必须先更新契约和真实壳实现,再通过这些检查。
|
||||
- 2026-06-18 原生壳统一验收门禁:根级 `npm run check:native-shells` 统一执行 H5 HostBridge 关键测试、Expo 壳 typecheck / test 和 Tauri 壳 typecheck / cargo test;根级 `npm run check` 会在 lint、主站测试、构建和内容检查后继续执行该门禁,避免 HostBridge 与两端壳验收散落成容易漏跑的单项命令。
|
||||
- 2026-06-18 分享卡图片导出:新增 `file.exportImage` HostBridge capability,H5 分享卡下载在 native app 中优先把 canvas 生成的 base64 图片交给宿主导出;Expo 壳写缓存图片后交给系统分享 / 保存面板,Tauri 壳通过系统保存对话框写入图片字节。该能力只接受 `image/png` / `image/jpeg` / `image/webp`、单次 5 MiB 内图片数据,成功只返回文件名和字节数,不暴露本机绝对路径;宿主未声明时保留浏览器下载。
|
||||
- 影响范围:`src/services/host-bridge/`、未来 `apps/mobile-shell/`、未来 `apps/desktop-shell/`、移动端支付 / 分享 / 深链 / 推送、桌面端系统能力、AI H5 sandbox 的 GameBridge 边界。
|
||||
- 验证方式:普通浏览器、小程序、Expo 壳、Tauri 壳都能返回正确 `getHostRuntime()`;未支持能力能回退 H5;固定玩法在各宿主中读取同一作品数据和运行态 snapshot;AI sandbox 无法直接调用 HostBridge;Tauri release 不允许任意远端页面调用桌面命令。
|
||||
- 关联文档:`docs/【前端架构】ExpoReactNative与Tauri宿主壳方案-2026-06-17.md`、`docs/【前端架构】宿主壳能力统一协议-2026-06-17.md`。
|
||||
|
||||
@@ -242,7 +242,7 @@ GameBridge 禁止:
|
||||
- iOS / Android 深链打开作品详情、创作页和邀请码。
|
||||
- 登录和支付先 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`、`host.events`、`share.open`、`share.setTarget`、`navigation.openNativePage`、`navigation.canGoBack`、`app.openExternalUrl`、`clipboard.writeText`、`file.exportText`、`haptics.impact` 和 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,成功只返回文件名和字节数;`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`、`host.events`、`share.open`、`share.setTarget`、`navigation.openNativePage`、`navigation.canGoBack`、`app.openExternalUrl`、`clipboard.writeText`、`file.exportText`、`file.exportImage`、`haptics.impact` 和 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
|
||||
|
||||
@@ -253,7 +253,7 @@ GameBridge 禁止:
|
||||
- 实现 runtime、openExternalUrl、clipboard、share fallback、窗口标题同步。
|
||||
- 验证 macOS / Windows / Linux 至少一条本地 smoke。
|
||||
|
||||
当前状态:已新增 `apps/desktop-shell/`,Tauri dev 直接加载本地主站 Vite,release 打包根 `dist` 主站资产。Rust 侧只把 `host_bridge_request` command 授给主窗口,`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 同步窗口标题并拒绝空标题 / 控制字符;H5 主站会按当前平台阶段先更新 `document.title`,再通过 `app.setTitle` 把同一标题同步给 Tauri 窗口,Expo 移动壳不声明该能力时静默忽略;不把 opener、clipboard 或 dialog 插件命令直接暴露给前端。当前真实能力为 `host.getRuntime`、`share.setTarget`、`share.open`、`navigation.openNativePage`、`app.openExternalUrl`、`app.setTitle`、`clipboard.writeText` 和 `file.exportText`;H5 会在主 App 启动时通过真实 `host.getRuntime` 回读并缓存这些能力,即使入口 URL 缺少 `hostCapabilities`,也只按宿主真实回包开启能力入口;其中 `share.open` 会把直接传入的分享 payload 或 `share.setTarget` 缓存的作品目标整理成非空分享文本并写入系统剪贴板,返回 `copied_to_clipboard`,发布分享弹窗在桌面壳中也通过该能力提供“系统分享”动作;`file.exportText` 通过系统保存对话框让用户选择本地路径,清洗文件名、限制单次文本导出不超过 5 MiB,写入成功后只返回文件名和字节数,不把本机绝对路径暴露给 H5,用户取消返回 `cancelled`。原生系统分享面板、登录和支付未接入真实插件 / 渠道前不声明支持,不返回 mock 成功。
|
||||
当前状态:已新增 `apps/desktop-shell/`,Tauri dev 直接加载本地主站 Vite,release 打包根 `dist` 主站资产。Rust 侧只把 `host_bridge_request` command 授给主窗口,`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 同步窗口标题并拒绝空标题 / 控制字符;H5 主站会按当前平台阶段先更新 `document.title`,再通过 `app.setTitle` 把同一标题同步给 Tauri 窗口,Expo 移动壳不声明该能力时静默忽略;不把 opener、clipboard 或 dialog 插件命令直接暴露给前端。当前真实能力为 `host.getRuntime`、`share.setTarget`、`share.open`、`navigation.openNativePage`、`app.openExternalUrl`、`app.setTitle`、`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:宿主能力扩展
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ AI H5 sandbox
|
||||
- `openHostExternalUrl()`:原生 App 宿主的受控外链入口。H5 中需要离开主站的外链在 `native_app` 下先通过 `app.openExternalUrl` 请求宿主系统浏览器打开;只允许 `http:`、`https:`、`mailto:`、`tel:`,相对路径会先归一化到当前站点绝对 URL。宿主不可用或拒绝时回退浏览器外链行为,普通浏览器和小程序保持原有 `<a>` 语义。
|
||||
- `navigateHostNativePage()`:受控跳转宿主页,供订阅授权、支付、登录等 adapter 复用。Expo 移动壳首版只接受同源 H5 route 并切换 WebView URL;Tauri 桌面壳同样只接受 `https://app.genarrative.world` 同源 H5 route 并在主窗口内跳转。真正原生页面、登录和支付能力必须等对应 SDK / 页面接入后再声明支持。
|
||||
- `exportHostTextFile()`:原生 App 宿主的受控文本导出入口。Expo 移动壳通过 `file.exportText` 写入缓存文本文件并交给系统分享 / 保存面板;Tauri 桌面壳通过 `file.exportText` 打开系统保存对话框并写入用户选择的文件。文件名必须清洗,单次文本不超过 5 MiB,成功只返回文件名和字节数,不把本机绝对路径暴露给 H5;系统分享不可用或用户取消时返回明确错误,由 H5 fallback 承接。
|
||||
- `exportHostImageFile()`:原生 App 宿主的受控图片导出入口。H5 只传自己生成的图片 `base64Data`、清洗后的文件名和允许的 `image/png` / `image/jpeg` / `image/webp` MIME;Expo 移动壳写入缓存图片后交给系统分享 / 保存面板,Tauri 桌面壳打开系统保存对话框并写入图片字节。单次图片不超过 5 MiB,成功只返回文件名和字节数,不回传本机绝对路径。当前分享卡下载在 native app 中优先走 `file.exportImage`,宿主未声明时保留浏览器下载路径。
|
||||
|
||||
## 迁移顺序
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ export const HOST_BRIDGE_METHODS = [
|
||||
'app.setTitle',
|
||||
'clipboard.writeText',
|
||||
'file.exportText',
|
||||
'file.exportImage',
|
||||
'haptics.impact',
|
||||
] as const;
|
||||
|
||||
@@ -171,6 +172,18 @@ export type FileExportTextResult = {
|
||||
bytes: number;
|
||||
};
|
||||
|
||||
export type FileExportImagePayload = {
|
||||
fileName: string;
|
||||
base64Data: string;
|
||||
mimeType: 'image/png' | 'image/jpeg' | 'image/webp';
|
||||
};
|
||||
|
||||
export type FileExportImageResult = {
|
||||
action: 'saved';
|
||||
fileName: string;
|
||||
bytes: number;
|
||||
};
|
||||
|
||||
export type HapticsImpactPayload = {
|
||||
style?: 'light' | 'medium' | 'heavy';
|
||||
};
|
||||
|
||||
@@ -207,6 +207,107 @@ describe('PublishShareModal', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('uses native host image export for share card download inside native app runtime', async () => {
|
||||
class MockFileReader {
|
||||
result: string | ArrayBuffer | null = null;
|
||||
onload: (() => void) | null = null;
|
||||
onerror: (() => void) | null = null;
|
||||
|
||||
readAsDataURL() {
|
||||
this.result = 'data:image/png;base64,c2hhcmUtY2FyZA==';
|
||||
this.onload?.();
|
||||
}
|
||||
}
|
||||
vi.stubGlobal('FileReader', MockFileReader);
|
||||
vi.stubGlobal(
|
||||
'Image',
|
||||
class MockImage {
|
||||
onload: (() => void) | null = null;
|
||||
naturalWidth = 900;
|
||||
naturalHeight = 900;
|
||||
width = 900;
|
||||
height = 900;
|
||||
set src(_value: string) {
|
||||
this.onload?.();
|
||||
}
|
||||
},
|
||||
);
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue({
|
||||
beginPath: vi.fn(),
|
||||
clearRect: vi.fn(),
|
||||
clip: vi.fn(),
|
||||
closePath: vi.fn(),
|
||||
createLinearGradient: vi.fn(() => ({
|
||||
addColorStop: vi.fn(),
|
||||
})),
|
||||
drawImage: vi.fn(),
|
||||
fill: vi.fn(),
|
||||
fillRect: vi.fn(),
|
||||
fillText: vi.fn(),
|
||||
lineTo: vi.fn(),
|
||||
measureText: vi.fn((text: string) => ({
|
||||
width: Array.from(text).length * 32,
|
||||
})),
|
||||
moveTo: vi.fn(),
|
||||
quadraticCurveTo: vi.fn(),
|
||||
restore: vi.fn(),
|
||||
save: vi.fn(),
|
||||
stroke: vi.fn(),
|
||||
} as unknown as CanvasRenderingContext2D);
|
||||
vi.spyOn(HTMLCanvasElement.prototype, 'toBlob').mockImplementation(
|
||||
(callback: BlobCallback) => {
|
||||
callback(new Blob(['share-card'], { type: 'image/png' }));
|
||||
},
|
||||
);
|
||||
const invoke = vi.fn(
|
||||
async (_command: string, args?: Record<string, unknown>) => {
|
||||
const request = (args as { request: { id: string } }).request;
|
||||
return {
|
||||
bridge: 'GenarrativeHostBridge',
|
||||
version: 1,
|
||||
id: request.id,
|
||||
ok: true,
|
||||
result: {
|
||||
action: 'saved',
|
||||
fileName: '暖灯猫街-PZ-00000001.png',
|
||||
bytes: 10,
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
window.history.replaceState(
|
||||
null,
|
||||
'',
|
||||
'/?clientRuntime=native_app&hostShell=tauri_desktop&hostCapabilities=file.exportImage',
|
||||
);
|
||||
window.__TAURI__ = {
|
||||
core: {
|
||||
invoke: asTauriInvoke(invoke),
|
||||
},
|
||||
};
|
||||
|
||||
render(<PublishShareModal open payload={payload} onClose={() => {}} />);
|
||||
|
||||
const dialog = screen.getByRole('dialog', { name: '分享给朋友' });
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: '下载卡片' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
within(dialog).getByRole('button', { name: '已下载' }),
|
||||
).toBeTruthy();
|
||||
});
|
||||
expect(invoke).toHaveBeenCalledWith('host_bridge_request', {
|
||||
request: expect.objectContaining({
|
||||
method: 'file.exportImage',
|
||||
payload: {
|
||||
fileName: '暖灯猫街-PZ-00000001.png',
|
||||
base64Data: 'c2hhcmUtY2FyZA==',
|
||||
mimeType: 'image/png',
|
||||
},
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
test('does not show native share action when native app shell does not declare share capability', () => {
|
||||
window.history.replaceState(
|
||||
null,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest';
|
||||
|
||||
import { readAssetBytes } from '../../services/assetReadUrlService';
|
||||
import * as hostBridge from '../../services/host-bridge/hostBridge';
|
||||
import {
|
||||
downloadPublishShareCardImage,
|
||||
resolvePublishShareCardCanvasImageSource,
|
||||
@@ -84,6 +85,21 @@ function installCanvasMocks() {
|
||||
);
|
||||
}
|
||||
|
||||
function installFileReaderMock() {
|
||||
class MockFileReader {
|
||||
result: string | ArrayBuffer | null = null;
|
||||
onload: (() => void) | null = null;
|
||||
onerror: (() => void) | null = null;
|
||||
|
||||
readAsDataURL() {
|
||||
this.result = 'data:image/png;base64,c2hhcmUtY2FyZA==';
|
||||
this.onload?.();
|
||||
}
|
||||
}
|
||||
|
||||
vi.stubGlobal('FileReader', MockFileReader);
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
@@ -124,6 +140,7 @@ describe('publishShareCardImage', () => {
|
||||
test('exports the same card content as the modal instead of adding extra branding', async () => {
|
||||
installObjectUrlMocks();
|
||||
installCanvasMocks();
|
||||
installFileReaderMock();
|
||||
|
||||
await expect(
|
||||
downloadPublishShareCardImage(
|
||||
@@ -143,4 +160,38 @@ describe('publishShareCardImage', () => {
|
||||
expect(fillTextCalls).toContain('PZ-BE68CC73');
|
||||
expect(fillTextCalls).not.toContain('陶泥儿');
|
||||
});
|
||||
|
||||
test('uses native host image export before browser download when available', async () => {
|
||||
installObjectUrlMocks();
|
||||
installCanvasMocks();
|
||||
installFileReaderMock();
|
||||
const exportHostImageFile = vi
|
||||
.spyOn(hostBridge, 'exportHostImageFile')
|
||||
.mockResolvedValue({
|
||||
action: 'saved',
|
||||
fileName: '三叶草-PZ-BE68CC73.png',
|
||||
bytes: 10,
|
||||
});
|
||||
const anchorClick = vi.spyOn(HTMLAnchorElement.prototype, 'click');
|
||||
|
||||
await expect(
|
||||
downloadPublishShareCardImage(
|
||||
{
|
||||
title: '三叶草',
|
||||
publicWorkCode: 'PZ-BE68CC73',
|
||||
stage: 'puzzle-gallery-detail',
|
||||
workTypeLabel: '拼图',
|
||||
coverImageSrc: '/cover.png',
|
||||
},
|
||||
'/cover.png',
|
||||
),
|
||||
).resolves.toBe(true);
|
||||
|
||||
expect(exportHostImageFile).toHaveBeenCalledWith({
|
||||
fileName: '三叶草-PZ-BE68CC73.png',
|
||||
base64Data: 'c2hhcmUtY2FyZA==',
|
||||
mimeType: 'image/png',
|
||||
});
|
||||
expect(anchorClick).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
readAssetBytes,
|
||||
shouldResolveAssetReadUrl,
|
||||
} from '../../services/assetReadUrlService';
|
||||
import { exportHostImageFile } from '../../services/host-bridge/hostBridge';
|
||||
import {
|
||||
buildPublishShareCardFileName,
|
||||
type PublishShareModalPayload,
|
||||
@@ -351,6 +352,53 @@ function canvasToBlob(canvas: HTMLCanvasElement) {
|
||||
});
|
||||
}
|
||||
|
||||
function blobToBase64Data(blob: Blob) {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const result = typeof reader.result === 'string' ? reader.result : '';
|
||||
const base64Data = result.split(',')[1] ?? '';
|
||||
if (base64Data) {
|
||||
resolve(base64Data);
|
||||
} else {
|
||||
reject(new Error('分享卡图片编码失败'));
|
||||
}
|
||||
};
|
||||
reader.onerror = () => reject(new Error('分享卡图片编码失败'));
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
}
|
||||
|
||||
async function exportShareCardBlob(blob: Blob, fileName: string) {
|
||||
const exported = await exportHostImageFile({
|
||||
fileName,
|
||||
base64Data: await blobToBase64Data(blob),
|
||||
mimeType: 'image/png',
|
||||
});
|
||||
|
||||
if (exported) {
|
||||
return;
|
||||
}
|
||||
|
||||
triggerDownload(blob, fileName);
|
||||
}
|
||||
|
||||
async function renderShareCardBlob(
|
||||
payload: PublishShareModalPayload,
|
||||
coverImageSrc: string,
|
||||
) {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = CARD_WIDTH;
|
||||
canvas.height = CARD_HEIGHT;
|
||||
const context = canvas.getContext('2d');
|
||||
if (!context) {
|
||||
return null;
|
||||
}
|
||||
|
||||
await drawShareCard(context, payload, coverImageSrc);
|
||||
return await canvasToBlob(canvas);
|
||||
}
|
||||
|
||||
function triggerDownload(blob: Blob, fileName: string) {
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const anchor = document.createElement('a');
|
||||
@@ -370,34 +418,18 @@ export async function downloadPublishShareCardImage(
|
||||
return false;
|
||||
}
|
||||
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = CARD_WIDTH;
|
||||
canvas.height = CARD_HEIGHT;
|
||||
const context = canvas.getContext('2d');
|
||||
if (!context) {
|
||||
let blob: Blob | null = null;
|
||||
|
||||
try {
|
||||
blob = await renderShareCardBlob(payload, coverImageSrc);
|
||||
} catch {
|
||||
blob = await renderShareCardBlob(payload, '');
|
||||
}
|
||||
|
||||
if (!blob) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await drawShareCard(context, payload, coverImageSrc);
|
||||
triggerDownload(
|
||||
await canvasToBlob(canvas),
|
||||
buildPublishShareCardFileName(payload),
|
||||
);
|
||||
return true;
|
||||
} catch {
|
||||
const fallbackCanvas = document.createElement('canvas');
|
||||
fallbackCanvas.width = CARD_WIDTH;
|
||||
fallbackCanvas.height = CARD_HEIGHT;
|
||||
const fallbackContext = fallbackCanvas.getContext('2d');
|
||||
if (!fallbackContext) {
|
||||
return false;
|
||||
}
|
||||
await drawShareCard(fallbackContext, payload, '');
|
||||
triggerDownload(
|
||||
await canvasToBlob(fallbackCanvas),
|
||||
buildPublishShareCardFileName(payload),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
await exportShareCardBlob(blob, buildPublishShareCardFileName(payload));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import type { HostBridgeCapability } from '../../../packages/shared/src/contract
|
||||
import {
|
||||
canUseHostShareGrid,
|
||||
canUseNativeHostCapability,
|
||||
exportHostImageFile,
|
||||
exportHostTextFile,
|
||||
getHostRuntime,
|
||||
getNativeAppHostRuntime,
|
||||
@@ -443,6 +444,7 @@ describe('hostBridge', () => {
|
||||
'app.openExternalUrl',
|
||||
'app.setTitle',
|
||||
'share.open',
|
||||
'file.exportImage',
|
||||
]),
|
||||
);
|
||||
window.__TAURI__ = {
|
||||
@@ -482,6 +484,13 @@ describe('hostBridge', () => {
|
||||
url: 'https://app.genarrative.world/works/detail?work=PZ-1',
|
||||
}),
|
||||
).resolves.toBe(true);
|
||||
await expect(
|
||||
exportHostImageFile({
|
||||
fileName: '分享卡.png',
|
||||
base64Data: 'c2hhcmUtY2FyZA==',
|
||||
mimeType: 'image/png',
|
||||
}),
|
||||
).resolves.toBe(true);
|
||||
|
||||
expect(invoke).toHaveBeenCalledWith('host_bridge_request', {
|
||||
request: expect.objectContaining({
|
||||
@@ -545,6 +554,17 @@ describe('hostBridge', () => {
|
||||
},
|
||||
}),
|
||||
});
|
||||
expect(invoke).toHaveBeenCalledWith('host_bridge_request', {
|
||||
request: expect.objectContaining({
|
||||
method: 'file.exportImage',
|
||||
payload: {
|
||||
fileName: '分享卡.png',
|
||||
base64Data: 'c2hhcmUtY2FyZA==',
|
||||
mimeType: 'image/png',
|
||||
},
|
||||
timeoutMs: 30000,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
test('原生 App 宿主不支持能力时回退到 H5 路径', async () => {
|
||||
@@ -598,15 +618,29 @@ describe('hostBridge', () => {
|
||||
url: 'https://app.genarrative.world/works/detail?work=PZ-1',
|
||||
}),
|
||||
).resolves.toBe(false);
|
||||
await expect(
|
||||
exportHostImageFile({
|
||||
fileName: '分享卡.png',
|
||||
base64Data: 'c2hhcmUtY2FyZA==',
|
||||
mimeType: 'image/png',
|
||||
}),
|
||||
).resolves.toBe(false);
|
||||
});
|
||||
|
||||
test('普通浏览器不处理宿主文本导出', async () => {
|
||||
test('普通浏览器不处理宿主文件导出', async () => {
|
||||
await expect(
|
||||
exportHostTextFile({
|
||||
fileName: '作品记录.txt',
|
||||
content: 'content',
|
||||
}),
|
||||
).resolves.toBe(false);
|
||||
await expect(
|
||||
exportHostImageFile({
|
||||
fileName: '分享卡.png',
|
||||
base64Data: 'c2hhcmUtY2FyZA==',
|
||||
mimeType: 'image/png',
|
||||
}),
|
||||
).resolves.toBe(false);
|
||||
});
|
||||
|
||||
test('原生 App 宿主通过 HostBridge 导出文本文件', async () => {
|
||||
@@ -694,4 +728,57 @@ describe('hostBridge', () => {
|
||||
}),
|
||||
).resolves.toBe(false);
|
||||
});
|
||||
|
||||
test('原生 App 宿主通过 HostBridge 导出图片文件', async () => {
|
||||
const invoke = vi.fn(
|
||||
async (_command: string, args?: Record<string, unknown>) => {
|
||||
const request = (args as { request: { id: string } }).request;
|
||||
return {
|
||||
bridge: 'GenarrativeHostBridge',
|
||||
version: 1,
|
||||
id: request.id,
|
||||
ok: true,
|
||||
result: {
|
||||
action: 'saved',
|
||||
fileName: '分享卡.png',
|
||||
bytes: 10,
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
window.history.replaceState(
|
||||
null,
|
||||
'',
|
||||
nativeAppPath(['file.exportImage']),
|
||||
);
|
||||
window.__TAURI__ = {
|
||||
core: {
|
||||
invoke: asTauriInvoke(invoke),
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
exportHostImageFile({
|
||||
fileName: '分享卡.png',
|
||||
base64Data: 'c2hhcmUtY2FyZA==',
|
||||
mimeType: 'image/png',
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
action: 'saved',
|
||||
fileName: '分享卡.png',
|
||||
bytes: 10,
|
||||
});
|
||||
|
||||
expect(invoke).toHaveBeenCalledWith('host_bridge_request', {
|
||||
request: expect.objectContaining({
|
||||
method: 'file.exportImage',
|
||||
payload: {
|
||||
fileName: '分享卡.png',
|
||||
base64Data: 'c2hhcmUtY2FyZA==',
|
||||
mimeType: 'image/png',
|
||||
},
|
||||
timeoutMs: 30000,
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import type {
|
||||
FileExportImagePayload,
|
||||
FileExportImageResult,
|
||||
FileExportTextPayload,
|
||||
FileExportTextResult,
|
||||
HapticsImpactPayload,
|
||||
@@ -73,6 +75,8 @@ export type HostShareGridRequest = {
|
||||
|
||||
export type HostFileExportTextRequest = FileExportTextPayload;
|
||||
|
||||
export type HostFileExportImageRequest = FileExportImagePayload;
|
||||
|
||||
export type HostClipboardWriteTextRequest = {
|
||||
text: string;
|
||||
};
|
||||
@@ -687,6 +691,27 @@ export async function exportHostTextFile(
|
||||
}
|
||||
}
|
||||
|
||||
export async function exportHostImageFile(
|
||||
params: HostFileExportImageRequest,
|
||||
) {
|
||||
if (!canUseNativeHostCapability('file.exportImage')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
return await requestNativeAppHostBridge<FileExportImageResult>(
|
||||
'file.exportImage',
|
||||
params,
|
||||
{ timeoutMs: 30000 },
|
||||
);
|
||||
} catch (error) {
|
||||
if (isUnsupportedHostBridgeError(error)) {
|
||||
return false;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function requestHostHapticsImpact(
|
||||
params: HostHapticsImpactRequest = {},
|
||||
) {
|
||||
|
||||
Reference in New Issue
Block a user