feat(style-source): 风格库插件(资源库面板浏览 310 个 AI 绘画风格)

- 直连 malongan.github.io 的 styles.json 与预览图(CORS *),无后端、不改宿主 CSP
- 面板宽度自适应:网格 auto-fill 列数,详情按 480px 拐点切「覆盖 body / 右侧栏」
  判定用 ResizeObserver(拖侧栏时视口不变,@media 不响应)
- 按容器建实例:宿主侧栏与放大窗口可同时渲染同一面板,各自独立 RO,数据走模块级共享
- 变量替换:{占位符} 按 variables 字段生成输入框,留空保留原占位符
- 插入:预览图 blob→dataURL→createImageNode(ref);提示词 createNode('prompt') 插选中节点右侧
- 修 grid-auto-rows 默认 auto 导致图片未加载时卡片塌成横条的坑(显式 max-content)
- 加 tools/harness.mjs(离线合成宿主)与 tools/e2e-real.mjs(真实网络冒烟)
- 已发布 KV:plugin-style-source.fd634473ee66.js(v1.0.0,integrity 校验通过)
This commit is contained in:
qiqi committed 2026-11-02 09:18:05 +08:00
1 parent c31c92d07a
commit 38a34ff533
6 files changed
+1453

No files matched your search

+849
View File
@@ -0,0 +1,849 @@
// iwb-plugin: 风格库 —— 资源库面板里浏览 310 个 AI 绘画风格,一键把预览图插入画布(ref 节点)或把提示词插入画布(prompt 节点)。
// 数据与图片来自 https://malongan.github.io/style-source (GitHub Pages,CORS 为 *),插件直连,无后端。
//
// 面板宽度可变(侧栏 240~560 拖动、放大窗口 920×600 八向缩放、embedded 嵌入),所以布局不能写死两栏:
// 网格列数交给 CSS auto-fill;详情用 480px 一个拐点切两态(窄=覆盖 body / 宽=右侧栏),同一个 DOM 只换定位。
// 判定用 ResizeObserver 而不是 @media —— 拖侧栏时视口没变,@media 完全不响应。
//
// ⚠️ 宿主 ui-lib-sidebar.js 里侧栏和放大窗口可以同时渲染同一个插件面板(两处都调 mount,容器是不同的 DOM 节点),
// 所以这里按「一个容器一个实例」组织:每个实例有自己的 DOM 引用和 ResizeObserver,数据/图片/选中项走模块级共享。
// 早期版本用单个全局 dom 指针,第二个容器一挂载就把第一个容器的 RO 断了,旧容器再也不响应宽度变化。
//
// 面板容器 .iwb-full-panel-plugin 在宿主 style.css 里没有任何样式定义(裸 div),
// 宽高必须由插件根自己保证,否则在 flex 父级里撑不开或溢出双滚动条。
;(function (global) {
'use strict'
if (!global.IWBPluginHost) return
const DEFAULT_DATA = 'https://malongan.github.io/style-source/data/styles.json'
const PAGE_SIZE = 90 // 网格分批渲染,避免一次建 310 个 DOM
const WIDE_MIN = 480 // 详情从「覆盖 body」切到「右侧栏」的宽度拐点
const PREF_KEY = 'iwb.style-source.prefs.v1'
// 分类中文名:取自项目自带的 gallery/src/gallery.js(去掉 emoji,与宿主面板风格统一)
const CAT_NAMES = {
social_media: '社交媒体', brand_kv: '品牌视觉', 'e-commerce': '电商', science: '科研',
print: '印刷品', ip_character: 'IP 角色', travel: '旅行', fashion: '时尚',
creative: '创意', vigo_cookbook: 'Cookbook', typography: '字体设计', editorial: '编辑画册',
}
// ---------------- 模块级共享缓存 ----------------
// 多容器共用:切侧栏/放大窗口时不重拉 1.1MB JSON、不重下预览图、不丢选中项与变量输入。
const CACHE = {
data: null, // { meta, styles:[...] }
loading: null, // Promise
blobs: {}, // url -> Promise<Blob>
selId: null,
selOpen: false,
query: '',
cat: 'all',
vars: {}, // styleId -> { 占位符名: 用户输入 }
}
// host 元素 -> 实例。容器被 React 卸载后随 WeakMap 自动释放
const INSTANCES = new WeakMap()
// ---------------- 小工具 ----------------
function el(tag, attrs, kids) {
const node = document.createElement(tag)
if (attrs) {
for (const key in attrs) {
const value = attrs[key]
if (value === null || value === undefined) continue
if (key === 'class') node.className = value
else if (key === 'text') node.textContent = String(value)
else if (key.slice(0, 2) === 'on') node.addEventListener(key.slice(2).toLowerCase(), value)
// checked/disabled 是布尔属性:setAttribute('disabled','false') 依然是「有值」⇒ 仍然禁用,必须走 property
else if (key === 'checked' || key === 'disabled' || key === 'selected') node[key] = Boolean(value)
else node.setAttribute(key, String(value))
}
}
if (kids !== null && kids !== undefined) {
const arr = Array.isArray(kids) ? kids : [kids]
for (const kid of arr) {
if (kid === null || kid === undefined || kid === false) continue
node.appendChild(typeof kid === 'string' ? document.createTextNode(kid) : kid)
}
}
return node
}
function prefAll() {
try {
const raw = global.localStorage.getItem(PREF_KEY)
return raw ? JSON.parse(raw) || {} : {}
} catch (error) { return {} }
}
function prefSet(key, value) {
try {
const all = prefAll()
all[key] = value
global.localStorage.setItem(PREF_KEY, JSON.stringify(all))
} catch (error) { /* 隐私模式下写不了,忽略 */ }
}
function readErr(error) {
const msg = String((error && (error.message || error)) || '未知错误')
if (/Failed to fetch|NetworkError|Load failed/i.test(msg)) {
return '网络请求失败(可能被断网/代理拦截,或数据源 CORS 变了)'
}
return msg
}
// ---------------- 样式 ----------------
const CSS = `
.iwb-ss-root {
position: relative;
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
overflow: hidden;
background: var(--iwb-panel, #fff);
color: var(--iwb-text, #1c2333);
font-size: var(--fs-md, 12px);
line-height: 1.5;
}
.iwb-ss-root *, .iwb-ss-root *::before, .iwb-ss-root *::after { box-sizing: border-box; }
.iwb-ss-tools { flex: 0 0 auto; display: flex; gap: 6px; align-items: center; padding: 8px 10px 6px; }
.iwb-ss-search {
flex: 1 1 auto; min-width: 0; height: 28px; padding: 0 9px;
border: 1px solid var(--iwb-border, #d5d9e0); border-radius: var(--rd-sm, 6px);
background: var(--iwb-layer2, #fff); color: inherit; font-size: var(--fs-md, 12px);
outline: none; font-family: inherit;
}
.iwb-ss-search::placeholder { color: var(--iwb-text2, #4d5668); opacity: .55; }
.iwb-ss-search:focus { border-color: var(--iwb-brand, #6b7280); }
.iwb-ss-btn {
flex: 0 0 auto; height: 28px; padding: 0 10px;
border: 1px solid var(--iwb-border, #d5d9e0); border-radius: var(--rd-sm, 6px);
background: var(--iwb-layer2, #fff); color: inherit; font-size: var(--fs-md, 12px);
cursor: pointer; white-space: nowrap; font-family: inherit;
}
.iwb-ss-btn:hover:not(:disabled) { border-color: var(--iwb-border2, #b9bfca); background: var(--iwb-layer, #f0f1f4); }
.iwb-ss-btn:disabled { opacity: .45; cursor: not-allowed; }
.iwb-ss-btn.is-key { border-color: var(--iwb-brand, #6b7280); }
.iwb-ss-btn.is-key:hover:not(:disabled) { background: var(--iwb-brand, #6b7280); color: var(--iwb-panel, #fff); }
/* 分类 chips:单行横向滚动。窄面板下如果换行会直接吃掉半屏高度 */
.iwb-ss-chips {
flex: 0 0 auto; display: flex; gap: 4px; padding: 0 10px 7px;
overflow-x: auto; overflow-y: hidden; scrollbar-width: none;
}
.iwb-ss-chips::-webkit-scrollbar { display: none; }
.iwb-ss-chip {
flex: 0 0 auto; height: 22px; padding: 0 9px;
border: 1px solid var(--iwb-border, #d5d9e0); border-radius: 11px;
background: transparent; color: var(--iwb-text2, #4d5668);
font-size: var(--fs-sm, 11px); cursor: pointer; white-space: nowrap; font-family: inherit;
}
.iwb-ss-chip:hover { border-color: var(--iwb-border2, #b9bfca); }
.iwb-ss-chip.is-on { background: var(--iwb-brand, #6b7280); border-color: var(--iwb-brand, #6b7280); color: var(--iwb-panel, #fff); }
.iwb-ss-body { flex: 1 1 auto; min-height: 0; min-width: 0; display: flex; position: relative; }
.iwb-ss-grid {
flex: 1 1 auto; min-width: 0; min-height: 0; overflow-y: auto;
display: grid; grid-template-columns: repeat(auto-fill, minmax(112px, 1fr));
/* ⚠️ grid-auto-rows 必须显式 max-content:默认 auto 时,图片还没加载出固有尺寸(naturalWidth=0),
行高会塌到「一行文字」的高度(实测 18.89px),卡片被 overflow:hidden 裁成一条横杠,名称也看不见。 */
grid-auto-rows: max-content;
gap: 8px; padding: 2px 10px 10px; align-content: start;
}
.iwb-ss-card {
position: relative; display: flex; flex-direction: column; min-width: 0;
border: 1px solid var(--iwb-border, #d5d9e0); border-radius: var(--rd, 8px);
overflow: hidden; background: var(--iwb-layer2, #fff); cursor: pointer;
}
.iwb-ss-card:hover { border-color: var(--iwb-border2, #b9bfca); }
.iwb-ss-card.is-sel { border-color: var(--iwb-brand, #6b7280); box-shadow: inset 0 0 0 1px var(--iwb-brand, #6b7280); }
.iwb-ss-thumb { display: block; width: 100%; aspect-ratio: 3 / 4; object-fit: cover; background: var(--iwb-layer, #f0f1f4); }
.iwb-ss-nothumb {
width: 100%; aspect-ratio: 3 / 4; display: flex; align-items: center; justify-content: center;
background: var(--iwb-layer, #f0f1f4); color: var(--iwb-text2, #4d5668); opacity: .5; font-size: var(--fs-xs, 10px);
}
.iwb-ss-cardmeta { padding: 3px 6px 5px; min-width: 0; }
.iwb-ss-cardname {
font-size: var(--fs-sm, 11px); line-height: 1.35;
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.iwb-ss-cardcode { font-size: var(--fs-xs, 10px); color: var(--iwb-text2, #4d5668); opacity: .7; }
/* 详情:一个 DOM 两种形态。窄档覆盖 .iwb-ss-body(保留顶部搜索/分类,便于边看边换) */
.iwb-ss-detail {
display: none; flex-direction: column; min-width: 0; min-height: 0;
background: var(--iwb-panel, #fff);
}
.iwb-ss-root[data-layout="narrow"] .iwb-ss-detail.is-open { display: flex; position: absolute; inset: 0; z-index: 5; }
.iwb-ss-root[data-layout="wide"] .iwb-ss-detail { display: flex; flex: 0 0 46%; max-width: 380px; border-left: 1px solid var(--iwb-border, #d5d9e0); }
.iwb-ss-dhead {
flex: 0 0 auto; display: flex; align-items: center; gap: 6px;
padding: 7px 10px; border-bottom: 1px solid var(--iwb-border, #d5d9e0);
}
.iwb-ss-dtitle {
flex: 1 1 auto; min-width: 0; font-size: var(--fs-lg, 13px); font-weight: 500;
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.iwb-ss-dclose {
flex: 0 0 auto; width: 24px; height: 24px; padding: 0; line-height: 1;
border: 1px solid var(--iwb-border, #d5d9e0); border-radius: var(--rd-sm, 6px);
background: transparent; color: inherit; cursor: pointer; font-size: 13px; font-family: inherit;
}
.iwb-ss-dbody {
flex: 1 1 auto; min-height: 0; overflow-y: auto;
padding: 10px; display: flex; flex-direction: column; gap: 10px;
}
.iwb-ss-dfoot {
flex: 0 0 auto; display: flex; gap: 6px;
padding: 8px 10px; border-top: 1px solid var(--iwb-border, #d5d9e0);
}
.iwb-ss-dfoot .iwb-ss-btn { flex: 1 1 0; height: 30px; }
/* 预览图比例差异极大(9:21 竖图到 21:9 横图都有)。不限高的话竖图会撑满详情栏,变量和提示词全被挤到折叠以下。
用 contain 而不是 cover:宁可两侧留底色,也不裁掉画面 —— 用户是来参考构图的。 */
.iwb-ss-big {
display: block; width: 100%; max-height: 320px; object-fit: contain;
border-radius: var(--rd, 8px); border: 1px solid var(--iwb-border, #d5d9e0); background: var(--iwb-layer, #f0f1f4);
}
.iwb-ss-tagrow { display: flex; flex-wrap: wrap; gap: 4px; }
.iwb-ss-tag {
font-size: var(--fs-xs, 10px); padding: 1px 7px; border-radius: 9px;
background: var(--iwb-layer, #f0f1f4); color: var(--iwb-text2, #4d5668);
}
.iwb-ss-label {
font-size: var(--fs-sm, 11px); color: var(--iwb-text2, #4d5668);
display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 4px;
}
.iwb-ss-summary { font-size: var(--fs-md, 12px); color: var(--iwb-text2, #4d5668); line-height: 1.6; }
.iwb-ss-text {
font-size: var(--fs-md, 12px); line-height: 1.7; white-space: pre-wrap; word-break: break-word;
background: var(--iwb-layer, #f0f1f4); padding: 8px; border-radius: var(--rd-sm, 6px);
max-height: 150px; overflow-y: auto;
}
.iwb-ss-root[data-layout="narrow"] .iwb-ss-big { max-height: 240px; }
.iwb-ss-root[data-layout="narrow"] .iwb-ss-text { max-height: 240px; }
.iwb-ss-var { display: flex; align-items: center; gap: 6px; margin-bottom: 5px; }
.iwb-ss-varlabel {
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;
}
.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);
background: var(--iwb-layer2, #fff); color: inherit; font-size: var(--fs-sm, 11px);
outline: none; font-family: inherit;
}
.iwb-ss-varinput:focus { border-color: var(--iwb-brand, #6b7280); }
.iwb-ss-check { display: flex; align-items: center; gap: 6px; font-size: var(--fs-sm, 11px); color: var(--iwb-text2, #4d5668); cursor: pointer; }
.iwb-ss-check input { margin: 0; }
.iwb-ss-status {
flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 8px;
padding: 4px 10px 6px; font-size: var(--fs-sm, 11px);
color: var(--iwb-text2, #4d5668); opacity: .8;
}
.iwb-ss-empty { grid-column: 1 / -1; padding: 26px 14px; text-align: center; color: var(--iwb-text2, #4d5668); font-size: var(--fs-md, 12px); line-height: 1.9; opacity: .75; }
.iwb-ss-toast {
position: absolute; left: 50%; bottom: 46px; z-index: 20;
transform: translateX(-50%) translateY(6px);
max-width: 88%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
background: rgba(22, 26, 34, .9); color: #fff;
font-size: var(--fs-md, 12px); padding: 6px 12px; border-radius: 14px;
opacity: 0; pointer-events: none; transition: opacity .18s ease, transform .18s ease;
}
.iwb-ss-toast.is-show { opacity: 1; transform: translateX(-50%) translateY(0); }
`
function ensureStyle() {
const id = 'iwb-ss-style'
if (document.getElementById(id)) return
try {
;(document.head || document.documentElement).appendChild(el('style', { id: id, text: CSS }))
} catch (error) { /* 样式注入失败不影响功能,只是丑一点 */ }
}
// ---------------- 数据 ----------------
function dataUrlOf(ctx) {
let value = ''
try { value = String(ctx.settings.get('dataUrl') || '') } catch (error) { value = '' }
return value.trim() || DEFAULT_DATA
}
function loadData(ctx, force) {
if (CACHE.data && !force) return Promise.resolve(CACHE.data)
if (CACHE.loading) return CACHE.loading
const url = dataUrlOf(ctx)
// credentials: 'omit' —— 公共静态文件,别把宿主的 cookie 带过去
CACHE.loading = fetch(url, { mode: 'cors', credentials: 'omit' })
.then((resp) => {
if (!resp.ok) throw new Error('HTTP ' + resp.status + '(' + url + ')')
return resp.json()
})
.then((json) => {
const list = json && json.styles
if (!Array.isArray(list) || !list.length) throw new Error('数据格式不对:没有 styles 数组')
CACHE.data = { meta: json.meta || {}, styles: list }
CACHE.loading = null
return CACHE.data
})
.catch((error) => {
CACHE.loading = null
throw error
})
return CACHE.loading
}
function thumbOf(style) {
return style.preview_webp_thumb || style.preview_webp ||
(Array.isArray(style.preview_urls) && style.preview_urls[0]) || ''
}
function bigOf(style) {
return style.preview_webp || (Array.isArray(style.preview_urls) && style.preview_urls[0]) || thumbOf(style)
}
function catName(key) { return CAT_NAMES[key] || key }
function filtered() {
const list = (CACHE.data && CACHE.data.styles) || []
const q = CACHE.query.trim().toLowerCase()
return list.filter((s) => {
if (CACHE.cat !== 'all' && s.category !== CACHE.cat) return false
if (!q) return true
const hay = [
s.name, s.code, s.id, s.category, s.summary,
(s.tags || []).join(' '), (s.triggers || []).join(' '),
].join(' ').toLowerCase()
return hay.indexOf(q) >= 0
})
}
function styleById(id) {
const list = (CACHE.data && CACHE.data.styles) || []
for (const s of list) if (s.id === id) return s
return null
}
// ---------------- 变量 ----------------
// variables 的 value 有两种写法:'角色描述' 和 '{诗词}'(自带花括号),统一剥成占位符名
function varKeys(style) {
const vars = style && style.variables
if (!vars || typeof vars !== 'object') return []
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
seen[name] = true
out.push({ label: label, name: name })
}
return out
}
// 留空的变量保留 {原占位符} 原样 —— 替换成空串会把提示词结构弄丢,用户后面根本看不出漏了什么
function applyVars(style, values) {
let text = String((style && style.prompt) || '')
for (const item of varKeys(style)) {
const val = String((values && values[item.name]) || '').trim()
if (!val) continue
// 用 split/join 而不是正则:占位符名里可能出现正则元字符
text = text.split('{' + item.name + '}').join(val)
}
return text
}
function unfilledCount(style, values) {
return varKeys(style).filter((item) => !String((values && values[item.name]) || '').trim()).length
}
// ---------------- 取图 ----------------
function loadBlob(url) {
if (CACHE.blobs[url]) return CACHE.blobs[url]
const promise = fetch(url, { mode: 'cors', credentials: 'omit' }).then((resp) => {
if (!resp.ok) throw new Error('图片 HTTP ' + resp.status)
return resp.blob()
})
CACHE.blobs[url] = promise
promise.catch(() => { delete CACHE.blobs[url] }) // 失败不缓存,下次还能重试
return promise
}
function blobToDataUrl(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => resolve(String(reader.result || ''))
reader.onerror = () => reject(new Error('读取图片失败'))
reader.readAsDataURL(blob)
})
}
// ---------------- 插画布 ----------------
// getNodes 里没有节点宽度,用经验值估:prompt 节点约 320 宽,留 60 间距
const GAP_X = 380
function nextSpot(ctx) {
let nodes = []
let sel = null
try { nodes = ctx.canvas.getNodes() || [] } catch (error) { nodes = [] }
try { sel = ctx.canvas.getSelectedNode() } catch (error) { sel = null }
if (sel && sel.id) {
for (const n of nodes) {
if (n.id === sel.id) return { x: Math.round((Number(n.x) || 0) + GAP_X), y: Math.round(Number(n.y) || 0) }
}
}
if (!nodes.length) return { x: 80, y: 80 }
let best = nodes[0]
let maxX = -Infinity
for (const n of nodes) {
const x = Number(n.x) || 0
if (x > maxX) { maxX = x; best = n }
}
return { x: Math.round(maxX + GAP_X), y: Math.round(Number(best.y) || 0) }
}
function useThumb() {
return prefAll().thumbOnly === true
}
// ---------------- 面板实例 ----------------
// 每个 mount 容器一个实例:独立 DOM 引用 + 独立 ResizeObserver,数据走 CACHE 共享。
function mount(host, ctx) {
const prev = INSTANCES.get(host)
if (prev) {
try { prev.destroy() } catch (error) { /* 忽略 */ }
INSTANCES.delete(host)
}
ensureStyle()
host.innerHTML = ''
const ui = {
root: null, search: null, chips: null, grid: null, detail: null, status: null, toastEl: null,
btnRef: null, btnPrompt: null, busy: false, timer: null, seq: 0,
}
const view = { list: [], count: 0 }
const root = el('div', { class: 'iwb-ss-root' })
root.setAttribute('data-layout', 'narrow')
const search = el('input', {
class: 'iwb-ss-search', type: 'search',
placeholder: '搜索风格 / 编号 / 标签', value: CACHE.query,
})
const refreshBtn = el('button', {
class: 'iwb-ss-btn', text: '刷新', title: '重新拉取风格数据',
onClick: () => {
CACHE.data = null
CACHE.loading = null
CACHE.blobs = {}
ensureData()
},
})
const chips = el('div', { class: 'iwb-ss-chips' })
const grid = el('div', { class: 'iwb-ss-grid' })
const detail = el('div', { class: 'iwb-ss-detail' })
const body = el('div', { class: 'iwb-ss-body' }, [grid, detail])
const status = el('div', { class: 'iwb-ss-status' })
const toastEl = el('div', { class: 'iwb-ss-toast' })
root.appendChild(el('div', { class: 'iwb-ss-tools' }, [search, refreshBtn]))
root.appendChild(chips)
root.appendChild(body)
root.appendChild(status)
root.appendChild(toastEl)
host.appendChild(root)
ui.root = root
ui.search = search
ui.chips = chips
ui.grid = grid
ui.detail = detail
ui.status = status
ui.toastEl = toastEl
// ---- 交互反馈 ----
function toast(text) {
if (!ui.toastEl) return
ui.toastEl.textContent = text
ui.toastEl.classList.add('is-show')
global.setTimeout(() => {
if (ui.toastEl) ui.toastEl.classList.remove('is-show')
}, 2200)
}
function busy(on, text) {
ui.busy = Boolean(on)
if (ui.btnRef) {
ui.btnRef.disabled = Boolean(on)
ui.btnRef.textContent = on ? (text || '处理中…') : '插入参考图'
}
if (ui.btnPrompt) ui.btnPrompt.disabled = Boolean(on)
}
// ---- 插入动作 ----
async function insertImage(style) {
const api = ctx.canvas
if (!api || typeof api.createImageNode !== 'function') { toast('当前宿主不支持插入图片(缺 canvasWrite 能力)'); return }
const url = useThumb() ? thumbOf(style) : bigOf(style)
if (!url) { toast('这条风格没有预览图'); return }
try {
busy(true, '正在取图…')
const blob = await loadBlob(url)
const dataUrl = await blobToDataUrl(blob)
// createImageNode 只认 data: URL(宿主 app.js 里 /^data:/i 校验),必须 blob → base64
const id = api.createImageNode({
dataUrl: dataUrl,
name: String(style.code || 'style') + '_' + String(style.name || ''),
})
if (!id) throw new Error('画布拒绝了这张图(data URL 无效)')
toast('已插入参考图')
} catch (error) {
toast('插图失败:' + readErr(error))
} finally {
busy(false)
}
}
function insertPrompt(style) {
const api = ctx.canvas
if (!api || typeof api.createNode !== 'function') { toast('当前宿主不支持插入节点(缺 canvasWrite 能力)'); return }
const values = CACHE.vars[style.id] || {}
const text = applyVars(style, values).trim()
if (!text) { toast('这条风格没有提示词'); return }
const spot = nextSpot(ctx)
// createNode 不会自己避让,坐标必须插件算好(createImageNode 内部才走 findSpot 自动排布)
const id = api.createNode('prompt', spot.x, spot.y, { text: text })
if (!id) { toast('插入失败:prompt 节点类型未注册'); return }
const left = unfilledCount(style, values)
toast(left ? '已插入提示词(还有 ' + left + ' 个变量没填)' : '已插入提示词')
}
// ---- 渲染 ----
function renderChips() {
const all = (CACHE.data && CACHE.data.styles) || []
const counts = {}
for (const s of all) counts[s.category] = (counts[s.category] || 0) + 1
const keys = Object.keys(counts).sort((a, b) => counts[b] - counts[a])
ui.chips.innerHTML = ''
ui.chips.appendChild(el('button', {
class: 'iwb-ss-chip' + (CACHE.cat === 'all' ? ' is-on' : ''),
text: '全部 ' + all.length,
onClick: () => { CACHE.cat = 'all'; prefSet('cat', 'all'); renderAll() },
}))
for (const key of keys) {
ui.chips.appendChild(el('button', {
class: 'iwb-ss-chip' + (CACHE.cat === key ? ' is-on' : ''),
text: catName(key) + ' ' + counts[key],
title: key,
onClick: () => { CACHE.cat = key; prefSet('cat', key); renderAll() },
}))
}
}
function cardNode(style) {
const isSel = CACHE.selId === style.id
const thumb = thumbOf(style)
const media = thumb
? el('img', {
class: 'iwb-ss-thumb', src: thumb, alt: String(style.name || ''),
loading: 'lazy', decoding: 'async', referrerpolicy: 'no-referrer',
})
: el('div', { class: 'iwb-ss-nothumb', text: String(style.code || '') })
return el('div', {
class: 'iwb-ss-card' + (isSel ? ' is-sel' : ''),
title: String(style.name || '') + (style.summary ? '\n' + style.summary : ''),
onClick: () => selectStyle(style.id),
}, [
media,
el('div', { class: 'iwb-ss-cardmeta' }, [
el('div', { class: 'iwb-ss-cardname', text: String(style.name || '未命名') }),
el('div', { class: 'iwb-ss-cardcode', text: String(style.code || '') }),
]),
])
}
function appendCards(from, to) {
const frag = document.createDocumentFragment()
for (let i = from; i < to; i++) frag.appendChild(cardNode(view.list[i]))
ui.grid.appendChild(frag)
view.count = to
}
function renderGrid() {
ui.grid.innerHTML = ''
view.count = 0
if (!view.list.length) {
ui.grid.appendChild(el('div', { class: 'iwb-ss-empty', text: '没有匹配的风格,换个关键词或分类试试' }))
return
}
appendCards(0, Math.min(view.list.length, PAGE_SIZE))
}
function renderStatus() {
const total = (CACHE.data && CACHE.data.styles.length) || 0
const shown = view.list.length
const left = Math.max(0, shown - view.count)
ui.status.textContent = ''
ui.status.appendChild(el('span', {
text: (CACHE.query.trim() || CACHE.cat !== 'all')
? '找到 ' + shown + ' 个 / 共 ' + total
: '共 ' + total + ' 个风格',
}))
ui.status.appendChild(el('span', { text: left > 0 ? '下滑加载更多(还剩 ' + left + ')' : '' }))
}
function selectStyle(id) {
CACHE.selId = id
CACHE.selOpen = true
prefSet('selId', id)
const cards = ui.grid.querySelectorAll('.iwb-ss-card')
for (let i = 0; i < cards.length; i++) cards[i].classList.remove('is-sel')
const idx = view.list.findIndex((s) => s.id === id)
if (idx >= 0 && idx < view.count && cards[idx]) cards[idx].classList.add('is-sel')
renderDetail()
}
function renderDetail() {
const style = CACHE.selId ? styleById(CACHE.selId) : null
if (!style) {
ui.detail.classList.remove('is-open')
ui.detail.innerHTML = ''
ui.detail.appendChild(el('div', { class: 'iwb-ss-empty', text: '从左边点一个风格,这里显示大图、提示词和变量' }))
return
}
ui.detail.classList.toggle('is-open', CACHE.selOpen)
ui.detail.innerHTML = ''
const big = bigOf(style)
const values = CACHE.vars[style.id] || (CACHE.vars[style.id] = {})
const keys = varKeys(style)
const head = el('div', { class: 'iwb-ss-dhead' }, [
el('div', { class: 'iwb-ss-dtitle', text: String(style.name || '未命名') }),
el('button', {
class: 'iwb-ss-dclose', text: '✕', title: '关闭详情',
onClick: () => {
CACHE.selOpen = false
ui.detail.classList.remove('is-open')
},
}),
])
const bodyEl = el('div', { class: 'iwb-ss-dbody' })
if (big) {
bodyEl.appendChild(el('img', {
class: 'iwb-ss-big', src: big, alt: String(style.name || ''),
loading: 'lazy', decoding: 'async', referrerpolicy: 'no-referrer',
}))
}
const tagRow = el('div', { class: 'iwb-ss-tagrow' })
if (style.code) tagRow.appendChild(el('span', { class: 'iwb-ss-tag', text: String(style.code) }))
if (style.ratio) tagRow.appendChild(el('span', { class: 'iwb-ss-tag', text: String(style.ratio) }))
for (const t of (style.tags || []).slice(0, 8)) tagRow.appendChild(el('span', { class: 'iwb-ss-tag', text: String(t) }))
bodyEl.appendChild(tagRow)
if (style.summary) bodyEl.appendChild(el('div', { class: 'iwb-ss-summary', text: String(style.summary) }))
// 变量区:改输入只更新预览文本,不重建 DOM(否则每敲一个字就丢焦点)
const preview = el('div', { class: 'iwb-ss-text' })
const unfilled = el('span', { class: 'iwb-ss-tag', text: '' })
const refreshPreview = () => {
preview.textContent = applyVars(style, values)
const left = unfilledCount(style, values)
unfilled.textContent = left ? left + ' 个未填' : '已全部填好'
}
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() },
}),
]))
}
bodyEl.appendChild(varBox)
}
bodyEl.appendChild(el('div', { class: 'iwb-ss-label' }, [el('span', { text: '提示词' })]))
bodyEl.appendChild(preview)
refreshPreview()
bodyEl.appendChild(el('label', { class: 'iwb-ss-check' }, [
el('input', {
type: 'checkbox', checked: useThumb(),
onChange: (event) => { prefSet('thumbOnly', event.target.checked) },
}),
el('span', { text: '插图用缩略图(更省画布体积)' }),
]))
if (style.source_url) {
bodyEl.appendChild(el('div', { class: 'iwb-ss-label' }, [
el('span', { text: '来源:' + String(style.source_author || '未知') }),
el('a', {
href: String(style.source_url), target: '_blank', rel: 'noopener noreferrer',
text: '打开原帖', style: 'color: inherit; text-decoration: underline;',
}),
]))
}
ui.btnRef = el('button', {
class: 'iwb-ss-btn', text: '插入参考图',
onClick: () => insertImage(style),
})
ui.btnPrompt = el('button', {
class: 'iwb-ss-btn is-key', text: '插入提示词',
onClick: () => insertPrompt(style),
})
ui.detail.appendChild(head)
ui.detail.appendChild(bodyEl)
ui.detail.appendChild(el('div', { class: 'iwb-ss-dfoot' }, [ui.btnRef, ui.btnPrompt]))
}
function renderAll() {
renderChips()
view.list = filtered()
renderGrid()
renderStatus()
renderDetail()
}
function renderHint(text, retry) {
ui.grid.innerHTML = ''
ui.grid.appendChild(el('div', { class: 'iwb-ss-empty' }, [
el('div', { text: text }),
retry ? el('div', { style: 'margin-top:10px;' }, [
el('button', { class: 'iwb-ss-btn', text: '重试', onClick: retry }),
]) : null,
]))
}
function ensureData() {
if (CACHE.data) { renderAll(); return }
const seq = ++ui.seq
ui.status.textContent = '正在加载风格数据…'
renderHint('正在加载风格数据…')
loadData(ctx)
.then(() => {
if (seq !== ui.seq || !root.isConnected) return
renderAll()
})
.catch((error) => {
if (seq !== ui.seq || !root.isConnected) return
ui.status.textContent = '加载失败'
renderHint('风格数据加载失败:' + readErr(error), () => {
CACHE.data = null
CACHE.loading = null
ensureData()
})
})
}
// ---- 事件 ----
// 搜索防抖 150ms:310 条同步过滤很快,但每键都重排网格会闪
search.addEventListener('input', () => {
if (ui.timer) global.clearTimeout(ui.timer)
ui.timer = global.setTimeout(() => {
CACHE.query = search.value
view.list = filtered()
renderGrid()
renderStatus()
}, 150)
})
// 滚到底自动续渲染
grid.addEventListener('scroll', () => {
if (ui.busy) return
if (view.count >= view.list.length) return
if (grid.scrollTop + grid.clientHeight < grid.scrollHeight - 240) return
appendCards(view.count, Math.min(view.list.length, view.count + PAGE_SIZE))
renderStatus()
})
// 宽度自适应:拖侧栏/缩放放大窗口时视口不变,@media 不响应,必须观察元素自身
// 先同步判一次:RO 回调要等下一帧,宽容器否则会先闪一帧窄布局
const startW = Math.max(host.clientWidth || 0, root.getBoundingClientRect().width || 0)
if (startW) root.setAttribute('data-layout', startW >= WIDE_MIN ? 'wide' : 'narrow')
let ro = null
if (typeof global.ResizeObserver === 'function') {
ro = new global.ResizeObserver((entries) => {
if (!root.isConnected) return
const width = entries && entries[0] ? entries[0].contentRect.width : 0
root.setAttribute('data-layout', width >= WIDE_MIN ? 'wide' : 'narrow')
})
ro.observe(root)
} else {
root.setAttribute('data-layout', 'wide')
}
const instance = {
destroy() {
if (ro) { try { ro.disconnect() } catch (error) { /* 忽略 */ } ro = null }
if (ui.timer) { global.clearTimeout(ui.timer); ui.timer = null }
ui.seq++
},
}
INSTANCES.set(host, instance)
ensureData()
}
// ---------------- 注册 ----------------
global.IWBPluginHost.register({
id: 'style-source',
name: '风格库',
version: '1.0.0',
apiVersion: 1,
capabilities: ['panels', 'canvas', 'canvasWrite'],
settings: {
dataUrl: {
type: 'text',
label: '风格数据地址',
desc: 'styles.json 的地址。默认直连 GitHub Pages;国内慢可自行镜像后改这里。',
default: DEFAULT_DATA,
},
},
}, function (ctx) {
const prefs = prefAll()
if (prefs.cat && typeof prefs.cat === 'string') CACHE.cat = prefs.cat
if (prefs.selId && typeof prefs.selId === 'string') CACHE.selId = prefs.selId
ctx.ui.registerPanel({
id: 'style-panel',
title: '风格库',
icon: 'palette',
mount: (host) => mount(host, ctx),
})
return {}
})
})(typeof window !== 'undefined' ? window : globalThis)