Files
qiqi 18eaeb96f2 fix(clipboard): mac ⌘C/⌘V 一条命令贴一切(copy 事件主通道 + keydown 主动粘贴)
mac 的 WKWebView 只在第一响应者可编辑时派发 paste 事件;Menu::default() 的 Edit>Copy/Paste
又永远 enabled,所以「焦点在输入框/有选区」时 keydown 到不了 JS —— 复制节点组静默失败、
⌘V 只剩一句「请按 Ctrl+Shift+V」。本次把两条通道都换掉:

- 复制:DOM copy 事件里同步 clipboardData.setData(text/html 带标记 + text/plain 摘要),
  keydown 留 80ms 兜底,Workbench 卸载时摘监听(否则回首页 ⌘C 会复制旧画布)。
- 粘贴:⌘V keydown 主动粘贴,指针在画布即接管,逐级降级(系统剪贴板富读取 → 原生文本
  → 原生图片 → 应用内剪贴板);150ms 内等到 paste 事件就让给事件通道,一次按键只贴一份。
- 输入框内:指针在画布 → 改贴画布;只有「N 个节点」摘要 → 拦下不进输入框;
  带提示词全文 → 放行原生。
- 标记双写注释 + data-iwb-graph 属性(WKWebView 会剥注释);decode 两处都找。
- 未选中节点复制、复制/粘贴失败都有提示;notice 的 err/info 5.2s 自动消失。

门禁:clipboard-graph 56 项 / clipboard-paste 100 项,e2e 用例 5、19 按新语义更新
(e2e 已知红与基线一致:7 条,均为无头环境剪贴板限制)。
2026-11-26 12:45:56 +08:00

216 lines
12 KiB
JavaScript
Raw Permalink 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.
'use strict'
// 统一剪贴板的序列化(src/clipboard-graph.js)—— 独立文件
// 背景(用户 2026-11-11 二次裁定):复制节点要能直接用 Ctrl+V 贴回来,不再要求 Ctrl+Shift+V。
// 做法是把节点组写进系统剪贴板的 text/html(带 iwb:graph 标记)+ text/plain(人话摘要)。
// 这个文件守的是「标记能不能原样往返」—— 一旦丢字/丢节点,Ctrl+V 就会贴出错节点。
const fs = require('fs')
const path = require('path')
const root = path.join(__dirname, '..')
const SRC = fs.readFileSync(path.join(root, 'src/clipboard-graph.js'), 'utf8')
const box = {}
new Function('window', 'globalThis', SRC)(box, box)
const G = box.IWBClipboardGraph
let pass = 0, fail = 0
const ok = (name, cond) => { if (cond) { pass++; console.log(' ✅ ' + name) } else { fail++; console.log(' ❌ ' + name) } }
const eq = (name, got, want) => ok(name + '(' + JSON.stringify(got) + ' === ' + JSON.stringify(want) + ')', got === want)
const mkClip = (over) => Object.assign({
app: 'image-workbench', type: 'iwb-clipboard', at: 1760000000000,
nodes: [
{ id: 'n1', type: 'prompt', x: 0, y: 0, data: { text: '一只赛博朋克风格的猫', title: '' } },
{ id: 'n2', type: 'ref', x: 300, y: 0, data: { url: '', data: null, name: 'ref.png', localName: null } },
],
edges: [{ id: 'e1', from: 'n1', to: 'n2' }],
groups: [{ id: 'g1', name: '分组 1', memberIds: ['n1', 'n2'] }],
}, over || {})
// ---- ① 导出 ----
ok('模块导出完整', !!G && typeof G.htmlFor === 'function' && typeof G.decode === 'function' && typeof G.write === 'function')
eq('标记常量', G.MARK, 'iwb:graph:v1:')
// ---- ② 往返 ----
{
const c = mkClip()
const html = G.htmlFor(c)
ok('htmlFor 含标记', html.indexOf('iwb:graph:v1:') >= 0)
const back = G.decode(html)
ok('decode 能解回', !!back)
eq('节点数一致', back && back.nodes.length, 2)
eq('连线数一致', back && back.edges.length, 1)
eq('分组数一致', back && back.groups.length, 1)
eq('中文提示词不丢字', back && back.nodes[0].data.text, '一只赛博朋克风格的猫')
eq('分组 id 保留', back && back.groups[0].memberIds.join(','), 'n1,n2')
eq('at 时间戳保留', back && back.at, 1760000000000)
}
// ---- ③ 中文必须能编码:btoa 只吃 latin1,直接 btoa(JSON) 会抛 InvalidCharacterError ----
{
let threw = null
let html = ''
try { html = G.htmlFor(mkClip()) } catch (e) { threw = e }
ok('中文不会让编码抛异常(btoa latin1 坑)', threw === null)
ok('中文往返后仍是中文', (G.decode(html) || { nodes: [{ data: {} }] }).nodes[0].data.text === '一只赛博朋克风格的猫')
}
// ---- ④ Chrome 读回来会把 fragment 包成完整文档:decode 不能假设以注释开头 ----
{
const html = G.htmlFor(mkClip())
const wrapped = '<html><head></head><body>' + html + '</body></html>'
eq('被 <html> 包裹后仍能解', (G.decode(wrapped) || {}).nodes.length, 2)
eq('前面有别的节点也能解', (G.decode('<div>无关内容</div>' + html) || {}).nodes.length, 2)
}
// ---- ⑤ 坏输入一律返回 null,绝不抛 ----
eq('没有标记 → null', G.decode('<div>普通网页内容</div>'), null)
eq('空字符串 → null', G.decode(''), null)
eq('null → null', G.decode(null), null)
eq('标记后跟垃圾 → null', G.decode('<!--iwb:graph:v1:@@@@-->'), null)
eq('base64 但 JSON 坏 → null', G.decode('<!--iwb:graph:v1:' + G.encodeText('{not json') + '-->'), null)
eq('nodes 为空数组 → null', G.decode('<!--iwb:graph:v1:' + G.encodeText(JSON.stringify({ nodes: [] })) + '-->'), null)
eq('nodes 不是数组 → null', G.decode('<!--iwb:graph:v1:' + G.encodeText(JSON.stringify({ nodes: 'x' })) + '-->'), null)
eq('标记没闭合(被截断)仍尽力解出', (G.decode('<!--iwb:graph:v1:' + G.encodeText(JSON.stringify({ nodes: [{ id: 'a' }] }))) || {}).nodes.length, 1)
// ---- ⑥ text/plain 是给别的应用看的「人话」 ----
{
eq('有提示词 → 就是提示词全文', G.plainFor(mkClip()), '一只赛博朋克风格的猫')
eq('没有提示词 → N 个节点', G.plainFor({ nodes: [{ type: 'ref', data: {} }] }), '1 个节点')
eq('带分组名', G.plainFor({ nodes: [{ type: 'ref', data: {} }, { type: 'ref', data: {} }], groups: [{ name: '分组 1' }] }), '2 个节点(分组 1)')
const withB64 = G.plainFor({ nodes: [{ type: 'ref', data: { data: 'data:image/png;base64,' + 'A'.repeat(5000) } }] })
ok('绝不把图片 base64 塞进 text/plain(旧实现被撤回的原因)', withB64.indexOf('base64') < 0 && withB64.length < 40)
const long = G.plainFor({ nodes: [{ type: 'prompt', data: { text: 'x'.repeat(50000) } }] })
ok('超长提示词有上限(不把 5 万字塞进剪贴板)', long.length === 20000)
}
// ---- ⑦ htmlFor 里的摘要要转义,不能把提示词当标签 ----
{
const html = G.htmlFor({ nodes: [{ type: 'prompt', data: { text: '<img src=x onerror=alert(1)>' } }] })
ok('摘要里的尖括号被转义', html.indexOf('<img src=x') < 0 && html.indexOf('&lt;img') >= 0)
eq('转义后仍能解回', (G.decode(html) || {}).nodes.length, 1)
}
// ---- ⑧ 体积:大 payload 不能爆栈(String.fromCharCode.apply 有参数上限)----
{
const big = mkClip({
nodes: [{ id: 'big', type: 'prompt', x: 0, y: 0, data: { text: '中文测试'.repeat(60000) } }],
edges: [], groups: [],
})
let threw = null, back = null
try { back = G.decode(G.htmlFor(big)) } catch (e) { threw = e }
ok('1MB 级中文 payload 编解码不抛(分块 base64)', threw === null)
eq('大 payload 节点数一致', back && back.nodes.length, 1)
eq('大 payload 文本长度一致', back && back.nodes[0].data.text.length, '中文测试'.repeat(60000).length)
}
// ---- ⑨ write:环境不支持时降级为 false(不 reject、不抛)----
;(async () => {
{
const r = await G.write(mkClip())
eq('没有 navigator.clipboard → false', r, false)
}
{
const b2 = {}
new Function('window', 'globalThis', SRC)(b2, b2)
const G2 = b2.IWBClipboardGraph
b2.navigator = { clipboard: { write: () => Promise.resolve() } }
b2.ClipboardItem = function (data) { this.data = data }
b2.Blob = function (parts, opts) { this.parts = parts; this.type = opts && opts.type }
const r = await G2.write(mkClip())
eq('能写时返回 true', r, true)
}
{
const b3 = {}
new Function('window', 'globalThis', SRC)(b3, b3)
const G3 = b3.IWBClipboardGraph
b3.navigator = { clipboard: { write: () => Promise.reject(new DOMException('denied', 'NotAllowedError')) } }
b3.ClipboardItem = function (data) { this.data = data }
b3.Blob = function (parts, opts) { this.parts = parts; this.type = opts && opts.type }
eq('写入被拒 → false(不抛)', await G3.write(mkClip()), false)
}
{
const b4 = {}
new Function('window', 'globalThis', SRC)(b4, b4)
const G4 = b4.IWBClipboardGraph
b4.navigator = { clipboard: { write: () => { throw new Error('boom') } } }
b4.ClipboardItem = function (data) { this.data = data }
b4.Blob = function (parts, opts) { this.parts = parts; this.type = opts && opts.type }
eq('写入同步抛错 → false(不抛)', await G4.write(mkClip()), false)
}
// ---- ⑧ 双标记 + copy 事件通道(2026-11-26)----
// 背景:WKWebView 写/读剪贴板时会剥掉 HTML 注释 ⇒ 只剩 data-iwb-graph 属性可用;
// 复制改由 DOM copy 事件同步写 clipboardData(mac 上 ⌘C 被原生菜单接管时 keydown 到不了 JS)。
{
const c = mkClip()
const html = G.htmlFor(c)
ok('htmlFor 同时写了注释标记与 data-iwb-graph 属性', html.indexOf('iwb:graph:v1:') >= 0 && html.indexOf('data-iwb-graph=') >= 0)
const attrOnly = html.replace(/<!--[\s\S]*?-->/, '') // 模拟 WebKit 把注释剥掉
ok('注释被剥掉后属性仍能解回', !!G.decode(attrOnly))
eq('属性解回的节点数一致', (G.decode(attrOnly) || {}).nodes ? G.decode(attrOnly).nodes.length : -1, 2)
eq('属性用单引号包裹也能解', !!G.decode(html.replace(/data-iwb-graph="[^"]*"/, (m) => m.replace(/"/g, "'"))), true)
eq('没有标记 → null', G.decode('<div>普通网页</div>'), null)
}
{
const c = mkClip()
const dt = { data: {}, setData(k, v) { this.data[k] = v } }
const ev = { clipboardData: dt, defaultPrevented: false, preventDefault() { ev.defaultPrevented = true } }
eq('writeToEvent 返回 true', G.writeToEvent(ev, c), true)
ok('写了 text/html(带标记)', String(dt.data['text/html']).indexOf('iwb:graph:v1:') >= 0)
eq('写了 text/plain(人话摘要,不是裸 JSON)', dt.data['text/plain'], G.plainFor(c))
eq('writeToEvent 不碰 preventDefault(交给调用方)', ev.defaultPrevented, false)
eq('没有 clipboardData → false(不抛)', G.writeToEvent({}, c), false)
}
{
// bindCopy:注册 copy 监听,事件里同步写剪贴板 + 落内部剪贴板
const b = { h: {}, addEventListener(t, fn) { (b.h[t] = b.h[t] || []).push(fn) }, removeEventListener(t, fn) { const a = b.h[t] || []; const i = a.indexOf(fn); if (i >= 0) a.splice(i, 1) } }
new Function('window', 'globalThis', SRC)(b, b)
let staged = null
let notice = null
let sysOk = null
const ctx = {
ids: () => ['n1', 'n2'],
clipboardOf: () => mkClip(),
stageClip: (c) => { staged = c; notice = { type: 'ok', text: '已复制 ' + c.nodes.length + ' 个节点' }; return true },
setNotice: (n) => { notice = n },
markSys: (ok) => { sysOk = ok },
hasTextSelection: () => false,
}
let current = ctx
b.IWBClipboardGraph.bindCopy(() => current)
const fire = (ev) => (b.h.copy || []).forEach((fn) => fn(ev))
const dt = { data: {}, setData(k, v) { this.data[k] = v } }
const ev = { target: {}, clipboardData: dt, defaultPrevented: false, preventDefault() { ev.defaultPrevented = true } }
fire(ev)
ok('copy 事件:同步写进 clipboardData', String(dt.data['text/html']).indexOf('iwb:graph:v1:') >= 0)
eq('copy 事件:preventDefault(不覆盖用户其它剪贴板内容)', ev.defaultPrevented, true)
eq('copy 事件:内部剪贴板也落了一份', !!staged, true)
eq('copy 事件:标记系统剪贴板可写', sysOk, true)
ok('copy 事件:提示已复制', !!notice && String(notice.text).indexOf('已复制') >= 0)
// 有文本选区 → 让原生复制文字(不许抢)
staged = null
current = Object.assign({}, ctx, { hasTextSelection: () => true })
const ev2 = { target: {}, clipboardData: { setData() { throw new Error('不该写剪贴板') } }, defaultPrevented: false, preventDefault() { ev2.defaultPrevented = true } }
fire(ev2)
eq('有文本选区 → 不写剪贴板(原生复制文字)', staged, null)
eq('有文本选区 → 不 preventDefault', ev2.defaultPrevented, false)
// 没选中节点 → 说一句,别静默
notice = null
current = Object.assign({}, ctx, { ids: () => [] })
fire({ target: {}, clipboardData: { setData() {} }, defaultPrevented: false, preventDefault() {} })
ok('没选中节点 → 提示没有可复制的内容', !!notice && String(notice.text).indexOf('没有可复制') >= 0)
// 解绑后必须真的摘掉监听(否则回到首页按 ⌘C 会去复制已卸载那份 refs)
b.IWBClipboardGraph.unbindCopy()
staged = null
current = ctx
fire({ target: {}, clipboardData: { setData() { staged = 'wrote' } }, defaultPrevented: false, preventDefault() {} })
eq('unbindCopy 之后 copy 事件不再被处理', staged, null)
// 重新绑定可以恢复(Workbench 重挂载)
b.IWBClipboardGraph.bindCopy(() => current)
fire({ target: {}, clipboardData: { setData() {} }, defaultPrevented: false, preventDefault() {} })
eq('重新 bindCopy 后恢复处理', !!staged, true)
}
console.log('\n' + (fail ? '❌' : '✅') + ' clipboard-graph: ' + pass + ' passed, ' + fail + ' failed')
if (fail) process.exit(1)
})()