Files
image-workbench-desktop/src/clipboard-graph.js
T

152 lines
7.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* 统一剪贴板:把节点 / 节点组写进**系统剪贴板**(v3.24.68)
*
* 为什么需要这个模块:
* Ctrl+C 原本只写内部剪贴板(内存 + 本地存储),系统剪贴板一个字不动;
* 而 Ctrl+V 是浏览器 paste 事件,只能看到系统剪贴板 —— 于是「复制节点 → Ctrl+V」
* 贴出来的是**上一次复制的东西**,用户必须额外记住 Ctrl+Shift+V 才能贴节点组。
* 用户 2026-11-11 二次裁定:一个键贴所有,不再单独要求 Ctrl+Shift+V。
*
* 做法(Figma 同款思路):
* 复制时同时写 text/html(带 `<!--iwb:graph:v1:<b64>-->` 标记)与 text/plain(人话摘要)。
* Ctrl+V 时直接从 paste 事件的 clipboardData 读 html —— 零权限、零异步、跨标签页天然可用。
*
* 为什么不用自定义 MIME(web application/x-...):
* Chromium 支持,但 Safari / Firefox 支持面窄;text/html 是三端通用的最大公约数。
*
* 为什么注释标记能活下来:
* 实测(线上 v3.24.67,Chromium):写入 100KB / 500KB / 2MB / 5MB 的标记全部原样读回。
* 但 execCommand('copy') 兜底会把注释丢掉 → 因此**不做** execCommand 兜底,失败就降级为内部剪贴板。
*
* 历史教训(勿退回):更早的实现把**裸 JSON** 写进系统剪贴板,粘到别的应用是一坨 JSON,被撤回。
* 现在 text/plain 是「提示词全文」或「N 个节点」,粘到微信 / Word 是可读文本。
*/
;(function (global) {
'use strict'
const g = (global && typeof global === 'object') ? global : {}
const MARK = 'iwb:graph:v1:'
const MAX_PLAIN = 20000 // text/plain 里提示词的上限:超过就没必要整段塞进剪贴板
const str = (v) => (v == null ? '' : String(v))
/* UTF-8 → base64。不能直接 btoa(JSON.stringify(clip)):btoa 只吃 latin1,中文会抛
* InvalidCharacterError;也不能 String.fromCharCode(...bytes) 一次性展开,几十 KB 就爆栈。
* 分块 32KB 是两者之间的稳妥点。 */
function encodeText(text) {
const bytes = new TextEncoder().encode(text)
let bin = ''
const CH = 0x8000
for (let i = 0; i < bytes.length; i += CH) bin += String.fromCharCode.apply(null, bytes.subarray(i, i + CH))
return btoa(bin)
}
function decodeText(b64) {
const bin = atob(b64)
const bytes = new Uint8Array(bin.length)
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
return new TextDecoder().decode(bytes)
}
// HTML 特殊字符转义(摘要会进 text/html,不能把用户提示词当标签解释)
const esc = (s) => str(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
/* 给别的应用看的「人话」:优先取节点组里的提示词全文(复制一个提示词节点 → 粘到微信
* 直接拿到提示词,这是最实用的),没有提示词就退化成「N 个节点」。
* 绝不能把图片 base64 放进 text/plain —— 那正是旧实现被撤回的原因。 */
function plainFor(clip) {
const nodes = (clip && Array.isArray(clip.nodes)) ? clip.nodes : []
for (let i = 0; i < nodes.length; i++) {
const n = nodes[i]
const t = (n && n.type === 'prompt' && n.data && typeof n.data.text === 'string') ? n.data.text : ''
if (t && t.trim()) return t.length > MAX_PLAIN ? t.slice(0, MAX_PLAIN) : t
}
const groups = (clip && Array.isArray(clip.groups)) ? clip.groups : []
const gname = groups.length && groups[0] && groups[0].name ? '(' + groups[0].name + ')' : ''
return nodes.length + ' 个节点' + gname
}
function htmlFor(clip) {
const payload = JSON.stringify({
app: clip && clip.app,
type: clip && clip.type,
at: clip && clip.at,
nodes: (clip && clip.nodes) || [],
edges: (clip && clip.edges) || [],
groups: (clip && clip.groups) || [],
})
const head = plainFor(clip)
return '<!--' + MARK + encodeText(payload) + '--><div>' + esc(head.slice(0, 200)) + '</div>'
}
/* 从 text/html 里把 clip 取回来。找不到标记、base64 坏掉、JSON 坏掉、nodes 为空
* —— 一律返回 null(交给上层走普通粘贴),绝不抛异常。
* 注意:Chrome 读回来时会把 fragment 包成 <html><head></head><body>…,所以用 indexOf
* 定位标记,不能假设它以注释开头。 */
function decode(html) {
const s = str(html)
const i = s.indexOf(MARK)
if (i < 0) return null
const start = i + MARK.length
const end = s.indexOf('-->', start)
const raw = (end > start ? s.slice(start, end) : s.slice(start))
const b64 = raw.replace(/[^A-Za-z0-9+/=]/g, '')
if (!b64) return null
try {
const obj = JSON.parse(decodeText(b64))
if (!obj || !Array.isArray(obj.nodes) || !obj.nodes.length) return null
return obj
} catch (e) { return null }
}
/* 写系统剪贴板。返回 Promise<boolean>:false 表示这个环境写不了
* (非 HTTPS / 老浏览器 / 无 ClipboardItem)→ 调用方降级到内部剪贴板 + Ctrl+Shift+V。
* 绝不 reject:复制是高频动作,不能因为剪贴板权限在控制台刷错误。 */
/* 桌面端兜底:WKWebView 里 ClipboardItem 写 text/html 常失败(返回 false),
* 于是复制节点等于「什么都没写」,Ctrl+V 会贴出上一次的文本。
* 这里改成:写不了富文本就写纯文本摘要,并记住这份摘要属于哪个 clip。
* 粘贴侧用 matchPlain() 精确比对(文字完全相等才算命中),不会把用户随手复制的文本误判成节点。 */
let lastPlain = null
function notePlain(plain, clip) {
lastPlain = { plain: str(plain), clip: clip || null, at: Date.now() }
}
function matchPlain(text) {
if (!lastPlain || !lastPlain.clip) return null
if (Date.now() - lastPlain.at > 10 * 60 * 1000) return null
return str(text) === lastPlain.plain ? lastPlain.clip : null
}
function write(clip) {
const plain = plainFor(clip)
const cb = (g.navigator && g.navigator.clipboard) || null
// 先记账:即使写剪贴板失败,内部匹配(matchPlain)也能让 Ctrl+V 贴回节点组
notePlain(plain, clip)
try {
if (cb && typeof cb.write === 'function' && typeof g.ClipboardItem === 'function' && typeof g.Blob === 'function') {
const item = new g.ClipboardItem({
'text/html': new g.Blob([htmlFor(clip)], { type: 'text/html' }),
'text/plain': new g.Blob([plain], { type: 'text/plain' }),
})
return Promise.resolve(cb.write([item])).then(() => true).catch(() => writePlainFallback(cb, plain, clip))
}
} catch (e) { /* 落到纯文本兜底 */ }
// WKWebView:没有 clipboard.write ⇒ 直接走纯文本兜底(旧实现这里直接 return false,等于什么都没写)
return writePlainFallback(cb, plain, clip)
}
/** 纯文本兜底:优先 navigator.clipboard.writeText,再退到 Rust arboard */
function writePlainFallback(cb, plain, clip) {
notePlain(plain, clip)
const T = g.__TAURI__
if (cb && typeof cb.writeText === 'function') {
return Promise.resolve(cb.writeText(plain)).then(() => true).catch(() => writeNativeText(T, plain))
}
return writeNativeText(T, plain)
}
function writeNativeText(T, plain) {
if (!T || !T.core || typeof T.core.invoke !== 'function') return Promise.resolve(false)
return Promise.resolve(T.core.invoke('clipboard_write_text', { text: str(plain) })).then(() => true).catch(() => false)
}
g.IWBClipboardGraph = Object.freeze({ MARK, encodeText, decodeText, htmlFor, plainFor, decode, write, matchPlain })
})(typeof window !== 'undefined' ? window : globalThis)