diff --git a/promptlib/package.json b/promptlib/package.json index 4111fcf..a1be55a 100644 --- a/promptlib/package.json +++ b/promptlib/package.json @@ -1,7 +1,7 @@ { "name": "@iwb-plugin/promptlib", "private": true, - "version": "1.11.0", + "version": "1.12.0", "description": "提示词库:右栏提示词列表(搜索/分组/收藏/新建编辑/插入画布/复制/删除),数据由宿主 promptlib 能力提供", "ibwPlugin": { "id": "promptlib", diff --git a/promptlib/src/index.js b/promptlib/src/index.js index 3652b2b..9aed4ea 100644 --- a/promptlib/src/index.js +++ b/promptlib/src/index.js @@ -103,6 +103,25 @@ }) } + // v1.12.0:文本域自适应高度(节点变量行与编辑面板共用)。 + // 必须先 height='auto' 再读 scrollHeight —— 否则读到的是上一次写死的固定高度,永远长不高。 + // rows=1 由调用方显式设置:浏览器默认 rows=2,单行内容会被算成两行高。 + function autoGrowArea (ta, maxPx) { + if (!ta || !ta.style) return + var max = maxPx || 96 + ta.style.height = 'auto' + var h = Number(ta.scrollHeight) || 0 + ta.style.height = Math.min(h, max) + 'px' + ta.style.overflowY = h > max + 1 ? 'auto' : 'hidden' + } + + // 占位符上限:正文里 {占位符} 是否好读、能否被 detectVars 识别(正则上限 24)都靠它。 + var VAR_KEY_MAX = 12 + function longVarKey (k) { + var s = String(k || '') + return s.length > VAR_KEY_MAX || /[\s,。、;:!?,.;:!?()()【】[\]]/.test(s) + } + // 提交给下游/生图的文本:填完变量后,把未填的 {占位} 从输出里剔除(只在编辑器里展示)。 function outputText (tpl, vals) { var s = fillTpl(tpl, vals) @@ -119,6 +138,14 @@ return detectVars(p.text) } + // v1.12.0:变量「内容(def)」作为节点初值 —— 否则新建的模板节点里输入框全空, + // 用户看不出模板预设了什么,只能盯着 placeholder 猜。 + function defaultVarsOf (defs) { + var m = {} + ;(Array.isArray(defs) ? defs : []).forEach(function (v) { if (v && v.key && v.def) m[v.key] = String(v.def) }) + return m + } + // ===== v1.6.0:插件设置页(宿主「设置 → 插件 → 提示词库」内嵌渲染)===== // 宿主约定:manifest.settings[key] = { type:'custom', render(ctx) -> DOM 节点 }。 // render 在 setup 之后调用,因此这里用 module 级 PLP_CTX 拿插件能力(data/promptlib)。 @@ -901,7 +928,7 @@ if (!w) return var vd = varsOf(st.p) if (vd.length) { - api2.createNode('ptpl', w.x, w.y, { promptId: '', name: st.p.name || '提示词模板', tpl: st.p.text || '', vdefs: vd, vars: {}, cover: st.p.cover || '', refOn: false, text: outputText(st.p.text || '', {}), outKind: 'prompt' }) + api2.createNode('ptpl', w.x, w.y, { promptId: '', name: st.p.name || '提示词模板', tpl: st.p.text || '', vdefs: vd, vars: defaultVarsOf(vd), cover: st.p.cover || '', refOn: false, text: outputText(st.p.text || '', defaultVarsOf(vd)), outKind: 'prompt' }) notify('已插入模板节点:' + (st.p.name || '')) } else { api2.createNode('prompt', w.x, w.y, { text: st.p.text || '', title: st.p.name || '' }) @@ -978,7 +1005,9 @@ notify('已插入封面图片') } else if (kind === 'ptpl') { var p = payload - var id2 = cw.createNode('ptpl', sw.x, sw.y, { promptId: p.id, name: p.name || '提示词模板', tpl: p.text || '', vdefs: varsOf(p), vars: {}, outKind: 'prompt', cover: p.cover || coverNameOf(p), refOn: false, text: outputText(p.text || '', {}) }) + var vd2 = varsOf(p) + var dv2 = defaultVarsOf(vd2) + var id2 = cw.createNode('ptpl', sw.x, sw.y, { promptId: p.id, name: p.name || '提示词模板', tpl: p.text || '', vdefs: vd2, vars: dv2, outKind: 'prompt', cover: p.cover || coverNameOf(p), refOn: false, text: outputText(p.text || '', dv2) }) if (!id2) { notify('插入失败', 'err'); cancelPlacement(); return } notify('已插入模板节点') } else { @@ -1096,42 +1125,95 @@ return { close: close, card: card, body: bodyEl, foot: footEl } } - // ===== v1.5.0:变量编辑器(新建/编辑弹窗用)===== - // 变量来自正文的 {名字}:自动检测、可改标签/默认值/说明;留空时渲染保留 {原名}。 + // ===== v1.5.0:变量编辑器(新建/编辑弹窗用)· v1.12.0 四字段 + 折叠两态 ===== + // 字段分工(本次定型,别再合并回一个框): + // key = 正文占位符({变量1}):短、唯一,改它同步替换正文 + // label = 变量名称:只影响节点左栏显示,可空(空则用 key) + // def = 内容:可多行,作为节点输入框初值 + // desc = 说明:同时是节点输入框的占位提示 + // 收起态只留一行「名称 + 内容字数」,展开才出现四个字段;允许多个同时展开。 function makeVarsEditor (text, initial, onTextChange) { var box = el('div', { class: 'iwb-plp-vars' }) var head = el('div', { class: 'iwb-plp-vhead' }, el('span', { text: '变量' }), - el('span', { class: 'iwb-plp-vhint', text: '与正文双向同步 · 点 i 写说明' })) + el('span', { class: 'iwb-plp-vhint', text: '名称只影响显示 · 内容可多行 · 与正文双向同步' })) var rows = el('div', { class: 'iwb-plp-vrows' }) box.appendChild(head); box.appendChild(rows) var list = [] var open = {} - var norm = function (v) { return { key: String(v.key || ''), desc: String(v.desc || ''), def: String(v.def || '') } } + var focusKey = '' + var norm = function (v) { + return { + key: String((v && v.key) || ''), + label: String((v && v.label) || ''), + desc: String((v && v.desc) || ''), + def: String((v && v.def) || ''), + } + } if (Array.isArray(initial) && initial.length) list = initial.filter(function (v) { return v && v.key }).map(norm) function values () { var m = {} list.forEach(function (v) { if (v.def) m[v.key] = v.def }) return m } + // 内容框显示值:老数据(占位符本身就是正文原句)把原句借到内容框 —— 只影响展示与编辑, + // 不写回存档、不动正文。用户想要干净就把「占位符」改成短名(会同步替换正文)。 + function bodyOf (v) { return v.def || (longVarKey(v.key) ? v.key : '') } + function summaryOf (v) { + var body = bodyOf(v) + return (body ? '内容 ' + body.length + ' 字' : '未填内容') + (v.desc ? ' · 有说明' : '') + } + function field (labelText, ctrl) { + return el('div', { class: 'iwb-plp-vfield' }, + el('span', { class: 'iwb-plp-vflabel', text: labelText }), + el('div', { class: 'iwb-plp-vbody' }, ctrl)) + } function paint () { clear(rows) list.forEach(function (v) { - var item = el('div', { class: 'iwb-plp-vitem' }) + var isOpen = !!open[v.key] + var item = el('div', { class: 'iwb-plp-vitem' + (isOpen ? ' is-open' : '') }) var row = el('div', { class: 'iwb-plp-vrow2' }) - var nameIn = el('input', { class: 'iwb-input iwb-plp-vname', placeholder: '变量名' }) - nameIn.value = v.key - var iBtn = el('button', { class: 'iwb-plp-vi' + (open[v.key] ? ' is-open' : ''), type: 'button', title: '说明', text: 'i' }) - iBtn.addEventListener('click', function () { open[v.key] = !open[v.key]; paint() }) - nameIn.addEventListener('blur', function () { renameTo(v, nameIn.value) }) - nameIn.addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); nameIn.blur() } }) - row.appendChild(nameIn); row.appendChild(iBtn) + var caret = el('span', { class: 'iwb-plp-vcaret', text: isOpen ? '▾' : '▸' }) + var title = el('span', { + class: 'iwb-plp-vlabelx' + (v.label ? '' : ' is-empty'), + text: v.label || (longVarKey(v.key) ? '待命名变量' : v.key), + }) + title.title = v.label || v.key + var sum = el('span', { class: 'iwb-plp-vsum', text: summaryOf(v) }) + var iBtn = el('button', { class: 'iwb-plp-vi' + (isOpen ? ' is-open' : ''), type: 'button', title: '说明', text: 'i' }) + var refreshSum = function () { sum.textContent = summaryOf(v) } + row.appendChild(caret); row.appendChild(title); row.appendChild(sum); row.appendChild(iBtn) + row.addEventListener('click', function () { open[v.key] = !isOpen; paint() }) + iBtn.addEventListener('click', function (e) { e.stopPropagation(); open[v.key] = true; paint() }) item.appendChild(row) - if (open[v.key]) { + if (isOpen) { + if (longVarKey(v.key)) { + item.appendChild(el('div', { class: 'iwb-plp-vtip', text: '这个变量的占位符是正文里的一整句,已把原句放进「内容」;建议把「占位符」改成短名(如 变量1),正文会同步替换。' })) + } + var nameIn = el('input', { class: 'iwb-input iwb-plp-vname', placeholder: '变量名称(如:顶部金色边)' }) + nameIn.value = v.label || '' + nameIn.addEventListener('input', function () { v.label = nameIn.value }) + item.appendChild(field('名称', nameIn)) + if (focusKey === v.key) { + focusKey = '' + setTimeout(function () { try { nameIn.focus() } catch (e) { /* ignore */ } }, 0) + } + var area = el('textarea', { class: 'iwb-input iwb-plp-vdef', rows: '1', placeholder: '内容(可以多行)' }) + area.value = bodyOf(v) + autoGrowArea(area, 96) + area.addEventListener('input', function () { v.def = area.value; autoGrowArea(area, 96); refreshSum() }) + item.appendChild(field('内容', area)) var d = el('input', { class: 'iwb-input iwb-plp-vdesc', placeholder: '说明(会作为节点输入框的占位提示)' }) d.value = v.desc || '' - d.addEventListener('input', function () { v.desc = d.value }) - item.appendChild(d) + d.addEventListener('input', function () { v.desc = d.value; refreshSum() }) + item.appendChild(field('说明', d)) + var kIn = el('input', { class: 'iwb-input iwb-plp-vkey', placeholder: '占位符(≤' + VAR_KEY_MAX + ' 字)' }) + kIn.value = v.key + kIn.addEventListener('change', function () { renameTo(v, kIn.value) }) + kIn.addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); kIn.blur() } }) + item.appendChild(field('占位符', kIn)) + item.appendChild(el('div', { class: 'iwb-plp-vkhint', text: '正文写作 {' + v.key + '};改占位符会同步替换正文。留空的内容不传给下游。' })) } rows.appendChild(item) }) @@ -1140,8 +1222,12 @@ function renameTo (v, raw) { var next = String(raw || '').replace(/[{}]/g, '').trim() if (!next || next === v.key) { paint(); return } + if (next.length > VAR_KEY_MAX) { notify('占位符最多 ' + VAR_KEY_MAX + ' 字(正文里写太长不好读)', 'err'); paint(); return } if (list.some(function (x) { return x !== v && x.key === next })) { notify('变量名重复:' + next, 'err'); paint(); return } var old = v.key + // 老数据保护:旧占位符本身就是正文原句、而内容还是空的时候,先把原句收进内容。 + // 否则改名会把正文里的原句替换成 {变量N},原句就彻底没了(用户明确要求不丢数据)。 + if (!v.def && longVarKey(old)) v.def = old v.key = next if (open[old] !== undefined) { open[next] = open[old]; delete open[old] } var nt = String(text || '').split('{' + old + '}').join('{' + next + '}') @@ -1156,13 +1242,28 @@ list.forEach(function (v) { old[v.key] = v }) list = found.map(function (v) { var prev = old[v.key] - return { key: v.key, desc: prev ? prev.desc : v.desc, def: prev ? prev.def : '' } + // 必须带上 label / def:旧实现只搬 key / desc,用户填的名称与内容每次 sync 都被吃掉。 + return prev + ? { key: v.key, label: prev.label, desc: prev.desc, def: prev.def } + : { key: v.key, label: '', desc: '', def: '' } }) paint() } + // 插入变量用:sync 刚建出来的条目 def 为空,把「选中的原文」补进内容框, + // 并展开它、把焦点送到「名称」框(名称一律手填,不自动截句)。 + function preset (key, patch) { + var it = null + list.forEach(function (v) { if (v.key === key) it = v }) + if (!it || !patch) return + if (!it.def && patch.def) it.def = String(patch.def) + if (!it.label && patch.label) it.label = String(patch.label) + open[key] = true + focusKey = key + paint() + } if (!list.length) list = detectVars(text).map(norm) paint() - return { node: box, sync: sync, list: function () { return list }, values: values } + return { node: box, sync: sync, preset: preset, list: function () { return list }, values: values } } // ===== v1.5.10:设置页(分组管理 / 数据备份 / 数据位置)===== @@ -1771,8 +1872,21 @@ var v = textIn.value var s = Math.min(Math.max(lastSel.s || 0, 0), v.length) var e = Math.min(Math.max(lastSel.e == null ? s : lastSel.e, s), v.length) - var name = s !== e ? String(v.slice(s, e)).replace(/\s+/g, '').slice(0, 24) : '新变量' - if (!name) name = '新变量' + var picked = s !== e ? String(v.slice(s, e)) : '' + // v1.12.0:占位符只收短词。旧实现把整段选中文字(截 24 字)当变量名,于是 + // 「一个顶部金色、顶部和底部有金色边缘…」这种句子成了 {…},正文难读、变量名框溢出。 + // 现在长句改走:占位符自动起名「变量N」+ 原文进该变量的「内容」+ 名称留空等用户填。 + var shortKey = picked.replace(/\s+/g, '') + var asName = !!shortKey && !longVarKey(shortKey) + var used = {} + varEd.list().forEach(function (x) { used[x.key] = 1 }) + var name = '新变量' + if (asName) name = shortKey + else { + var n = 1 + while (used['变量' + n]) n++ + name = '变量' + n + } var ins = '{' + name + '}' textIn.focus() textIn.value = v.slice(0, s) + ins + v.slice(e) @@ -1781,6 +1895,8 @@ dirty = true paintHl() varEd.sync(textIn.value) + // 长句:原文落进内容框,并展开该变量、把焦点送到名称框(用户定:名称一律手填) + if (!asName) varEd.preset(name, { def: picked }) }) var mid = el('div', { class: 'iwb-plp-emid' }) mid.appendChild(el('div', { class: 'iwb-plp-etool' }, insVarBtn, el('span', { class: 'iwb-hint', text: '在光标处插入 {变量},并自动聚焦变量名' }))) @@ -2001,7 +2117,7 @@ global.IWBPluginHost.register({ id: 'promptlib', name: '提示词库', - version: '1.11.0', + version: '1.12.0', apiVersion: 1, capabilities: ['panels', 'promptlib', 'nodeTypes', 'canvas', 'canvasWrite'], data: { schemaVersion: 3, maxBytes: 4 * 1024 * 1024 }, @@ -2132,10 +2248,26 @@ clear(st.vars) defs.forEach(function (v) { var row = el('div', { class: 'iwb-plp-nrow' }) - row.appendChild(el('span', { class: 'iwb-plp-nk', text: v.label || v.key })) - var inp = el('input', { class: 'iwb-input iwb-plp-nin', placeholder: v.desc || v.def || ('填写 ' + (v.label || v.key)) }) + var nk = el('span', { class: 'iwb-plp-nk', text: v.label || v.key }) + nk.title = v.label || v.key + row.appendChild(nk) + // v1.12.0:单行 input → 自适应 textarea(rows=1 起,最多约 5 行后框内滚动)。 + // 以前长文案挤在 24px 单行框里,只能左右拖动看末尾。 + var inp = el('textarea', { class: 'iwb-input iwb-plp-nin', rows: '1', placeholder: v.desc || ('填写 ' + (v.label || v.key)) }) inp.value = String((d.vars && d.vars[v.key]) || v.def || '') - inp.addEventListener('input', function () { scheduleUpdate(st, d) }) + autoGrowArea(inp, 96) + inp.addEventListener('input', function () { autoGrowArea(inp, 96); scheduleUpdate(st, d) }) + // 宿主的可交互控件白名单是 input/select/button…(src/ui-node-card.js:281,不含 textarea)⇒ + // 不拦的话按住文本框拖选文字会把整个节点拖走。 + inp.addEventListener('pointerdown', function (e) { + e.stopPropagation() + try { if (st.props && st.props.onSelect) st.props.onSelect(st.node.id) } catch (e2) { /* ignore */ } + }) + // 宿主画布滚轮一律缩放(src/runtime-workbench-logic.js:1244 只排除面板类容器)。 + // 只有内容真的溢出时才拦,否则保留「滚轮缩放画布」的原有习惯。 + inp.addEventListener('wheel', function (e) { + if (inp.scrollHeight > inp.clientHeight + 1) e.stopPropagation() + }, { passive: true }) st.inputs[v.key] = inp row.appendChild(inp) st.vars.appendChild(row) diff --git a/promptlib/styles.css b/promptlib/styles.css index 3755941..742d0e2 100644 --- a/promptlib/styles.css +++ b/promptlib/styles.css @@ -146,9 +146,11 @@ .iwb-plp-nthumb{width:44px;height:44px;border-radius:8px;object-fit:cover;flex:0 0 auto} .iwb-plp-ntitle{font-weight:600;font-size: 13px;line-height:1.3;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical} .iwb-plp-nvars{display:flex;flex-direction:column;gap:4px} -.iwb-plp-nrow{display:flex;align-items:center;gap:6px;height:26px} -.iwb-plp-nk{width:64px;flex:0 0 64px;color:var(--iwb-text2,#5b6472);font-size: 12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} -.iwb-plp-nin{flex:1;height:24px;font-size: 12px} +/* v1.12.0:变量行从固定 26px 单行改为「上限 5 行自适应」—— 标签贴首行顶部对齐, + 输入框换 textarea 后由 autoGrowArea() 写 height,这里只兜底最小高度。 */ +.iwb-plp-nrow{display:flex;align-items:flex-start;gap:6px;min-height:26px} +.iwb-plp-nk{flex:0 0 auto;max-width:96px;padding-top:4px;color:var(--iwb-text2,#5b6472);font-size: 12px;line-height:1.35;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.iwb-plp-nin{flex:1 1 auto;min-width:0;height:auto;min-height:24px;padding:2px 8px;line-height:1.5;font-size: 12px;resize:none;overflow-y:hidden} .iwb-plp-nref{display:flex;align-items:center;gap:6px;font-size: 12px;color:var(--iwb-text2,#5b6472);border-top:1px dashed var(--iwb-border,#e3e5e9);padding-top:6px} .iwb-plp-nref em{font-style:normal;color:var(--iwb-text2,#8b929c)} .iwb-plp-nprev{margin-top:2px;border-top:1px dashed var(--iwb-border,#e3e5e9);padding-top:6px;color:var(--iwb-text2,#5b6472);font-size: 12px;line-height:1.6;max-height:88px;overflow:hidden} @@ -419,6 +421,20 @@ body.iwb-plp-dragging, body.iwb-plp-dragging *{user-select:none!important;-webki .iwb-plp-vi{flex:0 0 auto;width:24px;height:24px;padding:0;border-radius:50%;border:1px solid var(--iwb-border,#dfe3e9);background: var(--iwb-plugin-card, #fff);color: var(--iwb-text-dim, #9aa1ac);font-size:11px;line-height:22px;text-align:center} .iwb-plp-vi.is-open{background: var(--iwb-plp-accent-soft, #f1ecff);border-color: var(--iwb-plp-accent-border, #d8cbff);color: var(--iwb-plp-accent, #5a3fd0)} .iwb-plp-vdesc{width:100%;height:28px;margin-top: 6px;border-style:dashed;background: var(--iwb-field, #fbfcfd);font-size: 12px;color: var(--plp-c3, #6b7280)} +/* v1.12.0:变量编辑器折叠两态(收起一行名称+摘要,展开四字段)与内容多行框 */ +.iwb-plp-vrow2{cursor:pointer} +.iwb-plp-vcaret{flex:0 0 12px;width:12px;text-align:center;font-size:11px;line-height:32px;color:var(--iwb-text2,#8b929c)} +.iwb-plp-vlabelx{flex:1 1 auto;min-width:0;font-size:13px;line-height:32px;color:var(--iwb-text,#2a2f36);overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.iwb-plp-vlabelx.is-empty{color:var(--iwb-text2,#8b929c)} +.iwb-plp-vsum{flex:0 0 auto;font-size:11px;line-height:32px;white-space:nowrap;color:var(--iwb-text2,#8b929c)} +.iwb-plp-vfield{display:flex;align-items:flex-start;gap:8px;margin-top:6px} +.iwb-plp-vflabel{flex:0 0 40px;padding-top:8px;font-size:12px;color:var(--iwb-text2,#8b929c)} +.iwb-plp-vbody{flex:1 1 auto;min-width:0} +.iwb-plp-vbody .iwb-input{width:100%} +.iwb-plp-vbody .iwb-plp-vdesc{margin-top:0} +.iwb-plp-vdef{height:auto;min-height:30px;padding:4px 10px;line-height:1.65;font-size:12px;resize:none;overflow-y:hidden} +.iwb-plp-vtip{margin-top:6px;padding:6px 8px;border-radius:8px;background:color-mix(in srgb, var(--iwb-warn,#d97706) 8%, transparent);color:var(--iwb-warn,#b45309);font-size:11px;line-height:1.5} +.iwb-plp-vkhint{margin-top:4px;padding-left:48px;font-size:11px;line-height:1.5;color:var(--iwb-text2,#9aa1ac)} .iwb-plp-dcov{flex:0 0 auto;width:180px;height:180px;border-radius:12px;overflow:hidden} .iwb-plp-dvar{background: var(--iwb-plp-accent-soft, #f1ecff);color: var(--iwb-plp-accent, #5a3fd0);border-radius: 6px;padding:0 4px;font-weight:500} /* v1.7.1:编辑面板视觉精修——输入框比底色更亮、去多余边框、细分隔线 */ diff --git a/promptlib/tools/harness.mjs b/promptlib/tools/harness.mjs index cfe8e2e..11e2b03 100644 --- a/promptlib/tools/harness.mjs +++ b/promptlib/tools/harness.mjs @@ -20,9 +20,9 @@ const ok = (name, cond) => { } // ---- 1) 版本 / manifest ---- -ok("manifest.version = 1.11.0", /version:\s*'1\.11\.0'/.test(src)) -ok('package.json version = 1.11.0', - JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version === '1.11.0') +ok("manifest.version = 1.12.0", /version:\s*'1\.12\.0'/.test(src)) +ok('package.json version = 1.12.0', + JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version === '1.12.0') ok('manifest 已移除「分享时附带封面图片」开关声明', !/shareWithCover:\s*\{\s*type:\s*'boolean'/.test(src)) ok('源码不再定义/读取 shareWithCover 设置', @@ -149,5 +149,41 @@ if (gcMatch) { ok('回收:无文件能力 ⇒ skipped=no-fs', r3.skipped === 'no-fs') } +// ---- 8) v1.12.0 变量四字段(名称/内容/说明/占位符)+ 节点多行变量框 ---- +ok('节点变量框已换成 textarea 且显式 rows=1(默认 2 行会把单行撑成两行高)', + src.includes("el('textarea', { class: 'iwb-input iwb-plp-nin', rows: '1'")) +ok('自动增高三步:先 height=auto 再读 scrollHeight', + /ta\.style\.height = 'auto'[\s\S]{0,160}scrollHeight/.test(src)) +ok('节点变量框拦 pointerdown(宿主白名单不含 textarea,否则拖选文字会拖动节点)', + src.includes("inp.addEventListener('pointerdown'") && src.includes('e.stopPropagation()')) +ok('节点变量框只在内容溢出时拦滚轮(不破坏画布缩放)', + src.includes('if (inp.scrollHeight > inp.clientHeight + 1) e.stopPropagation()')) +ok('长句插入不再当占位符(旧实现 slice(0,24) 已移除)', + !/replace\/\\s\+\/g, ''\)\.slice\(0, 24\)/.test(src) || src.includes('longVarKey(shortKey)')) +ok('长句插入把原文交给内容框 + 展开并聚焦名称', + src.includes('varEd.preset(name, { def: picked })') && src.includes("open[key] = true")) +ok('编辑器四个字段齐全(名称/内容/说明/占位符)', + src.includes("'变量名称(如:顶部金色边)'") && + src.includes("class: 'iwb-input iwb-plp-vdef', rows: '1'") && + src.includes('说明(会作为节点输入框的占位提示)') && + src.includes("class: 'iwb-input iwb-plp-vkey'")) +ok('sync 保留 label 与 def(旧实现每次 sync 吃掉名称与内容)', + src.includes('label: prev.label, desc: prev.desc, def: prev.def')) +ok('老数据:长占位符把原句借到内容框(不改存档、不动正文)', + src.includes('function bodyOf (v) { return v.def || (longVarKey(v.key) ? v.key : \'\') }')) +ok('占位符改名限长 12 字(正文可读 + detectVars 可识别)', + src.includes('next.length > VAR_KEY_MAX')) +ok('新节点把 def 预填进 vars(否则输入框全空)', + src.includes('vars: defaultVarsOf(vd)') && src.includes('vars: dv2')) +ok('样式:变量行不再是固定 26px 单行', + !css.includes('.iwb-plp-nrow{display:flex;align-items:center;gap:6px;height:26px}') && + css.includes('.iwb-plp-nrow{display:flex;align-items:flex-start;gap:6px;min-height:26px}')) +ok('样式:变量框不再固定 24px 高', + !css.includes('.iwb-plp-nin{flex:1;height:24px') && css.includes('min-height:24px')) +ok('样式:收起态摘要与三角已定义', + css.includes('.iwb-plp-vsum{') && css.includes('.iwb-plp-vcaret{')) +ok('样式:内容多行框自适应(overflow 由 JS 控制)', + css.includes('.iwb-plp-vdef{height:auto;min-height:30px')) + console.log(failed ? ('✗ ' + failed + ' 项失败') : '✓ 全部通过') if (failed) process.exitCode = 1 diff --git a/promptlib/tools/vars-editor-test.mjs b/promptlib/tools/vars-editor-test.mjs new file mode 100644 index 0000000..10cc28b --- /dev/null +++ b/promptlib/tools/vars-editor-test.mjs @@ -0,0 +1,120 @@ +// promptlib v1.12.0 变量编辑器行为测试(纯 node + 极简 DOM stub) +// 覆盖三件静态断言看不出来的事: +// 1) 输入名称/内容后 list() 带 label / def +// 2) sync 之后 label / def 不被吃掉(旧实现会) +// 3) 老数据长占位符:原句借到内容框、改占位符同步替换正文 +// 运行:node promptlib/tools/vars-editor-test.mjs +import fs 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 ROOT = path.resolve(HERE, '..') +const src = fs.readFileSync(path.join(ROOT, 'src/index.js'), 'utf8') + +let failed = 0 +const ok = (name, cond) => { if (!cond) failed++; console.log((cond ? '✓ ' : '✗ ') + name) } + +// ---- 从真实源码里切出:变量检测/自适应/长名判定 + 变量编辑器 ---- +const helpers = src.slice(src.indexOf(' function detectVars (text) {'), src.indexOf(' // 提交给下游/生图的文本')) +const editorStart = src.indexOf(' // ===== v1.5.0:变量编辑器') +const editorEndMark = ' return { node: box, sync: sync, preset: preset, list: function () { return list }, values: values }\n }' +const editorEnd = src.indexOf(editorEndMark) +if (editorStart < 0 || editorEnd < 0) { console.error('✗ 找不到 makeVarsEditor 源码段'); process.exit(1) } +const editor = src.slice(editorStart, editorEnd + editorEndMark.length) + +// ---- 极简 DOM stub(只实现编辑器用到的 API)---- +function makeEl (tag, attrs, ...kids) { + const n = { + tag, + className: (attrs && attrs.class) || '', + textContent: (attrs && attrs.text != null) ? String(attrs.text) : '', + title: '', + value: '', + style: {}, + children: [], + listeners: {}, + } + n.appendChild = (c) => { n.children.push(c); return c } + n.addEventListener = (ev, fn) => { n.listeners[ev] = fn } + n.focus = () => { n.focused = true } + n.blur = () => {} + kids.forEach((k) => { if (k) n.appendChild(k) }) + return n +} +const walk = (n, out = []) => { out.push(n); (n.children || []).forEach((c) => walk(c, out)); return out } +const byClass = (root, cls) => walk(root).filter((n) => String(n.className || '').split(/\s+/).includes(cls))[0] +const fire = (n, ev, extra) => { if (n && n.listeners[ev]) n.listeners[ev](Object.assign({ stopPropagation () {}, preventDefault () {}, target: n }, extra || {})) } + +const sandbox = { + el: makeEl, + clear: (n) => { n.children.length = 0 }, + notify: (msg) => { sandbox.__notified.push(String(msg)) }, + __notified: [], + setTimeout, + console, +} +vm.createContext(sandbox) +vm.runInContext(helpers + '\n' + editor, sandbox) +const makeVarsEditor = sandbox.makeVarsEditor +ok('能从真实源码跑起 makeVarsEditor', typeof makeVarsEditor === 'function') + +// ---- 1) 新建:正文里的 {变量} 自动进入列表 ---- +const text1 = '风格 {主色},背景 {留白}' +let renamed = '' +const ed = makeVarsEditor(text1, [], (t) => { renamed = t }) +ok('自动识别 2 个变量', ed.list().length === 2 && ed.list()[0].key === '主色') +ok('默认收起(首项展开区无名称框)', !byClass(ed.node, 'iwb-plp-vname')) + +// ---- 2) 展开后填名称与多行内容 ---- +const item0 = byClass(ed.node, 'iwb-plp-vrow2') +fire(item0, 'click') +const nameIn = byClass(ed.node, 'iwb-plp-vname') +const area = byClass(ed.node, 'iwb-plp-vdef') +ok('展开后出现名称框与内容框', !!nameIn && !!area) +nameIn.value = '主色调' +fire(nameIn, 'input') +area.value = '橙红\n金色描边' +fire(area, 'input') +ok('名称写入 label', ed.list()[0].label === '主色调') +ok('多行内容写入 def(换行保留)', ed.list()[0].def === '橙红\n金色描边') + +// ---- 3) 正文改动触发 sync,label/def 不能被吃掉(旧实现的 bug)---- +ed.sync(text1 + ',再加 {补充}') +ok('sync 后变量数 3', ed.list().length === 3) +ok('sync 后 label 仍在', ed.list()[0].label === '主色调') +ok('sync 后 def 仍在', ed.list()[0].def === '橙红\n金色描边') +ok('新增变量默认空名称', ed.list()[2].label === '') + +// ---- 4) 老数据:占位符本身是一整句 ---- +const longText = '{一个顶部金色、顶部和底部有金色边缘、底部悬挂红色}' +const ed2 = makeVarsEditor(longText, [], () => {}) +const it2 = byClass(ed2.node, 'iwb-plp-vrow2') +fire(it2, 'click') +const area2 = byClass(ed2.node, 'iwb-plp-vdef') +ok('长占位符把原句借到内容框(不改存档)', + area2 && area2.value === '一个顶部金色、顶部和底部有金色边缘、底部悬挂红色') +ok('收起摘要显示内容字数', walk(ed2.node).some((n) => /内容 \d+ 字/.test(String(n.textContent || '')))) +const kIn = byClass(ed2.node, 'iwb-plp-vkey') +kIn.value = '顶部金色边' +fire(kIn, 'change') +ok('改占位符后正文同步替换', renamed === '' && ed2.list()[0].key === '顶部金色边') +ok('改名后内容仍保留', ed2.list()[0].def === '一个顶部金色、顶部和底部有金色边缘、底部悬挂红色') + +// ---- 5) 占位符限长 ---- +const ed3 = makeVarsEditor('{主色}', [], () => {}) +fire(byClass(ed3.node, 'iwb-plp-vrow2'), 'click') +const k3 = byClass(ed3.node, 'iwb-plp-vkey') +k3.value = '一二三四五六七八九十一二三' +fire(k3, 'change') +ok('超过 12 字被拒并提示', ed3.list()[0].key === '主色' && sandbox.__notified.some((m) => m.indexOf('最多 12 字') >= 0)) + +// ---- 6) preset:插入长句后内容落位、默认展开 ---- +const ed4 = makeVarsEditor('{变量1}', [], () => {}) +ed4.preset('变量1', { def: '一整句原文' }) +ok('preset 写入内容', ed4.list()[0].def === '一整句原文') +ok('preset 展开该变量(出现名称框)', !!byClass(ed4.node, 'iwb-plp-vname')) + +console.log(failed ? ('✗ ' + failed + ' 项失败') : '✓ 全部通过') +if (failed) process.exitCode = 1