Files
image-workbench-desktop/src/clipboard-paste-once.js
T

60 lines
2.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.67)
*
* 场景:节点上的「粘贴图片替换」按钮(节点头部按钮 / 选中气泡按钮)。
* 点按钮时先试 navigator.clipboard.read();不支持或失败时,挂一个捕获阶段 paste 监听等用户按 Ctrl+V。
*
* 修的是什么:旧实现里的 once 监听只在**paste 事件到达时**自我摘除,
* 而 clipboard.read() 这条成功路径从不摘除它。于是用户点过一次按钮之后,
* 那个监听会一直挂在那里 —— 之后任何时候粘贴图片,它会先把旧参考图再替换一次
* (它只 preventDefault 不阻止冒泡,全局 onPaste 照样新建节点)。
* 实测「先按钮粘红图、再粘贴绿图」→ 参考图变成绿图,且「两个节点各点一次按钮」→ 一次粘贴替换两张。
* 现在:真正用上(拿到图片并交给 onImage)就立刻摘除。
*
* 另一处修的是「两套单例」:src/ui-node-card.js 用 W_NODECARD_PASTE_ONCE,
* src/runtime-workbench-logic.js 用 refs.pasteOnce,互相不知道对方存在,可以同时待命。
* 现在两边共用这一个槽位 —— 同一时刻最多一个待命监听。
*/
;(function (global) {
'use strict'
const g = (global && typeof global === 'object') ? global : {}
const store = (g.__IWB_PASTE_ONCE__ = g.__IWB_PASTE_ONCE__ || { slot: null })
function disarm() {
if (!store.slot) return
try { g.removeEventListener('paste', store.slot, true) } catch (e) { /* ignore */ }
store.slot = null
}
/* arm(onImage):注册一次待命。
* onImage 收到的是**图片 File 数组**(≥1 个),调用方取第一张即可。
* 不是图片的粘贴一律不拦截、也不摘除 —— 用户等的就是图片。 */
function arm(onImage) {
disarm()
const handler = (e) => {
const picked = []
const items = (e.clipboardData && e.clipboardData.items) || []
for (let i = 0; i < items.length; i++) {
const it = items[i]
if (!it || !it.type || String(it.type).toLowerCase().indexOf('image/') !== 0) continue
let f = null
try { f = it.getAsFile ? it.getAsFile() : null } catch (err) { f = null }
if (f) picked.push(f)
}
if (!picked.length) return
e.preventDefault()
disarm()
try { onImage(picked) } catch (err) { /* 应用失败不应把异常抛回浏览器事件栈 */ }
}
store.slot = handler
g.addEventListener('paste', handler, true)
return { disarm }
}
g.IWBPasteOnce = Object.freeze({
arm,
disarm,
pending: () => !!store.slot,
})
})(typeof window !== 'undefined' ? window : globalThis)