Files
iwb-plugins-desktop/style-source/src/index.js
T
qiqi 8dca2a5b67 feat(style-source): 拖拽插入 —— 按住「插入提示词/参考图」拖到画布上松手,节点落在松手点(1.2.0)
- 松手点交给宿主换算(ctx.canvas.screenToWorld),插件不碰 pan/zoom
- 拖拽中跟一张幽灵卡片,进画布提示「松手放这里」,松手不在画布上则取消
- 位移 <6px 视作点击,仍走 findSpot 自动找位;拖完抑制随后的 click(不会插两次)
- window + 捕获阶段监听:面板 .iwb-fullmask 的 stopPropagation 拦不住
- 详情重绘前摘掉旧监听(否则每选一次卡片叠 3 个 window 监听)
- harness 补 7 条断言(幽灵卡片 / pointer-events / 世界坐标换算 / 只插一次 / 画布外取消)
2026-11-02 21:01:36 +08:00

1096 lines
49 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.
// 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); }
/* 按住按钮往外拖 = 拖拽插入:按钮本体压暗,光标下跟一个幽灵卡片 */
.iwb-ss-btn { user-select: none; -webkit-user-select: none; touch-action: none; }
.iwb-ss-btn.is-dragging { opacity: .5; }
.iwb-ss-ghost {
position: fixed; z-index: 2147483000; left: 0; top: 0; pointer-events: none;
padding: 5px 10px; border-radius: 6px; font-size: 12px; line-height: 1.2;
font-family: inherit; white-space: nowrap;
background: rgba(22, 26, 34, .88); color: #fff;
border: 1px dashed rgba(255, 255, 255, .55);
transform: translate(-2px, -2px);
}
.iwb-ss-ghost.is-over { background: var(--iwb-brand, #6b7280); border-style: solid; }
/* 分类 chips:按面板宽度自动换行。
以前是单行横向滚动(scrollbar 又藏起来了):面板拖窄/拖宽时右边那几类永远看不见,用户以为只有 7 个分类。
现在交给 flex-wrap 排布 —— 宽档一行放完,窄档自然折成两三行,全部可见。
min-width:0 仍要留着:chips 的 max-content 近 950px,不允许收缩就会把祖先容器顶宽。 */
.iwb-ss-chips {
flex: 0 0 auto; display: flex; flex-wrap: wrap; align-content: flex-start;
gap: 4px; padding: 0 10px 7px;
min-width: 0; max-width: 100%;
}
.iwb-ss-chip {
flex: 0 1 auto; display: inline-flex; align-items: center; min-width: 0; max-width: 100%;
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-chipname { overflow: hidden; text-overflow: ellipsis; }
.iwb-ss-chipn { flex: 0 0 auto; margin-left: 4px; opacity: .6; }
/* 窄档(侧栏 240~480)不显示数量:13 个分类带上数字要折成 4 行,白吃掉 100px 高度;只留分类名能少一行 */
.iwb-ss-root[data-layout="narrow"] .iwb-ss-chipn { display: none; }
.iwb-ss-root[data-layout="narrow"] .iwb-ss-chip { padding: 0 7px; }
.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; }
/* 宽档详情栏:占 40%,上下限 300~380。上限不能再大 —— 详情是「停下来看」的动作,
栅格才是浏览主体;面板拉到 1040 时留 380 给详情,栅格能到 660(5 列),否则少一列。
min-width:0 必须有:flex 子项默认 min-width:auto,内容(长标签 / 按钮文字)会把栏撑出右边缘,
表现为「插入提示词」按钮最后一个字被裁在面板外。 */
.iwb-ss-root[data-layout="wide"] .iwb-ss-detail { display: flex; flex: 0 0 40%; min-width: 300px; 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; min-width: 0; height: 30px; padding: 0 6px; overflow: hidden; text-overflow: ellipsis; }
/* 预览图比例差异极大(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;
}
/* 提示词里有 {X}、但数据里没声明变量 ⇒ 标签只能用占位符名,压暗一点做区分 */
.iwb-ss-varlabel.is-implicit { opacity: .62; font-style: italic; }
.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) { /* 样式注入失败不影响功能,只是丑一点 */ }
}
// ---------------- 长提示词:节点内滚动,不让节点越拉越长 ----------------
//
// 宿主 renderPromptBody 用 autoGrow 把 textarea 高度直接设成 scrollHeight(无上限),
// 所以一条 1500 字的风格提示词插进画布会变成一根两米高的柱子,一张卡就吃掉整个视口。
// 宿主里 prompt/textout/plugin 用的都是 .iwb-textarea-plain,这里给这类文本域加一个 max-height:
// · 不再增长 ⇒ 节点尺寸固定(≈ max-height + 内边距),一眼能看出插了几张卡;
// · 宿主 .iwb-textarea 本身是 overflow-y:auto,超出部分在节点内滚动,内容一个字都不丢;
// · 想看全文照旧用节点气泡的「放大编辑」(⌘/Ctrl+E),那里是不限高的浮层。
// 选择器只碰节点内的纯文本域,宿主的弹窗/设置面板(.iwb-modal-lg .iwb-textarea)不受影响。
//
// ⚠️ 必须排除 `.iwb-node-fixed`(节点 h 有值 = 用户手动拉过尺寸):
// 宿主 style.css 里有 `.iwb-node-fixed .iwb-textarea{flex:1 1 auto;max-height:none;height:auto!important}`,
// 手拉节点时靠它把文本域撑满节点。原来不加 :not() 时两条规则特异性同为 (0,2,0),
// 而插件样式注入得更晚 ⇒ 上限赢了 ⇒ 节点被拉高后文字仍卡在 240px、下面一片空白(2026-11-02 反馈)。
const PROMPT_MAX_H = 240
function capHeightOf(ctx) {
let raw = ''
try { raw = ctx.settings.get('promptMaxH') } catch (error) { raw = '' }
const num = Math.round(Number(raw))
if (!Number.isFinite(num) || num <= 0) return PROMPT_MAX_H
return Math.max(120, Math.min(800, num))
}
function ensureNodeCapStyle(ctx) {
const id = 'iwb-ss-nodecap'
const maxH = capHeightOf(ctx)
let node = document.getElementById(id)
try {
if (!node) {
node = el('style', { id: id })
;(document.head || document.documentElement).appendChild(node)
}
// 默认(自动高)节点压住上限;手动拉过尺寸的节点交给宿主拉伸规则,一个字都不裁
node.textContent = '.iwb-node:not(.iwb-node-fixed) .iwb-textarea-plain{max-height:' + maxH + 'px}'
+ '.iwb-node.iwb-node-fixed .iwb-textarea-plain{max-height:none}'
} 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
}
// ---------------- 变量 ----------------
//
// **判断依据只有一个:提示词里真实出现的 `{占位符}`**。插入时替换的就是文本里的这个东西,
// 所以「数据里声明了、提示词里没有」的变量填了也不生效(线上 970 条变量里 625 条属于这种),
// 以前按声明表生成输入框,于是有的风格一堆输入框全是摆设、有的干脆一个都没有。
//
// style.variables 现在只用来给占位符配一个好看的中文标签,两种写法都兼容:
// { 诗词: '{诗词}' } ← 新写法:值是占位符本体(带花括号)
// { '`SUBJECT`': 'main subject' } ← 老导入数据:值是人话,只能拿 key 兜底(key 上还残留反引号)
const PH_RE = /\{([^{}\n]{1,40})\}/g
// 变量全部平铺,不做折叠:折叠按钮的"收起"状态容易让人以为变量就这些
// 排掉 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 = []
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(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 : {}
// desc 是「这条变量该怎么填」的说明(数据仓 styles.json 的 variable_descs),
// 按 kv_var 索引;要转到占位符名上才能和 names 对上
const descs = (style && style.variable_descs && typeof style.variable_descs === 'object') ? style.variable_descs : {}
const labelOf = {}
const descOf = {}
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
if (hit && !descOf[hit]) {
const text = String(descs[key] == null ? '' : descs[key]).trim()
if (text) descOf[hit] = text
}
}
const declared = []
const implicit = []
for (const name of names) {
const item = {
name: name,
label: labelOf[name] || name.replace(/[_-]+/g, ' ').trim() || name,
desc: descOf[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) || '')
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)
})
}
// ---------------- 插画布 ----------------
// 位置一律交给宿主:createNode / createImageNode 收到空坐标时走宿主 findSpot()
// (视口中心起螺旋扫空位、跳过已有节点、钳在视口内)。
// 插件这边只拿得到节点 x/y,没有 pan/zoom 也没有各节点实测高度 —— 自己排必然插到看不见的地方或压住节点。
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()
ensureNodeCapStyle(ctx)
host.innerHTML = ''
// ⚠️ 宿主给的面板容器 .iwb-full-panel-plugin 是裸 div,没任何样式,flex 子项默认 flex:0 1 auto:
// ① min-width auto + 13 个分类 chips 单行不换行(max-content≈950px)⇒ 容器被顶宽,右侧被裁;
// ② 反过来,父容器(.iwb-full-main,display:flex)宽 1040 时它只按**内容宽度**占 664,
// 插件的 width:100% 只能等于 664 ⇒ 右边留一大片空白(用户拉宽窗口后最明显)。
// 所以两件事都要做:允许收缩(min-width:0)+ 明确占满剩余空间(flex:1 1 0%,basis 0 才不吃内容宽度)。
// ⚠️ 但只在「自身没有显式宽度 + 父容器是 flex row」时才设 flex:宿主侧栏里容器可能带固定宽度,
// 无条件 flex:1 会把它拉到父容器满宽(2026-11-02 之前的坑)。
host.style.minWidth = '0'
host.style.minHeight = '0'
host.style.height = '100%'
host.style.overflow = 'hidden'
try {
const parent = host.parentElement
const cs = parent && global.getComputedStyle ? global.getComputedStyle(parent) : null
const isRow = cs && cs.display.indexOf('flex') >= 0 && /^row/.test(String(cs.flexDirection || ''))
if (isRow && !host.style.width) host.style.flex = '1 1 0%'
} catch (error) { /* 拿不到父容器样式就维持原生行为 */ }
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, justDragged: false,
}
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, at) {
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
// at = 拖拽松手点(世界坐标);不传 ⇒ 宿主 findSpot 找位
const payload = {
dataUrl: dataUrl,
name: String(style.code || 'style') + '_' + String(style.name || ''),
}
if (at && Number.isFinite(at.x) && Number.isFinite(at.y)) { payload.x = at.x; payload.y = at.y }
const id = api.createImageNode(payload)
if (!id) throw new Error('画布拒绝了这张图(data URL 无效)')
toast('已插入参考图')
} catch (error) {
toast('插图失败:' + readErr(error))
} finally {
busy(false)
}
}
function insertPrompt(style, at) {
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 }
// 不传坐标(点击):null/null ⇒ 宿主走 findSpot(视口中心 + 避开已有节点 + 避开浮层)
// 传了坐标(拖拽松手):直接落在松手点
const dropAt = (at && Number.isFinite(at.x) && Number.isFinite(at.y)) ? { x: at.x, y: at.y } : null
const id = dropAt ? api.createNode('prompt', dropAt.x, dropAt.y, { text: text }) : api.createNode('prompt', null, null, { text: text })
if (!id) { toast('插入失败:prompt 节点类型未注册'); return }
const left = unfilledCount(style, values)
// 超过最大高度就会在节点内滚动:说一声,免得用户以为内容被截掉了
const capped = text.split('\n').reduce((n, line) => n + Math.max(1, Math.ceil(line.length / 24)), 0) * 19 > capHeightOf(ctx)
const tail = capped ? ',长内容在节点内滚动(⌘E 看全文)' : ''
toast((left ? '已插入提示词(还有 ' + left + ' 个变量没填)' : '已插入提示词') + tail)
}
// ---- 拖拽插入:按住按钮 → 拖到画布上松手 → 节点落在松手位置 ----
//
// 为什么要有第二套交互:点击插入只能由宿主 findSpot 猜位置(视口中心、避开已有节点与浮层),
// 但"我想放在这里"是宿主猜不出来的。拖拽把落点交回给用户:松手点即节点左上角。
//
// 关键约束:
// · 插件面板在 .iwb-fullmask 里,宿主在 mask 上挂了 onPointerDown/Move 并 stopPropagation
// ⇒ 监听必须挂在 window 且用**捕获阶段**,否则事件到不了插件;
// · 屏幕 → 世界坐标只能问宿主(pan/zoom 在它手里):ctx.canvas.screenToWorld;
// · 松手点不在画布上(比如还在面板里)⇒ 取消,不建节点;
// · 位移不足阈值 ⇒ 视为点击,走原来的 findSpot 路径(click 与拖拽并存)。
const DRAG_MIN = 6
const dragHooks = []
function clearDragHooks() {
for (const fn of dragHooks.splice(0)) { try { fn() } catch (error) { /* 忽略 */ } }
}
function overCanvas(clientX, clientY) {
try {
const hit = document.elementFromPoint(clientX, clientY)
return !!(hit && hit.closest && hit.closest('.iwb-canvas'))
} catch (error) { return false }
}
function attachDragInsert(btn, label, drop) {
const api = ctx.canvas
// 旧宿主没有 screenToWorld ⇒ 只有点击插入(功能不倒退)
if (!api || typeof api.screenToWorld !== 'function') return
let drag = null
const cleanup = () => {
if (drag && drag.ghost && drag.ghost.parentNode) drag.ghost.parentNode.removeChild(drag.ghost)
btn.classList.remove('is-dragging')
drag = null
}
btn.addEventListener('pointerdown', (event) => {
if (event.button !== 0 || ui.busy || btn.disabled) return
drag = { id: event.pointerId, sx: event.clientX, sy: event.clientY, moved: false, ghost: null }
})
const onMove = (event) => {
if (!drag || event.pointerId !== drag.id) return
if (!drag.moved) {
if (Math.abs(event.clientX - drag.sx) + Math.abs(event.clientY - drag.sy) < DRAG_MIN) return
drag.moved = true
drag.ghost = el('div', { class: 'iwb-ss-ghost', text: '拖到画布上松手' })
document.body.appendChild(drag.ghost)
btn.classList.add('is-dragging')
// 指针捕获:拖出窗口外也能收到 pointerup(失败不影响 —— window 捕获监听仍在)
try { btn.setPointerCapture(event.pointerId) } catch (error) { /* 忽略 */ }
}
const over = overCanvas(event.clientX, event.clientY)
drag.ghost.style.left = event.clientX + 'px'
drag.ghost.style.top = event.clientY + 'px'
drag.ghost.classList.toggle('is-over', over)
drag.ghost.textContent = over ? label + '(松手放这里)' : '拖到画布上松手'
}
const onUp = (event) => {
if (!drag || event.pointerId !== drag.id) return
if (!drag.moved) { drag = null; return }
const over = overCanvas(event.clientX, event.clientY)
const world = over ? api.screenToWorld(event.clientX, event.clientY) : null
cleanup()
if (!over || !world) { toast('松手位置不在画布上,已取消'); return }
// 抑制紧随其后的 click(松手又回到按钮上时浏览器仍会派发 click ⇒ 否则会插入两次)
ui.justDragged = true
global.setTimeout(() => { ui.justDragged = false }, 400)
drop(world)
}
const onCancel = () => { if (drag && drag.moved) toast('已取消'); cleanup() }
// 捕获阶段 + window:面板的 stopPropagation 拦不住,且拖到画布上仍收得到
global.addEventListener('pointermove', onMove, true)
global.addEventListener('pointerup', onUp, true)
global.addEventListener('pointercancel', onCancel, true)
dragHooks.push(() => {
global.removeEventListener('pointermove', onMove, true)
global.removeEventListener('pointerup', onUp, true)
global.removeEventListener('pointercancel', onCancel, true)
})
}
// ---- 渲染 ----
// 名称与数量拆成两个 span:窄档只藏数量(.iwb-ss-chipn 在 CSS 里 display:none),
// 名称单独 overflow:hidden 才能在极端窄的时候省略号收尾而不是把 chip 撑出面板
function chipNode(text, count, on, title, active) {
return el('button', {
class: 'iwb-ss-chip' + (active ? ' is-on' : ''),
title: title || (text + ' ' + count),
onClick: on,
}, [
el('span', { class: 'iwb-ss-chipname', text: text }),
el('span', { class: 'iwb-ss-chipn', text: String(count) }),
])
}
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(chipNode('全部', all.length, () => {
CACHE.cat = 'all'; prefSet('cat', 'all'); renderAll()
}, '全部', CACHE.cat === 'all'))
for (const key of keys) {
ui.chips.appendChild(chipNode(catName(key), counts[key], () => {
CACHE.cat = key; prefSet('cat', key); renderAll()
}, key, CACHE.cat === key))
}
}
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() {
clearDragHooks() // 详情重绘会换掉两个按钮 ⇒ 先摘掉旧按钮的拖拽监听(否则每次选中都叠 3 个 window 监听)
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', {})
const rowOf = (item) => el('div', { class: item.desc ? 'iwb-ss-var has-desc' : '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',
// 占位符名放 data 属性:placeholder 会被 desc 占用,测试和排错都靠这个稳定取值
'data-var-name': item.name,
// 有 desc 就用它做占位提示(灰色、输入后消失),比英文占位符名有用;
// 完整的 desc 挂在 title 上,太长的在这里能看全
placeholder: item.desc || item.name,
title: item.desc || '',
value: String(values[item.name] || ''),
onInput: (event) => { values[item.name] = event.target.value; refreshPreview() },
}),
])
// 全部平铺(Vigo 那批最多 24 个,详情页本身可滚动,不再折叠)
for (const item of keys) varBox.appendChild(rowOf(item))
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: '插入参考图',
title: '点击:自动找位置插入参考图;按住拖到画布上松手:放在你指定的位置',
onClick: () => { if (ui.justDragged) return; insertImage(style) },
})
const style0 = style
ui.btnPrompt = el('button', {
class: 'iwb-ss-btn is-key', text: '插入提示词',
title: '点击:自动找位置插入提示词;按住拖到画布上松手:放在你指定的位置。内容按「最大高度」截断显示,节点内可滚动,全文用气泡「放大编辑」⌘E 查看',
onClick: () => { if (ui.justDragged) return; insertPrompt(style0) },
})
attachDragInsert(ui.btnRef, '参考图', (at) => insertImage(style0, at))
attachDragInsert(ui.btnPrompt, '提示词', (at) => insertPrompt(style0, at))
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 }
clearDragHooks()
ui.seq++
},
}
INSTANCES.set(host, instance)
ensureData()
}
// ---------------- 注册 ----------------
global.IWBPluginHost.register({
id: 'style-source',
name: '风格库',
version: '1.2.0',
apiVersion: 1,
capabilities: ['panels', 'canvas', 'canvasWrite'],
settings: {
dataUrl: {
type: 'text',
label: '风格数据地址',
desc: 'styles.json 的地址。默认直连 GitHub Pages;国内慢可自行镜像后改这里。',
default: DEFAULT_DATA,
},
promptMaxH: {
type: 'text',
label: '文本节点最大高度(px)',
desc: '提示词超过这个高度就不再撑高节点,改为节点内滚动(120~800)。想看全文用节点气泡的「放大编辑」⌘E。留空 = 240。',
default: String(PROMPT_MAX_H),
},
},
}, 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)