1441 lines
68 KiB
JavaScript
1441 lines
68 KiB
JavaScript
// 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: color-mix(in srgb, var(--iwb-text, #1c2333) 88%, transparent); color: var(--iwb-on-brand, #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: color-mix(in srgb, var(--iwb-text, #1c2333) 90%, transparent); color: var(--iwb-on-brand, #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); }
|
||
|
||
/* ─────────── 样式节点(画布内的节点体,v1.3.0 / 2026-11-14)───────────
|
||
宿主把这一块交给插件自己画(.iwb-plugin-node-body 不含内边距),所以这里的 padding 是唯一的内边距。
|
||
宽度以宿主节点默认宽 264 为基准:264 − 24(padding) = 240 内容宽。 */
|
||
.iwb-ssn { display: flex; flex-direction: column; gap: 9px; padding: 10px 12px; color: var(--iwb-text, #1f2430); font-size: 12px; box-sizing: border-box; }
|
||
.iwb-ssn-top { display: flex; align-items: flex-start; gap: 9px; }
|
||
.iwb-ssn-thumb {
|
||
width: 56px; height: 56px; flex: 0 0 auto; border-radius: 7px; object-fit: cover;
|
||
background: var(--iwb-layer, #f0f1f4); border: 1px solid var(--iwb-border, #d5d9e0);
|
||
}
|
||
.iwb-ssn-thumb.is-empty { display: flex; align-items: center; justify-content: center; font-size: 10px; color: var(--iwb-text2, #6b7280); }
|
||
.iwb-ssn-meta { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; gap: 4px; }
|
||
.iwb-ssn-name { font-size: 12.5px; font-weight: 600; line-height: 1.25; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||
.iwb-ssn-code { font-size: 10.5px; color: var(--iwb-text2, #6b7280); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; letter-spacing: .02em; }
|
||
/* 参考图开关:整行可点(不要求精准点那个小方框 —— 节点在画布上常被缩放) */
|
||
.iwb-ssn-ref {
|
||
display: flex; align-items: center; gap: 6px; margin-top: 1px; padding: 3px 6px; border-radius: 6px;
|
||
background: var(--iwb-layer, #f0f1f4); cursor: pointer; user-select: none;
|
||
font-size: 11px; color: var(--iwb-text2, #4d5668);
|
||
}
|
||
.iwb-ssn-ref input { margin: 0; flex: 0 0 auto; cursor: pointer; }
|
||
.iwb-ssn-ref > span { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||
.iwb-ssn-ref > em { flex: 0 0 auto; font-style: normal; opacity: .75; font-size: 10px; }
|
||
.iwb-ssn-ref.is-on { background: color-mix(in srgb, var(--iwb-brand, #1677ff) 14%, transparent); color: var(--iwb-brand, #1677ff); }
|
||
.iwb-ssn-ref.is-off { opacity: .72; }
|
||
.iwb-ssn-toggle {
|
||
flex: 0 0 auto; width: 22px; height: 22px; padding: 0; margin: 0; border: 0; border-radius: 6px;
|
||
background: transparent; color: var(--iwb-text2, #6b7280); cursor: pointer; line-height: 1;
|
||
display: inline-flex; align-items: center; justify-content: center; font-size: 13px;
|
||
}
|
||
.iwb-ssn-toggle:hover { background: var(--iwb-layer, #f0f1f4); color: var(--iwb-text, #1f2430); }
|
||
/* 变量行:label 左、输入右,一行 28px。
|
||
早期草稿是「label 一行 + 输入一行」= 56px/个,Vigo 那批 24 个变量就是 1344px —— 画布上没法看。
|
||
单行布局把同样的信息压到 32px/行(含 gap),不删任何字段。 */
|
||
.iwb-ssn-vars { display: flex; flex-direction: column; gap: 4px; }
|
||
.iwb-ssn-vars.is-hidden { display: none; }
|
||
.iwb-ssn-row { display: flex; align-items: center; gap: 8px; height: 28px; }
|
||
.iwb-ssn-row > label {
|
||
flex: 0 0 72px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||
font-size: 11.5px; color: var(--iwb-text2, #4d5668);
|
||
}
|
||
.iwb-ssn-row > label.is-implicit { opacity: .68; }
|
||
.iwb-ssn-row > input {
|
||
flex: 1 1 auto; min-width: 0; height: 26px; padding: 0 7px; box-sizing: border-box;
|
||
border-radius: 6px; border: 1px solid var(--iwb-border, #d5d9e0);
|
||
background: var(--iwb-bg, #fff); color: inherit; font: inherit; font-size: 11.5px;
|
||
}
|
||
.iwb-ssn-row > input:focus { outline: none; border-color: var(--iwb-brand, #1677ff); }
|
||
.iwb-ssn-row > input::placeholder { color: var(--iwb-text2, #6b7280); opacity: .6; }
|
||
.iwb-ssn-foot { display: flex; align-items: center; gap: 6px; font-size: 10.5px; color: var(--iwb-text2, #6b7280); }
|
||
.iwb-ssn-warn { color: var(--iwb-warn, #d97706); }
|
||
.iwb-ssn-empty { padding: 6px 2px; font-size: 11px; color: var(--iwb-text2, #6b7280); line-height: 1.6; }
|
||
`
|
||
|
||
function ensureStyle() {
|
||
const id = 'iwb-ss-style'
|
||
if (typeof document === 'undefined' || !document.createElement) return
|
||
if (document.getElementById(id)) return
|
||
try {
|
||
;(document.head || document.documentElement).appendChild(el('style', { id: id, text: CSS }))
|
||
} catch (error) { /* 样式注入失败不影响功能,只是丑一点 */ }
|
||
}
|
||
|
||
// v1.3.2(2026-11-14,同一事故的第三次):样式在**脚本执行时**就注入,不等 setup,更不等面板 mount。
|
||
// 1.3.0 只在 mount() 里注入 —— 从存档直接进画布(面板从不 mount)时节点体是无样式裸 DOM,
|
||
// `<img class="iwb-ssn-thumb">` 按原图尺寸铺满节点,就是用户看到的「图片都跑出来了 / 样式坏了」。
|
||
// 1.3.1 把注入提前到 setup,但发布链路只上传了字节、清单没换(线上仍是 1.3.0),等于没修。
|
||
// 现在三层兜底:脚本执行(这里)→ setup → renderStyleNode。
|
||
ensureStyle()
|
||
|
||
// ---------------- 长提示词:节点内滚动,不让节点越拉越长 ----------------
|
||
//
|
||
// 宿主 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
|
||
}
|
||
|
||
// ---------------- 样式节点(模块级:注册时就要拿到 render,不能藏在 mount 里)----------------
|
||
// ---- 样式节点(v1.3.0 / 2026-11-14)----
|
||
//
|
||
// 和「插入提示词」的本质区别:那个落一个纯 prompt 节点,文本一落地就和风格库脱钩 ——
|
||
// 认不出是哪条风格、改一个词只能删了重插。样式节点把这些一起带上(随画布存档):
|
||
// styleId / name / code 来源三件套(一张画布上常有七八个样式节点,靠它分辨)
|
||
// promptTpl 原始模板(库里模板以后更新,也不会偷偷改掉老画布)
|
||
// varMeta / vars / text 变量结构 + 用户填的值 + 渲染结果
|
||
// outKind = 'prompt' 宿主连线白名单据此把它当提示词节点(可连 gen / combine / batch / llm / prompt)
|
||
// refOn / refUrl 示例图作参考,走 URL(宿主本来就支持 url 型参考图,不必转 base64)
|
||
//
|
||
// ⚠️ 节点上**没有生成按钮**,这是用户 2026-11-14 明确定的:样式节点只负责「把变量填进模板」,
|
||
// 出图一律交给下游生图节点(它自己已经处理了四家渠道差异、尺寸收敛、并发与恢复)。
|
||
const STYLE_NODE_TYPE = 'plugin:style-source:style'
|
||
|
||
// 节点自带模板,不能再走 varKeys(style)(那要整条 styles.json 记录)。
|
||
// 语义与 applyVars 完全一致:只替换「用户真填了的」,留空的保留 {原样}
|
||
// —— 替换成空串会把提示词结构弄丢,用户看不出漏了什么。
|
||
function fillTpl(tpl, vars) {
|
||
let text = String(tpl || '')
|
||
const v = vars || {}
|
||
for (const name of Object.keys(v)) {
|
||
const val = String(v[name] == null ? '' : v[name]).trim()
|
||
if (!val) continue
|
||
text = text.split('{' + name + '}').join(val)
|
||
}
|
||
return text
|
||
}
|
||
|
||
// 宿主契约:插件节点的 render(node, props, host) 是**往 host 这个真实 DOM 里画**,不是返回 vDOM。
|
||
// host 跨渲染稳定(宿主用固定 div 承载,见 app.js 的 PluginDomBody)—— 这正是为了不重建 DOM:
|
||
// 变量输入框一旦被重建,每敲一个字就会失焦。
|
||
// 所以这里做「建一次骨架 + 之后只同步值」。
|
||
function renderStyleNode(node, props, host) {
|
||
// 兜底:万一节点体先于 setup 渲染(宿主注册表现在支持「注册后立刻重画」),
|
||
// 这一句保证样式一定在 —— 少一次注入就是「缩略图铺满节点」那种事故。
|
||
ensureStyle()
|
||
let st = host.__ssn
|
||
if (!st) {
|
||
host.textContent = ''
|
||
st = host.__ssn = buildStyleNodeSkeleton(host)
|
||
}
|
||
st.node = node
|
||
st.props = props
|
||
syncStyleNode(st, (node && node.data) || {})
|
||
}
|
||
|
||
function buildStyleNodeSkeleton(host) {
|
||
const thumb = el('img', { class: 'iwb-ssn-thumb', alt: '', loading: 'lazy', draggable: 'false' })
|
||
thumb.addEventListener('error', () => { thumb.style.display = 'none' })
|
||
thumb.addEventListener('load', () => { thumb.style.display = '' })
|
||
// 内联兜底(v1.3.2):`.iwb-ssn-thumb` 的 56px 如果因为样式表缺失/被覆盖没生效,
|
||
// 浏览器会按图片**原始尺寸**铺开 —— 一张 1024px 的示例图足以把节点撑爆。
|
||
// 这里用行内样式钉死尺寸:样式表正常时两者取值相同(零视觉差异),样式表失效时至少不炸。
|
||
thumb.style.width = '56px'
|
||
thumb.style.height = '56px'
|
||
thumb.style.flex = '0 0 auto'
|
||
thumb.style.objectFit = 'cover'
|
||
thumb.style.borderRadius = '7px'
|
||
const nameEl = el('div', { class: 'iwb-ssn-name' })
|
||
const codeEl = el('div', { class: 'iwb-ssn-code' })
|
||
const refChk = el('input', { type: 'checkbox' })
|
||
const refTxt = el('span', {})
|
||
const refNum = el('em', {})
|
||
const refBox = el('label', { class: 'iwb-ssn-ref' }, [refChk, refTxt, refNum])
|
||
const toggle = el('button', { class: 'iwb-ssn-toggle', type: 'button', text: '⌃' })
|
||
const varsBox = el('div', { class: 'iwb-ssn-vars' })
|
||
const foot = el('div', { class: 'iwb-ssn-foot' })
|
||
const root = el('div', { class: 'iwb-ssn' }, [
|
||
el('div', { class: 'iwb-ssn-top' }, [
|
||
thumb,
|
||
el('div', { class: 'iwb-ssn-meta' }, [nameEl, codeEl, refBox]),
|
||
toggle,
|
||
]),
|
||
varsBox,
|
||
foot,
|
||
])
|
||
host.appendChild(root)
|
||
|
||
const st = { root: root, thumb: thumb, nameEl: nameEl, codeEl: codeEl, refBox: refBox, refChk: refChk, refTxt: refTxt, refNum: refNum, toggle: toggle, varsBox: varsBox, foot: foot, rows: {}, varSig: '', footSig: '', timer: null, draft: null, node: null, props: null }
|
||
|
||
// 收起 / 展开:写回 data.collapsed(随存档走),节点高度由宿主实测,不锁 n.h
|
||
toggle.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||
toggle.addEventListener('click', (e) => {
|
||
e.stopPropagation(); e.preventDefault()
|
||
if (!st.node || !st.props) return
|
||
st.props.onUpdate(st.node.id, { collapsed: !(st.node.data && st.node.data.collapsed) })
|
||
})
|
||
|
||
// 参考图开关:只切换 refOn,不增删任何节点(所以取消勾选不会在画布上留孤儿)
|
||
refChk.addEventListener('change', () => {
|
||
if (!st.node || !st.props) return
|
||
const on = Boolean(refChk.checked)
|
||
st.props.onUpdate(st.node.id, { refOn: on })
|
||
st.refBox.classList.toggle('is-on', on)
|
||
st.refBox.classList.toggle('is-off', !on)
|
||
st.refTxt.textContent = on ? '示例图作参考' : '示例图不作参考'
|
||
st.refNum.textContent = on ? '1 张' : '0'
|
||
})
|
||
return st
|
||
}
|
||
|
||
function commitStyleVars(st) {
|
||
if (!st.draft) return
|
||
const vars = Object.assign({}, st.draft)
|
||
st.draft = null
|
||
const tpl = String((st.node.data && st.node.data.promptTpl) || '')
|
||
// vars 与 text 必须**同一次** onUpdate 写回:分开写会出现「界面填了新词、生图拿的旧词」
|
||
st.props.onUpdate(st.node.id, { vars: vars, text: fillTpl(tpl, vars) })
|
||
}
|
||
|
||
function syncStyleNode(st, d) {
|
||
const name = String(d.name || '')
|
||
const nameText = name || '(未命名风格)'
|
||
if (st.nameEl.textContent !== nameText) st.nameEl.textContent = nameText
|
||
st.nameEl.title = nameText
|
||
const codeText = String(d.code || d.styleId || '')
|
||
if (st.codeEl.textContent !== codeText) st.codeEl.textContent = codeText
|
||
st.codeEl.title = codeText
|
||
|
||
const preview = String(d.preview || '')
|
||
if (st.thumb.dataset.src !== preview) {
|
||
st.thumb.dataset.src = preview
|
||
if (preview) { st.thumb.style.display = ''; st.thumb.style.visibility = ''; st.thumb.src = preview } else {
|
||
// 没有预览图时**整块不占位**(display:none 而不是 visibility:hidden):
|
||
// 留 56px 空白会让名称和编号无缘无故右移,看起来像排版错位
|
||
st.thumb.removeAttribute('src')
|
||
st.thumb.style.display = 'none'
|
||
}
|
||
}
|
||
|
||
const hasRef = !!String(d.refUrl || '').trim()
|
||
const on = d.refOn === true && hasRef
|
||
if (st.refChk.checked !== on) st.refChk.checked = on
|
||
// 没有示例图就别让人点了还以为是开关坏了:直接禁用并说明原因
|
||
if (st.refChk.disabled !== !hasRef) st.refChk.disabled = !hasRef
|
||
st.refBox.classList.toggle('is-on', on)
|
||
st.refBox.classList.toggle('is-off', !on)
|
||
const refLabel = on ? '示例图作参考' : '示例图不作参考'
|
||
if (st.refTxt.textContent !== refLabel) st.refTxt.textContent = refLabel
|
||
const refCount = on ? '1 张' : '0'
|
||
if (st.refNum.textContent !== refCount) st.refNum.textContent = refCount
|
||
st.refBox.title = on
|
||
? '出图时会带上这张示例图(在生图节点的参考图区能看到它)'
|
||
: (hasRef ? '当前只输出提示词,不带这张图;勾上就会带上' : '这条风格没有示例图,无法作参考')
|
||
|
||
const collapsed = d.collapsed === true
|
||
st.varsBox.classList.toggle('is-hidden', collapsed)
|
||
const toggleText = collapsed ? '⌄' : '⌃'
|
||
if (st.toggle.textContent !== toggleText) st.toggle.textContent = toggleText
|
||
st.toggle.title = collapsed ? '展开变量' : '收起变量'
|
||
|
||
const meta = Array.isArray(d.varMeta) ? d.varMeta : []
|
||
const sig = meta.map((m) => m.n).join('\u0000')
|
||
if (sig !== st.varSig) {
|
||
st.varSig = sig
|
||
st.varsBox.textContent = ''
|
||
st.rows = {}
|
||
if (!meta.length) {
|
||
st.varsBox.appendChild(el('div', { class: 'iwb-ssn-empty', text: '这条风格的提示词没有变量,直接连到生图节点即可。' }))
|
||
} else {
|
||
for (const m of meta) st.varsBox.appendChild(buildVarRow(st, m))
|
||
}
|
||
}
|
||
|
||
// 值同步:正在编辑的那个输入框不覆盖(否则光标跳到末尾,等于打断输入)
|
||
const vars = d.vars || {}
|
||
for (const m of meta) {
|
||
const input = st.rows[m.n]
|
||
if (!input) continue
|
||
if (input === document.activeElement) continue
|
||
const cur = String(vars[m.n] == null ? '' : vars[m.n])
|
||
if (input.value !== cur) input.value = cur
|
||
}
|
||
|
||
const total = meta.length
|
||
const left = meta.filter((m) => !String(vars[m.n] == null ? '' : vars[m.n]).trim()).length
|
||
const footText = !total ? '无变量' : (left ? '还有 ' + left + ' 个变量没填(留空的保留 {原样})' : '变量已填完 · 连到生图节点即可出图')
|
||
const footSig = footText + '|' + (left ? 'warn' : 'ok')
|
||
if (st.footSig !== footSig) {
|
||
st.footSig = footSig
|
||
st.foot.textContent = ''
|
||
st.foot.appendChild(el('span', { class: left ? 'iwb-ssn-warn' : '', text: footText }))
|
||
}
|
||
}
|
||
|
||
function buildVarRow(st, m) {
|
||
const label = el('label', { text: String(m.l || m.n), title: String(m.l || m.n) + (m.d ? ':' + m.d : '') })
|
||
if (!m.x) label.classList.add('is-implicit') // 数据里没声明过的变量:标签就是占位符名,弱化一点
|
||
const input = el('input', {
|
||
type: 'text',
|
||
placeholder: String(m.d || ('{' + m.n + '}')),
|
||
spellcheck: 'false',
|
||
autocomplete: 'off',
|
||
title: String(m.d || ('留空则保留 {' + m.n + '}')),
|
||
})
|
||
input.value = ''
|
||
// 画布上:点输入框是「编辑」,不能顺带拖动节点
|
||
input.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||
input.addEventListener('input', () => {
|
||
if (!st.draft) st.draft = Object.assign({}, (st.node && st.node.data && st.node.data.vars) || {})
|
||
st.draft[m.n] = input.value
|
||
if (st.timer) global.clearTimeout(st.timer)
|
||
// 300ms 防抖:每敲一个字符就 onUpdate,会让整张图的 graphCacheKey 失效十几次、撤销历史也炸掉
|
||
st.timer = global.setTimeout(() => { st.timer = null; commitStyleVars(st) }, 300)
|
||
})
|
||
input.addEventListener('blur', () => {
|
||
if (st.timer) { global.clearTimeout(st.timer); st.timer = null }
|
||
commitStyleVars(st)
|
||
})
|
||
input.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); input.blur() } })
|
||
st.rows[m.n] = input
|
||
return el('div', { class: 'iwb-ssn-row' }, [label, input])
|
||
}
|
||
|
||
// 插件卸载 / 节点体被 LOD 替换时清掉定时器(宿主会在 host 卸载时调这里)
|
||
renderStyleNode.dispose = function (host) {
|
||
const st = host && host.__ssn
|
||
if (st && st.timer) global.clearTimeout(st.timer)
|
||
if (host) host.__ssn = null
|
||
}
|
||
|
||
// ---------------- 面板实例 ----------------
|
||
// 每个 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)
|
||
}
|
||
|
||
|
||
function insertStyleNode(style, at) {
|
||
const api = ctx.canvas
|
||
if (!api || typeof api.createNode !== 'function') { toast('当前宿主不支持插入节点(缺 canvasWrite 能力)'); return }
|
||
const vars = Object.assign({}, CACHE.vars[style.id] || {})
|
||
const thumb = thumbOf(style)
|
||
const meta = varKeys(style).map((it) => ({ n: it.name, l: it.label, d: it.desc || '', x: it.declared ? 1 : 0 }))
|
||
const data = {
|
||
variant: 'style', // 宿主的降级兜底:类型没注册时仍认得出这是插件节点
|
||
styleId: String(style.id || ''),
|
||
name: String(style.name || ''),
|
||
code: String(style.code || ''),
|
||
outKind: 'prompt', // 关键标记:让它在连线规则里等同提示词节点
|
||
promptTpl: String(style.prompt || ''),
|
||
varMeta: meta,
|
||
vars: vars,
|
||
text: fillTpl(style.prompt, vars).trim(),
|
||
preview: String(thumb || ''),
|
||
refName: String(style.code || style.id || 'style') + '.png',
|
||
// 默认勾选:风格库的示例图本来就是这条风格的视觉基准,带上出图更贴。
|
||
// 只想要文字时在节点上取消勾选即可 —— 一次点击,不产生/不残留任何节点。
|
||
refOn: Boolean(thumb),
|
||
refUrl: String(thumb || ''),
|
||
collapsed: false,
|
||
}
|
||
const dropAt = (at && Number.isFinite(at.x) && Number.isFinite(at.y)) ? { x: at.x, y: at.y } : null
|
||
const id = dropAt
|
||
? api.createNode(STYLE_NODE_TYPE, dropAt.x, dropAt.y, data)
|
||
: api.createNode(STYLE_NODE_TYPE, null, null, data)
|
||
if (!id) { toast('插入失败:样式节点类型未注册(宿主版本较旧?)'); return }
|
||
const left = meta.filter((m) => !String(vars[m.n] || '').trim()).length
|
||
toast(left ? '已插入样式节点(还有 ' + left + ' 个变量没填)' : '已插入样式节点')
|
||
}
|
||
|
||
// ---- 拖拽插入:按住按钮 → 拖到画布上松手 → 节点落在松手位置 ----
|
||
//
|
||
// 为什么要有第二套交互:点击插入只能由宿主 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;',
|
||
}),
|
||
]))
|
||
}
|
||
|
||
const style0 = style
|
||
// 新增的第三颗(2026-11-14,用户要求「新增一个插入节点的按钮」,不动原来两颗的行为)
|
||
ui.btnStyle = el('button', {
|
||
class: 'iwb-ss-btn', text: '样式节点',
|
||
title: '插入样式节点:带缩略图、变量表单、示例图开关,连到生图节点即可出图(节点本身不带生成按钮)。也可按住拖到画布上指定位置',
|
||
onClick: () => { if (ui.justDragged) return; insertStyleNode(style0) },
|
||
})
|
||
ui.btnRef = el('button', {
|
||
class: 'iwb-ss-btn', text: '插入参考图',
|
||
title: '点击:自动找位置插入参考图;按住拖到画布上松手:放在你指定的位置',
|
||
onClick: () => { if (ui.justDragged) return; insertImage(style) },
|
||
})
|
||
ui.btnPrompt = el('button', {
|
||
class: 'iwb-ss-btn is-key', text: '插入提示词',
|
||
title: '点击:自动找位置插入提示词;按住拖到画布上松手:放在你指定的位置。内容按「最大高度」截断显示,节点内可滚动,全文用气泡「放大编辑」⌘E 查看',
|
||
onClick: () => { if (ui.justDragged) return; insertPrompt(style0) },
|
||
})
|
||
attachDragInsert(ui.btnStyle, '样式节点', (at) => insertStyleNode(style0, at))
|
||
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.btnStyle, 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.3.3',
|
||
apiVersion: 1,
|
||
capabilities: ['panels', 'canvas', 'canvasWrite', 'nodeTypes'],
|
||
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),
|
||
})
|
||
|
||
// 样式节点变体(v1.3.0)。注意能力名是 nodeTypes、但挂在 ctx 上的 key 是 `nodes`
|
||
// (plugin-host.js 的 CAPABILITY_API_KEYS:nodeTypes → 'nodes'),写成 ctx.nodeTypes 会静默失效。
|
||
// 不传 run ⇒ 节点上不会出现「运行」按钮(用户明确要求:出图交给下游生图节点)。
|
||
//
|
||
// v1.3.1(2026-11-14,用户报障「图片都跑出来了」):CSS 原先进在 `mount()` 里 ——
|
||
// 只有打开过「风格库」面板才会注入。但从存档打开画布时,节点体先渲染、面板根本不 mount ⇒
|
||
// 节点里的 `<img class="iwb-ssn-thumb">` 拿不到 56px 约束,按原图尺寸铺满整个节点。
|
||
// 现在在注册变体前就把样式注入(mount 里那次是幂等兜底)。
|
||
ensureStyle()
|
||
if (ctx.nodes && typeof ctx.nodes.register === 'function') {
|
||
ctx.nodes.register({
|
||
id: 'style',
|
||
title: '样式节点',
|
||
defaults: {},
|
||
// 只出不入:宿主任务图的兜底分支是 `children.length ? children : [自己]`,
|
||
// 一旦被连了入边,样式节点自己渲染的提示词就会被上游文本顶掉,用户填的变量全部失效。
|
||
ports: { in: false, out: true },
|
||
height: 360,
|
||
render: renderStyleNode,
|
||
})
|
||
}
|
||
|
||
return {}
|
||
})
|
||
})(typeof window !== 'undefined' ? window : globalThis)
|