接入桌面壳分享复制能力
Tauri HostBridge 声明 share.setTarget 和 share.open 真实能力 桌面壳将分享 payload 或已同步作品目标整理为非空文本写入系统剪贴板 补充桌面壳分享文本解析测试和配置守卫 更新 Expo React Native 与 Tauri 宿主壳方案及团队共享决策记录
This commit is contained in:
@@ -34,7 +34,7 @@ const requiredUrlParts = [
|
||||
'hostShell=tauri_desktop',
|
||||
'hostPlatform=unknown',
|
||||
'bridgeVersion=1',
|
||||
'hostCapabilities=host.getRuntime,app.openExternalUrl,clipboard.writeText',
|
||||
'hostCapabilities=host.getRuntime,share.open,share.setTarget,app.openExternalUrl,clipboard.writeText',
|
||||
];
|
||||
|
||||
for (const part of requiredUrlParts) {
|
||||
@@ -53,7 +53,10 @@ const requiredPermissions = [
|
||||
const requiredBuildCommands = ['host_bridge_request'];
|
||||
const requiredMainSnippets = [
|
||||
'tauri_plugin_clipboard_manager::init()',
|
||||
'"share.open"',
|
||||
'"share.setTarget"',
|
||||
'"clipboard.writeText"',
|
||||
'"copied_to_clipboard"',
|
||||
];
|
||||
|
||||
for (const permission of requiredPermissions) {
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use std::sync::Mutex;
|
||||
use tauri_plugin_clipboard_manager::ClipboardExt;
|
||||
use tauri_plugin_opener::OpenerExt;
|
||||
|
||||
const HOST_BRIDGE_PROTOCOL: &str = "GenarrativeHostBridge";
|
||||
const HOST_BRIDGE_VERSION: u8 = 1;
|
||||
const WEB_APP_ORIGIN: &str = "https://app.genarrative.world";
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -45,6 +47,11 @@ struct HostBridgeResponse {
|
||||
error: Option<HostBridgeError>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct DesktopShareState {
|
||||
target: Mutex<Option<Value>>,
|
||||
}
|
||||
|
||||
fn desktop_platform() -> &'static str {
|
||||
if cfg!(target_os = "macos") {
|
||||
"macos"
|
||||
@@ -60,6 +67,8 @@ fn desktop_platform() -> &'static str {
|
||||
fn capabilities() -> Vec<&'static str> {
|
||||
vec![
|
||||
"host.getRuntime",
|
||||
"share.open",
|
||||
"share.setTarget",
|
||||
"app.openExternalUrl",
|
||||
"clipboard.writeText",
|
||||
]
|
||||
@@ -120,6 +129,79 @@ fn required_string_payload<'a>(
|
||||
})
|
||||
}
|
||||
|
||||
fn payload_string<'a>(value: &'a Value, field: &str) -> Option<&'a str> {
|
||||
value
|
||||
.get(field)
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|text| !text.is_empty())
|
||||
}
|
||||
|
||||
fn share_target_payload(value: &Value) -> &Value {
|
||||
value.get("target").unwrap_or(value)
|
||||
}
|
||||
|
||||
fn work_detail_url(work: &str) -> String {
|
||||
format!("{}/works/detail?work={}", WEB_APP_ORIGIN, work)
|
||||
}
|
||||
|
||||
fn share_text_from_value(value: &Value) -> Option<String> {
|
||||
let target = share_target_payload(value);
|
||||
let payload = target.get("payload").unwrap_or(target);
|
||||
let title = payload_string(payload, "title");
|
||||
let message = payload_string(payload, "message");
|
||||
let url = payload_string(payload, "url").or_else(|| payload_string(payload, "href"));
|
||||
let work_url = payload_string(payload, "work").map(work_detail_url);
|
||||
let path_url = payload_string(payload, "path")
|
||||
.or_else(|| payload_string(payload, "targetPath"))
|
||||
.map(|path| format!("{}{}", WEB_APP_ORIGIN, path));
|
||||
let resolved_url = url.map(str::to_owned).or(work_url).or(path_url);
|
||||
let parts = [title, message, resolved_url.as_deref()]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
if parts.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(parts.join("\n"))
|
||||
}
|
||||
}
|
||||
|
||||
fn share_text_from_request(
|
||||
request: &HostBridgeRequest,
|
||||
share_state: &DesktopShareState,
|
||||
) -> Result<String, HostBridgeResponse> {
|
||||
if let Some(payload) = request.payload.as_ref() {
|
||||
if let Some(text) = share_text_from_value(payload) {
|
||||
return Ok(text);
|
||||
}
|
||||
}
|
||||
|
||||
let stored_target = share_state
|
||||
.target
|
||||
.lock()
|
||||
.map_err(|_| {
|
||||
failed(
|
||||
request.id.clone(),
|
||||
"host_error",
|
||||
"share target lock poisoned",
|
||||
)
|
||||
})?
|
||||
.clone();
|
||||
|
||||
stored_target
|
||||
.as_ref()
|
||||
.and_then(share_text_from_value)
|
||||
.ok_or_else(|| {
|
||||
failed(
|
||||
request.id.clone(),
|
||||
"invalid_request",
|
||||
"share target is required",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn resolve_host_bridge_request(request: HostBridgeRequest) -> HostBridgeResponse {
|
||||
if let Some(response) = validate_request(&request) {
|
||||
return response;
|
||||
@@ -145,8 +227,9 @@ fn resolve_host_bridge_request(request: HostBridgeRequest) -> HostBridgeResponse
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn host_bridge_request(
|
||||
fn host_bridge_request(
|
||||
app: tauri::AppHandle,
|
||||
share_state: tauri::State<'_, DesktopShareState>,
|
||||
request: HostBridgeRequest,
|
||||
) -> HostBridgeResponse {
|
||||
if let Some(response) = validate_request(&request) {
|
||||
@@ -176,12 +259,46 @@ async fn host_bridge_request(
|
||||
Err(error) => failed(request.id, "host_error", error.to_string()),
|
||||
}
|
||||
}
|
||||
"share.setTarget" => {
|
||||
let target = request
|
||||
.payload
|
||||
.as_ref()
|
||||
.and_then(|payload| payload.get("target"));
|
||||
let Some(target) = target else {
|
||||
return failed(request.id, "invalid_request", "target is required");
|
||||
};
|
||||
|
||||
match share_state.target.lock() {
|
||||
Ok(mut current_target) => {
|
||||
*current_target = Some(target.clone());
|
||||
ok(request.id, json!(true))
|
||||
}
|
||||
Err(_) => failed(request.id, "host_error", "share target lock poisoned"),
|
||||
}
|
||||
}
|
||||
"share.open" => {
|
||||
let share_text = match share_text_from_request(&request, &share_state) {
|
||||
Ok(text) => text,
|
||||
Err(response) => return response,
|
||||
};
|
||||
|
||||
match app.clipboard().write_text(share_text) {
|
||||
Ok(()) => ok(
|
||||
request.id,
|
||||
json!({
|
||||
"action": "copied_to_clipboard"
|
||||
}),
|
||||
),
|
||||
Err(error) => failed(request.id, "host_error", error.to_string()),
|
||||
}
|
||||
}
|
||||
_ => resolve_host_bridge_request(request),
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
tauri::Builder::default()
|
||||
.manage(DesktopShareState::default())
|
||||
.plugin(tauri_plugin_clipboard_manager::init())
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.setup(|app| {
|
||||
@@ -219,6 +336,14 @@ mod tests {
|
||||
assert_eq!(result["shell"], "tauri_desktop");
|
||||
assert_eq!(result["bridgeVersion"], HOST_BRIDGE_VERSION);
|
||||
assert_eq!(result["capabilities"], json!(capabilities()));
|
||||
assert!(result["capabilities"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!("share.open")));
|
||||
assert!(result["capabilities"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!("share.setTarget")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -254,4 +379,62 @@ mod tests {
|
||||
assert_eq!(error.code, "invalid_request");
|
||||
assert_eq!(error.message, "text is required");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn share_text_uses_direct_share_payload() {
|
||||
let state = DesktopShareState::default();
|
||||
let mut open = request("share.open");
|
||||
open.payload = Some(json!({
|
||||
"title": "测试作品",
|
||||
"message": "来玩这个作品",
|
||||
"url": "https://app.genarrative.world/works/detail?work=PZ-1"
|
||||
}));
|
||||
|
||||
let text = share_text_from_request(&open, &state).expect("share text");
|
||||
|
||||
assert_eq!(
|
||||
text,
|
||||
"测试作品\n来玩这个作品\nhttps://app.genarrative.world/works/detail?work=PZ-1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn share_text_uses_stored_work_target() {
|
||||
let state = DesktopShareState::default();
|
||||
let mut set_target = request("share.setTarget");
|
||||
set_target.payload = Some(json!({
|
||||
"target": {
|
||||
"type": "genarrative:share-target",
|
||||
"payload": {
|
||||
"work": "PZ-1",
|
||||
"title": "测试作品"
|
||||
}
|
||||
}
|
||||
}));
|
||||
let target = set_target
|
||||
.payload
|
||||
.as_ref()
|
||||
.and_then(|payload| payload.get("target"))
|
||||
.expect("target");
|
||||
*state.target.lock().expect("share target lock") = Some(target.clone());
|
||||
|
||||
let text = share_text_from_request(&request("share.open"), &state).expect("share text");
|
||||
|
||||
assert_eq!(
|
||||
text,
|
||||
"测试作品\nhttps://app.genarrative.world/works/detail?work=PZ-1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn share_text_requires_payload_or_stored_target() {
|
||||
let state = DesktopShareState::default();
|
||||
let response =
|
||||
share_text_from_request(&request("share.open"), &state).expect_err("missing target");
|
||||
|
||||
assert!(!response.ok);
|
||||
let error = response.error.expect("error");
|
||||
assert_eq!(error.code, "invalid_request");
|
||||
assert_eq!(error.message, "share target is required");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,app.openExternalUrl,clipboard.writeText",
|
||||
"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,app.openExternalUrl,clipboard.writeText",
|
||||
"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,app.openExternalUrl,clipboard.writeText",
|
||||
"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,app.openExternalUrl,clipboard.writeText",
|
||||
"title": "Genarrative",
|
||||
"width": 1280,
|
||||
"height": 820,
|
||||
|
||||
Reference in New Issue
Block a user