diff --git a/style-source/README.md b/style-source/README.md index f11cf0b..f1375c0 100644 --- a/style-source/README.md +++ b/style-source/README.md @@ -18,10 +18,37 @@ - **分类**:chips 按面板宽度**自动换行**(宽档一行铺完,窄档折两三行,永远不会把后面的分类藏起来);按数量降序,记住上次选的分类。窄档不显示数量后缀,省一行高度。 - **网格**:分批渲染(每批 90 个),滚到底自动续渲染;缩略图原生懒加载。 - **详情**:窄面板铺满覆盖层,宽面板变右侧栏;大图 + 标签 + 摘要 + 提示词 + 变量表单。 -- **变量替换**:提示词里的 `{角色描述}` 这类占位符给输入框,填了就替换,**留空的保留 `{原占位符}`**(换成空串会把提示词结构弄丢)。未填数量实时提示。 +- **变量替换**:提示词里的 `{角色描述}` 这类占位符给输入框,填了就替换,**留空的保留 `{原占位符}`**(换成空串会把提示词结构弄丢)。未填数量实时提示。输入框最多先摆 6 个,其余折在「展开其余 N 个变量」里(Vigo 那批风格单条提示词最多 24 个占位符)。 - **插入参考图**:`fetch` 大图 → blob → dataURL → `createImageNode`(宿主只认 `data:` URL)。 - **插入提示词**:插到当前选中节点右侧;没选中时插到最右节点的右侧;空画布落 `(80, 80)`。 +## 变量:只有提示词里的 `{占位符}` 才算数 + +**判断依据只有一条**:`prompt` 里真实出现的 `{名字}`。插入时替换的就是这段文本,所以 + +- 「`variables` 里声明了、但提示词里没有这个占位符」⇒ 输入框是摆设,填了什么都不会被替换(线上 970 条声明里 271 条属于这种); +- 「提示词里有 `{xxx}`、`variables` 里一条都没写」⇒ 以前干脆不出输入框,`{xxx}` 原样插进画布(78 个风格)。 + +现在统一按提示词抽变量,`variables` 退化成「给占位符配标签」,两种写法都认: + +| 写法 | 数据里的样子 | 结果 | +|---|---|---| +| 推荐 | `{ 诗词: '{诗词}' }` | 标签「诗词」→ 替换 `{诗词}` | +| 也认 | `{ 诗词: 诗词 }` | 同上(值没花括号时自动按名字比) | +| 兜底 | key 写成 `` `SUBJECT` ``、值写成人话 `main subject` | 值对不上时拿 key 去找 `{SUBJECT}`,标签取 SUBJECT | + +两个都没对上的占位符**照样出输入框**,标签退化成占位符名(`brand_name` → `brand name`,浅色斜体标记)。 + +写新风格时要注意的: + +1. 想被替换的地方一律用**半角花括号**包一个短标识符:`{主角}`、`{SUBJECT}`、`{brand_name}`;带引号/逗号/冒号的内容会被当成 JSON 碎片忽略。 +2. 每个占位符在 `variables` 里补一条,标签写中文、值是占位符本体(`style_var: "{主角}"`),面板才会显示中文标签。 +3. 别用 `[SQUARE_BRACKETS]`:16 个风格这么写,插件只认花括号,这些不会被替换。 +4. `variables` 必须是**列表** `[{kv_var, style_var, desc?}]`;`generate_data.py` 只解析列表,写成 mapping 会被静默丢掉(`validate_style.py` 会报错)。 +5. 标签里别留 markdown 反引号(Vigo 那批导入数据有 392 条 `` `SUBJECT` ``,插件会剥掉但源数据该改)。 + +数据体检脚本(在 [style-source](https://github.com/malongan/style-source) 仓):`python3 scripts/audit_variables.py`,会列出声明落空、有占位符没声明、标签带残留的风格。当前 310 个风格:215 个含占位符、171 个有声明、64 个两者都无;声明命中 699 条 / 落空 271 条。 + ## 面板宽度自适应(重要) 资源库面板宽度不是固定的:侧栏 240–560 可拖、放大窗口 920×600 可八向缩放、还有 embedded 嵌入形态。所以: @@ -77,7 +104,7 @@ ```bash cp src/index.js /tmp/plugin-style-source.js cd ../image-workbench-web -node scripts/plugins-publish.mjs /tmp/plugin-<其余插件>.js /tmp/plugin-style-source.js --upload --version style-source=1.0.2 +node scripts/plugins-publish.mjs /tmp/plugin-<其余插件>.js /tmp/plugin-style-source.js --upload --version style-source=1.0.3 ``` 图标:宿主 `app.js` 的 `PLUGIN_ICONS` 可加 `'style-source': 'palette'`(不加则用面板 manifest 自带的 `palette`,效果一致)。 diff --git a/style-source/package.json b/style-source/package.json index 8873ccd..6a76287 100644 --- a/style-source/package.json +++ b/style-source/package.json @@ -1,7 +1,7 @@ { "name": "@iwb-plugin/style-source", "private": true, - "version": "1.0.2", + "version": "1.0.3", "description": "风格库:资源库面板里浏览 310 个 AI 绘画风格(12 分类 / 搜索 / 变量替换),一键把预览图插入画布 ref 节点、把提示词插入 prompt 节点", "ibwPlugin": { "id": "style-source", diff --git a/style-source/src/index.js b/style-source/src/index.js index 0f8e9eb..ad00a05 100644 --- a/style-source/src/index.js +++ b/style-source/src/index.js @@ -244,6 +244,9 @@ flex: 0 0 auto; font-size: var(--fs-sm, 11px); color: var(--iwb-text2, #4d5668); max-width: 44%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +/* 提示词里有 {X}、但数据里没声明变量 ⇒ 标签只能用占位符名,压暗一点做区分 */ +.iwb-ss-varlabel.is-implicit { opacity: .62; font-style: italic; } +.iwb-ss-vartoggle { width: 100%; height: 24px; margin: 2px 0 4px; font-size: var(--fs-sm, 11px); } .iwb-ss-varinput { flex: 1 1 auto; min-width: 0; height: 24px; padding: 0 7px; border: 1px solid var(--iwb-border, #d5d9e0); border-radius: var(--rd-sm, 6px); @@ -383,23 +386,77 @@ } // ---------------- 变量 ---------------- + // + // **判断依据只有一个:提示词里真实出现的 `{占位符}`**。插入时替换的就是文本里的这个东西, + // 所以「数据里声明了、提示词里没有」的变量填了也不生效(线上 970 条变量里 625 条属于这种), + // 以前按声明表生成输入框,于是有的风格一堆输入框全是摆设、有的干脆一个都没有。 + // + // style.variables 现在只用来给占位符配一个好看的中文标签,两种写法都兼容: + // { 诗词: '{诗词}' } ← 新写法:值是占位符本体(带花括号) + // { '`SUBJECT`': 'main subject' } ← 老导入数据:值是人话,只能拿 key 兜底(key 上还残留反引号) + const PH_RE = /\{([^{}\n]{1,40})\}/g - // variables 的 value 有两种写法:'角色描述' 和 '{诗词}'(自带花括号),统一剥成占位符名 - function varKeys(style) { - const vars = style && style.variables - if (!vars || typeof vars !== 'object') return [] + // 变量区默认显示几个,其余折叠(Vigo 那批风格单条提示词最多 24 个占位符) + const VAR_SHOW = 6 + + // 排掉 JSON 碎片、句子、空括号:占位符名只能是一个短标识符 + function isPlaceholderName(name) { + if (!name || name.length > 40) return false + if (/["':,;{}\[\]\\]/.test(name)) return false + if (/\s{2,}/.test(name)) return false + return /[A-Za-z0-9\u4e00-\u9fa5]/.test(name) + } + + function promptPlaceholders(style) { + const text = String((style && style.prompt) || '') const seen = {} const out = [] - for (const label of Object.keys(vars)) { - const raw = String(vars[label] || '').trim() - const name = raw.replace(/^\{+/, '').replace(/\}+$/, '').trim() || label - if (!name || seen[name]) continue + let m + PH_RE.lastIndex = 0 + while ((m = PH_RE.exec(text))) { + const name = m[1].trim() + if (!isPlaceholderName(name) || seen[name]) continue seen[name] = true - out.push({ label: label, name: name }) + out.push(name) } return out } + // 去掉 markdown 残留(反引号/星号)—— Vigo 那批数据的 key 全是 `` `SUBJECT` `` + function cleanLabel(text) { + return String(text || '').replace(/[`*]/g, '').trim() + } + function stripBraces(text) { + return String(text || '').trim().replace(/^\{+/, '').replace(/\}+$/, '').trim() + } + + function varKeys(style) { + const names = promptPlaceholders(style) + if (!names.length) return [] + const vars = (style && style.variables && typeof style.variables === 'object') ? style.variables : {} + const labelOf = {} + for (const key of Object.keys(vars)) { + const raw = String(vars[key] == null ? '' : vars[key]).trim() + const keyName = cleanLabel(key) + const label = keyName || stripBraces(raw) + const cands = [stripBraces(raw), keyName] + const hit = cands.find((c) => c && names.indexOf(c) >= 0) + if (hit && !labelOf[hit]) labelOf[hit] = label || hit + } + const declared = [] + const implicit = [] + for (const name of names) { + const item = { + name: name, + label: labelOf[name] || name.replace(/[_-]+/g, ' ').trim() || name, + declared: Boolean(labelOf[name]), + } + ;(item.declared ? declared : implicit).push(item) + } + // 声明过的(人工挑过的中文标签)排前面,没声明的按提示词里的出现顺序跟在后面 + return declared.concat(implicit) + } + // 留空的变量保留 {原占位符} 原样 —— 替换成空串会把提示词结构弄丢,用户后面根本看不出漏了什么 function applyVars(style, values) { let text = String((style && style.prompt) || '') @@ -747,15 +804,34 @@ if (keys.length) { bodyEl.appendChild(el('div', { class: 'iwb-ss-label' }, [el('span', { text: '变量' }), unfilled])) const varBox = el('div', {}) - for (const item of keys) { - varBox.appendChild(el('div', { class: 'iwb-ss-var' }, [ - el('span', { class: 'iwb-ss-varlabel', text: item.label, title: item.label + ' → {' + item.name + '}' }), - el('input', { - class: 'iwb-ss-varinput', type: 'text', - placeholder: item.name, value: String(values[item.name] || ''), - onInput: (event) => { values[item.name] = event.target.value; refreshPreview() }, - }), - ])) + const rowOf = (item) => el('div', { class: 'iwb-ss-var' }, [ + el('span', { + class: 'iwb-ss-varlabel' + (item.declared ? '' : ' is-implicit'), + text: item.label, + title: (item.declared ? '' : '数据里没声明这个变量,标签直接用占位符名\n') + '{' + item.name + '}', + }), + el('input', { + class: 'iwb-ss-varinput', type: 'text', + placeholder: item.name, value: String(values[item.name] || ''), + onInput: (event) => { values[item.name] = event.target.value; refreshPreview() }, + }), + ]) + // 一次铺满 24 个输入框会把详情页顶爆(Vigo 那批就是),先给 6 个,其余折起来 + for (const item of keys.slice(0, VAR_SHOW)) varBox.appendChild(rowOf(item)) + const tail = keys.slice(VAR_SHOW) + if (tail.length) { + const more = el('div', { class: 'iwb-ss-varmore', style: 'display:none' }) + for (const item of tail) more.appendChild(rowOf(item)) + const toggle = el('button', { + class: 'iwb-ss-btn iwb-ss-vartoggle', text: '展开其余 ' + tail.length + ' 个变量', + onClick: () => { + const opening = more.style.display === 'none' + more.style.display = opening ? '' : 'none' + toggle.textContent = opening ? '收起' : '展开其余 ' + tail.length + ' 个变量' + }, + }) + varBox.appendChild(toggle) + varBox.appendChild(more) } bodyEl.appendChild(varBox) } @@ -892,7 +968,7 @@ global.IWBPluginHost.register({ id: 'style-source', name: '风格库', - version: '1.0.2', + version: '1.0.3', apiVersion: 1, capabilities: ['panels', 'canvas', 'canvasWrite'], settings: { diff --git a/style-source/tools/harness.mjs b/style-source/tools/harness.mjs index 4f23a01..3befd23 100644 --- a/style-source/tools/harness.mjs +++ b/style-source/tools/harness.mjs @@ -133,7 +133,7 @@ async function main() { const m = window.__manifest return { id: m.id, name: m.name, version: m.version, apiVersion: m.apiVersion, caps: m.capabilities, hasDataUrl: Boolean(m.settings && m.settings.dataUrl) } }) - check('manifest id/version 正确', manifest.id === 'style-source' && manifest.version === '1.0.2', JSON.stringify({ id: manifest.id, version: manifest.version })) + check('manifest id/version 正确', manifest.id === 'style-source' && manifest.version === '1.0.3', JSON.stringify({ id: manifest.id, version: manifest.version })) check('capabilities 含 panels+canvas+canvasWrite', ['panels', 'canvas', 'canvasWrite'].every((c) => manifest.caps.includes(c)), manifest.caps.join(',')) check('settings 暴露 dataUrl', manifest.hasDataUrl) @@ -395,6 +395,92 @@ async function main() { check('点分类「电商」后 chips 高亮切换', Boolean(clickCat) && catState.on.startsWith('电商'), clickCat + ' → ' + catState.on) check('分类筛选改变了结果数', /找到 \d+ 个/.test(catState.status), catState.status) + // ---- 变量来源:只认提示词里真实出现的 {占位符} ---- + // 线上 970 条 variables 里有 625 条的值只是人话描述(没有花括号),按声明表造输入框时全都对不上号 ⇒ + // 「有的有、有的没有」;反过来还有 78 个风格提示词里明明有 {xxx} 却一条都没声明。 + // 现在统一从提示词抽,声明表只用来配中文标签(并兼容 key 上带反引号的脏数据)。 + const openBySearch = async (q) => { + // 窄档里详情是**覆盖层**,不先关掉会挡住栅格,点不到卡片 + await page.evaluate(() => { + const box = window.__hostA.querySelector('.iwb-ss-detail.is-open') + const close = box && box.querySelector('.iwb-ss-dclose') + if (close) close.click() + const all = document.querySelector('#hostA .iwb-ss-chip') + if (all && !all.classList.contains('is-on')) all.click() + }) + await page.waitForTimeout(140) + await page.locator('#hostA .iwb-ss-search').fill(q) + await page.waitForTimeout(340) + await page.locator('#hostA .iwb-ss-card').first().click() + await page.waitForTimeout(140) + return page.evaluate(() => { + const box = window.__hostA.querySelector('.iwb-ss-detail') + const inputs = Array.from(box.querySelectorAll('.iwb-ss-varinput')) + const toggle = box.querySelector('.iwb-ss-vartoggle') + const more = box.querySelector('.iwb-ss-varmore') + const preview = (box.querySelector('.iwb-ss-text') || {}).textContent || '' + const names = inputs.map((i) => i.getAttribute('placeholder')) + return { + name: ((box.querySelector('.iwb-ss-dtitle') || {}).textContent || '').trim(), + labels: Array.from(box.querySelectorAll('.iwb-ss-varlabel')).map((e) => e.textContent), + pairs: inputs.map((i) => ({ + name: i.getAttribute('placeholder'), + label: (i.parentNode.querySelector('.iwb-ss-varlabel') || {}).textContent || '', + implicit: Boolean(i.parentNode.querySelector('.iwb-ss-varlabel.is-implicit')), + })), + names: names, + visible: inputs.filter((i) => i.getBoundingClientRect().height > 0).length, + dead: names.filter((n) => preview.indexOf('{' + n + '}') < 0).length, + hasVarLabel: Array.from(box.querySelectorAll('.iwb-ss-label')).some((e) => e.textContent.indexOf('变量') >= 0), + toggle: toggle ? toggle.textContent : '', + moreHidden: more ? getComputedStyle(more).display === 'none' : null, + } + }) + } + + const undeclared = await openBySearch('婚礼喜字影像画报') + check('提示词有占位符、数据没声明的风格也有输入框', + undeclared.names.length === 3 && undeclared.dead === 0, undeclared.name + ' → ' + undeclared.names.join(',')) + + const vigo = await openBySearch('黄黑漫画食品小志广告风格') + const subj = vigo.pairs.find((p) => p.name === 'SUBJECT') + check('脏 key 的反引号被剥掉,占位符 {SUBJECT} 认回声明过的标签', + Boolean(subj) && subj.label === 'SUBJECT' && !subj.implicit, + subj ? subj.label + ' → {' + subj.name + '}' + (subj.implicit ? '(按未声明处理)' : '') : '没有 SUBJECT 输入框') + check('声明表不会凭空造输入框(每个输入框都能在提示词里找到)', + vigo.dead === 0, 'inputs=' + vigo.names.length + ' dead=' + vigo.dead) + + const mondrian = await openBySearch('蒙德里安秩序风') + check('声明与提示词对不上时退回占位符名(不再静默消失)', + mondrian.names.length === 8 && mondrian.pairs.every((p) => p.implicit && p.label.indexOf('`') < 0), + mondrian.pairs.slice(0, 3).map((p) => p.label + '→{' + p.name + '}').join(', ')) + check('变量超过 6 个时先给 6 个、其余折叠', + mondrian.visible === 6 && mondrian.names.length > 6 && /展开其余 \d+ 个变量/.test(mondrian.toggle), + '可见=' + mondrian.visible + ' 全部=' + mondrian.names.length + ' / ' + mondrian.toggle) + check('折叠区默认收起', mondrian.moreHidden === true) + + const expand = await page.evaluate(() => { + const box = window.__hostA.querySelector('.iwb-ss-detail') + const btn = box.querySelector('.iwb-ss-vartoggle') + if (!btn) return null + btn.click() + const more = box.querySelector('.iwb-ss-varmore') + return { + shown: more ? getComputedStyle(more).display !== 'none' : null, + count: more ? more.querySelectorAll('.iwb-ss-varinput').length : 0, + text: btn.textContent, + } + }) + check('点「展开」后其余变量出现', Boolean(expand) && expand.shown === true && expand.count > 0, + expand ? '展开 ' + expand.count + ' 个 / 按钮=' + expand.text : '') + + const noVar = await openBySearch('旷野的风') + check('提示词里没有占位符就不摆空输入框', + noVar.names.length === 0 && noVar.hasVarLabel === false, noVar.name + ' inputs=' + noVar.names.length) + + await page.locator('#hostA .iwb-ss-search').fill('') + await page.waitForTimeout(200) + // ---- 多容器并存(宿主侧栏 + 放大窗口可能同时渲染同一插件面板) ---- // 早期版本用单个全局 dom 指针,第二个容器一挂载就把第一个容器的 RO 断掉 —— 这里专门守住这条 const dual = await page.evaluate(() => { @@ -429,6 +515,7 @@ async function main() { // ---- 截图留档(先移除 hostB,否则 flex 会把 hostA 压缩、截不到真实宽度) ---- const shotWide = path.resolve(HERE, 'shot-wide.png') const shotNarrow = path.resolve(HERE, 'shot-narrow.png') + const shotVars = path.resolve(HERE, 'shot-vars.png') await page.evaluate(() => { if (window.__hostB) window.__hostB.remove() window.__hostA.style.width = '980px' @@ -448,8 +535,17 @@ async function main() { }) await page.waitForTimeout(400) await page.locator('#hostA').screenshot({ path: shotNarrow }).catch(() => {}) + // 变量区留档:8 个占位符 → 前 6 个 + 「展开其余 2 个」 + await page.evaluate(() => { window.__hostA.style.width = '980px'; window.__hostA.style.height = '1180px' }) + await page.waitForTimeout(260) + await page.locator('#hostA .iwb-ss-search').fill('黄黑漫画食品小志广告风格') + await page.waitForTimeout(340) + await page.locator('#hostA .iwb-ss-card').first().click() + await page.waitForTimeout(380) + await page.locator('#hostA .iwb-ss-detail').screenshot({ path: shotVars }) console.log('· 截图:' + shotWide) console.log('· 截图:' + shotNarrow) + console.log('· 截图:' + shotVars) check('无页面 JS 异常', errors.length === 0, errors.slice(0, 2).join(' | '))