Files
image-workbench-desktop/tests/image-writeback-test.js
T
qiqi 5728efd9b4 refactor: 图片写回收口到 src/image-writeback.js(3.26.183 前置)
四个线上问题(174~182)都落在同一条链上:插件写图 → 节点数据 → 缩略图缓存 → 渲染。
旧实现分散在 app.js 插件桥与 runtime-workbench-logic,顺序靠人记,改一处漏一处就复发。

- 新增 src/image-writeback.js 三入口:
  · replaceNodeImage:引用化 → 一次 commit → saveNow → 回读校验(失败回滚旧图)→ 旧/新双 key 失效 → bump
  · replaceNodeImageSync:同步严格布尔、只改内存不落盘(blank-canvas / white-bg-800 依赖此语义)
  · createNodeImage:同步返回 id,大图后台引用化(6 个建图插件零改动)
- app.js 只做装配:删除 origImagePatch 与三个写入口旧实现;「还原替换前原图」支持引用形态
- 阈值只留一条判据:IMPORT_INLINE_MAX + wImportImage(keepOriginal);删除 182 的 200KB + 裸 wImgRefWrite 旁路
- orig 一起引用化,并补进 HISTORY_IMG_REF_FIELDS(撤销快照不再整串存旧图)
- 单测 tests/image-writeback-test.js(23 条断言)已进 test:unit
- 棘轮记账:MAX_APP_JS_LINES 8743→8911(+168)、MAX_WORKBENCH_LINES 2333→2505(+172,相对 HEAD −19)
  (174~182 修 bug 期间累计 +196 未记账,本轮把写回逻辑搬进 src 后按实测显式上调)
- 门禁修复:裁剪矩形守卫文本(cullRectsOf 已用 p = pad + extra)、事实文档数字与基线锚点、模块顺序/耦合面快照
- 文档:plugin-development.md 修正 ctx.canvasWrite 旧写法 + 新增「图片写回契约」表;
  workflow-2026-12-02.md 增加分工红线(代码改动只在 mac 侧,构建机只做流程性动作)
2026-12-02 07:40:02 +08:00

139 lines
7.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 图片写回唯一收口的契约测试(src/image-writeback.js)—— 2026-12-02 新增
//
// 为什么单独钉:v3.26.174~182 的 4 个线上问题都在这条链上,而三个入口的语义
// (同步布尔 / 异步校验 / 后台引用化)是插件侧(blank-canvas、white-bg-800、
// image-annotate)直接依赖的契约。任何一条被改成"看起来差不多"的写法,
// 都会以"图不落地 / CPU 空转 / 提示成功其实没保存"的形式复发。
'use strict'
const fs = require('fs')
const path = require('path')
const src = fs.readFileSync(path.join(__dirname, '..', 'src', 'image-writeback.js'), 'utf8')
const box = {}
new Function('window', 'globalThis', src)(box, box)
const W = box.IWBImageWriteback
let pass = 0
let fail = 0
const ok = (name, cond, extra) => {
if (cond) { pass++; console.log(' ✅ ' + name) } else { fail++; console.log(' ❌ ' + name + (extra ? ' → ' + JSON.stringify(extra) : '')) }
}
const SMALL = 'data:image/png;base64,AAAA'
const BIG = 'data:image/png;base64,' + 'A'.repeat(4000)
const REF = { __blob: 'blob-1' }
// 造一份可控依赖:importer 只对「大于内联阈值」的输入给出引用(与 wImportImage 同语义)
function make (opts) {
const o = opts || {}
const st = { refs: { nodes: [{ id: 'n1', type: 'ref', data: { data: o.initial || SMALL, url: '' } }] }, commits: 0, saves: 0, invalidated: [], bumps: 0, imported: [] }
const deps = {
refs: st.refs,
updateNode: (id, patch) => { st.refs.nodes = st.refs.nodes.map((n) => (n.id === id ? { ...n, data: { ...n.data, ...patch } } : n)); st.commits++ },
commitCanvas: (next) => { st.refs.nodes = next; st.commits++ },
saveNow: async () => { st.saves++ },
readWorkspace: () => ({ ok: true, value: { workspaces: [{ id: 'w1', nodes: st.refs.nodes }] } }),
activeWsId: () => 'w1',
inlineMax: 3000,
importer: async (dataUrl) => { st.imported.push(dataUrl); return { ok: true, data: REF, ref: REF } },
invalidate: (v) => st.invalidated.push(v),
bump: () => { st.bumps++ },
resolveRef: async () => 'data:image/png;base64,ORIGINAL',
createRefNode: (payload) => { const id = 'n' + (st.refs.nodes.length + 1); st.refs.nodes = st.refs.nodes.concat([{ id: id, type: 'ref', data: { data: String(payload.dataUrl) } }]); return id },
log: () => {},
}
return { w: W.create(deps), st, deps }
}
const node = (st, id) => st.refs.nodes.find((n) => n.id === (id || 'n1'))
const hasBase64 = (d) => Object.keys(d || {}).some((k) => typeof d[k] === 'string' && d[k].indexOf('data:') === 0)
async function main () {
// ── ① 同步入口:严格布尔、不落盘、只 commit 一次(blank-canvas / white-bg-800 依赖)──
{
const { w, st } = make()
const r = w.replaceNodeImageSync('n1', BIG)
ok('①-1 同步入口返回严格布尔 true(不是 Promise)', r === true && typeof r === 'boolean')
ok('①-2 同步入口不落盘(saveNow 0 次)', st.saves === 0, st.saves)
ok('①-3 同步入口只 commit 一次(UI 必须立刻更新)', st.commits === 1, st.commits)
ok('①-4 非法数据/不存在的节点返回 false', w.replaceNodeImageSync('n1', 'http://x/y.png') === false && w.replaceNodeImageSync('nope', BIG) === false)
}
// ── ② 异步入口:data / localRef / ref 三者同指一个引用,节点里不留 base64 ──
{
const { w, st } = make()
const r = await w.replaceNodeImage('n1', BIG)
const d = node(st).data
ok('②-1 返回 {ok:true}', !!(r && r.ok === true), r)
ok('②-2 data / localRef / ref 是同一个引用对象', d.data === REF && d.localRef === REF && d.ref === REF)
// orig 允许是 string(旧图本来是内联的,小图不引用化);这里只看显示/落盘用的四个字段
const shown = { data: d.data, url: d.url, localRef: d.localRef, ref: d.ref }
ok('②-3 显示/落盘字段里没有 data: 字符串残留', !hasBase64(shown), Object.keys(shown))
ok('②-4 落盘 1 次 + bump 至少 1 次', st.saves === 1 && st.bumps >= 1, { saves: st.saves, bumps: st.bumps })
}
// ── ③ orig 两次覆盖都保留且是引用;还原能取回原图 ──
{
const { w, st } = make({ initial: BIG })
await w.replaceNodeImage('n1', BIG.replace('A', 'B'))
const first = node(st).data.orig
ok('③-1 首覆盖:orig 已引用化(不是 base64 字符串)', !!first && typeof first === 'object' && first === REF, typeof first)
await w.replaceNodeImage('n1', BIG.replace('A', 'C'))
const second = node(st).data.orig
ok('③-2 第二次覆盖:orig 仍是引用、没丢', !!second && typeof second === 'object', typeof second)
const rr = await w.restoreOrig('n1')
const d = node(st).data
ok('③-3 还原动作能把原图取回来(清空 orig)', !!(rr && rr.ok) && d.orig === '' && /ORIGINAL|^data:/.test(String(d.data)))
}
// ── ③b 旧图已是引用、又没有 orig 时:直接把该引用当备份(否则第二次覆盖会静默丢 orig)──
{
const { w, st } = make()
st.refs.nodes = [{ id: 'n1', type: 'ref', data: { data: REF, url: '', localRef: REF, ref: REF } }]
await w.replaceNodeImage('n1', BIG.replace('A', 'E'))
const d = node(st).data
ok('③b-1 旧图是引用时,原样当备份(不再丢失 orig)', d.orig === REF, typeof d.orig)
ok('③b-2 备份没有引发额外写库(引用不再引用化)', st.imported.length === 1, st.imported.length)
}
// ── ④ 阈值唯一:<= inlineMax 不引用;> inlineMax 恰好引用一次 ──
{
const small = make()
const r = await small.w.replaceNodeImage('n1', SMALL.replace('AAAA', 'AAAB'))
ok('④-1 小图不产生引用(importer 0 次、data 仍是字符串)', small.st.imported.length === 0 && typeof node(small.st).data.data === 'string', { calls: small.st.imported.length })
ok('④-2 小图也不留 localRef/ref', node(small.st).data.localRef === null && node(small.st).data.ref === null)
const big = make()
await big.w.replaceNodeImage('n1', BIG)
ok('④-3 大图恰好引用一次(不含旧图备份时)', big.st.imported.length === 1, big.st.imported.length)
}
// ── ⑤ 双 key 失效:旧值 + 新值都失效(引用对象也要取到 key)──
{
const { w, st } = make({ initial: BIG })
await w.replaceNodeImage('n1', BIG.replace('A', 'D'))
const got = st.invalidated
ok('⑤-1 旧值被失效', got.some((v) => typeof v === 'string' && v.indexOf('data:') === 0 && v !== BIG.replace('A', 'D')), got.map((v) => typeof v))
ok('⑤-2 新引用也被失效(供 512/256 两档删除)', got.includes(REF))
ok('⑤-3 invalidate 由模块统一调用(不是各调用点各写一套)', st.bumps >= 1 && got.length >= 3, got.length)
}
// ── ⑥ 建节点:同步返回 id;大图后台引用化,小图不动 ──
{
const { w, st } = make()
const idSmall = w.createNodeImage({ dataUrl: SMALL, name: 'a.png' })
const idBig = w.createNodeImage({ dataUrl: BIG, name: 'b.png' })
ok('⑥-1 同步返回节点 id', typeof idSmall === 'string' && typeof idBig === 'string')
await new Promise((r) => setTimeout(r, 10))
const bigN = st.refs.nodes.find((n) => n.id === idBig)
ok('⑥-2 大图在后台被引用化', bigN && bigN.data.data === REF, bigN && typeof bigN.data.data)
ok('⑥-3 小图保持内联(不写库)', st.imported.length === 1, st.imported.length)
ok('⑥-4 非法 data URL 返回 null', w.createNodeImage({ dataUrl: 'https://x/y.png' }) === null)
}
console.log('')
console.log(pass + ' passed, ' + fail + ' failed')
if (fail) process.exit(1)
}
main().catch((e) => { console.error(e); process.exit(1) })