feat(image-annotate): 选区编辑 + 便利版 UI + 单张输出预设(1.1.0)

This commit is contained in:
qiqi committed 2026-11-04 17:00:49 +08:00
1 parent b9ace636ef
commit 662d7eae77
22 files changed
+3795 -343

No files matched your search

+40 -1
View File
@@ -54,7 +54,7 @@ const browser = await chromium.launch()
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('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message + ' @ ' + String(e.stack || '').split('\n').slice(1, 4).join(' | ')))
page.on('dialog', (d) => { consoleErrors.push('unexpected dialog: ' + d.message()); d.dismiss().catch(() => {}) })
// 造一张真实的 96x64 PNG 作为节点图片
@@ -191,6 +191,45 @@ if (!SKIP_PASTE) {
await page.locator('.iwb-editor-tool[data-tool="brush"]').click()
}
// ---------- 4.7) v1.1:选区 / 单层 Delete / 还原原图 / ≤500KB 预设 ----------
const dbg = () => page.evaluate(() => window.__iwbEditor.__debug())
const v11Box = await page.locator('.iwb-editor-layer-canvas').first().boundingBox()
await page.locator('.iwb-editor-tool[data-tool="marquee"]').click()
await page.mouse.move(v11Box.x + v11Box.width * 0.25, v11Box.y + v11Box.height * 0.25)
await page.mouse.down()
await page.mouse.move(v11Box.x + v11Box.width * 0.7, v11Box.y + v11Box.height * 0.7, { steps: 8 })
await page.mouse.up()
await page.waitForTimeout(150)
const v11sel = (await dbg()).selection
check('v1.1 框选 + 浮动操作条出现', Boolean(v11sel && v11sel.w > 5 && v11sel.h > 5) &&
await page.locator('.iwb-editor-sel-bar').isVisible(), JSON.stringify(v11sel))
const v11px = (x, y) => page.evaluate(({ px, py }) => {
const d = window.__iwbEditor.__debug()
return { base: d.pixel('base', px, py), draw: d.pixel('draw', px, py) }
}, { px: x, py: y })
const vcX = Math.round(v11sel.x + v11sel.w / 2)
const vcY = Math.round(v11sel.y + v11sel.h / 2)
const v11before = await v11px(vcX, vcY)
await page.locator('.iwb-editor-sel-bar button[data-sel-cmd="sel.fill"]').click()
await page.locator('.iwb-editor-sel-bar button[data-sel-cmd="sel.delete"]').click()
const v11after = await v11px(vcX, vcY)
check('v1.1 Delete 只清当前层(base 像素原样)',
v11after.draw[3] === 0 && JSON.stringify(v11after.base) === JSON.stringify(v11before.base),
'draw=' + JSON.stringify(v11after.draw) + ' base=' + JSON.stringify(v11after.base))
await page.keyboard.press('Control+z')
const v11layersBeforeReset = (await dbg()).layers.length
await page.locator('[data-action="reset"]').click()
check('v1.1 还原原图=只剩原图+画笔层,不留下空白层', (await dbg()).layers.length === 2, JSON.stringify((await dbg()).layers))
await page.keyboard.press('Control+z')
check('v1.1 还原原图可 Ctrl+Z 撤销', (await dbg()).layers.length === v11layersBeforeReset,
'层数 ' + v11layersBeforeReset + ' → 2 → ' + (await dbg()).layers.length)
await page.locator('[data-action="toggleExportSettings"]').click()
await page.locator('[data-export-key="preset"][data-export-value="ecom800"]').click()
check('v1.1 ≤500KB 输出预设可切换', (await dbg()).exportOptions.maxKB === 500,
JSON.stringify((await dbg()).exportOptions))
await page.locator('[data-export-key="preset"][data-export-value="original"]').click()
await page.locator('.iwb-editor-tool[data-tool="brush"]').click()
// ---------- 5) 覆盖:回写真机画布 ----------
await page.mouse.move(400, 300)
await page.mouse.down()
+252
View File
@@ -0,0 +1,252 @@
// 标注插件本地端到端(开发用,不进 CI)。
//
// 为什么需要它:真站 e2e 要发布后才能跑;本探针直接把构建产物注入合成宿主,
// 在真实 Chromium 里验证「选区 / 命令层 / 撤销 / 还原原图 / 输出预设 / 便利 UI」
// 以及 ESM 循环打包后是否真的能跑起来。网络完全本地,不依赖线上 KV 与 CSP。
//
// 运行:node image-annotate/tools/harness.mjs
// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)
import { createRequire } from 'node:module'
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url))
const REPO = path.resolve(HERE, '../..')
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
const PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js')
let chromium = null
for (const base of [process.env.IWB_PLAYWRIGHT_ROOT, REPO, HOST_REPO, process.cwd()].filter(Boolean)) {
try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch { /* 试下一个 */ }
}
if (!chromium) {
console.error('✗ 找不到 playwright。请在含 node_modules 的目录执行,或指定 IWB_PLAYWRIGHT_ROOT')
process.exit(2)
}
let failed = 0
const check = (name, ok, detail) => {
if (!ok) failed++
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
const poll = async (fn, timeout = 8000, step = 80) => {
const end = Date.now() + timeout
for (;;) {
let v
try { v = await fn() } catch { v = false }
if (v) return v
if (Date.now() > end) return false
await new Promise((r) => setTimeout(r, step))
}
}
const browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, acceptDownloads: true })
const errors = []
page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()) })
page.on('pageerror', (e) => errors.push('pageerror: ' + e.message))
page.on('dialog', (d) => { errors.push('unexpected dialog: ' + d.message()); d.dismiss().catch(() => {}) })
await page.setContent('<!doctype html><html><head><meta charset="utf-8"></head><body><div id="host"></div></body></html>')
const PNG = await page.evaluate(() => {
const c = document.createElement('canvas')
c.width = 96; c.height = 64
const x = c.getContext('2d')
x.fillStyle = '#2f6fed'; x.fillRect(0, 0, 96, 64)
x.fillStyle = '#ffffff'; x.fillRect(20, 12, 56, 40)
return c.toDataURL('image/png')
})
// ---------- 合成宿主 ----------
await page.evaluate(() => {
window.IWBPluginHost = {
register(manifest, factory) { window.__manifest = manifest; window.__factory = factory },
snapshot() { return { initialized: true } },
list() { return [] }
}
window.__actions = {}
window.__commands = {}
window.__settings = {}
window.__writes = []
})
await page.addScriptTag({ path: PLUGIN_ENTRY })
const boot = await page.evaluate((png) => {
const ctx = {
id: 'image-annotate', manifest: window.__manifest, apiVersion: 1,
log() {},
settings: {
get(k) { return window.__settings[k] },
set(k, v) { window.__settings[k] = v },
all() { return { ...window.__settings } }
},
storage: { get() {}, set() {}, remove() {}, keys() { return [] } },
events: { on() { return () => {} }, emit() { return true } },
canvas: {
getNodeImage() { return { dataUrl: png } },
getSelectedNode() { return { id: 'r1', type: 'ref', name: 'src.png' } },
setNodeImage(id, dataUrl) { window.__writes.push({ kind: 'replace', id, len: String(dataUrl).length }); return true },
createImageNode(o) { window.__writes.push({ kind: 'newNode', len: String(o.dataUrl).length }); return { id: 'r2' } }
},
nodeActions: { register(r) { window.__actions[r.id] = r } },
commands: { register(r) { window.__commands[r.id] = r } }
}
window.__plugin = window.__factory(ctx)
window.__commands['annotate-selected'].run().catch(() => {})
return { version: window.__manifest.version, settingsSchema: Object.keys(window.__manifest.settings || {}) }
}, PNG)
check('产物可执行(循环打包未炸)', boot.version === '1.1.0', 'version=' + boot.version)
check('manifest 声明输出预设设置项', boot.settingsSchema.includes('exportPreset') && boot.settingsSchema.includes('panelsCollapsed'), boot.settingsSchema.join(','))
await page.locator('#iwb-editor-overlay').waitFor({ state: 'visible', timeout: 15000 })
const dbg = () => page.evaluate(() => window.__iwbEditor.__debug())
const pixel = (cx, cy) => page.evaluate(({ x, y }) => {
const d = window.__iwbEditor.__debug()
return { base: d.pixel('base', x, y), draw: d.pixel('draw', x, y), layers: d.layers.map(l => ({ id: l.id, a: d.pixel(l.id, x, y) })) }
}, { x: cx, y: cy })
check('编辑器打开 + 便利 UI 五区齐全', await page.evaluate(() => {
const q = (s) => Boolean(document.querySelector(s))
return q('.iwb-editor-optionbar') && q('.iwb-editor-statusbar') && q('.iwb-editor-sel-bar') &&
q('.iwb-editor-toast') && q('.iwb-editor-selection-overlay') && q('.iwb-editor-cursor-overlay') &&
q('[data-action="download"]') && q('[data-action="toggleMore"]')
}))
check('新增选区工具按钮', (await page.locator('.iwb-editor-tool[data-tool="marquee"]').count()) === 1 &&
(await page.locator('.iwb-editor-tool[data-tool="lasso"]').count()) === 1)
const imgBox = await page.locator('.iwb-editor-layer-canvas').first().boundingBox()
const drag = async (x1, y1, x2, y2) => {
await page.mouse.move(x1, y1)
await page.mouse.down()
await page.mouse.move(x2, y2, { steps: 8 })
await page.mouse.up()
await page.waitForTimeout(120)
}
// ---------- P1 选区 ----------
await page.locator('.iwb-editor-tool[data-tool="marquee"]').click()
await drag(imgBox.x + imgBox.width * 0.25, imgBox.y + imgBox.height * 0.25,
imgBox.x + imgBox.width * 0.7, imgBox.y + imgBox.height * 0.7)
const sel = (await dbg()).selection
check('拖出矩形选区 + 蚂蚁线启动', Boolean(sel && sel.w > 5 && sel.h > 5) && (await dbg()).ants, JSON.stringify(sel))
check('选区浮动操作条自动出现', await page.locator('.iwb-editor-sel-bar').isVisible())
const cx = Math.round(sel.x + sel.w / 2)
const cy = Math.round(sel.y + sel.h / 2)
const beforeFill = await pixel(cx, cy)
await page.locator('.iwb-editor-sel-bar button[data-sel-cmd="sel.fill"]').click()
const afterFill = await pixel(cx, cy)
check('填充只写当前层(base 像素不变)',
afterFill.draw && afterFill.draw[3] > 0 && JSON.stringify(afterFill.base) === JSON.stringify(beforeFill.base),
'draw=' + JSON.stringify(afterFill.draw) + ' base=' + JSON.stringify(afterFill.base))
const layersBeforeCopy = (await dbg()).layers.length
await page.locator('.iwb-editor-sel-bar button[data-sel-cmd="sel.copy"]').click()
const afterCopy = await dbg()
check('复制为新层:像素落在选区原位、原层不变',
afterCopy.layers.length === layersBeforeCopy + 1 && (await pixel(cx, cy)).draw[3] > 0,
'层数 ' + layersBeforeCopy + ' → ' + afterCopy.layers.length)
check('复制来源为当前层:新层有填充像素', afterCopy.layers.some(l => l.name === '选区副本') &&
(await pixel(cx, cy)).layers.some(v => v.id !== 'base' && v.id !== 'draw' && v.a && v.a[3] > 0))
await page.keyboard.press('Control+z')
check('Ctrl+Z 撤销「复制为新层」(图层数可回退)', (await dbg()).layers.length === layersBeforeCopy, '层数=' + (await dbg()).layers.length)
await page.locator('.iwb-editor-sel-bar button[data-sel-cmd="sel.delete"]').click()
const afterDelete = await pixel(cx, cy)
check('Delete 只清当前层:draw 挖空、base 与其它层原样',
afterDelete.draw[3] === 0 && JSON.stringify(afterDelete.base) === JSON.stringify(beforeFill.base),
'draw=' + JSON.stringify(afterDelete.draw) + ' base=' + JSON.stringify(afterDelete.base))
await page.keyboard.press('Control+z')
check('Ctrl+Z 恢复被清除的像素', (await pixel(cx, cy)).draw[3] > 0)
// 三入口共用命令层
await page.keyboard.press('Control+j')
const afterHotkey = await dbg()
check('快捷键 Ctrl+J 与浮动条共用 execute()',
afterHotkey.layers.length === layersBeforeCopy + 1 && afterHotkey.historyLabels.includes('复制为新层'),
'labels=' + JSON.stringify(afterHotkey.historyLabels.slice(-3)))
await page.keyboard.press('Control+z')
await page.mouse.click(imgBox.x + imgBox.width * 0.8, imgBox.y + imgBox.height * 0.2, { button: 'right' })
check('右键菜单复用同一条操作条', await page.locator('.iwb-editor-sel-bar.as-menu').count() === 1)
// ---------- 还原原图(用户裁定:全部还原 + 可撤销) ----------
await page.keyboard.press('Control+a') // 重建选区(右键/工具切换不会改像素)
await page.keyboard.press('Control+j') // 制造一个额外的选区副本层
const beforeReset = await dbg()
await page.locator('[data-action="reset"]').click()
const afterReset = await dbg()
check('还原原图:只剩「原图 + 空画笔层」,无空白粘贴层',
afterReset.layers.length === 2 && afterReset.layers.some(l => l.id === 'base') && afterReset.layers.some(l => l.id === 'draw'),
JSON.stringify(afterReset.layers.map(l => l.name)))
check('还原原图清空矢量/选区但保留 base 像素',
!afterReset.selection && JSON.stringify((await pixel(cx, cy)).base) === JSON.stringify(beforeFill.base))
await page.keyboard.press('Control+z')
const afterUndoReset = await dbg()
check('Ctrl+Z 完整恢复还原前的图层结构(含被删的选区副本层)',
beforeReset.layers.length === 3 && afterUndoReset.layers.length === beforeReset.layers.length,
'还原前 ' + beforeReset.layers.length + ' → 还原后 ' + afterReset.layers.length + ' → 撤销后 ' + afterUndoReset.layers.length)
// ---------- 单张输出预设(≤500KB) ----------
await page.locator('[data-action="toggleExportSettings"]').click()
await page.locator('[data-export-key="preset"][data-export-value="ecom800"]').click()
const opt = (await dbg()).exportOptions
check('≤500KB 预设可切换并存 ctx.settings', opt.preset === 'ecom800' && opt.maxKB === 500 &&
(await page.evaluate(() => window.__settings.exportPreset)) === 'ecom800', JSON.stringify(opt))
await page.locator('[data-action="download"]').click()
const exported = await poll(async () => (await dbg()).lastExport)
check('下载只产一个结果:800×800 且 ≤500KB、编辑器不关闭',
Boolean(exported && exported.width === 800 && exported.height === 800 && exported.bytes <= 500 * 1024 &&
await page.locator('#iwb-editor-overlay').isVisible()), JSON.stringify(exported))
await page.locator('[data-action="toggleExportSettings"]').click() // 上一步点「下载」会自动收起面板
await page.locator('[data-export-key="format"][data-export-value="jpeg"]').click()
await page.locator('[data-export-key="bg"][data-export-value="white"]').click()
await page.locator('[data-action="download"]').click()
const jpg = await poll(async () => { const d = await dbg(); return d.lastExport && d.lastExport.format === 'jpeg' ? d.lastExport : false })
check('格式/背景切换生效(JPG + 白底)', Boolean(jpg) && (await dbg()).exportOptions.bg === 'white', JSON.stringify(jpg))
// ---------- 选区与裁剪互斥 ----------
await page.locator('.iwb-editor-tool[data-tool="crop"]').click()
check('切到裁剪会清掉选区', !(await dbg()).selection)
await page.locator('.iwb-editor-tool[data-tool="marquee"]').click()
check('切回选区会取消裁剪框', await page.evaluate(() => {
const bar = document.querySelector('.iwb-editor-crop-bar')
return bar && getComputedStyle(bar).display === 'none'
}))
// ---------- 回归:矢量对象经撤销/重做后仍可渲染(快照不得把 DOM 画布序列化成 {}) ----------
await page.locator('.iwb-editor-tool[data-tool="rect"]').click()
await drag(imgBox.x + imgBox.width * 0.2, imgBox.y + imgBox.height * 0.2,
imgBox.x + imgBox.width * 0.45, imgBox.y + imgBox.height * 0.45)
await page.keyboard.press('Control+z')
await page.keyboard.press('Control+Shift+z')
check('矢量对象撤销/重做后画布正常重建', await page.evaluate(() =>
document.querySelectorAll('.iwb-editor-vec-canvas').length >= 1))
await page.locator('.iwb-editor-tool[data-tool="brush"]').click()
// ---------- 旧流程回归:粘贴一步落层 + 覆盖写回 ----------
const beforePaste = (await dbg()).layers.length
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)
const pasted = await poll(async () => (await dbg()).layers.length === beforePaste + 1)
check('粘贴图片一步落层(不再需要 Enter 确认)', Boolean(pasted), '层数 ' + beforePaste + ' → ' + (await dbg()).layers.length)
await page.keyboard.press('Enter')
check('粘贴后按 Enter 不会重复落层', (await dbg()).layers.length === beforePaste + 1)
await page.locator('[data-action="replace"]').click()
const wrote = await poll(async () => page.evaluate(() => window.__writes.some(w => w.kind === 'replace')))
check('覆盖仍回写宿主节点并关闭编辑器', Boolean(wrote) &&
(await page.locator('#iwb-editor-overlay').isVisible().catch(() => false)) === false, JSON.stringify(await page.evaluate(() => window.__writes)))
check('无运行时错误 / 无弹窗', errors.length === 0, errors.slice(0, 3).join(' | '))
await browser.close()
console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过'))
process.exit(failed ? 1 : 0)