/* 统一剪贴板:把节点 / 节点组写进**系统剪贴板**(v3.24.68)
*
* 为什么需要这个模块:
* Ctrl+C 原本只写内部剪贴板(内存 + 本地存储),系统剪贴板一个字不动;
* 而 Ctrl+V 是浏览器 paste 事件,只能看到系统剪贴板 —— 于是「复制节点 → Ctrl+V」
* 贴出来的是**上一次复制的东西**,用户必须额外记住 Ctrl+Shift+V 才能贴节点组。
* 用户 2026-11-11 二次裁定:一个键贴所有,不再单独要求 Ctrl+Shift+V。
*
* 做法(Figma 同款思路):
* 复制时同时写 text/html(带 `` 标记)与 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, '&').replace(//g, '>')
/* 给别的应用看的「人话」:优先取节点组里的提示词全文(复制一个提示词节点 → 粘到微信
* 直接拿到提示词,这是最实用的),没有提示词就退化成「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
}
/* 标记写两份(2026-11-26):
* ① HTML 注释 —— Chromium 侧实测原样保留,粘到别的应用也不显示;
* ② `data-iwb-graph` 属性 —— WKWebView(mac 桌面端)在写/读剪贴板时会过一遍 HTML 清洗,
* 注释被整段丢掉(实测写入 208 B、读回 414 B、标记消失),属性值能活下来。
* 两份带的是同一串 base64,谁活着都能解出来;decode() 两个位置都找。 */
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)
const b64 = encodeText(payload)
return '
' + esc(head.slice(0, 200)) + '
'
}
// 属性形态的标记(引号单双都认:不同应用回写 HTML 时引号风格不一致)
function b64FromAttr(s) {
const m = /data-iwb-graph\s*=\s*("([^"]*)"|'([^']*)')/i.exec(s)
if (!m) return ''
return str(m[2] != null ? m[2] : m[3]).replace(/[^A-Za-z0-9+/=]/g, '')
}
function b64FromComment(s) {
const i = s.indexOf(MARK)
if (i < 0) return ''
const start = i + MARK.length
const end = s.indexOf('-->', start)
const raw = (end > start ? s.slice(start, end) : s.slice(start))
return raw.replace(/[^A-Za-z0-9+/=]/g, '')
}
function parseB64(b64) {
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 }
}
/* 从 text/html 里把 clip 取回来。找不到标记、base64 坏掉、JSON 坏掉、nodes 为空
* —— 一律返回 null(交给上层走普通粘贴),绝不抛异常。
* 注意:Chrome 读回来时会把 fragment 包成 …,所以用 indexOf
* 定位标记,不能假设它以注释开头。 */
function decode(html) {
const s = str(html)
return parseB64(b64FromComment(s)) || parseB64(b64FromAttr(s))
}
/* 在 DOM `copy` 事件里**同步**写系统剪贴板(2026-11-26 起这是复制的主通道)。
*
* 为什么不用 navigator.clipboard.write:它是异步的,在 WKWebView 里写 text/html 经常被拒,
* 失败后只能降级成"纯文本摘要 + matchPlain 全等比对"(脆);而且 mac 上 ⌘C 被原生菜单
* Edit>Copy 接管时,keydown 根本到不了 JS,异步那条链路连触发都没有。
* clipboardData.setData 由用户手势直接授权、同步生效,Chromium / WKWebView 都可用。
*
* 同时 notePlain():即使 text/html 被清洗掉,粘贴侧还能靠"纯文本摘要全等"认回节点组。 */
function writeToEvent(e, clip) {
const dt = e && e.clipboardData
if (!dt || typeof dt.setData !== 'function') return false
const plain = plainFor(clip)
let ok = true
try { dt.setData('text/plain', plain) } catch (err) { ok = false }
try { dt.setData('text/html', htmlFor(clip)) } catch (err) { ok = false }
// 即使 setData 抛错也记账:内部剪贴板与 matchPlain 仍能让 ⌘V 贴回来
notePlain(plain, clip)
return ok
}
/* 写系统剪贴板。返回 Promise: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)
}
/* 复制主通道:DOM `copy` 事件(2026-11-26)。
*
* 旧实现只有 keydown 一条路(app.js 的 `hit('copy')`)。mac 桌面端 `Menu::default()` 的
* Edit>Copy 绑的是 `copy:` 且 `setAutoenablesItems(false)` 永远 enabled —— 只要第一响应者
* 认为"有东西可复制"(可编辑焦点 / 文本选区),AppKit 直接处理掉,keydown 到不了 JS,
* 于是"复制节点组"静默失败:没有提示、系统剪贴板没内容,用户觉得是随机 bug。
*
* 改法:复制统一由 `copy` 事件驱动(原生菜单处理的复制同样会派发这个事件),
* keydown 只保留一个兜底定时器(个别 WebView 不派发 copy 事件时才用旧异步链路)。
* 判定顺序:有文本选区 → 让原生复制文字;没选中节点 → 让原生走(并说一句没东西可复制,
* 否则又是一次"按了没反应")。
*/
let copyCtxOf = null // 最新的取值函数(Workbench 重挂载后必须换成本次渲染的)
let copyBound = null // { onCopy, onKey }:已注册的处理函数,供 unbindCopy 摘除
function bindCopy(getCtx) {
if (typeof getCtx === 'function') copyCtxOf = getCtx
if (copyBound || typeof window === 'undefined' || !window.addEventListener) return
let handledAt = 0
const ctxNow = () => (copyCtxOf ? copyCtxOf() : null)
function selOf(ctx) {
try { const ids = ctx.ids && ctx.ids(); return Array.isArray(ids) ? ids : [] } catch (e) { return [] }
}
function textSelected(ctx, el) {
const C = g.IWBClipboardCopy
try {
if (C && typeof C.hasTextSelection === 'function') return !!C.hasTextSelection(el)
} catch (e) { /* ignore */ }
return false
}
const onCopy = (e) => {
const ctx = ctxNow()
if (!ctx) return
handledAt = Date.now()
const ids = selOf(ctx)
const t = e && e.target
if (textSelected(ctx, t)) return // 用户要复制文字 → 原生
if (!ids.length) {
// 没选中节点、也没选中文字:原生复制是空操作。明确说一句,别让用户以为按键坏了。
if (ctx.setNotice) ctx.setNotice({ type: 'err', text: '没有可复制的节点:先在画布上选中或框选节点' })
return
}
let clip = null
try { clip = ctx.clipboardOf ? ctx.clipboardOf(ids) : null } catch (err) { clip = null }
if (!clip) {
if (ctx.setNotice) ctx.setNotice({ type: 'err', text: '选中的节点无法复制(可能还在加载)' })
return
}
const wrote = writeToEvent(e, clip)
if (wrote) {
try { e.preventDefault() } catch (err) { /* ignore */ }
if (ctx.markSys) ctx.markSys(true)
if (ctx.stageClip) ctx.stageClip(clip)
return
}
// setData 不可用(极端环境):让原生走,同时用旧异步链路补写系统剪贴板
if (ctx.copyNodes) ctx.copyNodes(ids)
}
/* keydown 兜底:copy 事件没派发时(不派发 `copy` 的 WebView / 焦点在 iframe),
* 按旧链路再复制一次。keydown 里**不 preventDefault** —— 一 prevent 就取消了原生复制动作,
* `copy` 事件反而不会派发。
* 80ms 而不是 0:copy 事件由浏览器在 keydown 的默认动作里同步派发,正常都在 10ms 内到;
* 留 80ms 是给"事件稍晚一点"的环境,同时保证「⌘C 之后立刻 ⌘V」时剪贴板已经写好
* (旧实现没有延迟,但那条路在 mac 上根本走不到 —— 参见 bindCopy 顶部注释)。 */
const onKey = (e) => {
if (!(e.metaKey || e.ctrlKey) || e.shiftKey || e.altKey) return
if (String(e.key || '').toLowerCase() !== 'c') return
const ctx = ctxNow()
if (!ctx) return
const at = Date.now()
setTimeout(() => {
if (handledAt >= at) return // copy 事件已经处理过
const ids = selOf(ctx)
if (!ids.length) return
if (textSelected(ctx, e.target)) return
if (ctx.copyNodes) ctx.copyNodes(ids)
}, 80)
}
window.addEventListener('copy', onCopy, true)
window.addEventListener('keydown', onKey, true)
copyBound = { onCopy, onKey }
}
/* 摘掉监听(Workbench 卸载 / 依赖变化时由 app.js 调用)。
* 不摘会出事:关掉画布回到首页后 ⌘C 仍走这条路,闭包里是**已经卸载的那份 refs** ——
* 会去复制旧画布上"当时的选中节点",用户在首页按一次 ⌘C 就莫名其妙改了剪贴板。 */
function unbindCopy() {
if (!copyBound) return
try { window.removeEventListener('copy', copyBound.onCopy, true) } catch (e) { /* ignore */ }
try { window.removeEventListener('keydown', copyBound.onKey, true) } catch (e) { /* ignore */ }
copyBound = null
}
g.IWBClipboardGraph = Object.freeze({ MARK, encodeText, decodeText, htmlFor, plainFor, decode, write, writeToEvent, matchPlain, bindCopy, unbindCopy })
})(typeof window !== 'undefined' ? window : globalThis)