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 条,均为无头环境剪贴板限制)。
This commit is contained in:
qiqi committed 2026-11-26 12:45:56 +08:00
1 parent 9c27a8178b
commit 18eaeb96f2
11 files changed
+573 -131

No files matched your search

+150 -14
View File
@@ -66,6 +66,11 @@
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,
@@ -76,7 +81,33 @@
groups: (clip && clip.groups) || [],
})
const head = plainFor(clip)
return '<!--' + MARK + encodeText(payload) + '--><div>' + esc(head.slice(0, 200)) + '</div>'
const b64 = encodeText(payload)
return '<!--' + MARK + b64 + '--><div data-iwb-graph="' + b64 + '">' + esc(head.slice(0, 200)) + '</div>'
}
// 属性形态的标记(引号单双都认:不同应用回写 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 为空
@@ -85,18 +116,27 @@
* 定位标记,不能假设它以注释开头。 */
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 }
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<boolean>:false 表示这个环境写不了
@@ -147,5 +187,101 @@
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 })
/* 复制主通道: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)