fitBody 只比 text/fontSize ⇒ 宿主改宽度(拖宽、侧栏开合、首帧未布局)时沿用旧行数高度。 高度缓存加入 clientWidth,高度按行高整数行对齐,并加 ResizeObserver(骨架摘除时自断)。 harness 增加宽度 160→420 变矮、整数行残差两条断言;版本断言改为对齐 package.json。
375 lines
18 KiB
JavaScript
375 lines
18 KiB
JavaScript
// 便利贴插件本地契约测试(纯 node,不依赖 playwright / 真浏览器)。
|
||
// 用最小 DOM / window stub 跑真实 src/index.js(IIFE),验证:
|
||
// manifest 字段 / 节点类型注册(标题/不连线/height)/ 面板注册 /
|
||
// CSS 脚本执行时就注入 / 字号闭集与 A+/A− / 粗细切换 / 8 色背景 + 色轮自定义 /
|
||
// 多行文本写回 data / 幂等同步(编辑中不覆盖、值变才写 DOM)/ 插入走 createNode(null,null)。
|
||
//
|
||
// 运行:node sticky/tools/harness.mjs (退出码 0 = 全过)
|
||
import { readFileSync } from 'node:fs'
|
||
import path from 'node:path'
|
||
import { fileURLToPath } from 'node:url'
|
||
import vm from 'node:vm'
|
||
|
||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||
const ENTRY = path.resolve(HERE, '../src/index.js')
|
||
const source = readFileSync(ENTRY, 'utf8')
|
||
|
||
let failed = 0
|
||
const check = (name, ok, detail) => {
|
||
if (!ok) failed++
|
||
console.log((ok ? '✓ ' : '✗ ') + name + (detail ? ' ' + detail : ''))
|
||
}
|
||
|
||
// ---------- 极简 DOM stub ----------
|
||
function makeNode(tag) {
|
||
return {
|
||
tagName: String(tag).toUpperCase(),
|
||
children: [], parentNode: null, _text: '', attrs: {}, listeners: {},
|
||
style: {}, className: '', hidden: false, value: '',
|
||
// textarea 自适应高度需要 scrollHeight:按「行数 × 行高 + 上下 padding」模拟。
|
||
// 给了 clientWidth 就按宽度粗估换行(越宽行数越少)—— v1.0.8「宽度变了高度要跟着重算」靠它验证。
|
||
get scrollHeight() {
|
||
if (String(tag).toUpperCase() !== 'TEXTAREA') return 0
|
||
const size = parseFloat(this.style.fontSize) || 14
|
||
const w = Number(this.clientWidth) || 0
|
||
const text = String(this.value || '')
|
||
let lines = 0
|
||
if (w > 40) {
|
||
const per = Math.max(1, Math.floor((w - 24) / (size * 0.55)))
|
||
text.split('\n').forEach((p) => { lines += Math.max(1, Math.ceil(p.length / per)) })
|
||
} else {
|
||
lines = Math.max(1, text.split('\n').length)
|
||
}
|
||
return Math.ceil(Math.max(1, lines) * size * 1.7) + 24
|
||
},
|
||
get textContent() { return this._text },
|
||
set textContent(v) { this._text = String(v); this.children = [] },
|
||
get firstChild() { return this.children[0] || null },
|
||
appendChild(c) { this.children.push(c); c.parentNode = this; return c },
|
||
removeChild(c) { const i = this.children.indexOf(c); if (i >= 0) this.children.splice(i, 1); return c },
|
||
setAttribute(k, v) { this.attrs[k] = String(v); if (k === 'style') this.style = parseStyle(String(v)) },
|
||
removeAttribute(k) { delete this.attrs[k] },
|
||
getAttribute(k) { return k in this.attrs ? this.attrs[k] : null },
|
||
focus() { this.__doc && (this.__doc.activeElement = this) },
|
||
blur() { this.__doc && this.__doc.activeElement === this && (this.__doc.activeElement = null); this.fire('blur') },
|
||
addEventListener(ev, fn) { (this.listeners[ev] = this.listeners[ev] || []).push(fn) },
|
||
fire(ev, data) {
|
||
const payload = Object.assign({ target: this, stopPropagation() {} }, data)
|
||
let n = this
|
||
while (n) {
|
||
;(n.listeners[ev] || []).forEach((fn) => fn(payload))
|
||
n = n.parentNode
|
||
}
|
||
},
|
||
querySelector(cls) {
|
||
const needle = cls.replace('.', '')
|
||
const q = [this]
|
||
while (q.length) {
|
||
const n = q.shift()
|
||
if (String(n.className).split(/\s+/).indexOf(needle) >= 0) return n
|
||
q.push(...(n.children || []))
|
||
}
|
||
return null
|
||
},
|
||
click() { this.fire('click') },
|
||
}
|
||
}
|
||
function parseStyle(s) {
|
||
const out = {}
|
||
s.split(';').forEach((part) => {
|
||
const i = part.indexOf(':')
|
||
if (i > 0) out[part.slice(0, i).trim()] = part.slice(i + 1).trim()
|
||
})
|
||
return out
|
||
}
|
||
|
||
function runPlugin() {
|
||
const head = makeNode('head')
|
||
const bodyEl = makeNode('body')
|
||
const document = {
|
||
head, documentElement: head, body: bodyEl, activeElement: null,
|
||
createElement: (tag) => { const n = makeNode(tag); n.__doc = document; return n },
|
||
createTextNode: (t) => ({ nodeType: 3, textContent: String(t) }),
|
||
getElementById: (id) => findById(head, id) || findById(bodyEl, id),
|
||
}
|
||
const registrations = []
|
||
let panelApi = null, nodeApi = null
|
||
const updates = []
|
||
const createCalls = []
|
||
const host = {
|
||
IWBPluginHost: {
|
||
register(manifest, factory) {
|
||
registrations.push({ manifest, factory })
|
||
},
|
||
},
|
||
document,
|
||
React: null,
|
||
}
|
||
const ctx = {
|
||
nodes: { register(def) { nodeApi = def; return true } },
|
||
ui: { registerPanel(def) { panelApi = def; return true } },
|
||
canvas: {
|
||
createNode(type, x, y, data) { createCalls.push({ type, x, y, data }); return 'n1' },
|
||
getNodes() { return [] },
|
||
focusNode() {},
|
||
},
|
||
}
|
||
const sandbox = Object.assign(host, {
|
||
console: { log() {}, warn() {}, error() {} },
|
||
window: host,
|
||
globalThis: host,
|
||
})
|
||
vm.createContext(sandbox)
|
||
vm.runInContext(source, sandbox)
|
||
// 触发工厂
|
||
registrations[0].factory(ctx)
|
||
return { registrations, manifest: registrations[0].manifest, nodeApi, panelApi, ctx, updates, createCalls, document, head }
|
||
}
|
||
function findById(root, id) {
|
||
if (root.attrs && root.attrs.id === id) return root
|
||
for (const c of root.children || []) { const r = findById(c, id); if (r) return r }
|
||
return null
|
||
}
|
||
|
||
// ---------- 测试 ----------
|
||
const r = runPlugin()
|
||
|
||
check('manifest.id = sticky', r.manifest.id === 'sticky')
|
||
check('manifest.name = 便利贴', r.manifest.name === '便利贴')
|
||
const PKG_VERSION = JSON.parse(readFileSync(path.resolve(HERE, '../package.json'), 'utf8')).version
|
||
check('manifest.version = package.json', r.manifest.version === PKG_VERSION, r.manifest.version + ' / ' + PKG_VERSION)
|
||
check('manifest.apiVersion = 1', r.manifest.apiVersion === 1)
|
||
check('capabilities 含 panels/nodeTypes/canvas',
|
||
['panels', 'nodeTypes', 'canvas'].every((c) => r.manifest.capabilities.includes(c)))
|
||
check('CSS 在脚本执行时就注入(#iwb-sticky-style)', !!findById(r.head, 'iwb-sticky-style'))
|
||
|
||
check('节点类型已注册', !!r.nodeApi)
|
||
check('节点 ports 全关(不连线)', r.nodeApi && r.nodeApi.ports.in === false && r.nodeApi.ports.out === false)
|
||
check('节点 title = 便利贴', r.nodeApi && r.nodeApi.title === '便利贴')
|
||
check('节点有 render 函数', r.nodeApi && typeof r.nodeApi.render === 'function')
|
||
check('面板已注册', !!r.panelApi && typeof r.panelApi.mount === 'function')
|
||
|
||
// 构造节点 host 并渲染(带 onUpdate 收集 patch)
|
||
function makeNodeHost() {
|
||
const h = makeNode('div')
|
||
h.__updates = []
|
||
const props = { onUpdate(id, patch) { h.__updates.push({ id, patch }) } }
|
||
const node = { id: 'n1', type: 'plugin:sticky:sticky', data: { text: '标题', fontSize: 14, fontWeight: 400, bgColor: '#FCE8B0' } }
|
||
r.nodeApi.render(node, props, h)
|
||
return { h, node, props }
|
||
}
|
||
const nh = makeNodeHost()
|
||
check('节点体注入 .iwb-sticky-node', !!findByClass(nh.h, 'iwb-sticky-node'))
|
||
check('节点体有工具条 A+/A−/B + 色板按钮', !!findByClass(nh.h, 'iwb-sticky-tools') && !!findByClass(nh.h, 'iwb-sticky-pal'))
|
||
check('节点体有 textarea', findByClass(nh.h, 'iwb-sticky-body') && findByClass(nh.h, 'iwb-sticky-body').tagName === 'TEXTAREA')
|
||
check('默认文本同步到 textarea', findByClass(nh.h, 'iwb-sticky-body').value === '标题')
|
||
|
||
// v1.0.2:色板挂在工具条内(top:100% 落调色按钮下方),不再贴便签底部右下角盖住 resize 手柄
|
||
const toolsBox = findByClass(nh.h, 'iwb-sticky-tools')
|
||
const palBox = findByClass(nh.h, 'iwb-sticky-pal')
|
||
check('色板挂在工具条内(跟随调色按钮,不盖 resize 手柄)', palBox && palBox.parentNode === toolsBox)
|
||
check('色板 CSS top:100%(落按钮下方)', /\.iwb-sticky-pal\{position:absolute;top:100%/.test(injectedCssOf(r)))
|
||
// v1.0.2:textarea 高度随内容自适应(flex:0 0 auto + JS 写 height)
|
||
check('textarea flex:0 0 auto(不 flex 撑满留白)', /\.iwb-sticky-body\{flex:0 0 auto/.test(injectedCssOf(r)))
|
||
function injectedCssOf(rr) { return (findById(rr.head, 'iwb-sticky-style') || {}).textContent || '' }
|
||
const taInit = findByClass(nh.h, 'iwb-sticky-body')
|
||
check('textarea 显式 rows=1(不预留默认第二行)', taInit.getAttribute('rows') === '1')
|
||
check('textarea 初始高度按内容算出(贴字)', parseFloat(taInit.style.height) > 0)
|
||
check('调色圆点推到工具条最右(右上)', /\.iwb-sticky-dot\{[^}]*margin-left:auto/.test(injectedCssOf(r)))
|
||
|
||
// v1.0.3:宿主外框 minHeight 来自 node.h —— 旧 h 会把便签撑出一截空白且手柄拖不下去。
|
||
// 用带父节点卡片的 host 复现:渲染后必须把外框 minHeight 校正成内容高度,并同步改正 node.h。
|
||
const card = makeNode('div')
|
||
card.style.minHeight = '360px'
|
||
const host2 = makeNode('div')
|
||
card.appendChild(host2)
|
||
const node2 = { id: 'n2', type: 'plugin:sticky:sticky', h: 360,
|
||
data: { text: '范例', fontSize: 40, fontWeight: 600, bgColor: '#FCE8B0' } }
|
||
r.nodeApi.render(node2, { onUpdate() {} }, host2)
|
||
const expectedH = Math.round(30 + parseFloat(findByClass(host2, 'iwb-sticky-body').style.height) + 2)
|
||
check('外框 minHeight 覆盖为内容高度(不再被旧 h 撑住)', card.style.minHeight === expectedH + 'px',
|
||
'card=' + card.style.minHeight + ' expected=' + expectedH + 'px')
|
||
check('旧 node.h 校正为内容高度(resize 起点贴字)', node2.h === expectedH, 'h=' + node2.h)
|
||
// 用户之后手动拖大的 h 不能被再次压回(仍然可拖大拖小)
|
||
node2.h = 260
|
||
r.nodeApi.render(node2, { onUpdate() {} }, host2)
|
||
check('用户拖大后的 h 保留(可拖大)', node2.h === 260 && card.style.minHeight === '260px',
|
||
'h=' + node2.h + ' minH=' + card.style.minHeight)
|
||
|
||
// v1.0.6:自动跟随内容的 h 必须双向伸缩——两行退回一行时外框要跟着缩回去。
|
||
const card3 = makeNode('div')
|
||
const host3 = makeNode('div')
|
||
card3.appendChild(host3)
|
||
const node3 = { id: 'n3', type: 'plugin:sticky:sticky',
|
||
data: { text: '一行', fontSize: 40, fontWeight: 400, bgColor: '#FCE8B0' } }
|
||
const pass3 = { onUpdate() {} }
|
||
r.nodeApi.render(node3, pass3, host3)
|
||
const hOneLine = node3.h
|
||
node3.data.text = '第一行\n第二行'
|
||
r.nodeApi.render(node3, pass3, host3)
|
||
const hTwoLines = node3.h
|
||
check('文本一行变两行:外框自动长高', hTwoLines > hOneLine, hOneLine + ' → ' + hTwoLines)
|
||
node3.data.text = '一行'
|
||
r.nodeApi.render(node3, pass3, host3)
|
||
check('文本两行退回一行:外框自动缩回(v1.0.6)',
|
||
node3.h === hOneLine && card3.style.minHeight === hOneLine + 'px',
|
||
'h=' + node3.h + ' minH=' + card3.style.minHeight)
|
||
|
||
function findByClass(root, cls) {
|
||
const needle = cls.split('.').filter(Boolean).pop()
|
||
const q = [root]
|
||
while (q.length) {
|
||
const n = q.shift()
|
||
if (String(n.className).split(/\s+/).indexOf(needle) >= 0) return n
|
||
q.push(...(n.children || []))
|
||
}
|
||
return null
|
||
}
|
||
const btn = (cls) => {
|
||
const q = [nh.h]
|
||
while (q.length) {
|
||
const n = q.shift()
|
||
if (String(n.className).split(/\s+/).indexOf(cls) >= 0) return n
|
||
q.push(...(n.children || []))
|
||
}
|
||
return null
|
||
}
|
||
|
||
// A+ → +2 步进(无上限)
|
||
btn('iwb-sticky-btn') // 占位,实际按 data-act 找
|
||
const plus = nh.h.querySelectorAll ? null : findByAct(nh.h, 'plus')
|
||
function findByAct(root, act) {
|
||
const q = [root]
|
||
while (q.length) {
|
||
const n = q.shift()
|
||
if (n.attrs && n.attrs['data-act'] === act) return n
|
||
q.push(...(n.children || []))
|
||
}
|
||
return null
|
||
}
|
||
findByAct(nh.h, 'plus').fire('click', { target: findByAct(nh.h, 'plus') })
|
||
check('A+ 写 fontSize=16(+2 步进)', nh.h.__updates.some((u) => u.patch.fontSize === 16))
|
||
findByAct(nh.h, 'minus').fire('click', { target: findByAct(nh.h, 'minus') })
|
||
check('A− 写 fontSize=12(−2 步进)', nh.h.__updates.some((u) => u.patch.fontSize === 12))
|
||
// 无上限:把数据设成 100,A+ 仍继续涨(旧闭集会钳回 24)
|
||
nh.node.data.fontSize = 100
|
||
nh.h.__updates.length = 0
|
||
findByAct(nh.h, 'plus').fire('click', { target: findByAct(nh.h, 'plus') })
|
||
check('字号无上限(100 → 102)', nh.h.__updates.some((u) => u.patch.fontSize === 102))
|
||
// 字号变大 → textarea 高度跟着涨(贴字自适应)
|
||
const taSize = findByClass(nh.h, 'iwb-sticky-body')
|
||
const hBefore = parseFloat(taSize.style.height)
|
||
nh.node.data.fontSize = 40
|
||
r.nodeApi.render(nh.node, nh.props, nh.h)
|
||
check('字号 14→40 时 textarea 高度重算变大', parseFloat(taSize.style.height) > hBefore)
|
||
nh.node.data.fontSize = 14
|
||
// v1.0.8(用户反馈「文字下面又多出一行空白行」):宽度变化必须重算高度。
|
||
// 旧实现只比 text/size ⇒ 先窄后宽时行数少了、高度仍按多的那行留着,正好空出一整行。
|
||
{
|
||
const hostW = makeNode('div')
|
||
const nodeW = { id: 'w1', type: 'plugin:sticky:sticky', data: { text: 'x'.repeat(120), fontSize: 14, fontWeight: 400, bgColor: '#FCE8B0' } }
|
||
const propsW = { onUpdate() {} }
|
||
const taW = () => findByClass(hostW, 'iwb-sticky-body')
|
||
r.nodeApi.render(nodeW, propsW, hostW)
|
||
taW().clientWidth = 160
|
||
r.nodeApi.render(nodeW, propsW, hostW)
|
||
const tall = parseFloat(taW().style.height)
|
||
taW().clientWidth = 420
|
||
r.nodeApi.render(nodeW, propsW, hostW)
|
||
const wide = parseFloat(taW().style.height)
|
||
check('宽度 160→420(同一段文字)textarea 高度跟着变矮', wide < tall, tall + ' → ' + wide)
|
||
// 行高对齐:高度必须是「行高 × 整数行 + padding」,不能带半行误差
|
||
const padY = 24
|
||
const lineH = 14 * 1.7
|
||
const rem = ((wide - padY) % lineH + lineH) % lineH
|
||
check('高度按整数行对齐(无半行残差)', rem < 1.5 || rem > lineH - 1.5, 'remainder=' + rem.toFixed(2))
|
||
}
|
||
findByAct(nh.h, 'bold').fire('click', { target: findByAct(nh.h, 'bold') })
|
||
check('B 切 fontWeight=600', nh.h.__updates.some((u) => u.patch.fontWeight === 600))
|
||
|
||
// 色板:展开 + 点第 3 个色块(橙)写 bgColor
|
||
const paletteBtn = findByAct(nh.h, 'palette')
|
||
paletteBtn.fire('click', { target: paletteBtn })
|
||
const pal = findByClass(nh.h, 'iwb-sticky-pal')
|
||
check('点背景按钮展开色板', pal.hidden === false)
|
||
const swatches = []
|
||
;(function walk(n) { (n.children || []).forEach((c) => { if (String(c.className).indexOf('iwb-sticky-pal-sw') >= 0) swatches.push(c); walk(c) }) })(pal)
|
||
check('色板有 8 个预设色', swatches.length === 8)
|
||
swatches[2].fire('click', { target: swatches[2] })
|
||
check('点色块写 bgColor=#EF9F27', nh.h.__updates.some((u) => u.patch.bgColor === '#EF9F27'))
|
||
check('选色后色板收起', pal.hidden === true)
|
||
check('有色轮自定义按钮', !!findByAct(nh.h, 'wheel'))
|
||
|
||
// v1.0.7:自定义调色(色轮)也必须自动收起面板
|
||
paletteBtn.fire('click', { target: paletteBtn })
|
||
check('再次展开色板(自定义调色前)', pal.hidden === false)
|
||
const wheelBtn = findByAct(nh.h, 'wheel')
|
||
wheelBtn.fire('click', { target: wheelBtn })
|
||
check('点色轮打开取色器时色板自动收起', pal.hidden === true)
|
||
const colorInput = findByAct(nh.h, 'color')
|
||
check('有隐藏的原生取色 input', !!colorInput && colorInput.tagName === 'INPUT')
|
||
paletteBtn.fire('click', { target: paletteBtn })
|
||
nh.h.__updates.length = 0
|
||
colorInput.value = '#C0392B'
|
||
colorInput.fire('change', { target: colorInput })
|
||
check('自定义色写回 bgColor', nh.h.__updates.some((u) => u.patch.bgColor === '#C0392B'))
|
||
check('自定义色确认后色板保持收起', pal.hidden === true)
|
||
|
||
// ---- 单击选中 / 双击编辑状态机 ----
|
||
const ta = findByClass(nh.h, 'iwb-sticky-body')
|
||
check('正文默认只读(单击穿透给节点选中/拖动)', ta.readOnly === true && ta.getAttribute('readonly') !== null)
|
||
const injectedCss = (findById(r.head, 'iwb-sticky-style') || {}).textContent || ''
|
||
check('根容器 flex:1 撑满宿主(修拖动后漏底)', /\.iwb-sticky-node\{[^}]*flex:1 1 auto/.test(injectedCss))
|
||
check('纸片圆角对齐宿主节点(node-radius - 1px 边框)',
|
||
/\.iwb-sticky-node\{[^}]*border-radius:calc\(var\(--iwb-node-radius, 14px\) - 1px\)/.test(injectedCss))
|
||
const rootNode = findByClass(nh.h, 'iwb-sticky-node')
|
||
const dblEv = { target: ta, stopPropagation() {} }
|
||
rootNode.fire('dblclick', dblEv)
|
||
check('双击正文进入编辑(解除 readonly)', ta.readOnly === false && ta.className.indexOf('iwb-sticky-editing') >= 0)
|
||
check('双击后 textarea 获得焦点', r.document.activeElement === ta)
|
||
// 编辑态下 pointerdown 冒泡被拦(不拖节点)
|
||
let downStopped = false
|
||
ta.fire('pointerdown', { target: ta, stopPropagation() { downStopped = true } })
|
||
check('编辑态 pointerdown 不冒泡给宿主', downStopped)
|
||
// 失焦退出编辑、恢复只读
|
||
ta.fire('blur')
|
||
check('失焦退出编辑(恢复 readonly)', ta.readOnly === true && ta.className.indexOf('iwb-sticky-editing') < 0)
|
||
|
||
// 多行文本写回(编辑态)
|
||
ta.fire('dblclick', { target: ta, stopPropagation() {} })
|
||
ta.value = '第一行\n第二行\n第三行'
|
||
ta.fire('input', { target: ta })
|
||
check('多行文本写回 data.text', nh.h.__updates.some((u) => u.patch.text === '第一行\n第二行\n第三行'))
|
||
|
||
// 幂等同步:编辑中不覆盖正在输入的 textarea
|
||
const active = ta
|
||
r.document.activeElement = active
|
||
nh.node.data.text = '外部改的值'
|
||
r.nodeApi.render(nh.node, nh.props, nh.h)
|
||
check('编辑中的 textarea 不被外部数据覆盖', ta.value === '第一行\n第二行\n第三行')
|
||
ta.fire('blur') // 退出编辑态
|
||
r.document.activeElement = null
|
||
nh.node.data.text = '外部改的值'
|
||
r.nodeApi.render(nh.node, nh.props, nh.h)
|
||
check('非编辑态 textarea 跟随数据更新', ta.value === '外部改的值')
|
||
|
||
// 深/浅背景自动取文字色(运行时算,不写死)
|
||
const st = nh.h.__sticky
|
||
check('浅色背景取深色文字', st.root.style.color === '#1c2333')
|
||
nh.node.data.bgColor = '#1F3350'
|
||
r.nodeApi.render(nh.node, nh.props, nh.h)
|
||
check('深色背景取白色文字', st.root.style.color === '#ffffff')
|
||
|
||
// 面板插入便利贴走 createNode(null,null)
|
||
const panelHost = makeNode('div')
|
||
r.panelApi.mount(panelHost, r.ctx)
|
||
const addBtn = findByClass(panelHost, 'iwb-sticky-add')
|
||
addBtn.fire('click', { target: addBtn })
|
||
check('插入便利贴调 canvas.createNode', r.createCalls.length === 1)
|
||
check('createNode 类型 = plugin:sticky:sticky', r.createCalls[0] && r.createCalls[0].type === 'plugin:sticky:sticky')
|
||
check('createNode 坐标 null/null(宿主找空位)', r.createCalls[0] && r.createCalls[0].x === null && r.createCalls[0].y === null)
|
||
check('插入带默认样式数据', r.createCalls[0] && r.createCalls[0].data.fontSize === 14 && r.createCalls[0].data.bgColor === '#FCE8B0')
|
||
|
||
console.log('\n' + (failed ? '✗ ' + failed + ' 项失败' : '✓ 全部通过'))
|
||
process.exit(failed ? 1 : 0)
|