feat(image-annotate): 编辑器内 ⌘/Ctrl+V 粘贴剪贴板图片为新图层(1.0.4)

- 粘贴优先级:剪贴板图片文件 > text/html 的 <img src> > text/plain 图片 URL/data URL
- 命中后进入既有「图片放置」模式(拖动/缩放,点外部或回车确认,Esc 取消)
- URL 一律 fetch→blob→dataURL(跨域图直接挂 <img> 会污染画布,导出时 toBlob 抛 SecurityError);
  data: URL 反而不能 fetch(CSP connect-src 无 data:),直接走 loadImage
- 命中即 stopImmediatePropagation:宿主在 window 气泡阶段也监听 paste(建 ref 节点+下载),
  不掐断会一次粘贴双响应,且宿主抢先建节点会破坏后续「覆盖」写回(e2e 实测抓到)
- 正在文字输入框打字时不抢 text/html 与 text/plain 的粘贴
- e2e 新增合成 ClipboardEvent 粘贴用例;修过期 SRI 断言(内容寻址名带哈希)
This commit is contained in:
qiqi committed 2026-11-04 15:49:50 +08:00
1 parent 0cdadc3a89
commit 5f9303986a
6 files changed
+179 -11

No files matched your search

+14 -5
View File
@@ -24,6 +24,17 @@
- 点「覆盖」→ `ctx.canvas.setNodeImage(nodeId, dataUrl)`
- 点「新建」→ `ctx.canvas.createImageNode({ dataUrl, name })`(宿主会建一个 `ref` 节点)
### 剪贴板粘贴(v1.0.4)
编辑器打开时按 **⌘/Ctrl+V**,把剪贴板里的图片**贴为新图层**(与「导入图片为新图层」同一流程:
先进入放置模式调整大小/位置,点外部或回车确认,Esc 取消)。优先级:
1. 剪贴板里的**图片文件**(截图 / 右键复制图片)
2. `text/html` 里的 `<img src>`(网页里复制图片的形态)
3. `text/plain` 的图片 URL / data URL
实现要点:URL 必须 **fetch→blob→dataURL**(直接 `new Image(url)` 会污染画布,导出时 toBlob 抛 SecurityError),
而 `data:` URL 不能 fetch(CSP `connect-src` 不含 `data:`,会被拦)要直接走 `loadImage`。
正在文字输入框打字时不抢文本粘贴。
## 已知限制(v1)
- **远程 http(s) 图片不支持**:`ctx.canvas.getNodeImage` 对非 data: 字符串只返回 `{ url }`(画布读像素会污染),
插件会给出「请先转存为本地位图」的提示。对象引用(`{__blob}` 等)会被宿主解成 dataUrl,正常可用。
@@ -51,12 +62,10 @@ npm run validate # 契约校验
```bash
cd /Users/qiqi/open/github/image-workbench-web
cp /Users/qiqi/open/github/iwb-plugins/image-annotate/src/index.js /tmp/plugin-image-annotate.js
# ⚠️ 必须把所有插件文件一起传入:发布器用「传入的文件」重建清单,不做合并。
# 只传自己 → 别的插件会从 plugins/index.json 里消失(已实测踩到,靠 git checkout 复原)。
cp /Users/qiqi/open/github/iwb-plugins/xianyi-cutout/src/index.js /tmp/plugin-xianyi-cutout.js
node scripts/plugins-publish.mjs /tmp/plugin-image-annotate.js /tmp/plugin-xianyi-cutout.js \
--version image-annotate=1.0.1 # 默认 dry-run,检查 diff 后再加 --upload
node scripts/plugins-publish.mjs /tmp/plugin-image-annotate.js --version image-annotate=1.0.4 # 先 dry-run,检查后加 --upload
```
发布脚本**默认与线上清单合并**(本次没传的插件原样保留),只传自己的文件即可;`--prune` 才会缩减清单(别用)。
版本两处一起改:`package.json`(构建时注入 manifest)+ `--version`。上传后回读校验清单与本地一致。
发布后刷新即生效(KV 为测试站/正式站共享;新插件在插件管理里**默认未启用**,需手动开启)。
## 验证(可选,开发用)
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@iwb-plugin/image-annotate",
"private": true,
"version": "1.0.3",
"version": "1.0.4",
"description": "IWB 插件:图片标注 / 修图(编辑器移植自 iwb-plaus 扩展,纯 Canvas 2D)",
"ibwPlugin": {
"id": "image-annotate",
+1 -1
View File
@@ -69,7 +69,7 @@ import { bindEvents } from './events.js'
<div class="iwb-editor-layer-panel-header">
<span class="iwb-editor-layer-panel-title">图层</span>
<div class="iwb-editor-layer-add-group">
<button class="iwb-editor-layer-add-btn" data-action="addBitmapLayer" title="导入图片为新图层"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/><line x1="19" y1="8" x2="19" y2="14"/><line x1="22" y1="11" x2="16" y2="11"/></svg></button>
<button class="iwb-editor-layer-add-btn" data-action="addBitmapLayer" title="导入图片为新图层(也可直接 ⌘/Ctrl+V 粘贴剪贴板图片)"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/><line x1="19" y1="8" x2="19" y2="14"/><line x1="22" y1="11" x2="16" y2="11"/></svg></button>
<button class="iwb-editor-layer-add-btn" data-action="addBlankLayer" title="新建空白图层"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg></button>
</div>
</div>
+72 -1
View File
@@ -1108,11 +1108,13 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
})
}
/** 全局监听:键盘快捷键、窗口失焦、modal 内阻止冒泡 */
/** 全局监听:键盘快捷键、窗口失焦、剪贴板粘贴、modal 内阻止冒泡 */
function bindGlobalListeners() {
// 键盘快捷键
document.addEventListener('keydown', onKeydown, true)
document.addEventListener('keyup', onKeyup, true)
// 剪贴板粘贴(⌘/Ctrl+V):编辑器打开时把剪贴板里的图片贴为新图层
document.addEventListener('paste', onPaste, true)
// 窗口失焦
window.addEventListener('blur', () => {
@@ -1355,3 +1357,72 @@ import { hexToRgb, parseRatio, rgbToHex } from '../vendor/image-math.js'
updateCursor()
}
}
// ============ 剪贴板粘贴(⌘/Ctrl+V 贴为新图层)============
/**
* 优先级:剪贴板里的图片文件(截图 / 复制图片)> text/html 里的 <img src>(网页里复制图片的形态)
* > text/plain 的图片 URL。命中即 preventDefault,进入「图片放置」模式 ——
* 与「导入图片为新图层」完全同一流程:拖动 / 缩放调好后点外部或回车确认,Esc 取消。
* 两个坑(都实测过):
* 1) URL 不能直接 new Image(url):跨域图会污染所有画布,导出时 toBlob 抛 SecurityError
* (表现是「图片跨域无法导出」)⇒ 必须 fetch→blob→dataURL(CSP connect-src 放行 https:);
* 反过来 data: URL 不能 fetch(connect-src 没有 data:,会被 CSP 拦),要直接走 loadImage。
* 2) 正在输入文字(isTyping)时不抢 text/html 与 text/plain 的粘贴 —— 用户可能就是想往文字输入框里贴 URL。
*/
function onPaste(e) {
if (!S.open) return
const cd = e.clipboardData
if (!cd) return
// ① 图片文件(截图 / 右键复制图片)
const items = cd.items || []
for (const item of items) {
if (item.kind === 'file' && /^image\//.test(item.type)) {
const file = item.getAsFile()
if (!file) continue
// 宿主在 window 气泡阶段也监听 paste(会把图片建成 ref 节点 + 触发下载)——
// 编辑器打开时这次粘贴归编辑器,必须掐断后续传播,否则一次粘贴出两层表现
e.preventDefault()
e.stopImmediatePropagation()
const reader = new FileReader()
reader.onload = async () => {
try { addBitmapLayer(await loadImage(reader.result)) }
catch (err) { console.error('[IWB编辑器] 粘贴图层失败:', err) }
}
reader.readAsDataURL(file)
return
}
}
if (isTyping(e)) return
// ② 网页复制的图片:text/html 里带 <img src="...">
const html = typeof cd.getData === 'function' ? (cd.getData('text/html') || '') : ''
if (html) {
const m = /<img[^>]*\ssrc\s*=\s*["']([^"']+)["']/i.exec(html)
if (m) { e.preventDefault(); e.stopImmediatePropagation(); pasteImageFromUrl(m[1]); return }
}
// ③ 纯文本:图片链接 / data URL
const text = (typeof cd.getData === 'function' ? (cd.getData('text/plain') || '') : '').trim()
if (/^(https?:\/\/\S+|data:image\/\S+)$/i.test(text)) { e.preventDefault(); e.stopImmediatePropagation(); pasteImageFromUrl(text); return }
}
/** 把 URL / data URL 的图片取回并贴为新图层;失败时给出可见提示(console + alert,编辑器没有 toast) */
async function pasteImageFromUrl(url) {
try {
let dataUrl = url
if (!/^data:image\//i.test(url)) {
const resp = await fetch(url)
if (!resp.ok) throw new Error('HTTP ' + resp.status)
const blob = await resp.blob()
if (!/^image\//.test(blob.type)) throw new Error('链接不是图片(' + (blob.type || '未知类型') + ')')
dataUrl = await new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => resolve(reader.result)
reader.onerror = () => reject(new Error('图片读取失败'))
reader.readAsDataURL(blob)
})
}
addBitmapLayer(await loadImage(dataUrl))
} catch (err) {
console.error('[IWB编辑器] 粘贴图片链接失败:', err)
try { window.alert('粘贴失败:' + ((err && err.message) || '无法读取剪贴板里的图片链接')) } catch (e) { /* 忽略 */ }
}
}
+69 -2
View File
@@ -9,7 +9,7 @@
var __IWB_ANNOTATE_MANIFEST__ = {
id: 'image-annotate',
name: '标注 / 修图',
version: '1.0.3',
version: '1.0.4',
apiVersion: 1,
capabilities: ['commands', 'nodeActions', 'canvas', 'canvasWrite'],
}
@@ -1105,7 +1105,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
<div class="iwb-editor-layer-panel-header">
<span class="iwb-editor-layer-panel-title">图层</span>
<div class="iwb-editor-layer-add-group">
<button class="iwb-editor-layer-add-btn" data-action="addBitmapLayer" title="导入图片为新图层"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/><line x1="19" y1="8" x2="19" y2="14"/><line x1="22" y1="11" x2="16" y2="11"/></svg></button>
<button class="iwb-editor-layer-add-btn" data-action="addBitmapLayer" title="导入图片为新图层(也可直接 ⌘/Ctrl+V 粘贴剪贴板图片)"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/><line x1="19" y1="8" x2="19" y2="14"/><line x1="22" y1="11" x2="16" y2="11"/></svg></button>
<button class="iwb-editor-layer-add-btn" data-action="addBlankLayer" title="新建空白图层"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg></button>
</div>
</div>
@@ -2344,6 +2344,7 @@ var __IWB_ANNOTATE_MANIFEST__ = {
function bindGlobalListeners() {
document.addEventListener("keydown", onKeydown, true);
document.addEventListener("keyup", onKeyup, true);
document.addEventListener("paste", onPaste, true);
window.addEventListener("blur", () => {
if (S.spaceDown) {
S.spaceDown = false;
@@ -2626,6 +2627,72 @@ var __IWB_ANNOTATE_MANIFEST__ = {
updateCursor();
}
}
function onPaste(e) {
if (!S.open) return;
const cd = e.clipboardData;
if (!cd) return;
const items = cd.items || [];
for (const item of items) {
if (item.kind === "file" && /^image\//.test(item.type)) {
const file = item.getAsFile();
if (!file) continue;
e.preventDefault();
e.stopImmediatePropagation();
const reader = new FileReader();
reader.onload = async () => {
try {
addBitmapLayer(await loadImage(reader.result));
} catch (err) {
console.error("[IWB编辑器] 粘贴图层失败:", err);
}
};
reader.readAsDataURL(file);
return;
}
}
if (isTyping(e)) return;
const html = typeof cd.getData === "function" ? cd.getData("text/html") || "" : "";
if (html) {
const m = /<img[^>]*\ssrc\s*=\s*["']([^"']+)["']/i.exec(html);
if (m) {
e.preventDefault();
e.stopImmediatePropagation();
pasteImageFromUrl(m[1]);
return;
}
}
const text = (typeof cd.getData === "function" ? cd.getData("text/plain") || "" : "").trim();
if (/^(https?:\/\/\S+|data:image\/\S+)$/i.test(text)) {
e.preventDefault();
e.stopImmediatePropagation();
pasteImageFromUrl(text);
return;
}
}
async function pasteImageFromUrl(url) {
try {
let dataUrl = url;
if (!/^data:image\//i.test(url)) {
const resp = await fetch(url);
if (!resp.ok) throw new Error("HTTP " + resp.status);
const blob = await resp.blob();
if (!/^image\//.test(blob.type)) throw new Error("链接不是图片(" + (blob.type || "未知类型") + ")");
dataUrl = await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject(new Error("图片读取失败"));
reader.readAsDataURL(blob);
});
}
addBitmapLayer(await loadImage(dataUrl));
} catch (err) {
console.error("[IWB编辑器] 粘贴图片链接失败:", err);
try {
window.alert("粘贴失败:" + (err && err.message || "无法读取剪贴板里的图片链接"));
} catch (e) {
}
}
}
// image-annotate/plugin/editor/viewport.js
function syncOverlayCanvas() {
+22 -1
View File
@@ -55,6 +55,7 @@ const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } })
const consoleErrors = []
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) })
page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message))
page.on('dialog', (d) => { consoleErrors.push('unexpected dialog: ' + d.message()); d.dismiss().catch(() => {}) })
// 造一张真实的 96x64 PNG 作为节点图片
await page.goto('about:blank')
@@ -92,7 +93,7 @@ check('从真实 KV 加载并启用(SRI 通过)', Boolean(active), JSON.stri
check('线上版本 = package.json(' + WANT_VERSION + ')', Boolean(active && active.version === WANT_VERSION), active && active.version)
const scripts = await page.evaluate(() => Array.from(document.querySelectorAll('script[src*="/plugins/"]')).map((s) => ({ src: s.getAttribute('src'), integrity: s.getAttribute('integrity') || '' })))
check('插件脚本用 SRI(sha256) 加载', scripts.some((s) => /plugin-image-annotate\.js$/.test(s.src) && /^sha256-/.test(s.integrity)), JSON.stringify(scripts))
check('插件脚本用 SRI(sha256) 加载', scripts.some((s) => /^\/plugins\/plugin-image-annotate\.[a-f0-9]{12}\.js$/.test(s.src) && /^sha256-/.test(s.integrity)), JSON.stringify(scripts))
// ---------- 2) 打开工作区 + 节点存在 ----------
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
@@ -128,6 +129,26 @@ check('编辑器浮层可见', opened.display === 'flex' && opened.position ===
check('样式注入生效(CSP unsafe-inline)', opened.styleInjected)
check('浮层压住宿主 UI', Number(opened.zIndex) >= 999998, 'z=' + opened.zIndex + ' bg=' + opened.bg)
// ---------- 4.5) 剪贴板粘贴:⌘V 把剪贴板图片贴为新图层 ----------
// 合成 ClipboardEvent(带 image/png File),粘贴应进入「图片放置」模式;回车确认后图层面板 +1 项。
// SKIP_PASTE=1 可跳过(隔离「粘贴」与「覆盖写回」两条链路的排查用)。
const SKIP_PASTE = process.env.SKIP_PASTE === '1'
const layersBefore = await page.evaluate(() => document.querySelectorAll('.iwb-editor-layer-list > *').length)
if (!SKIP_PASTE) {
await page.evaluate((png) => {
const bin = atob(png.split(',')[1])
const bytes = new Uint8Array(bin.length)
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
const dt = new DataTransfer()
dt.items.add(new File([bytes], 'paste.png', { type: 'image/png' }))
document.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true }))
}, PNG)
await page.waitForTimeout(800) // FileReader → loadImage → 进入放置模式
await page.keyboard.press('Enter') // 确认放置 → 落层
const pasted = await poll(async () => page.evaluate((n) => document.querySelectorAll('.iwb-editor-layer-list > *').length > n, layersBefore))
check('⌘V 粘贴剪贴板图片 → 确认后图层面板 +1', Boolean(pasted), '图层项 ' + layersBefore + ' → ' + await page.evaluate(() => document.querySelectorAll('.iwb-editor-layer-list > *').length))
}
// ---------- 5) 覆盖:回写真机画布 ----------
await page.mouse.move(400, 300)
await page.mouse.down()