Compare commits

..
Author SHA1 Message Date
qiqi e1d4f90374 fix(gallery): 图片卡片去掉插入按钮仅保留下载 (1.7.2)
validate / validate (push) Canceled after 0s
2026-11-25 18:39:58 +08:00
qiqi e20dda594b chore: 清除网页端残留(删 e2e 脚本 + 改文档口径 + 文案去「网页版」)
validate / validate (push) Canceled after 0s
本仓只服务桌面宿主 image-workbench-desktop,与网页端无限画布工具无关。

1) 删除 5 个网页端 e2e 脚本(共 1538 行):batch-export / image-vectorize /
   white-bg-800 / image-annotate 的 e2e-site.mjs,style-source 的 e2e-test-site.mjs。
   它们默认连 test.image-workbench-web.pages.dev、用 iwb_web_* 网页存档造数据、
   断言「线上版本」,与桌面端无关;README 却误称为「桌面客户端端到端」。
   关键断言已由各 harness 覆盖(图层排序 / CSS 注入闸门 / ZIP CRC 校验),
   删除不丢测试能力。npm scripts 与 CI 均未引用这些脚本。

2) 修正 5 份 README:把指向被删脚本的验证章节改写为 harness + 客户端市场确认;
   style-source 的「三层测试」改为两层。

3) browser / album 源码里的「网页版」注释与降级提示文案改为「旧客户端 /
   不支持路径引用的宿主」,保留全部降级逻辑与行为;两处运行时提示只在
   旧客户端或合成测试宿主出现,桌面端正常路径不可达。

纯清理,插件行为零变化,不改版本、不发市场。npm test 全过、语法检查全过,
全仓 Grep 已无「网页版 / 网页端 / image-workbench-web / e2e-site / pages.dev」残留。
2026-11-25 16:04:09 +08:00
qiqi e614fca7a3 chore(tests): 测试脚本依赖查找路径从网页端仓改到桌面端仓
validate / validate (push) Canceled after 0s
本仓只服务桌面宿主 image-workbench-desktop,与网页端无限画布工具无关。
14 个测试/工具脚本里共 15 处仍把 image-workbench-web 当 playwright/esbuild
的依赖后备目录(含 path.resolve、报错文案、album viewer-e2e 的多余候选),
全部改为 image-workbench-desktop;album 里重复的 web 仓候选直接删掉。

这些常量只用于找 node_modules,不参与任何插件逻辑,行为零变化。
桌面仓已确认有 playwright 1.64.1 / esbuild 0.28.2,改后依赖解析有效。

本轮不动 6 处 test.image-workbench-web.pages.dev 网址(属于网页端 e2e
脚本的废弃处理,另案);插件源码与版本未动,不需要发市场。
2026-11-25 15:55:46 +08:00
qiqi c1001ed61e fix(gallery): 设置浮层 z-index 收进 --iwb-z-ctx-menu(过宿主 token-lint)
validate / validate (push) Canceled after 0s
同步到宿主仓后 npm run lint:tokens 拦下 plugins/gallery/styles.css 的 z-index: 30:
它是存量裸值,但 1.7.1 改 bottom 时整行被当成「新增行」,于是重新被检查。
按 design-tokens.md §3.6 层级表换成 var(--iwb-z-ctx-menu, 91):仍低于
curtain(100)/command(120),面板内浮层的相对层级不变,视觉无差异。
harness 加「不得再写死裸 z-index」断言,浏览器核对 computed z-index = 91。
2026-11-25 14:15:31 +08:00
qiqi 2a484dac05 feat(gallery): 1.7.1 底栏三个图标加大(14→18,命中区 20→28)
validate / validate (push) Canceled after 0s
用户实测:右栏「图库」底部的刷新 / 打开本地目录 / 设置三个图标太小,齿轮几乎看不清。

按宿主 design-tokens.md §3.8 落地(图标尺寸闭集 14/16/18、描边 1.6、命中区 ≥28×28):
- SVG 14 → 18(ICON_PX,CSS 用 var(--iwb-icon-lg, 18px) 覆盖,宿主 token 缺失才用属性兜底);
- stroke-width 1.5 → 1.6;
- 按钮 20×20 → 28×28,工具组 gap 0 → 4(三个大图标不再紧贴);
- 设置浮层 bottom 34 → 40:底栏长高到 35px + 容器底 4,仍用 34 会被图标压住。
左侧计数文字、三个图标的交互与类名都没动;新增尺寸全在 token 闭集内。

测试:新增 gallery/tools/harness.mjs(19 项静态断言,含旧值反向断言与散值检查),
并入默认 npm test;新增 gallery/tools/foot-visual-check.mjs(Chromium 挂真实面板 11 项:
computed 28/18、gap、浮层不压底栏、亮暗尺寸一致、改前 14/20 对照),注册 test:gallery:visual。
npm test 与真浏览器核对全过,对比图 /tmp/gal-foot-171-compare.png 已人工核对。
2026-11-25 14:13:28 +08:00
29 changed files with 322 additions and 1567 deletions

No files matched your search

+2 -2
View File
@@ -251,7 +251,7 @@
const hasFileRef = items.some((it) => fileRefOf(it && it.src))
st.btnSettle.style.display = hasFileRef ? '' : 'none'
// 「文件夹」只在能做路径引用的宿主里有意义(桌面端)。旧写法 `canReference() || true` 恒真,
// 于是在网页版点它永远没反应。网页版仍可用「+ 添加图片」走文件选择器。
// 于是在不支持路径引用的宿主里点它永远没反应(这类宿主仍可用「+ 添加图片」走文件选择器)。
const canRef = !!(ctx.images && typeof ctx.images.canReference === 'function' && ctx.images.canReference())
st.btnDir.style.display = canRef ? '' : 'none'
st.btnClear.style.display = items.length ? '' : 'none'
@@ -676,7 +676,7 @@
} catch (e) { st.busy = ''; st.sig = ''; sync(ctx, st, st.node, st.props) }
return
}
// 网页版:没有路径 ⇒ 退回文件选择 + 复制进画布存储
// 不支持路径引用的宿主:退回文件选择 + 复制进画布存储
const input = document.createElement('input')
input.type = 'file'; input.accept = 'image/*'; input.multiple = true
input.style.display = 'none'
+1 -1
View File
@@ -184,7 +184,7 @@ ok('跨页拖拽用「每页容量」换算,不用「本页格子数」',
ok('删除不再硬编码跳回第 1 页', !/\{ items, page: 0 \}/.test(src) && /page: Math\.min\(pageNow, pagesNow - 1\)/.test(src))
ok('空节点不再显示「全部 0 张一页展示」(压着空态提示的废话)',
/const showOne = !showPager && items\.length > 0/.test(src))
ok('「文件夹」按钮不再 canReference() || true(网页版点了没反应)',
ok('「文件夹」按钮不再 canReference() || true(不支持路径引用时点了没反应)',
!/\|\| true \? '' : 'none'/.test(src))
ok('addPaths 里没有 keep 死变量', !/const keep = \(st\.node\.data/.test(src))
ok('缩略图请求并发去重(st.pending,否则导入 30 张要解 60 次原图)',
+1 -2
View File
@@ -21,8 +21,7 @@ const css = readFileSync(path.join(ROOT, 'styles.css'), 'utf8')
let chromium = null
for (const base of [process.env.IWB_PLAYWRIGHT_ROOT,
'/Users/qiqi/open/github/image-workbench-desktop',
'/Users/qiqi/open/github/image-workbench-web', ROOT]) {
'/Users/qiqi/open/github/image-workbench-desktop', ROOT]) {
if (!base) continue
try { chromium = createRequire(path.join(base, 'package.json'))('playwright').chromium; break } catch (e) { /* 试下一个 */ }
}
+3 -9
View File
@@ -95,15 +95,9 @@ mock 宿主 + 真实 Chromium,覆盖:manifest / 面板注册与挂载 / 列
需要 Playwright(可从桌面仓 `node_modules` 解析,或 `IWB_PLAYWRIGHT_ROOT` 指定)+ 系统 `unzip`、`python3`,不进 CI。
**发布后必须再跑一次真机**(mock 抓不到宿主 CSS / 真实 CSP / 真实面板挂载):
```bash
node batch-export/tools/e2e-site.mjs
```
覆盖:市场安装加载 + SRI + 资源中心 tab 出现 + 面板挂载 + 列表 2 行 +
**勾选框与文字同行(1.0.1 修的就是这个:`.iwb-bx-f input{width:100%}` 把 checkbox 撑满整行)** +
队列跑通 + 下载 ZIP + python3 校验 4 条目 / CRC / PNG·JPEG magic / UTF-8 名。
harness 用真实 Chromium 注入宿主 CSS 变量与 CSP 约束,覆盖面板挂载、勾选框与文字同行
(1.0.1 修的就是这个:`.iwb-bx-f input{width:100%}` 把 checkbox 撑满整行)、队列跑通、
下载 ZIP + python3 校验条目 / CRC / PNG·JPEG magic / UTF-8 名。发布后在客户端市场里确认版本与加载状态即可。
## 发布
-282
View File
@@ -1,282 +0,0 @@
// 真实站点端到端(开发用,不进 CI)—— batch-export「批量出图」。
//
// 为什么需要它:harness.mjs 用的是 mock 宿主,面板样式与真实宿主 CSS 变量、真实 CSP、真实
// 画布桥都不会被执行到。发布后跑一遍这个脚本,能抓到 mock 里永远绿的问题 ——
// 例如 `.iwb-bx-f input{width:100%}` 把 checkbox 撑满整行、把标签挤到面板最右(1.0.0 首次发布即中招)。
//
// 它不 mock /plugins/*:走真实 KV 加载 + 浏览器 SRI(fail-closed)+ 真实资源中心面板挂载。
//
// 运行(需要 Playwright + python3):
// node batch-export/tools/e2e-site.mjs # 默认测试站
// IWB_BASE_URL=https://iwb.maqiart.eu.org node batch-export/tools/e2e-site.mjs # 正式站
// 依赖:playwright(本仓/宿主仓 node_modules 均可;或用 IWB_PLAYWRIGHT_ROOT 指定)。
import { createRequire } from 'node:module'
import { execFileSync } from 'node:child_process'
import { readFileSync, existsSync, statSync } from 'node:fs'
import path from 'node:path'
import os from 'node:os'
import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url)) // <repo>/batch-export/tools
const REPO = path.resolve(HERE, '../..') // <repo>
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
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:')
console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node batch-export/tools/e2e-site.mjs')
process.exit(2)
}
const BASE = process.env.IWB_BASE_URL || 'https://test.image-workbench-web.pages.dev'
const WANT_VERSION = JSON.parse(readFileSync(path.join(REPO, 'batch-export/package.json'), 'utf8')).version
const ZIP_OUT = path.join(os.tmpdir(), 'iwb-batch-e2e.zip')
let failed = 0
const check = (name, ok, detail) => {
if (!ok) failed++
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')')
const browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, acceptDownloads: true })
const consoleErrors = []
page.on('console', (m) => { if (m.type() === 'error') consoleErrors.push(m.text()) })
page.on('pageerror', (e) => consoleErrors.push('pageerror: ' + e.message))
// 造两张 200×120 的参考图(非正方形,等比缩放/居中被真正练到)
await page.goto('about:blank')
const PNG = await page.evaluate(() => {
const c = document.createElement('canvas')
c.width = 200; c.height = 120
const x = c.getContext('2d')
x.fillStyle = '#2f6fed'; x.fillRect(0, 0, 200, 120)
return c.toDataURL('image/png')
})
// 插件系统是 opt-in(新插件默认不启用),种子必须显式 enabled
await page.addInitScript((d) => {
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify({ providers: [], canvas: {} }))
const ws = {
workspaces: [{
id: 'w1', name: 'W',
nodes: [
{ id: 'r1', type: 'ref', x: 140, y: 140, data: { url: '', data: d.png, name: '菜单A.png', localName: null } },
{ id: 'r2', type: 'ref', x: 460, y: 140, data: { url: '', data: d.png, name: '菜单B.png', localName: null } },
],
edges: [], groups: [],
}],
activeId: 'w1', rev: 1,
}
localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
localStorage.setItem('iwb_ws_active', ws.activeId)
localStorage.setItem('iwb_ws_w1', JSON.stringify(ws.workspaces[0]))
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
localStorage.setItem('iwb_plugins', JSON.stringify({ 'batch-export': { enabled: true, settings: {}, data: {} } }))
}, { png: PNG })
// ---------- 1) 站点可达 ----------
const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' })
check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status()))
// ---------- 2) 真实 KV 加载 + 启用 ----------
await page.waitForFunction(() => window.IWBPluginHost && window.IWBPluginHost.snapshot().initialized === true, null, { timeout: 30000 })
await page.waitForFunction(() => window.IWBPluginHost.list().some((x) => x.id === 'batch-export'), null, { timeout: 20000 })
const info = await page.evaluate(() => {
const p = window.IWBPluginHost.list().find((x) => x.id === 'batch-export')
return p ? { version: p.version, enabled: p.enabled, active: p.active, capabilities: p.capabilities, error: p.error } : null
})
check('从真实 KV 加载并启用(active)', Boolean(info && info.active && info.enabled && !info.error), JSON.stringify(info))
check('线上版本 = batch-export/package.json(' + WANT_VERSION + ')', Boolean(info && info.version === WANT_VERSION), info && info.version)
// ---------- 3) 面板 tab ----------
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await page.locator('.iwb-canvas:not(.iwb-canvas-hidden)').waitFor({ state: 'visible', timeout: 30000 })
check('画布打开、2 个 ref 节点', (await page.locator('.iwb-node[data-node-id^="r"]').count()) === 2)
await page.locator('button[title^="资源中心"]').first().click()
const tab = page.locator('.iwb-res-tab', { hasText: '批量出图' })
check('资源中心出现「批量出图」tab', (await tab.count()) >= 1)
await tab.first().click()
await page.waitForTimeout(1200)
const mounted = await page.locator('.iwb-full-panel-plugin').count()
check('面板已挂载(真实宿主容器)', mounted >= 1)
// 宿主 .iwb-full-main 是 flex 行容器,只给图库/节点组容器 width:100%;插件容器不撑满就会按内容收缩
const widthInfo = await page.evaluate(() => {
const main = document.querySelector('.iwb-full-main')
const box = document.querySelector('.iwb-bx')
return {
main: main ? Math.round(main.clientWidth) : 0,
box: box ? Math.round(box.clientWidth) : 0,
}
})
check('面板撑满内容区宽度(不按内容收缩)',
widthInfo.main > 0 && widthInfo.box >= widthInfo.main - 2, JSON.stringify(widthInfo))
const rows = await page.locator('.iwb-bx-item').count()
check('面板列出 2 个 ref 节点', rows === 2, 'rows=' + rows)
// 1.0.0 首发的真实 bug:checkbox 被 .iwb-bx-f input{width:100%} 撑满整行,标签被挤到最右
const chk = await page.evaluate(() => {
const lab = document.querySelector('.iwb-bx-rowchk')
if (!lab) return null
const input = lab.querySelector('input[type=checkbox]')
const span = lab.querySelector('span')
if (!input || !span) return null
const a = input.getBoundingClientRect()
const b = span.getBoundingClientRect()
return { gap: Math.round(b.left - a.right), sameLine: Math.abs(a.top - b.top) < 12, inputW: Math.round(a.width) }
})
check('「走本地鲜艺抠图」勾选框与文字同行且紧邻', Boolean(chk && chk.sameLine && chk.gap >= 0 && chk.gap <= 12 && chk.inputW <= 24), JSON.stringify(chk))
const cutLabel = await page.evaluate(() => {
const s = document.querySelector('.iwb-bx-rowchk span')
return s ? s.textContent.trim() : ''
})
check('抠图开关文案写明「本地鲜艺抠图」+ 端口', /鲜艺/.test(cutLabel) && /30092/.test(cutLabel), cutLabel)
// 1.1.0:配置区与列表之间要有明显的隔断(灰底小节头),操作按钮归到列表区
const sec = await page.evaluate(() => {
const s = document.querySelector('.iwb-bx-sec')
if (!s) return null
const bar = document.querySelector('.iwb-bx-bar')
const a = s.getBoundingClientRect()
const b = bar.getBoundingClientRect()
return {
text: (s.textContent || '').trim().slice(0, 24),
btns: Array.from(s.querySelectorAll('button')).map((x) => x.textContent.trim()),
bg: getComputedStyle(s).backgroundColor,
belowConfig: a.top >= b.bottom - 1,
}
})
check('隔断:「待处理节点」小节头在配置区正下方,带灰底 + 全选/清空/刷新',
Boolean(sec && sec.belowConfig && sec.text.indexOf('待处理节点') === 0 &&
JSON.stringify(sec.btns) === JSON.stringify(['全选', '清空', '刷新']) && sec.bg !== 'rgba(0, 0, 0, 0)'),
JSON.stringify(sec))
// 1.1.0:缩略图必须**跑之前**就在(30px 显示 / 64px 源图)
if (rows) {
const preThumb = await page.evaluate(() => {
const imgs = Array.from(document.querySelectorAll('.iwb-bx-item img.iwb-bx-thumb'))
return { n: imgs.length, w: imgs[0] ? imgs[0].naturalWidth : 0, cssW: imgs[0] ? Math.round(imgs[0].getBoundingClientRect().width) : 0 }
})
check('列表行首常驻源图缩略图(2 张、64px 位图 / 30px 显示)',
preThumb.n === 2 && preThumb.w === 64 && preThumb.cssW === 30, JSON.stringify(preThumb))
// 1.1.0 的 bug:「清空」后勾选框视觉上仍勾着(el() 用 setAttribute('checked','false'))
await page.getByRole('button', { name: '清空', exact: true }).click()
const cleared = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item input[type=checkbox]')).map((c) => c.checked))
check('「清空」真的取消勾选', cleared.length === 2 && cleared.every((v) => v === false), JSON.stringify(cleared))
await page.getByRole('button', { name: '全选', exact: true }).click()
}
// ---------- 4) 跑队列 ----------
if (!rows) {
console.log('\n' + (await page.locator('.iwb-full-panel-plugin').first().innerText()))
} else {
await page.getByRole('button', { name: '全选', exact: true }).click()
await page.getByRole('button', { name: '开始出图', exact: true }).click()
await page.waitForFunction(() => {
const b = Array.from(document.querySelectorAll('button')).find((x) => x.textContent.trim() === '导出 ZIP')
return b && !b.disabled
}, null, { timeout: 120000 })
const fails = await page.locator('.iwb-bx-item', { hasText: '失败' }).count()
check('队列跑完、无失败项', fails === 0, 'fail=' + fails)
// 跑完必须「看得见图」:行内缩略图 + 一条说明产物在哪的提示条(1.0.1 之前只有一行文字,用户以为没产出)
const thumbs = await page.locator('.iwb-bx-thumb').count()
check('行内显示产物缩略图(2 张)', thumbs === 2, 'thumbs=' + thumbs)
const thumbOk = thumbs ? await page.evaluate(() => {
const im = document.querySelector('.iwb-bx-thumb')
return { src: String(im.getAttribute('src') || '').slice(0, 5), w: im.naturalWidth, h: im.naturalHeight }
}) : null
check('缩略图是真解码出来的位图(800×800)', Boolean(thumbOk && thumbOk.src === 'blob:' && thumbOk.w === 800 && thumbOk.h === 800), JSON.stringify(thumbOk))
// ---------- 4.5) 行内单张下载(1.2.0):不依赖 ZIP,产物在内存里直接落盘 ----------
const dlState = await page.evaluate(() => Array.from(document.querySelectorAll('.iwb-bx-item .iwb-bx-dl')).map((b) => ({
text: b.textContent, disabled: b.disabled, title: b.title,
})))
check('行内下载:每行 JPG / PNG 各一个(2 行 = 4 个)',
dlState.length === 4 && dlState[0].text === 'JPG' && dlState[1].text === 'PNG',
JSON.stringify(dlState.map((b) => b.text)))
check('行内下载:双版本跑完后全部可点', dlState.every((b) => b.disabled === false), JSON.stringify(dlState.map((b) => b.disabled)))
const [jpgDl] = await Promise.all([
page.waitForEvent('download', { timeout: 30000 }),
page.locator('.iwb-bx-item').first().locator('.iwb-bx-dl').first().click(),
])
check('行内下载:点 JPG 直接下载单张(不必先导出 ZIP)',
/\.jpg$/.test(jpgDl.suggestedFilename()), jpgDl.suggestedFilename())
const doneText = await page.locator('.iwb-bx-done').first().innerText()
check('完成提示条说明「已生成 → 点导出 ZIP」(不写入画布)', /已生成 4 个文件/.test(doneText) && /导出 ZIP/.test(doneText) && /不写入画布/.test(doneText), doneText)
// 1.0.2 的坑:.iwb-bx-btn-hot 与 .iwb-bx-btn 同特异性且定义在前,背景被覆盖 → 高亮没生效
const zipBg = await page.evaluate(() => {
const b = Array.from(document.querySelectorAll('button')).find((x) => x.textContent.trim() === '导出 ZIP')
return b ? getComputedStyle(b).backgroundColor : ''
})
check('导出按钮转为高亮(rgb(29,158,117))', zipBg === 'rgb(29, 158, 117)', zipBg)
// ---------- 5) 导出 ZIP 并用 python3 校验(系统 unzip 对 UTF-8 名会乱码,见 README) ----------
const [download] = await Promise.all([
page.waitForEvent('download', { timeout: 60000 }),
page.getByRole('button', { name: '导出 ZIP', exact: true }).click(),
])
await download.saveAs(ZIP_OUT)
check('ZIP 已下载', existsSync(ZIP_OUT), existsSync(ZIP_OUT) ? statSync(ZIP_OUT).size + ' bytes' : '缺失')
const doneAfter = await page.locator('.iwb-bx-done').first().innerText()
check('导出后提示条显示已下载的文件名', /已下载 batch_.*\.zip/.test(doneAfter), doneAfter)
try {
const report = execFileSync('python3', ['-c', `
import zipfile, sys
z = zipfile.ZipFile(sys.argv[1])
assert z.testzip() is None, 'CRC 损坏'
for i in z.infolist():
b = z.read(i.filename)
ext = i.filename.rsplit('.', 1)[-1]
ok = b[:4] == b'\\x89PNG' if ext == 'png' else b[:3] == b'\\xff\\xd8\\xff'
print('%-28s %7dB %s %s' % (i.filename, i.file_size, '格式OK' if ok else '格式BAD', 'utf8' if i.flag_bits & 0x800 else 'nomb'))
`, ZIP_OUT], { encoding: 'utf8' })
console.log(report.trim())
const lines = report.trim().split('\n').filter(Boolean)
check('ZIP 4 个条目(2 张 × 双版本)', lines.length === 4, 'entries=' + lines.length)
check('ZIP 条目格式与 UTF-8 文件名标记正确', lines.every((l) => /格式OK/.test(l) && /utf8/.test(l)))
check('双版本命名 <原名>_800x800.png/.jpg', lines.some((l) => /菜单A_800x800\.png/.test(l)) && lines.some((l) => /菜单A_800x800\.jpg/.test(l)))
} catch (e) {
check('ZIP 结构校验(python3)', false, String((e && e.stdout) || (e && e.message)).slice(0, 200))
}
}
// ---------- 6) 切到「图库 / 节点组」时不得串页(1.1.0) ----------
// 真机现象:切到「图库」后批量面板还压在图片上方 —— 宿主两端都渲染成 div 且无 key,
// React 复用同一 DOM 节点,只清理自己管理的子节点,插件 mount 进去的根节点留在原地。
const clickedGallery = await page.evaluate(() => {
const t = Array.from(document.querySelectorAll('.iwb-res-tab')).find((x) => /图库/.test(x.textContent))
if (t) t.click()
return Boolean(t)
})
await page.waitForTimeout(1200)
const gallery = await page.evaluate(() => ({
historyMounted: document.querySelectorAll('.iwb-history-embedded').length,
panelsInDom: document.querySelectorAll('.iwb-bx').length,
panelInsideHistory: Boolean(document.querySelector('.iwb-history-embedded .iwb-bx')),
}))
check('切到「图库」:批量面板自动摘除,图库内不再混入插件 DOM',
clickedGallery && gallery.historyMounted >= 1 && gallery.panelsInDom === 0 && gallery.panelInsideHistory === false,
JSON.stringify(gallery))
await page.locator('.iwb-res-tab', { hasText: '批量出图' }).first().click()
await page.waitForTimeout(1500)
const backRows = await page.locator('.iwb-bx-item').count()
const backThumbs = await page.locator('.iwb-bx-item img.iwb-bx-thumb').count()
check('切回「批量出图」:面板自动重新挂载、列表与缩略图仍在',
backRows === 2 && backThumbs === 2, 'rows=' + backRows + ' thumbs=' + backThumbs)
// ---------- 7) 无 CSP / SRI 拦截、无页面错误 ----------
const bad = consoleErrors.filter((t) => /Content Security Policy|integrity|Refused to (execute|load|connect)/i.test(t))
check('无 CSP / SRI 拦截报错', bad.length === 0, bad.slice(0, 2).join(' | '))
check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '))
await browser.close()
console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过'))
process.exit(failed ? 1 : 0)
+1 -1
View File
@@ -16,7 +16,7 @@ import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url)) // <repo>/batch-export/tools
const REPO = path.resolve(HERE, '../..')
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop'
const PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js')
let chromium = null
+4 -4
View File
@@ -163,7 +163,7 @@
// 把网址放到画布上:新建一个「网页」节点并带上地址(宿主 canvasWrite 能力)。
// 宿主 createNode 认变体 id('web')—— 不在内置 NODE_TYPES 里时会自动走 addPluginNode。
// 返回 false 表示这个宿主没提供该能力(旧客户端 / 网页版),调用方自己选退路。
// 返回 false 表示这个宿主没提供该能力(旧客户端),调用方自己选退路。
function toCanvasNode(ctx, raw) {
var url = normalizeUrl(raw)
if (!url) return false
@@ -647,9 +647,9 @@
setZoom(st, clampZoom(pz0 / 100), false)
st.empty.textContent = '在上方地址栏输入网址,网页会显示在这里'
// 面板内浏览同样要靠宿主的原生 webview 引擎(src/canvas-webview.js):
// 没有它(网页版 / 旧客户端)就是一块白板,必须说清原因而不是干等。
// 没有它(旧客户端 / 合成测试宿主)就是一块白板,必须说清原因而不是干等。
var hasEngine = !!(global.IWBCanvasWebview || (global.window && global.window.IWBCanvasWebview))
if (!invoke()) st.empty.textContent = '面板内浏览需要桌面客户端;网页版请用系统浏览器打开。'
if (!invoke()) st.empty.textContent = '面板内浏览需要桌面客户端;请用系统浏览器打开。'
else if (!hasEngine) st.empty.textContent = '当前客户端还没有面板内浏览能力(需要 v3.25.30 及以上)。\n请先更新客户端。'
// 面板关掉就没了,「✕ 关闭这个网页」在面板里没有意义
st.close.style.display = 'none'
@@ -930,7 +930,7 @@
st.empty.textContent = '在地址栏输入网址,网页会显示在这个节点里'
} else if (!supported) {
st.empty.style.display = ''
st.empty.textContent = '画布内网页需要桌面客户端;网页版请用左侧「浏览器」面板。'
st.empty.textContent = '画布内网页需要桌面客户端;请用左侧「浏览器」面板。'
} else if (!engine) {
st.empty.style.display = ''
st.empty.textContent = '当前客户端还没有画布内网页能力(需要 v3.25.29 及以上)。\n请先更新客户端;升级前可以点上方 ↗ 用「浏览器」面板打开。'
+1 -1
View File
@@ -504,7 +504,7 @@ const okInvoke = () => (name) => {
nt.render({ id: 'n2', data: { url: 'https://www.baidu.com/' } }, { onUpdate() {} }, host)
const stage = host.children.find((c) => c.className === 'iwb-cwv-stage')
const empty = stage.children.find((c) => c.className === 'iwb-cwv-empty')
check('网页版节点显示「需要桌面客户端」提示', /桌面客户端/.test(empty._text), empty._text)
check('旧客户端节点显示「需要桌面客户端」提示', /桌面客户端/.test(empty._text), empty._text)
}
// ---------- 旧客户端(有 Tauri、但没有画布 webview 引擎)必须提示升级 ----------
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@iwb-plugin/gallery",
"private": true,
"version": "1.7.0",
"version": "1.7.2",
"description": "图库:右栏图片墙(筛选/多选/预览/插入画布/下载/删除),数据由宿主 gallery 能力提供",
"ibwPlugin": {
"id": "gallery",
+11 -11
View File
@@ -10,6 +10,8 @@
// ② 格子「插入」补 insertK(与右键/顶部一致,尺寸档不再被忽略)。
// ③ 插入/删除补「插入中…」状态,删除改成等宿主删完再重拉(固定 250ms 会拉到未删完的清单)。
// 注:搜索框在 v1.6.1 已按用户意见移除,不再加回。
// v1.7.2(2026-11-25):按用户意见去掉**图片卡片上**的「插入」按钮,卡片只保留「下载」;
// 顶部工具栏「插入 / 下载」和右键菜单的「插入画布」保持不变。
;(function (global) {
'use strict'
if (!global.IWBPluginHost) return
@@ -47,16 +49,20 @@
function clear (node) { while (node.firstChild) node.removeChild(node.firstChild) }
// v1.4.1:底栏按钮改用图标(窄栏里「刷新/设置」会被挤成竖排两行)
// v1.7.1:14px 在底栏里太小(齿轮细节几乎看不清)。按宿主 design-tokens.md §3.8
// 图标尺寸闭集 14/16/18 取最大档 --iwb-icon-lg(18),描边按规范 1.6;
// 命中区 ≥28×28 由 styles.css 的按钮尺寸兜住(图形放大不等于点击区变大)。
var SVG_NS = 'http://www.w3.org/2000/svg'
var ICON_PX = 18
function iconBtn (label, build, title) {
var b = el('button', { class: 'iwb-btn iwb-btn-sm iwb-gal-icobtn', title: title || label, 'aria-label': label })
var svg = document.createElementNS(SVG_NS, 'svg')
svg.setAttribute('viewBox', '0 0 16 16')
svg.setAttribute('width', '14')
svg.setAttribute('height', '14')
svg.setAttribute('width', String(ICON_PX))
svg.setAttribute('height', String(ICON_PX))
svg.setAttribute('fill', 'none')
svg.setAttribute('stroke', 'currentColor')
svg.setAttribute('stroke-width', '1.5')
svg.setAttribute('stroke-width', '1.6')
svg.setAttribute('stroke-linecap', 'round')
svg.setAttribute('stroke-linejoin', 'round')
svg.setAttribute('aria-hidden', 'true')
@@ -450,13 +456,7 @@
b.addEventListener('click', function (e) { e.stopPropagation(); fn() })
return b
}
acts.appendChild(act('插入', '插入到画布(参考图节点 · 尺寸按「设置 → 插入尺寸」)', function () {
// v1.7.0:格子里的「插入」此前没带 insertK,宿主按默认 1k 处理 —— 与右键菜单/顶部「插入」不一致
setStatus('插入中…')
ctx.gallery.insert([it.name], { insertK: cfg.insertK || '1k' }).then(function () {
setStatus('已插入:' + it.name)
}).catch(function () { setStatus('插入失败') })
}))
// v1.7.2:图片卡片上只留「下载」;插入仍可从顶部工具栏或右键菜单进入。
acts.appendChild(act('下载', '下载到本地', function () { doDownload([it.name]) }))
box.appendChild(acts)
return box
@@ -590,7 +590,7 @@
global.IWBPluginHost.register({
id: 'gallery',
name: '图库',
version: '1.7.0',
version: '1.7.2',
apiVersion: 1,
capabilities: ['panels', 'gallery'],
data: { schemaVersion: 1, maxBytes: 65536 },
+17 -6
View File
@@ -24,25 +24,36 @@
.iwb-gal-count { font-size: 11px; color: var(--iwb-text2); white-space: nowrap; }
.iwb-gal-sel { font-size: 11px; color: var(--iwb-brand); white-space: nowrap; }
.iwb-gal-status { font-size: 11px; color: var(--iwb-text2); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; flex: 0 1 auto; max-width: none; }
.iwb-gal-tools { display: flex; align-items: center; gap: 0; flex: 0 0 auto; margin-left: auto; }
/* v1.7.1:图标放大后三个按钮不再紧贴(4px 是 spacing 闭集值) */
.iwb-gal-tools { display: flex; align-items: center; gap: 4px; flex: 0 0 auto; margin-left: auto; }
/* ---- 图标按钮:无外框、无底色,只在悬停时给一点反馈 ---- */
/* ---- 图标按钮:无外框、无底色,只在悬停时给一点反馈 ----
v1.7.1:命中区 20×20 → 28×28(design-tokens.md §3.8「≥28×28」),
图形 14 → var(--iwb-icon-lg) 18;CSS 尺寸覆盖 SVG 的 presentation attribute,
属性里的 18 只作宿主 token 缺失时的兜底。 */
.iwb-gal-foot .iwb-gal-icobtn,
.iwb-gal-foot .iwb-gal-icobtn:hover,
.iwb-gal-foot .iwb-gal-icobtn:active {
width: 20px; height: 20px; min-width: 20px; padding: 0; box-sizing: border-box;
width: 28px; height: 28px; min-width: 28px; padding: 0; box-sizing: border-box;
display: inline-flex; align-items: center; justify-content: center; flex: 0 0 auto;
border: 0; box-shadow: none; background: transparent; border-radius: 6px;
color: var(--iwb-text2); line-height: 1; transform: none;
}
.iwb-gal-foot .iwb-gal-icobtn svg { display: block; pointer-events: none; }
.iwb-gal-foot .iwb-gal-icobtn svg {
display: block; pointer-events: none;
width: var(--iwb-icon-lg, 18px); height: var(--iwb-icon-lg, 18px);
}
.iwb-gal-foot .iwb-gal-icobtn:hover { background: var(--iwb-layer2); color: var(--iwb-text); }
.iwb-gal-foot .iwb-gal-icobtn:focus-visible { outline: 2px solid color-mix(in srgb, var(--iwb-brand) 60%, transparent); outline-offset: 1px; }
.iwb-gal-setbtn-on { color: var(--iwb-brand); background: var(--iwb-layer2); }
/* ---- 设置浮层(三个下拉不占前台) ---- */
/* ---- 设置浮层(三个下拉不占前台) ----
bottom 随底栏高度走:底栏 = padding-top 6 + border 1 + 按钮 28,再加容器底 4 → 39,
取 40 让浮层正好停在底栏上沿之外;仍用 34 会被放大后的图标压住。
z-index 按 §3.6 层级表走 --iwb-z-ctx-menu(面板内菜单浮层):原先裸写 30,
这行一改动就被 token-lint 当成新增裸值拦下;91 仍低于 curtain(100)/command(120)。 */
.iwb-gal-settings {
position: absolute; right: 8px; bottom: 34px; z-index: 30; width: 176px; max-width: calc(100% - 16px);
position: absolute; right: 8px; bottom: 40px; z-index: var(--iwb-z-ctx-menu, 91); width: 176px; max-width: calc(100% - 16px);
display: flex; flex-direction: column; gap: 8px; padding: 8px 10px;
background: var(--iwb-layer); border: 1px solid var(--iwb-border); border-radius: 8px;
box-shadow: 0 6px 18px rgba(0, 0, 0, .14);
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env node
/* 图库底栏图标「真浏览器」核对(v1.7.1)
* 静态断言只能证明代码里有 18/28,证明不了宿主 style.css + 插件 CSS 叠完后真的是这个尺寸。
* 这里加载宿主 token/style + 插件源码本体,用合成 ctx 挂载真实面板,量 computed、验浮层不压底栏,
* 并出「改前 14/20」与「改后 18/28」的亮色对比图 + 改后暗色图。
*
* 运行:node gallery/tools/foot-visual-check.mjs
* 依赖宿主仓 playwright(跨仓依赖,不进默认 npm test)。
*/
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url))
const HOST = path.resolve(HERE, '..', '..', '..', 'image-workbench-desktop')
const PW = pathToFileURL(path.resolve(HOST, 'node_modules', 'playwright', 'index.mjs')).href
const { chromium } = await import(PW)
const SRC = path.resolve(HERE, '..', 'src', 'index.js')
const CSS = path.resolve(HERE, '..', 'styles.css')
const TOKENS = path.resolve(HOST, 'src', 'design-tokens.css')
const HOSTCSS = path.resolve(HOST, 'style.css')
const cssText = readFileSync(CSS, 'utf8')
let failed = 0
const ok = (name, cond, actual) => {
if (!cond) failed++
console.log((cond ? '✓ ' : '✗ ') + name + (actual === undefined ? '' : ' → ' + JSON.stringify(actual)))
}
const browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 760, height: 520 }, deviceScaleFactor: 2 })
const errors = []
page.on('pageerror', (e) => errors.push(String(e)))
await page.setContent(`<!doctype html><html><head><meta charset="utf-8"></head>
<body style="margin:0;background:#f2f3f5">
<div style="padding:16px"><div id="host" style="width:320px;height:240px;display:flex;flex-direction:column;background:var(--iwb-panel)"></div></div>
</body></html>`)
await page.evaluate(() => { window.__TAURI__ = { core: {} }; window.IWBPluginHost = { register: (meta, factory) => { window.__reg = { meta, factory } } } })
await page.addStyleTag({ path: TOKENS })
await page.addStyleTag({ path: HOSTCSS })
await page.addStyleTag({ path: CSS })
await page.addScriptTag({ path: SRC })
const version = await page.evaluate(() => {
const names = Array.from({ length: 17 }, (_, i) => 'img-' + (i + 1) + '.png')
const items = names.map((name) => ({ name: name, w: 80, h: 80 }))
const thumb = 'data:image/svg+xml,' + encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="80" height="80"><rect width="80" height="80" fill="#dfe3e9"/></svg>')
const ctx = {
ui: { registerPanel: (p) => { window.__panel = p } },
data: { read: async () => ({}), patch: async () => ({ ok: true }) },
gallery: {
list: async () => ({ items: items, total: 17 }),
thumb: async () => thumb,
onChanged: () => () => {},
insert: async () => ({ ok: true }), remove: async () => ({ ok: true }),
download: async () => ({ ok: true }), preview: () => {}, openFolder: async () => ({ ok: true }),
},
}
window.__reg.factory(ctx)
window.__panel.mount(document.getElementById('host'))
return window.__reg.meta.version
})
ok('插件版本 = 1.7.2', version === '1.7.2', version)
await page.waitForTimeout(700)
const geo = await page.evaluate(() => {
const btns = Array.from(document.querySelectorAll('.iwb-gal-icobtn'))
const cs = (el) => getComputedStyle(el)
const tools = document.querySelector('.iwb-gal-tools')
const settings = document.querySelector('.iwb-gal-settings')
const foot = document.querySelector('.iwb-gal-foot')
return {
buttons: btns.length,
labels: btns.map((b) => b.getAttribute('aria-label')),
btnW: btns.map((b) => cs(b).width),
btnH: btns.map((b) => cs(b).height),
svgW: btns.map((b) => cs(b.querySelector('svg')).width),
svgAttr: btns.map((b) => b.querySelector('svg').getAttribute('width')),
gap: cs(tools).columnGap,
settingsBottom: cs(settings).bottom,
settingsZ: cs(settings).zIndex,
footH: cs(foot).height,
count: document.querySelector('.iwb-gal-count').textContent,
folderVisible: btns[1] && cs(btns[1]).display !== 'none',
cardActions: Array.from(document.querySelectorAll('.iwb-history-actions')).map((a) =>
Array.from(a.querySelectorAll('button')).map((b) => b.textContent.trim())),
toolbarLabels: Array.from(document.querySelectorAll('.iwb-gal-actions button')).map((b) => b.textContent.trim()),
}
})
console.log('几何 / 计算样式 =', JSON.stringify(geo))
ok('三个图标都在(刷新 / 打开本地目录 / 设置)', geo.buttons === 3 && geo.folderVisible, geo.labels)
ok('每张图卡片只剩「下载」', geo.cardActions.length > 0 && geo.cardActions.every((a) => a.join(',') === '下载'), geo.cardActions.slice(0, 3))
ok('顶部工具栏仍保留「插入」', geo.toolbarLabels.indexOf('插入') >= 0, geo.toolbarLabels)
ok('计数文字仍是 17 / 17 张(没动左侧信息区)', geo.count === '17 / 17 张', geo.count)
ok('命中区真的 28×28(不是只改了源码字符串)',
geo.btnW.every((w) => w === '28px') && geo.btnH.every((h) => h === '28px'), [geo.btnW, geo.btnH])
ok('图形真的 18×18(--iwb-icon-lg 生效)',
geo.svgW.every((w) => w === '18px') && geo.svgAttr.every((w) => w === '18'), geo.svgW)
ok('按钮间距 4px', geo.gap === '4px', geo.gap)
ok('设置浮层 bottom = 40px,底栏高度跟着长到 35px',
geo.settingsBottom === '40px' && geo.footH === '35px', [geo.settingsBottom, geo.footH])
ok('浮层层级真的取到 --iwb-z-ctx-menu(91)', geo.settingsZ === '91', geo.settingsZ)
// 设置浮层展开后不能被放大的底栏压住
await page.locator('button[aria-label="设置"]').click()
await page.waitForTimeout(120)
const overlap = await page.evaluate(() => {
const s = document.querySelector('.iwb-gal-settings').getBoundingClientRect()
const f = document.querySelector('.iwb-gal-foot').getBoundingClientRect()
return { settingsBottom: s.bottom, footTop: f.top, display: getComputedStyle(document.querySelector('.iwb-gal-settings')).display }
})
ok('设置浮层打开时停在底栏上沿之外(不压住图标)',
overlap.display !== 'none' && overlap.settingsBottom <= overlap.footTop + 1, overlap)
await page.locator('button[aria-label="设置"]').click()
await page.mouse.move(0, 0)
await page.waitForTimeout(120)
// 改前(1.7.0 口径)用同特异性覆盖规则模拟,不依赖 git 历史,脚本以后也能复跑
const old = await page.addStyleTag({ content: `
.iwb-gal-foot .iwb-gal-icobtn,
.iwb-gal-foot .iwb-gal-icobtn:hover,
.iwb-gal-foot .iwb-gal-icobtn:active { width:20px; height:20px; min-width:20px; }
.iwb-gal-foot .iwb-gal-icobtn svg { width:14px; height:14px; }
.iwb-gal-tools { gap:0; }
.iwb-gal-settings { bottom:34px; }` })
await page.waitForTimeout(100)
const beforeGeo = await page.evaluate(() => ({
btn: getComputedStyle(document.querySelector('.iwb-gal-icobtn')).width,
svg: getComputedStyle(document.querySelector('.iwb-gal-icobtn svg')).width,
}))
ok('覆盖出的「改前」确实是 14px 图形 / 20px 命中区',
beforeGeo.svg === '14px' && beforeGeo.btn === '20px', beforeGeo)
const before = (await page.locator('.iwb-gal-foot').screenshot()).toString('base64')
await old.evaluate((el) => el.remove())
await page.waitForTimeout(100)
const after = (await page.locator('.iwb-gal-foot').screenshot()).toString('base64')
await page.screenshot({ path: '/tmp/gal-foot-171-light.png', fullPage: true })
// 暗色:token 自动跟随,尺寸不变
await page.evaluate(() => document.documentElement.classList.add('theme-dark'))
await page.waitForTimeout(150)
const dark = await page.evaluate(() => ({
btn: getComputedStyle(document.querySelector('.iwb-gal-icobtn')).width,
svg: getComputedStyle(document.querySelector('.iwb-gal-icobtn svg')).width,
color: getComputedStyle(document.querySelector('.iwb-gal-icobtn')).color,
}))
ok('暗色下尺寸不变、图标色跟随 token', dark.btn === '28px' && dark.svg === '18px', dark)
await page.locator('.iwb-gal-foot').screenshot({ path: '/tmp/gal-foot-171-dark.png' })
await page.screenshot({ path: '/tmp/gal-foot-171-dark-full.png', fullPage: true })
// 对比图:两列底部对齐,标签用英文避免字体缺失
const cmp = await browser.newPage({ viewport: { width: 780, height: 240 }, deviceScaleFactor: 2 })
await cmp.setContent(`<!doctype html><html><head><meta charset="utf-8"></head>
<body style="margin:0;background:#fff;font-family:-apple-system,Helvetica,Arial,sans-serif">
<div style="display:flex;align-items:flex-end;gap:24px;padding:20px">
<div><div style="font-size:14px;font-weight:600;color:#333;margin-bottom:10px">BEFORE · 14px icon / 20x20 hit area</div>
<img src="data:image/png;base64,${before}" style="display:block;border:1px solid #e3e5e9"></div>
<div><div style="font-size:14px;font-weight:600;color:#333;margin-bottom:10px">AFTER · 18px icon / 28x28 hit area</div>
<img src="data:image/png;base64,${after}" style="display:block;border:1px solid #e3e5e9"></div>
</div></body></html>`)
await cmp.screenshot({ path: '/tmp/gal-foot-171-compare.png', fullPage: true })
ok('页面无 JS 报错', errors.length === 0, errors)
console.log('截图:/tmp/gal-foot-171-compare.png(对比)、-light.png、-dark.png、暗色全图')
console.log(failed ? ('✗ ' + failed + ' 项失败') : '✓ 全部通过')
if (failed) process.exitCode = 1
await browser.close()
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env node
/* 图库底栏图标的静态闸门(v1.7.1)
* 只改尺寸,不改交互;这些断言把「设计 token 口径」钉住,防止以后调样式时又缩回 14px/20×20。
* 运行:node gallery/tools/harness.mjs(已并入根 npm test)
*/
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url))
const ROOT = path.resolve(HERE, '..')
const src = readFileSync(path.join(ROOT, 'src/index.js'), 'utf8')
const css = readFileSync(path.join(ROOT, 'styles.css'), 'utf8')
const pkg = JSON.parse(readFileSync(path.join(ROOT, 'package.json'), 'utf8'))
let failed = 0
const ok = (name, cond, actual) => {
if (!cond) failed++
console.log((cond ? '✓ ' : '✗ ') + name + (actual === undefined ? '' : ' → ' + JSON.stringify(actual)))
}
// ---- 版本两处一致 ----
ok('package.json version = 1.7.2', pkg.version === '1.7.2', pkg.version)
ok('manifest.version = 1.7.2', /version:\s*'1\.7\.2'/.test(src))
// ---- 图标尺寸:宿主 design-tokens.md §3.8 闭集 14/16/18,取最大档 ----
ok('SVG 尺寸常量 ICON_PX = 18', /\bvar ICON_PX = 18\b/.test(src))
ok('SVG width/height 都取 ICON_PX(不是写死 14)',
/setAttribute\('width', String\(ICON_PX\)\)/.test(src) &&
/setAttribute\('height', String\(ICON_PX\)\)/.test(src))
ok('描边按规范 stroke-width 1.6', /setAttribute\('stroke-width', '1\.6'\)/.test(src))
ok('CSS 图形尺寸走 --iwb-icon-lg(宿主 token 缺失才兜底 18px)',
/\.iwb-gal-foot \.iwb-gal-icobtn svg\s*\{[^}]*width:\s*var\(--iwb-icon-lg, 18px\)[^}]*height:\s*var\(--iwb-icon-lg, 18px\)/.test(css))
ok('命中区 28×28(§3.8「≥28×28」)',
/width:\s*28px;\s*height:\s*28px;\s*min-width:\s*28px/.test(css))
ok('工具组间距 4px(三个大图标不再紧贴)', /\.iwb-gal-tools\s*\{[^}]*gap:\s*4px/.test(css))
ok('设置浮层 bottom 随底栏长高到 40px(仍用 34 会被图标压住)',
/\.iwb-gal-settings\s*\{[^}]*bottom:\s*40px/.test(css))
ok('浮层层级走 --iwb-z-*(不写死裸 z-index,token-lint 会拦)',
/\.iwb-gal-settings\s*\{[^}]*z-index:\s*var\(--iwb-z-ctx-menu, 91\)/.test(css) &&
!/z-index:\s*\d+/.test(css))
// ---- 反向断言:旧的「小图标」写法不得回流 ----
ok('不再有 14px 的 SVG 属性', !/setAttribute\('(?:width|height)', '14'\)/.test(src))
ok('不再有 stroke-width 1.5', !/setAttribute\('stroke-width', '1\.5'\)/.test(src))
ok('不再有 20×20 命中区', !/width:\s*20px;\s*height:\s*20px;\s*min-width:\s*20px/.test(css))
ok('不再有 gap: 0 的紧贴按钮', !/gap:\s*0\s*;/.test(css))
ok('不再有 bottom: 34px', !/bottom:\s*34px/.test(css))
// ---- 交互与契约不变 ----
ok('三个图标仍是刷新 / 打开本地目录 / 设置',
/iconBtn\('刷新'/.test(src) && /iconBtn\('打开本地目录'/.test(src) && /iconBtn\('设置'/.test(src))
ok('按钮类名未变(宿主旧 .iwb-btn-sm 不会盖回来)',
/class:\s*'iwb-btn iwb-btn-sm iwb-gal-icobtn'/.test(src) &&
/\.iwb-gal-foot \.iwb-gal-icobtn/.test(css))
ok('悬停 / 键盘聚焦反馈仍在',
/\.iwb-gal-foot \.iwb-gal-icobtn:hover\s*\{[^}]*background/.test(css) &&
/\.iwb-gal-foot \.iwb-gal-icobtn:focus-visible/.test(css))
ok('左侧计数 / 选中 / 状态文字字号没被顺手改掉',
/\.iwb-gal-count\s*\{[^}]*font-size:\s*11px/.test(css) &&
/\.iwb-gal-sel\s*\{[^}]*font-size:\s*11px/.test(css))
// ---- v1.7.2:图片卡片只留下载;顶部/右键插入入口不回退 ----
ok('图片卡片上没有「插入」按钮', !/acts\.appendChild\(act\('插入'/.test(src))
ok('图片卡片保留「下载」按钮', /acts\.appendChild\(act\('下载'/.test(src))
ok('顶部工具栏「插入」仍在', /actions\.appendChild\(btn\('插入'/.test(src))
ok('右键菜单「插入画布」仍在', /item\('插入画布'/.test(src))
// ---- 尺寸闭集(对齐宿主 plugin-scale-contract,防止放大时又引入散值)----
const FONT = new Set([11, 12, 13, 14, 15, 17, 20, 24])
const RADIUS = new Set([6, 8, 10, 12, 14, 999])
const SPACE = new Set([0, 2, 4, 6, 8, 10, 12, 16, 20, 24, 32, 40, 48, 64])
const stray = []
for (const m of css.matchAll(/([a-z-]+)\s*:\s*([^;{}]+)/g)) {
const prop = m[1].toLowerCase()
const val = m[2].trim()
if (val.includes('var(')) continue
const px = [...val.matchAll(/([0-9.]+)px/g)].map((x) => Number(x[1]))
if (prop === 'font-size' && px.some((n) => !FONT.has(n))) stray.push('font-size:' + val)
else if (prop === 'border-radius' && px.some((n) => !RADIUS.has(n))) stray.push('border-radius:' + val)
else if (/^(gap|row-gap|column-gap)$/.test(prop) || /^(padding|margin)/.test(prop)) {
if (px.some((n) => !SPACE.has(n))) stray.push(prop + ':' + val)
}
}
ok('CSS 字号 / 圆角 / 间距无新增散值', stray.length === 0, stray)
console.log(failed ? ('✗ ' + failed + ' 项失败') : '✓ 全部通过(gallery 1.7.2 卡片只留下载)')
if (failed) process.exitCode = 1
+7 -7
View File
@@ -19,7 +19,7 @@
持有几十 MB 的 base64 字符串)。合成宿主的 CSP 常把 `connect-src` 限为 `'self' https:`、**不含 `data:`** ⇒ `fetch(data:)` 被拦
(桌面客户端的 CSP 含 `data:`,但测试用的合成宿主按更严策略跑,故仍按最严口径处理)。
现改为**纯本地解码**(`atob` → `Uint8Array` → `Blob` → blob URL),与上游行为一致(同样拿到 blob URL),且不依赖 CSP/网络。
> 这类问题**只有带 CSP 的真机/合成宿主能测出来**(无 CSP 的 mock 页永远绿)。用例见 `image-annotate/tools/e2e-site.mjs`。
> 这类问题**只有带 CSP 的真机/合成宿主能测出来**(无 CSP 的 mock 页永远绿)。用例见 `image-annotate/tools/harness.mjs` 的 CSP 段。
### v1.1:选区、便利版 UI、单张输出
@@ -66,8 +66,7 @@
- **侧栏去重**:移除硬度/透明两条滑杆(与就地选项栏画笔/橡皮态完全重复);
侧栏保留调色板全量 + 笔刷大小(滑杆/数字/快捷点)+ 缩放行。
- 测试:`node image-annotate/tools/harness.mjs`(合成宿主,发布前,79 项);
`node image-annotate/tools/e2e-site.mjs`(桌面客户端 CSP/SRI,发布后)。
- 测试:`node image-annotate/tools/harness.mjs`(合成宿主 + 真实 Chromium,覆盖 CSP / 图层排序 / 输出几何,发布前必跑)。
## v1.2.2
@@ -1216,11 +1215,12 @@ node scripts/gen-market.js # 生成 market/index.json
发布后回读市场索引确认版本与哈希已更新,再在客户端市场安装验证——不能只看命令退出码。
## 验证(可选,开发用)
`tools/e2e-site.mjs`:**桌面客户端**端到端(市场安装 + SRI + 漂浮菜单 → 编辑器 → 覆盖/新建),
另含 v1.0.5 的图层顺序回归:画图形 + 粘贴截图 → 唯一高亮、点重叠区选中最上层截图、四个排序按钮逐一生效、原图始终在最底。
`tools/harness.mjs`:合成宿主 + 真实 Chromium,覆盖 CSP 适配、图层顺序回归(画图形 + 粘贴截图 → 唯一高亮、
点重叠区选中最上层截图、四个排序按钮逐一生效、原图始终在最底)、输出几何与编辑器命令。
需要 Playwright(可从桌面仓 `node_modules` 或全局解析),**不进 CI**(本仓 CI 只跑 `npm run validate`,不联网、无依赖)。
```bash
node image-annotate/tools/e2e-site.mjs
node image-annotate/tools/harness.mjs
```
> 为什么值得留着:mock 页没有 CSP,`connect-src` 类问题(如 `fetch(dataURL)`)在 mock 下永远绿,只有真机能抓出来。
> 为什么必须是真 Chromium:mock 页没有 CSP,`connect-src` 类问题(如 `fetch(dataURL)`)在纯 mock 下永远绿,
> harness 里的合成宿主带 CSP 闸门才能抓出来。
-437
View File
@@ -1,437 +0,0 @@
// 真实站点端到端(开发用,不进 CI)。
//
// 为什么需要它:mock 页没有 CSP,`connect-src` 一类问题(例如 `fetch(dataURL)` 被
// `connect-src 'self' https: …` 拦掉)在 mock 下永远绿,只有带 CSP 的真站能抓出来。
// 它不 mock /plugins/*:走真实 KV + 浏览器 SRI 校验 + 真实画布桥。
//
// 运行:
// node image-annotate/tools/e2e-site.mjs
// IWB_BASE_URL=https://iwb.maqiart.eu.org node image-annotate/tools/e2e-site.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)) // <repo>/image-annotate/tools
const REPO = path.resolve(HERE, '../..') // <repo>
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
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:')
console.error(' npm i -D playwright # 本仓或宿主仓皆可')
console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node image-annotate/tools/e2e-site.mjs')
process.exit(2)
}
const BASE = process.env.IWB_BASE_URL || 'https://test.image-workbench-web.pages.dev'
const WANT_VERSION = JSON.parse(readFileSync(path.join(REPO, 'image-annotate/package.json'), 'utf8')).version
const CFG = { providers: [], canvas: {} }
const WS = { workspaces: [{ id: 'w1', name: 'W', nodes: [], edges: [], groups: [] }], activeId: 'w1', rev: 1 }
let failed = 0
const check = (name, ok, detail) => {
if (!ok) failed++
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
const poll = async (fn, timeout = 25000, step = 250) => {
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))
}
}
console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')')
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 + ' @ ' + String(e.stack || '').split('\n').slice(1, 4).join(' | ')))
page.on('dialog', (d) => { consoleErrors.push('unexpected dialog: ' + d.message()); d.dismiss().catch(() => {}) })
// 造一张真实的 96x64 PNG 作为节点图片
await page.goto('about:blank')
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.addInitScript((d) => {
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg))
const ws = JSON.parse(JSON.stringify(d.ws))
ws.workspaces[0].nodes = [{ id: 'r1', type: 'ref', x: 140, y: 140, data: { url: '', data: d.png, name: 'src.png', localName: null } }]
localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
localStorage.setItem('iwb_ws_active', ws.activeId)
localStorage.setItem('iwb_ws_w1', JSON.stringify(ws.workspaces[0]))
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
localStorage.setItem('iwb_plugins', JSON.stringify({ 'image-annotate': { enabled: true, settings: {}, data: {} } }))
}, { cfg: CFG, ws: WS, png: PNG })
const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' })
check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status()))
await page.waitForFunction(() => Boolean(window.IWBPluginHost) && window.IWBPluginHost.snapshot().initialized === true, null, { timeout: 30000 })
// ---------- 1) 真实 KV 加载 + SRI + 启用 ----------
const active = await poll(async () => page.evaluate(() => {
const p = window.IWBPluginHost.list().find((x) => x.id === 'image-annotate')
return p && p.active ? { version: p.version, enabled: p.enabled, capabilities: p.capabilities, error: p.error } : false
}))
check('从真实 KV 加载并启用(SRI 通过)', Boolean(active), JSON.stringify(active))
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') || '' })))
// 文件名两种都合法:plugins-publish.mjs 产内容寻址名(.<hash12>.js,可 immutable 缓存),
// plugins-publish.sh(带主干守卫的合规通道)产固定名(plugin-image-annotate.js,走 no-cache+ETag)。
// 断言的关键是「必须带 integrity」,与命名策略无关。
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()
await page.locator('.iwb-canvas:not(.iwb-canvas-hidden)').waitFor({ state: 'visible', timeout: 30000 })
check('工作区打开、种子节点在画布', (await page.locator('.iwb-node[data-node-id="r1"]').count()) === 1)
// ---------- 3) 入口:节点漂浮菜单(回落右键插件命令)----------
const openEditor = async () => {
await page.locator('.iwb-node[data-node-id="r1"]').click()
const btn = page.locator('.iwb-node-floatbar button[title="标注 / 修图"]')
if (await btn.count()) { await btn.click(); return '漂浮菜单' }
await page.locator('.iwb-canvas').click({ button: 'right', position: { x: 900, y: 620 } })
await page.locator('.iwb-ctxmenu .iwb-ctx-item').filter({ hasText: '标注 / 修图:选中节点' }).click()
return '右键命令'
}
const entry = await openEditor()
check('节点入口可触发(漂浮菜单或右键命令)', true, entry)
// ---------- 4) 编辑器打开(真实 CSP 下注入样式)----------
await page.locator('#iwb-editor-overlay').waitFor({ state: 'visible', timeout: 30000 })
const opened = await page.evaluate(() => {
const el = document.querySelector('#iwb-editor-overlay')
const style = document.getElementById('iwb-annotate-style')
return {
display: getComputedStyle(el).display,
position: getComputedStyle(el).position,
zIndex: getComputedStyle(el).zIndex,
bg: getComputedStyle(el).backgroundColor,
styleInjected: Boolean(style && style.textContent.includes('.iwb-editor-')),
}
})
check('编辑器浮层可见', opened.display === 'flex' && opened.position === 'fixed')
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'
if (!SKIP_PASTE) {
// 先画一个矢量矩形,制造「截图 + 图形」共存场景 —— 这是 z 撞车 / 排序按钮失效的复现前提
const imgBox = await page.locator('.iwb-editor-layer-canvas').first().boundingBox()
await page.locator('.iwb-editor-tool[data-tool="rect"]').click()
await page.mouse.move(imgBox.x + imgBox.width * 0.25, imgBox.y + imgBox.height * 0.25)
await page.mouse.down()
await page.mouse.move(imgBox.x + imgBox.width * 0.75, imgBox.y + imgBox.height * 0.75, { steps: 8 })
await page.mouse.up()
await page.waitForTimeout(200)
const layersBefore = await page.evaluate(() => document.querySelectorAll('.iwb-editor-layer-list > *').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)
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))
// ---------- 4.6) 图层顺序回归(2026-11-04 修):z 唯一 / 选中唯一 / 四个排序按钮 ----------
const panelSeq = () => page.evaluate(() => Array.from(document.querySelectorAll('.iwb-editor-layer-list .iwb-layer-item'))
.map((n) => n.querySelector('.iwb-layer-name')?.textContent).join(' > '))
const activeCount = () => page.evaluate(() => document.querySelectorAll('.iwb-editor-layer-list .iwb-layer-item.active').length)
check('图层面板只有一个选中项(画笔目标改用 ✎ 标记)', (await activeCount()) === 1,
'active=' + await activeCount() + ' / ' + await panelSeq())
await page.locator('.iwb-editor-tool[data-tool="select"]').click()
await page.mouse.click(imgBox.x + imgBox.width * 0.5, imgBox.y + imgBox.height * 0.5)
await page.waitForTimeout(150)
const activeItem = await page.evaluate(() => {
const n = document.querySelector('.iwb-editor-layer-list .iwb-layer-item.active')
return n && { type: n.dataset.layerType, name: n.querySelector('.iwb-layer-name')?.textContent }
})
check('点击「截图+图形」重叠区选中最上层截图(不被下方图形抢走)',
Boolean(activeItem && activeItem.type === 'bitmap' && /图层/.test(activeItem.name)), JSON.stringify(activeItem))
// v1.13 起顶栏四个层级按钮已删除(改为图层拖动 + Ctrl+]/[ 快捷键),
// 这里改为断言「按钮确实没了」+ 用快捷键验证排序仍然可用。
check('顶栏不再有层级排序按钮(改用图层拖动 + Ctrl+]/[)',
(await page.locator('.iwb-editor-layer-btn').count()) === 0 &&
(await page.locator('.iwb-editor-header .iwb-editor-commands').count()) === 0,
'layerBtn=' + await page.locator('.iwb-editor-layer-btn').count())
// v1.18(用户 2026-11-10):撤销 / 重做 / 还原 从顶栏搬到工具条最右,
// 「适应窗口 / 收起侧栏」退到它前面两位。这里断言「末尾是撤销组、视图按钮在其前」
// —— 光看版本号挡不住产物没重建。
const toolsOrder = await page.evaluate(() => {
const kids = Array.from(document.querySelectorAll('.iwb-editor-tools > *'))
const acts = kids.filter((n) => n.dataset && n.dataset.action).map((n) => n.dataset.action)
const hist = kids[kids.length - 1]
return {
tail: acts.slice(-2),
lastIsHistory: Boolean(hist && hist.classList.contains('iwb-editor-history')),
histActs: [...(hist ? hist.querySelectorAll('[data-action]') : [])].map((b) => b.dataset.action),
headerHasHistory: Boolean(document.querySelector('.iwb-editor-header .iwb-editor-history')),
}
})
check('工具栏最右是「撤销/重做/还原」组(视图按钮在其前)',
JSON.stringify(toolsOrder.tail) === JSON.stringify(['zoomFit', 'togglePanels']) &&
toolsOrder.lastIsHistory && toolsOrder.histActs.join(',') === 'undo,redo,reset' &&
!toolsOrder.headerHasHistory, JSON.stringify(toolsOrder))
const before = await panelSeq()
const activeName = await page.evaluate(() => document.querySelector('.iwb-editor-layer-list .iwb-layer-item.active .iwb-layer-name')?.textContent)
await page.keyboard.press('Control+[') // 下移一层
const afterDown = await panelSeq()
check('Ctrl+[ 下移一层改变图层顺序', before !== afterDown, before + ' → ' + afterDown)
await page.keyboard.press('Control+]') // 上移一层
check('Ctrl+] 上移一层恢复原顺序', (await panelSeq()) === before, await panelSeq())
await page.keyboard.press('Control+Shift+[') // 置底
const afterBottom = await panelSeq()
check('Ctrl+Shift+[ 置底生效(元素不会消失)',
afterBottom !== before && afterBottom.endsWith(String(activeName)), afterBottom)
check('置底后原图不再被钉在最底 —— 图层可以压到原图下面(v1.13 解封)',
!afterBottom.endsWith('原图'), afterBottom)
await page.keyboard.press('Control+Shift+]') // 置顶
check('Ctrl+Shift+] 置顶生效', (await panelSeq()) !== afterBottom, await panelSeq())
check('排序后仍只有一个选中项', (await activeCount()) === 1, 'active=' + await activeCount())
// v1.15 图片调节:真站确认面板存在、11 项按参数表生成(DOM 由 adjust.js 生成,
// 构建时漏带就会是 0 行 —— 这类「打包产物缺模块」只有真站能发现)
const adjRowCount = await page.locator('.iwb-editor-adj-row').count()
const adjNames = await page.locator('.iwb-editor-adj-name').allTextContents()
check('右侧栏「图片调节」11 项齐全',
adjRowCount === 11 && adjNames.join('/') === '曝光/明度/对比度/阴影/高光/色相/饱和度/温度/色调/锐度/清晰度',
'rows=' + adjRowCount + ' ' + adjNames.join('/'))
check('调节面板认到了作用层(不是「无图层」)',
(await page.locator('.iwb-editor-adj-target').textContent()) !== '无图层',
await page.locator('.iwb-editor-adj-target').textContent())
// v1.19:右栏常驻调色面板已删(用户 2026-11-10),颜色只剩工具栏弹层一处。
// 真站里 DOM 与 CSS 分别打包,这里同时验「右栏干净」和「弹层头部一行 / 16 色 8 列」——
// 样式漏打包时,头部会退回竖排或色块掉成 6 列,这条会直接露出来。
const sideColor = await page.evaluate(() => ({
hasSide: Boolean(document.querySelector('.iwb-editor-left [data-color-surface]')),
firstSection: (document.querySelector('.iwb-editor-left > section') || {}).className || '',
}))
check('右栏调色模块已删(第一个模块是图片调节)',
sideColor.hasSide === false && /iwb-editor-adj/.test(sideColor.firstSection),
JSON.stringify(sideColor))
await page.locator('.iwb-editor-tools [data-action="toggleColorPop"][data-color-slot="stroke"]').click()
await page.waitForTimeout(240)
const popShape = await page.evaluate(() => {
const pop = document.querySelector('.iwb-editor-color-pop')
if (!pop) return null
const r = (el) => el.getBoundingClientRect()
const head = r(pop.querySelector('.iwb-color-pop-head'))
const items = [pop.querySelector('[data-action="palettePick"]'),
pop.querySelector('.iwb-editor-color-hex-input'),
pop.querySelector('[data-action="pinColorPop"]')].map((el) => {
const b = r(el)
return { c: b.top + b.height / 2, l: b.left, r: b.right }
})
const sw = [...pop.querySelectorAll('.iwb-editor-color-swatches [data-panel-color]')]
const grid = pop.querySelector('.iwb-editor-color-swatches')
return {
w: Math.round(r(pop).width),
sameRow: items.every((it) =>
Math.abs(it.c - (head.top + head.height / 2)) < 3 && it.l >= head.left - 1 && it.r <= head.right + 1),
common: sw.length,
cols: new Set(sw.map((b) => Math.round(r(b).left))).size,
swatch: sw.length ? Math.round(r(sw[0]).width) : 0,
// v1.20:去色占常用色第一格(20px 同尺寸、第一排最左)
noneFirst: grid.children[0] === pop.querySelector('[data-color-none]'),
cells: grid.children.length,
}
})
check('色板弹层:头部一行(吸管 / 色值 / 图钉同排)+ 去色占常用色第一格 + 15 色 8 列',
Boolean(popShape) && popShape.sameRow && popShape.noneFirst && popShape.cells === 16 &&
popShape.common === 15 && popShape.cols === 8 && popShape.swatch === 20 && popShape.w === 440,
JSON.stringify(popShape))
await page.keyboard.press('Escape')
await page.waitForTimeout(140)
const sideBefore = await page.evaluate(() => Math.round(document.querySelector('.iwb-editor-left').getBoundingClientRect().width))
const sideGrip = await page.locator('.iwb-editor-side-resizer').boundingBox()
if (sideGrip) {
await page.mouse.move(sideGrip.x + 3, sideGrip.y + 120)
await page.mouse.down()
await page.mouse.move(sideGrip.x + 3 - 70, sideGrip.y + 120, { steps: 6 })
await page.mouse.up()
await page.waitForTimeout(180)
}
const sideAfter = await page.evaluate(() => Math.round(document.querySelector('.iwb-editor-left').getBoundingClientRect().width))
check('右栏可以拖宽(不再固定 220)', sideAfter >= sideBefore + 60, sideBefore + ' → ' + sideAfter)
await page.locator('.iwb-editor-side-resizer').dblclick()
await page.waitForTimeout(150)
// v1.17:描边可以是「无色」。真站要验的是按钮真的出现在描边槽、点完对象上真的关了,
// 而不只是 CSS 里多了个类 —— 形状消失与否只有跑起来才知道。
await page.locator('.iwb-editor-tool[data-tool="rect"]').click()
await page.mouse.move(imgBox.x + imgBox.width * 0.12, imgBox.y + imgBox.height * 0.12)
await page.mouse.down()
await page.mouse.move(imgBox.x + imgBox.width * 0.30, imgBox.y + imgBox.height * 0.30, { steps: 6 })
await page.mouse.up()
await page.waitForTimeout(250)
await page.locator('.iwb-editor-tool[data-tool="select"]').click()
await page.mouse.click(imgBox.x + imgBox.width * 0.21, imgBox.y + imgBox.height * 0.21)
await page.waitForTimeout(200)
await page.locator('.iwb-editor-tools [data-action="toggleColorPop"][data-color-slot="stroke"]').click()
await page.waitForTimeout(250)
const noneOnStroke = await page.evaluate(() => {
const n = document.querySelector('.iwb-editor-color-pop [data-color-none]')
// v1.20:去色不再 hidden,改用 disabled 表达「这个上下文不能去色」
return Boolean(n) && Boolean(n.offsetParent) && !n.disabled
})
await page.evaluate(() => document.querySelector('.iwb-editor-color-pop [data-color-none]').click())
await page.waitForTimeout(300)
const noStrokeState = await page.evaluate(() => {
const d = window.__iwbEditor.__debug()
const s = d.shapes.find((x) => x.id === d.selectedShapeId)
return s ? { strokeOn: s.strokeOn, fill: s.fill } : null
})
check('真站:描边能置「无」(去掉描边顺手切实心,对象不会消失)',
noneOnStroke && Boolean(noStrokeState) && noStrokeState.strokeOn === false && noStrokeState.fill === true,
JSON.stringify({ noneOnStroke, noStrokeState }))
await page.keyboard.press('Escape')
await page.waitForTimeout(120)
// v1.14 字体选择:真站是带 CSP 的环境,这里确认下拉可用、字体切换真的落到了对象上。
// 系统字体不受 CSP 约束(CSP 管的是网络字体),所以只要 canvas 能画就没问题。
const famDbg = () => page.evaluate(() => window.__iwbEditor.__debug())
const FAM_SEL = '.iwb-editor-optionbar-body select[data-opt-text="fontFamily"]'
await page.locator('.iwb-editor-tool[data-tool="text"]').click()
const famBox = await page.locator('.iwb-editor-layer-canvas').first().boundingBox()
await page.mouse.click(famBox.x + 60, famBox.y + 60)
await page.waitForTimeout(300)
await page.evaluate(() => {
const el = document.querySelector('.iwb-editor-text-input')
if (!el) return
el.focus()
el.value = '字体测试'
el.dispatchEvent(new Event('input', { bubbles: true }))
})
await page.keyboard.press('Enter')
await page.waitForTimeout(400)
const famOpts = await page.locator(FAM_SEL + ' option').allTextContents()
check('真站选项栏出现字体下拉,四档:黑体 / 宋体 / 楷体 / 圆体',
famOpts.length === 4, JSON.stringify(famOpts))
const wSans = ((await famDbg()).texts.find((t) => t.text === '字体测试') || {}).box
await page.selectOption(FAM_SEL, 'serif')
await page.waitForTimeout(320)
const tSerif = (await famDbg()).texts.find((t) => t.text === '字体测试')
check('真站切换宋体生效,且中文宽度不变(全角等宽,版面不跳动)',
Boolean(tSerif && tSerif.fontFamily === 'serif' && wSans && Math.abs(tSerif.box.w - wSans.w) <= 1),
(wSans ? wSans.w : '?') + ' → ' + (tSerif ? tSerif.box.w : '?'))
await page.keyboard.press('Delete')
await page.waitForTimeout(200)
// 复原成画笔工具,避免影响后面「覆盖」链路的画笔取样
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()
// 1.2.1 起默认没有 id='draw' 的预建层:填充落进「当前活动层」,
// 所以这里读活动层像素而不是写死 'draw'
return { base: d.pixel('base', px, py), draw: d.pixel(d.activeLayerId, px, py), activeId: d.activeLayerId }
}, { 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 还原原图=只剩原图单层(1.2.1 起不预建画笔层)', (await dbg()).layers.length === 1, 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()
await page.mouse.move(760, 520, { steps: 8 })
await page.mouse.up()
await page.locator('[data-action="replace"]').click()
const replaced = await poll(async () => page.evaluate((orig) => {
const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}')
const n = (ws.nodes || []).find((x) => x.id === 'r1')
if (!n) return false
const v = n.data && (typeof n.data.data === 'string' ? n.data.data : (n.data.data && (n.data.data.__blob || JSON.stringify(n.data.data))))
return (ws.nodes.length === 1 && v && v !== orig) ? { nodes: ws.nodes.length, changed: true } : false
}, PNG))
check('「覆盖」写回原节点(节点数不变、内容已变)', Boolean(replaced), JSON.stringify(replaced))
check('编辑器导出后关闭', (await page.locator('#iwb-editor-overlay').isVisible().catch(() => false)) === false)
// ---------- 6) 新建:真机画布新增节点 ----------
await openEditor()
await page.locator('#iwb-editor-overlay').waitFor({ state: 'visible', timeout: 30000 })
await page.locator('[data-action="newNode"]').click()
const created = await poll(async () => page.evaluate(() => {
const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}')
return (ws.nodes || []).length === 2 ? { nodes: 2 } : false
}))
check('「新建」在真机画布新增节点', Boolean(created), JSON.stringify(created))
await page.locator('.iwb-canvas').waitFor({ state: 'visible' })
check('画布渲染出 2 个节点', (await page.locator('.iwb-node').count()) === 2)
// ---------- 7) 无 CSP / 运行时错误 ----------
const bad = consoleErrors.filter((t) => /Content Security Policy|integrity|Refused to (execute|load|connect)/i.test(t))
check('无 CSP / SRI 拦截报错', bad.length === 0, bad.slice(0, 2).join(' | '))
check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '))
await browser.close()
console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过'))
process.exit(failed ? 1 : 0)
+1 -1
View File
@@ -13,7 +13,7 @@ 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 HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop'
const PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js')
// 版本真源是 package.json(构建时注入 manifest),探针不再硬编码,免得每次发版都要改测试
const PKG_VERSION = JSON.parse(readFileSync(path.resolve(HERE, '../package.json'), 'utf8')).version
+1 -2
View File
@@ -136,8 +136,7 @@ potrace 与其 JS 移植都是 **GPL-2.0**(见 `plugin/vendor/potrace/LICENSE`
```bash
npm run build -- image-vectorize # plugin/ → src/index.js(esbuild IIFE)
npm run validate # 契约校验
node image-vectorize/tools/harness.mjs # 本地端到端(合成宿主 + 真 Chromium,64 项)
node image-vectorize/tools/e2e-site.mjs # 桌面客户端端到端(市场安装 / SRI / CSP / 真实画布桥)
node image-vectorize/tools/harness.mjs # 本地端到端(合成宿主 + 真 Chromium,64 项,含 CSP / 画布桥)
# 拿真实素材调参数(不进 CI,最快看到效果):
node image-vectorize/tools/trace-cli.mjs ~/Desktop/menu.png --mode gray --levels 3
+1 -1
View File
@@ -7,7 +7,7 @@ import { createRequire } from 'node:module'
const HERE = path.dirname(fileURLToPath(import.meta.url))
const PLUGIN = path.resolve(HERE, '../plugin')
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop'
const REPO = path.resolve(HERE, '../..')
export function esbuildModule() {
-276
View File
@@ -1,276 +0,0 @@
// 真实站点端到端(开发用,不进 CI)。
//
// 与 harness 的分工:harness 用合成宿主,能验功能但不能验真实 CSP/网络;这里走真站 ——
// 真实的 `_headers`(**不含 wasm-unsafe-eval**)、真实 KV、浏览器 SRI 校验、真实画布桥。
// v0.2 是纯 JS potrace,所以这里反而要断言「wasm 仍被 CSP 拦住」——防止有人为了别的功能
// 悄悄把 'wasm-unsafe-eval' 加回去。
//
// 运行:
// node image-vectorize/tools/e2e-site.mjs
// IWB_BASE_URL=https://iwb.maqiart.eu.org node image-vectorize/tools/e2e-site.mjs
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'
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)
}
const BASE = process.env.IWB_BASE_URL || 'https://test.image-workbench-web.pages.dev'
const PLUGIN_ID = 'image-vectorize'
const WANT_VERSION = JSON.parse(readFileSync(path.join(REPO, 'image-vectorize/package.json'), 'utf8')).version
const CFG = { providers: [], canvas: {} }
const WS = { workspaces: [{ id: 'w1', name: 'W', nodes: [], edges: [], groups: [] }], activeId: 'w1', rev: 1 }
let failed = 0
const check = (name, ok, detail) => {
if (!ok) failed++
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
const poll = async (fn, timeout = 25000, step = 250) => {
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 sleep(step)
}
}
console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')')
const browser = await chromium.launch()
// 剪贴板要显式授权(真站是 https,安全上下文成立;本地 file/about:blank 测不到这条)
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } })
try {
await context.grantPermissions(['clipboard-read', 'clipboard-write'], { origin: new URL(BASE).origin })
} catch (error) {
console.log('(剪贴板授权失败,相关断言会跳过:' + (error && error.message) + ')')
}
const page = await context.newPage()
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(() => {}) })
await page.goto('about:blank')
const PNG = await page.evaluate(() => {
const c = document.createElement('canvas')
c.width = 320; c.height = 320
const g = c.getContext('2d')
g.fillStyle = '#ffffff'; g.fillRect(0, 0, 320, 320)
g.fillStyle = '#e8422f'; g.beginPath(); g.arc(96, 96, 58, 0, Math.PI * 2); g.fill()
g.fillStyle = '#1f5fa8'; g.beginPath(); g.roundRect(170, 130, 120, 84, 12); g.fill()
g.fillStyle = '#111111'; g.font = 'bold 38px "PingFang SC", sans-serif'; g.fillText('菜单', 96, 250)
return c.toDataURL('image/png')
})
await page.addInitScript((d) => {
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg))
const ws = JSON.parse(JSON.stringify(d.ws))
ws.workspaces[0].nodes = [{ id: 'r1', type: 'ref', x: 140, y: 140, data: { url: '', data: d.png, name: 'src.png', localName: null } }]
localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
localStorage.setItem('iwb_ws_active', ws.activeId)
localStorage.setItem('iwb_ws_w1', JSON.stringify(ws.workspaces[0]))
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
localStorage.setItem('iwb_plugins', JSON.stringify({ [d.id]: { enabled: true, settings: {}, data: {} } }))
}, { cfg: CFG, ws: WS, png: PNG, id: PLUGIN_ID })
const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' })
check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status()))
// ---------- 1) 真实 KV 加载 + SRI ----------
await page.waitForFunction(() => Boolean(window.IWBPluginHost) && window.IWBPluginHost.snapshot().initialized === true, null, { timeout: 30000 })
const active = await poll(async () => page.evaluate((id) => {
const p = window.IWBPluginHost.list().find((x) => x.id === id)
return p && p.active ? { version: p.version, enabled: p.enabled, capabilities: p.capabilities, error: p.error } : false
}, PLUGIN_ID))
check('从真实 KV 加载并启用(SRI 通过)', Boolean(active), JSON.stringify(active))
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) => s.src.indexOf('/plugins/plugin-' + PLUGIN_ID + '.') === 0 && /^sha256-/.test(s.integrity)),
JSON.stringify(scripts.map((s) => s.src)))
// ---------- 2) 宿主 CSP 不再放行 wasm(v0.2 纯 JS,不需要放宽) ----------
const cspProbe = await page.evaluate(async () => {
try {
const b = Uint8Array.from(atob('AGFzbQEAAAA='), (c) => c.charCodeAt(0))
await WebAssembly.instantiate(b)
return 'ok'
} catch (e) { return 'blocked: ' + e.message }
})
check('宿主 CSP 仍禁止 wasm 编译(本插件是纯 JS,不该再放宽)', cspProbe.indexOf('blocked') === 0, cspProbe.slice(0, 120))
// ---------- 3) 打开工作区 ----------
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await page.locator('.iwb-canvas:not(.iwb-canvas-hidden)').waitFor({ state: 'visible', timeout: 30000 })
check('工作区打开、种子节点在画布', (await page.locator('.iwb-node[data-node-id="r1"]').count()) === 1)
// ---------- 4) 入口 → 模态 ----------
await page.locator('.iwb-node[data-node-id="r1"]').click()
const floatBtn = page.locator('.iwb-node-floatbar button[title="位图转矢量"]')
let entry = ''
if (await floatBtn.count()) {
await floatBtn.click()
entry = '漂浮菜单'
} else {
await page.locator('.iwb-canvas').click({ button: 'right', position: { x: 900, y: 620 } })
await page.locator('.iwb-ctxmenu .iwb-ctx-item').filter({ hasText: '位图转矢量' }).first().click()
entry = '右键命令'
}
await page.locator('.vz-modal').waitFor({ state: 'visible', timeout: 30000 })
check('节点入口可触发(' + entry + ')', true)
check('样式注入生效(CSP unsafe-inline)', await page.evaluate(() => {
const s = document.getElementById('iwb-vectorize-style')
return Boolean(s && s.textContent.indexOf('.vz-') >= 0)
}))
// 用户 2026-11-09:取消与保存为节点互换,四颗按钮同一套描边配色(绿色主按钮已去掉)。
// 这条同时是「线上真的是新版」的活体证据 —— 光看版本号挡不住产物没重建。
check('顶栏顺序 保存为节点→复制→下载→取消,四颗同色', await page.evaluate(() => {
const btns = [...document.querySelectorAll('.vz-header .vz-btn')]
if (btns.map((b) => b.dataset.act).join(',') !== 'save,copy,svg,cancel') return false
const colors = new Set(btns.map((b) => getComputedStyle(b).backgroundColor + '|' + getComputedStyle(b).color))
return colors.size === 1
}))
// ---------- 5) 真站 CSP 下引擎能跑 ----------
const paths = await poll(async () => {
// 统计项是「元素」,合并模式下会带后缀「(N 孤岛合并)」,只取前面的数字
const t = await page.locator('[data-stat="elements"]').textContent()
const m = /^\s*(\d+)/.exec(t || '')
return m && Number(m[1]) > 0 ? m[1] : false
}, 30000)
check('真站描摹成功(纯 JS 引擎,无 wasm)', Boolean(paths), '元素=' + paths)
check('默认按孤岛拆分(元素数 > 层数)', Number(paths) > 3, '元素=' + paths)
check('预览为 blob: SVG', await page.evaluate(() => {
const v = document.querySelector('[data-stage="vector"]')
return Boolean(v && /^blob:/.test(v.src) && !v.hidden)
}))
const stats = await page.evaluate(() => ({
levels: Number(document.querySelector('[data-stat="levels"]').textContent),
bytes: document.querySelector('[data-stat="bytes"]').textContent,
ms: document.querySelector('[data-stat="ms"]').textContent,
}))
check('灰度层数正常(3 层)', stats.levels >= 3, JSON.stringify(stats))
// ---------- 5.5) 面板形态:高级默认打开 + 精度默认精细 ----------
check('高级参数默认展开', await page.evaluate(() => {
const box = document.querySelector('[data-adv]')
return Boolean(box && !box.hidden)
}))
check('精度默认「精细」', await page.evaluate(() => {
const a = document.querySelector('[data-seg-group="precision"] button.active')
return Boolean(a && a.dataset.value === 'fine')
}))
// v0.3.1:预览白底 + 填充/背景并排(真站 CSP 下 CSS 得真生效,不能只信本地)
check('预览区白底、无棋盘格', await page.evaluate(() => {
const cs = getComputedStyle(document.querySelector('.vz-preview'))
const m = /rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(cs.backgroundColor)
return Boolean(m) && Number(m[1]) > 240 && cs.backgroundImage === 'none'
}))
check('「填充 / 背景」两个色块并排在同一行', await page.evaluate(() => {
const a = document.querySelector('[data-color="color"]')
const b = document.querySelector('[data-color="bg"]')
if (!a || !b) return false
const ra = a.getBoundingClientRect()
const rb = b.getBoundingClientRect()
return Math.abs(ra.top - rb.top) < 2 && rb.left > ra.right - 1
}))
// v0.4.0:预览缩放 / 平移(真站上鼠标手势得真能走通,不能只信本地合成宿主)
const pvBox = await page.locator('.vz-preview').boundingBox()
await page.mouse.move(pvBox.x + pvBox.width / 2 + 40, pvBox.y + pvBox.height / 2 - 20)
await page.mouse.wheel(0, -300)
await sleep(220)
// 断言「换算比例」而不是「比容器大」:正方形图 fit 进宽屏预览后本来就比容器窄,
// 拿 rect.width > clientWidth 会比较,放大了也可能不成立(实测真站 549 vs 1011)
check('滚轮放大预览、倍率胶囊出现', await page.evaluate(() => {
const p = document.querySelector('.vz-preview')
const v = document.querySelector('[data-stage="vector"]')
const z = Number(p.style.getPropertyValue('--vz-zoom') || 1)
const chip = document.querySelector('[data-zoom-chip]')
const ratio = v.getBoundingClientRect().width / v.clientWidth
return z > 1.1 && Boolean(chip) && !chip.hidden && Math.abs(ratio - z) < 0.02
}))
await page.mouse.dblclick(pvBox.x + pvBox.width / 2, pvBox.y + pvBox.height / 2)
await sleep(220)
check('双击复位回 100%', await page.evaluate(() => {
const p = document.querySelector('.vz-preview')
return Number(p.style.getPropertyValue('--vz-zoom') || 1) === 1
}))
// 回归:平滑滚轮(小数 deltaY)在真站也必须缩放。旧逻辑靠整数步长识别鼠标,会把这类滚轮当平移。
await page.evaluate(() => {
const p = document.querySelector('.vz-preview')
const r = p.getBoundingClientRect()
p.dispatchEvent(new WheelEvent('wheel', {
deltaY: -12.5, deltaMode: 0, bubbles: true, cancelable: true,
clientX: r.left + r.width / 2, clientY: r.top + r.height / 2,
}))
})
await sleep(160)
check('真站:小数步长滚轮照样放大', await page.evaluate(() => {
const p = document.querySelector('.vz-preview')
return Number(p.style.getPropertyValue('--vz-zoom') || 1) > 1.001
}))
await page.mouse.dblclick(pvBox.x + pvBox.width / 2, pvBox.y + pvBox.height / 2)
await sleep(160)
// ---------- 5.6) 复制到剪贴板(真写,读回校验口味) ----------
await page.locator('[data-act="copy"]').click()
await sleep(400)
const clip = await page.evaluate(async () => {
try {
const items = await navigator.clipboard.read()
const types = items[0] ? items[0].types : []
let svg = ''
if (types.indexOf('image/svg+xml') >= 0) svg = await (await items[0].getType('image/svg+xml')).text()
return { types, svg, status: (document.querySelector('[data-status-text]') || {}).textContent || '' }
} catch (e) { return { error: String(e && e.message) } }
})
if (clip.error) {
check('复制 SVG 写入剪贴板', false, clip.error)
} else {
check('复制 SVG:剪贴板含 image/svg+xml(Figma 按矢量粘贴)',
clip.types.indexOf('image/svg+xml') >= 0 && clip.svg.indexOf('<svg') === 0 && clip.svg.indexOf('<path') > 0,
clip.types.join(',') + ' / ' + clip.svg.length + 'B')
check('复制后给了反馈', /已复制/.test(clip.status), clip.status)
// 拆分是这个版本的核心诉求:粘到 Figma 必须是多个可单独选中的图层,而不是一个整体
const pathCount = (clip.svg.match(/<path/g) || []).length
check('剪贴板里是多个独立 path(Figma 可单独选中,不是一个整体)', pathCount >= 5 && !/<g\b/.test(clip.svg), 'path 元素=' + pathCount)
}
// ---------- 6) 保存为节点(真实画布桥) ----------
await page.locator('[data-act="save"]').click()
const saved = await poll(async () => (await page.locator('.iwb-node').count()) >= 2, 25000)
check('保存为节点:画布新增一个图片节点', Boolean(saved), 'nodes=' + await page.locator('.iwb-node').count())
check('模态已关闭', (await page.locator('.vz-root').count()) === 0)
const fatal = consoleErrors.filter((e) => /Content Security Policy|Refused to|SRI|integrity/i.test(e))
check('无 CSP / SRI 报错', fatal.length === 0, fatal.slice(0, 2).join(' | '))
if (consoleErrors.length) {
console.log('')
console.log('控制台错误(' + consoleErrors.length + ' 条,前 5 条):')
for (const e of consoleErrors.slice(0, 5)) console.log(' ' + String(e).slice(0, 180))
}
console.log('')
console.log(failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过')
await browser.close()
process.exit(failed ? 1 : 0)
+1 -1
View File
@@ -16,7 +16,7 @@ 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 HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop'
const PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js')
const WANT_VERSION = JSON.parse(readFileSync(path.join(HERE, '../package.json'), 'utf8')).version
+1 -1
View File
@@ -16,7 +16,7 @@ import { bundleEngine } from './bundle-engine.mjs'
const HERE = path.dirname(fileURLToPath(import.meta.url))
const REPO = path.resolve(HERE, '../..')
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop'
let chromium = null
for (const base of [HOST_REPO, REPO, process.cwd()]) {
+3 -1
View File
@@ -6,9 +6,11 @@
"scripts": {
"validate": "node scripts/validate.mjs",
"build": "node scripts/build-plugin.mjs",
"test": "npm run validate && npm run test:album && npm run test:promptlib",
"test": "npm run validate && npm run test:album && npm run test:promptlib && npm run test:gallery",
"test:album": "node album/tools/harness.mjs",
"test:album:e2e": "node album/tools/viewer-e2e.mjs",
"test:gallery": "node gallery/tools/harness.mjs",
"test:gallery:visual": "node gallery/tools/foot-visual-check.mjs",
"test:promptlib": "node promptlib/tools/harness.mjs && node promptlib/tools/vars-editor-test.mjs",
"test:promptlib:visual": "node promptlib/tools/vars-panel-visual-check.mjs"
},
+4 -5
View File
@@ -53,7 +53,7 @@
`ensureStyle()` 原本只在 `mount()`(面板)里调用 ⇒ **没打开过「风格库」面板**时,节点体是无样式的裸 DOM,
`<img class="iwb-ssn-thumb">` 按原图尺寸铺满整个节点(真机表现:图片"跑出来了")。
现在 setup 注册变体前注入一次,`renderStyleNode()` 里再兜一次(幂等)。
回归用例:`tools/e2e-test-site.mjs` 第 9 段(不开面板直接进存档画布,断言缩略图宽高 ≈56px)。
回归用例:`tools/harness.mjs` 的「样式表在脚本执行时就已注入(不开面板、不跑 setup 也在)」闸门,以及缩略图 56px 方块的断言。
### v1.3.2(2026-11-14)注入点再提前到脚本执行 + 缩略图内联兜底
@@ -182,15 +182,14 @@
数据与图片都是公网 `https://`,桌面宿主 `tauri.conf.json` 的 `img-src … https:` / `connect-src … https:` 已经放行。
对比 `ai-chat`(连本机 `http://127.0.0.1:3425`)必须单独加端口。
## 测试(三层,从快到慢)
## 测试(两层,从快到慢)
| 层 | 命令 | 覆盖什么 | 依赖 |
|---|---|---|---|
| 合成宿主 | `node tools/harness.mjs`(88 项) | 面板交互、详情页按钮顺序与同色、节点体结构、变量写入/防抖/不失焦、收起变量、截图 | 无(自带 mock 宿主) |
| 合成宿主 | `node tools/harness.mjs`(88 项) | 面板交互、详情页按钮顺序与同色、节点体结构、变量写入/防抖/不失焦、收起变量、CSS 注入闸门、截图 | 无(自带 mock 宿主 + 真 Chromium) |
| 线上数据真网 | `node tools/e2e-real.mjs`(10 项) | styles.json 真拉得到、卡片渲染、样式节点入口 | 网络 |
| 桌面客户端端到端 | `node tools/e2e-test-site.mjs`(15 项) | **宿主新接口到底接上没有**:进画布 → 开资源库 → 点「样式节点」→ 节点体由插件渲染、示例图默认勾选、变量输入不失焦、多变量不裁切、收起生效 | 桌面客户端已装本插件(`SITE=` 换地址,`HEADED=1` 看着跑) |
前两支只验插件自己;**第三支才验宿主**,发布宿主改动后必跑。
两支都验插件自己;发布宿主改动后,在桌面客户端市场里确认版本与加载状态,并用真实存档画布核对样式节点体(harness 的 CSS 闸门已覆盖「不开面板直接进画布」这一关键场景)。
## 发布
+1 -1
View File
@@ -15,7 +15,7 @@ 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 HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop'
const PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js')
let chromium = null
-283
View File
@@ -1,283 +0,0 @@
// 真机验收:**测试站上「宿主新接口 + 本插件」端到端**跑通(harness / e2e-real 都覆盖不到的那一层)。
//
// 为什么单独一支:
// - `tools/harness.mjs` 跑在合成宿主里,验不了「宿主的 PluginDomBody / 声明式参考图」是否真的接上;
// - `tools/e2e-real.mjs` 验的是「线上真网 + 插件面板」,不去点画布、不落节点。
// 这支脚本在**真的 test 站**里:双击进工作台 → 开资源库 → 点风格 → 点「样式节点」→ 检查节点体与输入体验。
//
// 用法:
// node tools/e2e-test-site.mjs # 默认 https://test.image-workbench-web.pages.dev/
// SITE=https://xxx.pages.dev/ node tools/e2e-test-site.mjs
// HEADED=1 node tools/e2e-test-site.mjs # 看着它跑
//
// 前置:宿主已部署含「插件节点体 + 声明式参考图」的版本,且 style-source 已在 KV 清单里。
// 全程只读:不动线上数据,浏览器用一次性 profile(跑完即弃)。
import { createRequire } from 'node:module'
import path from 'node:path'
import fs from 'node:fs'
const HERE = path.dirname(new URL(import.meta.url).pathname)
let chromium = null
for (const base of [path.resolve(HERE, '../..'), path.resolve(HERE, '../../../image-workbench-web'), process.cwd()]) {
const pkg = path.join(base, 'package.json')
if (!fs.existsSync(pkg)) continue
try { chromium = createRequire(pkg)('playwright').chromium; break } catch { /* 换下一个 */ }
}
if (!chromium) {
console.error('找不到 playwright:请在插件仓根目录或宿主仓(image-workbench-web)里跑')
process.exit(2)
}
const SITE = process.env.SITE || 'https://test.image-workbench-web.pages.dev/'
let failed = 0
const check = (name, ok, detail) => {
if (!ok) failed++
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
const shot = (name) => page.screenshot({ path: path.join(HERE, 'shot-testsite-' + name + '.png') }).catch(() => {})
const proxy = process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy
const browser = await chromium.launch({
headless: process.env.HEADED !== '1',
...(proxy ? { proxy: { server: proxy } } : {}),
})
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } })
const errors = []
page.on('pageerror', (e) => errors.push(String(e)))
await page.goto(SITE, { waitUntil: 'domcontentloaded' })
await page.waitForTimeout(1200)
// 启停状态只落 localStorage['iwb_plugins'](真机同款键)
await page.evaluate(() => {
localStorage.setItem('iwb_plugins', JSON.stringify({ 'style-source': { enabled: true, settings: {}, data: {} } }))
})
await page.reload({ waitUntil: 'domcontentloaded' })
await page.waitForTimeout(4000)
// ── 1. 宿主版本:三处新接口的特征串(压缩后函数名会变,只能查字符串) ──────────
const host = await page.evaluate(async () => {
const src = await (await fetch('/app.js', { cache: 'no-store' })).text()
const ver = await (await fetch('/version.json', { cache: 'no-store' })).json().catch(() => ({}))
return {
pluginBody: src.includes('iwb-plugin-node-body'),
selfRef: src.includes('style-ref.png'),
combineTag: src.includes('iwb-combine-src-tag'),
version: ver.version || '',
len: src.length,
}
})
check('测试站 app.js 含插件节点体 + 声明式参考图 + 组合来源标签', host.pluginBody && host.selfRef && host.combineTag,
JSON.stringify({ version: host.version, len: host.len }))
// ── 2. 插件已启用并激活 ───────────────────────────────────────────────────
const list = await page.evaluate(() => {
const h = window.IWBPluginHost
if (!h) return { noHost: true }
const l = typeof h.list === 'function' ? h.list() : []
return { list: l.map((p) => ({ id: p.id, version: p.version, enabled: p.enabled, active: p.active, error: p.error })) }
})
const me = (list.list || []).find((p) => p.id === 'style-source')
check('style-source 已启用并激活', Boolean(me && me.active), JSON.stringify(me))
// ── 3. 进工作台(首页卡片是「双击打开」,单击只是选中) ──────────────────────
await page.locator('.iwb-home-card').first().dblclick({ timeout: 8000 })
await page.waitForTimeout(3000)
const entered = await page.evaluate(() => ({ cards: document.querySelectorAll('.iwb-home-card').length }))
check('双击首页卡片进入画布', entered.cards === 0, JSON.stringify(entered))
// ── 4. 资源库 → 风格库 tab(N 是宿主「开关资源库」的快捷键) ──────────────────
await page.evaluate(() => { const a = document.activeElement; if (a && a.blur) a.blur() })
await page.keyboard.press('n')
await page.waitForTimeout(1200)
const tabs = await page.evaluate(() => [...document.querySelectorAll('.iwb-res-tab')].map((b) => (b.textContent || '').trim()))
await page.evaluate(() => {
const hit = [...document.querySelectorAll('.iwb-res-tab')].find((b) => /风格库/.test(b.textContent || ''))
if (hit) hit.click()
})
check('资源库里有「风格库」tab', tabs.includes('风格库'), JSON.stringify(tabs))
// 风格数据是直连 GitHub Pages 拉的,首次没缓存时快时慢 ⇒ 轮询,别写死等待
await page.waitForFunction(() => document.querySelectorAll('.iwb-ss-card').length > 0, null, { timeout: 30000 }).catch(() => {})
await page.waitForTimeout(300)
const cards = await page.locator('.iwb-ss-card').count()
check('风格库渲染出卡片', cards > 0, String(cards))
// ── 5. 详情页底部三颗按钮:同行、均分、「样式节点」在最左(不是替换掉原来两颗) ──
await page.locator('.iwb-ss-card').first().click()
await page.waitForTimeout(900)
const footInfo = await page.evaluate(() => {
const btns = [...document.querySelectorAll('.iwb-ss-dfoot .iwb-ss-btn')]
return { labels: btns.map((b) => (b.textContent || '').trim()), tops: btns.map((b) => Math.round(b.getBoundingClientRect().top)) }
})
check('详情页底部三颗按钮同行,「样式节点」在最左',
footInfo.labels.length === 3 && footInfo.labels[0] === '样式节点' && new Set(footInfo.tops).size <= 1,
JSON.stringify(footInfo))
// ── 6. 点「样式节点」→ 节点落地,节点体由插件渲染 ─────────────────────────────
await page.locator('.iwb-ss-dfoot .iwb-ss-btn').filter({ hasText: '样式节点' }).first().click()
await page.waitForTimeout(1600)
await page.keyboard.press('Escape')
await page.waitForTimeout(400)
await page.keyboard.press('f')
await page.waitForTimeout(700)
await shot('node')
const node1 = await page.evaluate(() => {
const b = document.querySelector('.iwb-plugin-node-body')
if (!b) return { bodies: 0 }
const rows = [...b.querySelectorAll('.iwb-ssn-row')]
return {
bodies: document.querySelectorAll('.iwb-plugin-node-body').length,
hasRoot: Boolean(b.querySelector('.iwb-ssn')),
name: (b.querySelector('.iwb-ssn-name') || {}).textContent || '',
code: (b.querySelector('.iwb-ssn-code') || {}).textContent || '',
rows: rows.length,
refChecked: b.querySelector('.iwb-ssn-ref input') ? b.querySelector('.iwb-ssn-ref input').checked : null,
hasRunBtn: [...b.querySelectorAll('button')].some((x) => /运行|生成/.test(x.textContent)),
foot: (b.querySelector('.iwb-ssn-foot') || {}).textContent || '',
}
})
check('样式节点落地且节点体由插件渲染(.iwb-ssn 存在)', node1.hasRoot === true, JSON.stringify(node1).slice(0, 300))
check('节点体有名称/编号/变量行,示例图默认勾选,且没有生成按钮',
Boolean(node1.name) && Boolean(node1.code) && node1.refChecked === true && node1.hasRunBtn === false,
JSON.stringify(node1).slice(0, 300))
// ── 7. 变量输入不失焦、值不被重渲染覆盖(PluginDomBody 固定容器生效) ─────────
const typing = await page.evaluate(async () => {
const b = document.querySelector('.iwb-plugin-node-body .iwb-ssn')
const input = b && b.querySelector('.iwb-ssn-row input')
if (!input) return { noBody: true }
input.focus()
input.value = '真机测试值'
input.dispatchEvent(new Event('input', { bubbles: true }))
await new Promise((r) => setTimeout(r, 700))
const b2 = document.querySelector('.iwb-plugin-node-body .iwb-ssn')
const input2 = b2.querySelector('.iwb-ssn-row input')
return { sameInput: input === input2, kept: input2.value, focusKept: document.activeElement === input2 }
})
check('变量输入不失焦、值不被重渲染覆盖',
typing.sameInput === true && typing.kept === '真机测试值' && typing.focusKept === true, JSON.stringify(typing))
// ── 8. 变量多的样式:全部露出、不裁切、单行 28px、收起/展开生效 ──────────────
// 上一步把焦点留在了变量输入框里;宿主的快捷键在 INPUT 上直接 return ⇒ 先 blur,否则按 n 只会打出一个字母
await page.evaluate(() => { const a = document.activeElement; if (a && a.blur) a.blur() })
await page.keyboard.press('n')
await page.waitForTimeout(1200)
await page.evaluate(() => {
const hit = [...document.querySelectorAll('.iwb-res-tab')].find((b) => /风格库/.test(b.textContent || ''))
if (hit) hit.click()
})
await page.waitForFunction(() => document.querySelectorAll('.iwb-ss-card').length > 0, null, { timeout: 30000 }).catch(() => {})
let picked = null
const total = await page.locator('.iwb-ss-card').count()
for (let i = 0; i < Math.min(total, 30); i++) {
await page.locator('.iwb-ss-card').nth(i).click()
await page.waitForTimeout(380)
const info = await page.evaluate(() => ({
n: document.querySelectorAll('.iwb-ss-dbody .iwb-ss-var').length,
title: (document.querySelector('.iwb-ss-dtitle') || {}).textContent || '',
}))
if (info.n >= 3) { picked = { idx: i, ...info }; break }
}
check('能找到一个变量 ≥3 的样式(用于压力验证)', Boolean(picked), JSON.stringify(picked))
if (picked) {
await page.locator('.iwb-ss-dfoot .iwb-ss-btn').filter({ hasText: '样式节点' }).first().click()
await page.waitForTimeout(1600)
await page.keyboard.press('Escape')
await page.waitForTimeout(400)
await page.keyboard.press('f')
await page.waitForTimeout(700)
await shot('multivar')
const multi = await page.evaluate(() => {
const all = [...document.querySelectorAll('.iwb-plugin-node-body')]
const b = all[all.length - 1]
if (!b) return { noBody: true }
const rows = [...b.querySelectorAll('.iwb-ssn-row')]
return {
bodies: all.length,
rows: rows.length,
labels: rows.map((x) => ((x.querySelector('label') || {}).textContent || '')).filter(Boolean),
rowH: rows.length ? Math.round(rows[0].getBoundingClientRect().height) : 0,
hiddenRows: rows.filter((x) => x.getBoundingClientRect().height < 8).length,
scrollH: b.scrollHeight,
clientH: b.clientHeight,
}
})
check('变量多的样式:所有变量行都露出、无零高行', multi.rows >= 3 && multi.hiddenRows === 0, JSON.stringify(multi).slice(0, 320))
check('节点体没有裁切(scrollHeight ≈ clientHeight)', Math.abs(multi.scrollH - multi.clientH) <= 2,
JSON.stringify({ s: multi.scrollH, c: multi.clientH }))
check('变量单行高度 28px 量级', multi.rowH >= 24 && multi.rowH <= 32, String(multi.rowH))
const collapsed = await page.evaluate(async () => {
const all = [...document.querySelectorAll('.iwb-plugin-node-body')]
const b = all[all.length - 1]
const btn = b && b.querySelector('.iwb-ssn-toggle')
if (!btn) return { noBtn: true }
const before = Math.round(b.querySelector('.iwb-ssn-vars').getBoundingClientRect().height)
btn.click()
await new Promise((r) => setTimeout(r, 500))
const box = b.querySelector('.iwb-ssn-vars')
return { before, after: Math.round(box.getBoundingClientRect().height), hidden: box.classList.contains('is-hidden'), tip: btn.title }
})
check('「收起变量」生效(变量区收起,按钮变成「展开变量」)',
collapsed.hidden === true && collapsed.after === 0 && collapsed.tip === '展开变量', JSON.stringify(collapsed))
await shot('collapsed')
}
// ── 9. 冷启动:**一次都没打开过「风格库」面板**,节点体也必须是有样式的 ──────────────
// v1.3.1 修的事故:CSS 原先进在 mount() 里,从存档打开画布时面板不 mount ⇒ `<img class="iwb-ssn-thumb">`
// 拿不到 56px 约束,按原图尺寸铺满整个节点(用户原话「图片都跑出来了」)。
{
const COLD_NODE = {
id: 'cold1', type: 'plugin:style-source:style', x: 260, y: 200, w: 300, h: 380,
data: {
variant: 'style', styleId: 'cold-style', name: '冷启动样式', code: 'ST9999', outKind: 'prompt',
promptTpl: '一张{主体}的图', varMeta: [{ key: '主体', label: '主体' }], vars: { 主体: '手表' },
text: '一张手表的图', preview: 'https://example.invalid/cold.png', refName: 'ST9999.png',
refOn: true, refUrl: 'https://example.invalid/cold.png', collapsed: false,
},
}
const ws = { workspaces: [{ id: 'w1', name: '冷启动', nodes: [COLD_NODE], edges: [], groups: [] }], activeId: 'w1', rev: 1 }
const ctx2 = await browser.newContext({ viewport: { width: 1400, height: 900 } })
const p2 = await ctx2.newPage()
await p2.addInitScript(({ ws, board }) => {
localStorage.clear()
localStorage.setItem('iwb_plugins', JSON.stringify({ 'style-source': { enabled: true, settings: {}, data: {} } }))
localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
localStorage.setItem('iwb_ws_active', 'w1')
localStorage.setItem('iwb_ws_w1', JSON.stringify(board))
}, { ws, board: ws.workspaces[0] })
await p2.goto(SITE, { waitUntil: 'domcontentloaded' })
await p2.waitForTimeout(1500)
await p2.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick().catch(() => {})
await p2.waitForFunction(() => Boolean(document.querySelector('.iwb-plugin-node-body')), null, { timeout: 20000 }).catch(() => {})
const cold = await p2.evaluate(() => {
const th = document.querySelector('.iwb-ssn-thumb')
const body = document.querySelector('.iwb-plugin-node-body')
const node = document.querySelector('.iwb-node')
return {
hasBody: Boolean(body),
hasStyle: Boolean(document.getElementById('iwb-ss-style')),
thumbW: th ? Math.round(th.getBoundingClientRect().width) : 0,
thumbH: th ? Math.round(th.getBoundingClientRect().height) : 0,
nodeW: node ? Math.round(node.getBoundingClientRect().width) : 0,
}
})
check('冷启动(没开过风格库):节点体成立 + 样式已注入', cold.hasBody && cold.hasStyle, JSON.stringify(cold))
check('冷启动:缩略图被 CSS 约束在 56px(不是按原图铺满节点)',
cold.thumbW >= 40 && cold.thumbW <= 62 && cold.thumbH >= 40 && cold.thumbH <= 62,
JSON.stringify({ w: cold.thumbW, h: cold.thumbH, nodeW: cold.nodeW }))
await p2.screenshot({ path: path.join(HERE, 'shot-testsite-coldstart.png') }).catch(() => {})
await ctx2.close()
}
check('全程无页面 JS 异常', errors.length === 0, errors.slice(0, 3).join(' | '))
await browser.close()
console.log('')
console.log(failed === 0 ? '全部通过' : failed + ' 项失败')
process.exit(failed === 0 ? 0 : 1)
+1 -1
View File
@@ -18,7 +18,7 @@ import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url)) // <repo>/style-source/tools
const REPO = path.resolve(HERE, '../..')
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop'
const PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js')
const STYLES_JSON = '/Users/qiqi/open/github/style-source/data/styles.json'
+1 -1
View File
@@ -103,7 +103,7 @@ npm run validate
```bash
node white-bg-800/tools/harness.mjs
```
- `tools/e2e-site.mjs`:真实桌面客户端的端到端(市场安装 + SRI + 漂浮菜单 → 新建节点),透明底等设置类用例由 harness 覆盖。
- 发布后回读市场索引 + 客户端市场里确认版本与加载状态;透明底等设置类用例由 harness 覆盖。
> harness 里的 mock `ctx.log` 必须是**函数**(真实宿主如此),早先写成对象导致凡是走 `ctx.log` 的分支全炸。
> 另外几何断言在有损格式下要留 ±4px 容差(jpeg 边缘振铃),精确几何用 `format=png` 的用例测。
-228
View File
@@ -1,228 +0,0 @@
// 真实站点端到端(开发用,不进 CI)—— white-bg-800「白底图」。
//
// 为什么需要它:mock 页没有 CSP,`connect-src` 一类问题(例如 `fetch(dataURL)` 被
// `connect-src 'self' https: …` 拦掉,因为宿主 CSP 的 `connect-src` 不含 `data:`)
// 在 mock 下永远绿,只有带真实 KV + 浏览器 SRI + 真实 CSP 的真站能抓出来。
// 它不 mock /plugins/*:走真实 KV 加载 + 浏览器 SRI(fail-closed)校验 + 真实画布桥。
//
// 运行(需要 Playwright):
// node white-bg-800/tools/e2e-site.mjs # 默认测试站
// IWB_BASE_URL=https://iwb.maqiart.eu.org node white-bg-800/tools/e2e-site.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)) // <repo>/white-bg-800/tools
const REPO = path.resolve(HERE, '../..') // <repo>
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
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:')
console.error(' npm i -D playwright # 本仓或宿主仓皆可')
console.error(' IWB_PLAYWRIGHT_ROOT=/path/to/repo node white-bg-800/tools/e2e-site.mjs')
process.exit(2)
}
const BASE = process.env.IWB_BASE_URL || 'https://test.image-workbench-web.pages.dev'
const WANT_VERSION = JSON.parse(readFileSync(path.join(REPO, 'white-bg-800/package.json'), 'utf8')).version
const CFG = { providers: [], canvas: {} }
const WS = { workspaces: [{ id: 'w1', name: 'W', nodes: [], edges: [], groups: [] }], activeId: 'w1', rev: 1 }
let failed = 0
const check = (name, ok, detail) => {
if (!ok) failed++
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
}
const poll = async (fn, timeout = 25000, step = 250) => {
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))
}
}
console.log('目标站点:' + BASE + '(期望插件版本 ' + WANT_VERSION + ')')
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))
// 造一张真实的 96x64 PNG 作为节点图片(故意非正方形,让 800 方画布的等比缩放/居中被真正练到)
await page.goto('about:blank')
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')
})
// 插件系统是 opt-in(新插件默认不启用),种子必须显式 enabled
await page.addInitScript((d) => {
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify(d.cfg))
const ws = JSON.parse(JSON.stringify(d.ws))
ws.workspaces[0].nodes = [{ id: 'r1', type: 'ref', x: 140, y: 140, data: { url: '', data: d.png, name: 'src.png', localName: null } }]
localStorage.setItem('iwb_web_workspaces', JSON.stringify(ws))
localStorage.setItem('iwb_ws_active', ws.activeId)
localStorage.setItem('iwb_ws_w1', JSON.stringify(ws.workspaces[0]))
localStorage.setItem('iwb_web_outputs', JSON.stringify([]))
localStorage.setItem('iwb_plugins', JSON.stringify({ 'white-bg-800': { enabled: true, settings: {}, data: {} } }))
}, { cfg: CFG, ws: WS, png: PNG })
// ---------- 1) 站点可达 ----------
const resp = await page.goto(BASE + '/', { waitUntil: 'domcontentloaded' })
check('站点可达', Boolean(resp && resp.ok()), resp && String(resp.status()))
// ---------- 2) 宿主就绪 + 真实 KV 加载并启用 ----------
const hostReady = await poll(async () => page.evaluate(() => Boolean(window.IWBPluginHost) && window.IWBPluginHost.snapshot().initialized === true), 30000)
check('window.IWBPluginHost 就绪(initialized)', Boolean(hostReady))
const active = await poll(async () => page.evaluate(() => {
const p = window.IWBPluginHost.list().find((x) => x.id === 'white-bg-800')
return p && p.active ? { version: p.version, enabled: p.enabled, capabilities: p.capabilities, error: p.error } : false
}))
check('从真实 KV 加载并启用(active)', Boolean(active), JSON.stringify(active))
// ---------- 3) 版本 ----------
check('线上版本 = white-bg-800/package.json(' + WANT_VERSION + ')', Boolean(active && active.version === WANT_VERSION), active && active.version)
// ---------- 4) SRI ----------
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-white-bg-800(\.[0-9a-f]{12})?\.js$/.test(s.src) && /^sha256-/.test(s.integrity)), JSON.stringify(scripts))
// ---------- 5) 打开工作区 + 种子节点 ----------
await page.locator('.iwb-home-card:not(.iwb-home-new)').first().dblclick()
await page.locator('.iwb-canvas:not(.iwb-canvas-hidden)').waitFor({ state: 'visible', timeout: 30000 })
check('工作区打开、种子节点在画布', (await page.locator('.iwb-node[data-node-id="r1"]').count()) === 1)
// ---------- 6) 入口:节点漂浮菜单(title 是静态字面量「白底图」;回落右键插件命令)----------
const triggerWhiteBg = async () => {
await page.locator('.iwb-node[data-node-id="r1"]').click()
const btn = page.locator('.iwb-node-floatbar button[title="白底图"]')
if (await btn.count()) { await btn.click(); return '漂浮菜单' }
await page.locator('.iwb-canvas').click({ button: 'right', position: { x: 900, y: 620 } })
await page.locator('.iwb-ctx-item').filter({ hasText: '白底图:选中节点' }).click()
return '右键命令'
}
const entry = await triggerWhiteBg()
check('节点入口可触发(漂浮菜单或右键命令)', true, entry)
// ---------- 7) 默认「新建」:恰好 2 个节点、新节点为 src_800x800.png ----------
const created = await poll(async () => page.evaluate(() => {
const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}')
const nodes = ws.nodes || []
if (nodes.length !== 2) return false
const n = nodes.find((x) => x.id !== 'r1') || nodes[1]
return { nodes: nodes.length, name: n.data && n.data.name }
}))
const wsNodes = created ? created.nodes : await page.evaluate(() => (JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}').nodes || []).length)
check('默认「新建」:iwb_ws_w1 恰好 2 个节点', wsNodes === 2, 'nodes=' + wsNodes)
check('新节点 data.name = src_800x800.jpg(默认 format=jpeg)', Boolean(created && /^src_800x800\.jpg$/.test(created.name || '')), created && String(created.name))
// ---------- 8) 页内解引用 + 解码新建 JPEG:800x800、左上像素为白色 ----------
// 宿主「C3」引用模型:localStorage 里只存引用,字节在别处 —— 假设 localStorage 里有 base64 是
// 不可能的(by design)。两种引用形态都要认:
// a) { __blob: 'imgblob_<hash>_<len>' } → IndexedDB(src/image-blob-store.js)
// b) { __cache: '<同源 URL>' } → 宿主把大 dataURL 外置成 /__iwb_cache__/xxx(当前线上形态)
// 故在页内经 IWBImageBlobStore 解引用或同源 fetch __cache(CSP connect-src 'self' 放行)。
const resolved = await poll(async () => page.evaluate(async () => {
// 读节点图(按优先级解引用):a) data: 字符串直用 b) {__blob} 引用解引用 c) 其余形态给诊断失败
const resolveNodeDataUrl = async (d) => {
if (typeof d === 'string' && /^data:/.test(d)) return { dataUrl: d, via: 'data:' } // a)
if (d && typeof d === 'object' && typeof d.__cache === 'string' && d.__cache) { // b2) 宿主把大 dataURL 外置成同源缓存引用
const toDataUrl = (blob) => new Promise((res) => {
const fr = new FileReader()
fr.onload = () => res(String(fr.result || ''))
fr.onerror = () => res('')
fr.readAsDataURL(blob)
})
try {
// /__iwb_cache__/<hash> 由 SW 直出;冷启动 SW 未接管时该路径会落到 Pages 404(返回 HTML)。
// 故优先直接读 Cache Storage,读不到再走 fetch(此时 SW 已接管)。
const abs = new URL(d.__cache, location.origin).href
if (typeof caches !== 'undefined') {
const hit = (await caches.match(abs)) || (await caches.match(d.__cache))
if (hit) {
const blob = await hit.blob()
const u = await toDataUrl(blob)
return u ? { dataUrl: u, via: '__cache(CS ' + blob.type + ')' } : { error: '__cache 读不出字节(' + d.__cache + ')' }
}
}
const resp = await fetch(abs)
const blob = await resp.blob()
const u = await toDataUrl(blob)
return u ? { dataUrl: u, via: '__cache(fetch ' + blob.type + ')' } : { error: '__cache 读不出字节(' + d.__cache + ')' }
} catch (e) {
return { error: '__cache 抓取抛错: ' + ((e && e.message) || String(e)) }
}
}
if (d && typeof d === 'object' && typeof d.__blob === 'string' && d.__blob) { // b)
const Lib = window.IWBImageBlobStore
if (!Lib) return { error: 'window.IWBImageBlobStore 缺失' }
try {
let u = ''
if (typeof Lib.resolveDataUrl === 'function') {
u = await Lib.resolveDataUrl(d.__blob)
} else if (typeof Lib.create === 'function') {
// 与 app.js:730 同一构造:idb 用宿主同一存储运行时(get 直出 Blob)
const idb = (window.IWBStorageRuntime && window.IWBStorageRuntime.indexedDb) ||
(window.IWBStorageFallbackIndexeddb && window.IWBStorageContract && window.IWBStorageFallbackIndexeddb.create({ contract: window.IWBStorageContract.indexedDb }))
if (!idb || typeof idb.get !== 'function') return { error: '取不到宿主 idb(IWBStorageRuntime.indexedDb)' }
u = await Lib.create({ idb }).resolveDataUrl(d.__blob)
} else {
return { error: 'IWBImageBlobStore 无 resolveDataUrl / create' }
}
return (typeof u === 'string' && u) ? { dataUrl: u, via: '__blob' } : { error: '解引用未返回字节(' + d.__blob + ')' }
} catch (e) {
return { error: '解引用抛错: ' + ((e && e.message) || String(e)) }
}
}
return { error: '未知 data 形态: ' + (d == null ? String(d) : typeof d) + ' keys=' + (d && typeof d === 'object' ? Object.keys(d).join(',') : '-') + ' sample=' + JSON.stringify(d).slice(0, 220) } // c)
}
const ws = JSON.parse(localStorage.getItem('iwb_ws_w1') || '{}')
const nodes = ws.nodes || []
const n = nodes.length === 2 ? (nodes.find((x) => x.id !== 'r1') || nodes[1]) : null
if (!n) return false // 新节点未就绪 → 重试
const r = await resolveNodeDataUrl(n.data && n.data.data)
if (r.error) return { error: r.error }
if (!/^data:image\/jpeg;base64,/.test(r.dataUrl)) return { error: '解引用结果不是 JPEG dataURL(via=' + r.via + '): ' + String(r.dataUrl).slice(0, 40) }
const img = new Image()
const ok = await new Promise((res) => { img.onload = () => res(true); img.onerror = () => res(false); img.src = r.dataUrl })
if (!ok) return { dataOk: true, via: r.via, decodeError: 'Image 解码失败' }
const c = document.createElement('canvas')
c.width = img.naturalWidth; c.height = img.naturalHeight
const x = c.getContext('2d')
x.drawImage(img, 0, 0)
const px = x.getImageData(0, 0, 1, 1).data
return { dataOk: true, via: r.via, w: img.naturalWidth, h: img.naturalHeight, px: [px[0], px[1], px[2], px[3]] }
}))
const d = resolved || {}
const dDiag = d.error || d.decodeError || (resolved ? '' : '轮询超时:新节点未出现')
check('新节点 data 为 JPEG 字节(引用已解析)', Boolean(d.dataOk), d.dataOk ? d.via : dDiag)
check('新建 JPEG 解码尺寸 = 800x800', Boolean(d.dataOk && d.w === 800 && d.h === 800), d.dataOk ? d.w + 'x' + d.h : dDiag)
// jpeg 有损:纯白角落允许 ±5 的压缩抖动,但 alpha 必须不透明
check('新建 JPEG 左上像素 ≈ 白色且不透明', Boolean(d.dataOk && d.px && d.px[0] >= 250 && d.px[1] >= 250 && d.px[2] >= 250 && d.px[3] === 255), JSON.stringify(d.px) || dDiag)
// 透明模式(transparent)不在此二次跑(需改设置再整轮重放,易碎)——由 white-bg-800/tools/harness.mjs 覆盖。
// ---------- 9) 无 CSP / SRI 拦截 ----------
const bad = consoleErrors.filter((t) => /Content Security Policy|integrity|Refused to (execute|load|connect)/i.test(t))
check('无 CSP / SRI 拦截报错', bad.length === 0, bad.slice(0, 2).join(' | '))
// ---------- 10) 无页面级运行时错误 ----------
check('无页面级运行时错误', consoleErrors.length === 0, consoleErrors.slice(0, 3).join(' | '))
await browser.close()
console.log('\n' + (failed ? '✗ 失败 ' + failed + ' 项' : '✓ 全部通过'))
process.exit(failed ? 1 : 0)
+1 -1
View File
@@ -15,7 +15,7 @@ import { fileURLToPath } from 'node:url'
const HERE = path.dirname(fileURLToPath(import.meta.url)) // <repo>/white-bg-800/tools
const REPO = path.resolve(HERE, '../..') // <repo>
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-web'
const HOST_REPO = '/Users/qiqi/open/github/image-workbench-desktop'
const PLUGIN_ENTRY = path.resolve(HERE, '../src/index.js')
let chromium = null