diff --git a/gallery/package.json b/gallery/package.json
index 33858c8..066f4a5 100644
--- a/gallery/package.json
+++ b/gallery/package.json
@@ -1,7 +1,7 @@
{
"name": "@iwb-plugin/gallery",
"private": true,
- "version": "1.7.5",
+ "version": "1.9.5",
"description": "图库:右栏图片墙(筛选/多选/预览/插入画布/下载/删除),数据由宿主 gallery 能力提供",
"ibwPlugin": {
"id": "gallery",
diff --git a/gallery/src/index.js b/gallery/src/index.js
index daeeba1..e5a852b 100644
--- a/gallery/src/index.js
+++ b/gallery/src/index.js
@@ -94,6 +94,7 @@
var cfg = Object.assign({}, DEF)
var items = []
var thumbCache = {}
+ var thumbOrder = [] // 缩略图缓存的上限管理(FIFO)
var thumbPending = {} // 进行中的缩略图请求(v1.6.9)
var total = 0
var limit = 100
@@ -339,36 +340,111 @@
settings.appendChild(row('range', RANGES, '时间范围', '按生成时间筛选'))
}
- function renderGrid () {
- clear(grid)
+ // v1.8.3:拖动停靠栏卡顿的根因是「每一帧 ResizeObserver → renderGrid → clear + 重建全部卡片」,
+ // 每张卡要重建 ~10 个节点、重新挂事件、重新 paint 缩略图。改成复用节点:把缓存里的卡片
+ // 直接 appendChild 到新列里(DOM 移动,不销毁),缩略图与事件全部保留。
+ // ── v1.9.0 虚拟列表:200+ 张时只渲染「视口附近」的卡片 ────────────────────
+ // 原来每次重排/滚动都把全部卡片建一遍(200 张 ≈ 2000+ DOM 节点),拖动停靠栏自然掉帧。
+ // 现在:先用「列宽 + 宽高比」纯数学算出每张卡的列与 y 偏移,再只为可见范围建 DOM,
+ // 上下用高度占位块撑住滚动条 —— 滚动位置、滚动条长度都和不虚拟化时一致。
+ var layoutState = null
+ var winState = { top: -1, viewH: 0 }
+ var scrollBound = false
+ var scrollRaf = 0
+
+ // 找到真正滚动的祖先(虚拟列表要按它的 scrollTop/clientHeight 算可见窗口)
+ var scCache = null
+ var padCache = null
+ function scrollerOf () {
+ if (scCache && scCache.isConnected) return scCache
+ padCache = null
+ var p = grid && grid.parentNode
+ while (p && p.nodeType === 1) {
+ var oy = ''
+ try { oy = global.getComputedStyle ? global.getComputedStyle(p).overflowY : '' } catch (e) { oy = '' }
+ if (p.scrollHeight > p.clientHeight + 4 && /(auto|scroll)/.test(String(oy))) { scCache = p; return p }
+ p = p.parentNode
+ }
+ scCache = (grid && grid.parentNode) || null
+ return scCache
+ }
+ // v1.9.3:不加滞回 —— 用户实测「拖动时列数不跟着变、停手才变」比偶尔多排一次更难受。
+ // 列数切换的重排代价已由「卡片节点复用」压到很低,所以直接按宽度实时切。
+ function colsFor (w, prev) {
var gap = 6
- // 每次重排都重新量一次宽度:面板显隐/停靠栏展开时 gridW 可能是旧值,
- // 只靠 ResizeObserver 会在「变成 0 再回来」期间漏掉,导致必须拖宽度才出图。
- var liveW = availableW()
- if (liveW > 0 && Math.abs(liveW - gridW) > 1) gridW = liveW
+ var tileW = Math.max(40, Number(cfg.tile) || 110)
+ return Math.max(1, Math.floor((w + gap) / (tileW + gap)))
+ }
+ function computeLayout () {
+ var gap = 6
+ var liveW = usableW()
+ if (liveW > 0) gridW = liveW
if (!gridW) gridW = 320
var tileW = Math.max(40, Number(cfg.tile) || 110)
- var n = Math.max(1, Math.floor((gridW + gap) / (tileW + gap)))
- // v1.6.6:列宽 = 均分宽度(铺满面板),图幅只决定「列数」——
- // 以前 min(图幅, 均分) 会留下右侧空白,看起来像没补齐。
- var colW = Math.max(40, (gridW - gap * (n - 1)) / n)
+ var n = colsFor(gridW, layoutState ? layoutState.n : 0)
+ var colW = Math.max(40, Math.floor((gridW - gap * (n - 1)) / n))
var cols = []
var heights = []
- for (var c = 0; c < n; c++) { cols.push([]); heights.push(0) }
+ for (var c = 0; c < n; c++) { cols.push({ list: [], h: 0 }); heights.push(0) }
for (var i = 0; i < items.length; i++) {
var it = items[i]
var ratio = (it.w && it.h) ? (it.h / it.w) : 1
+ var h = Math.max(24, Math.round(colW * ratio))
var min = 0
for (var j = 1; j < n; j++) if (heights[j] < heights[min]) min = j
- cols[min].push(it)
- heights[min] += colW * ratio + gap
+ cols[min].list.push({ it: it, y: heights[min], h: h })
+ heights[min] += h + gap
}
- for (var ci = 0; ci < cols.length; ci++) {
- var col = el('div', { class: 'iwb-history-col', style: 'width:' + Math.round(colW) + 'px;flex:0 0 auto' })
- for (var k = 0; k < cols[ci].length; k++) col.appendChild(itemNode(cols[ci][k]))
- grid.appendChild(col)
+ var totalH = 0
+ for (var c2 = 0; c2 < n; c2++) { cols[c2].h = heights[c2] ? heights[c2] - gap : 0; if (cols[c2].h > totalH) totalH = cols[c2].h }
+ return { n: n, colW: colW, gap: gap, cols: cols, totalH: totalH }
+ }
+
+ function spacer (h) {
+ var d = el('div', { class: 'iwb-gal-spacer' })
+ d.style.height = Math.max(0, Math.round(h)) + 'px'
+ d.style.flex = '0 0 auto'
+ return d
+ }
+
+ function renderGrid (force) {
+ var sc = scrollerOf()
+ if (sc && !scrollBound) {
+ scrollBound = true
+ sc.addEventListener('scroll', function () {
+ if (scrollRaf) return
+ scrollRaf = global.requestAnimationFrame(function () { scrollRaf = 0; try { renderGrid() } catch (e) { /* ignore */ } })
+ }, { passive: true })
+ }
+ if (force || !layoutState) layoutState = computeLayout()
+ var L = layoutState
+ var virtual = !!(sc && sc.scrollHeight > sc.clientHeight + 40)
+ var top = virtual ? sc.scrollTop : 0
+ var viewH = virtual ? sc.clientHeight : 100000
+ // 滚动幅度不大且已有内容 ⇒ 不重建(滚动事件很密,重建一次就是几十个节点)
+ if (!force && winState.top >= 0 && grid.firstChild && Math.abs(top - winState.top) < viewH * 0.6 && winState.viewH === viewH) return
+ winState.top = top
+ winState.viewH = viewH
+ var from = Math.max(0, top - viewH * 1.2)
+ var to = top + viewH * 2.4
+ clear(grid)
+ for (var ci = 0; ci < L.cols.length; ci++) {
+ var colDef = L.cols[ci]
+ var list = colDef.list
+ var box = el('div', { class: 'iwb-history-col', style: 'width:' + L.colW + 'px;flex:0 0 auto' })
+ var start = 0
+ while (start < list.length && list[start].y + list[start].h < from) start++
+ var end = start
+ while (end < list.length && list[end].y <= to) end++
+ var topY = start < list.length ? list[start].y : colDef.h
+ if (topY > 0) box.appendChild(spacer(topY))
+ for (var k = start; k < end; k++) box.appendChild(itemNode(list[k].it, k))
+ var bottomY = end < list.length ? list[end].y : colDef.h
+ if (bottomY < colDef.h) box.appendChild(spacer(colDef.h - bottomY))
+ grid.appendChild(box)
}
empty.style.display = items.length ? 'none' : ''
+ try { syncSelection() } catch (e) { /* ignore */ }
clear(more)
if (total > items.length) {
var b = el('button', { class: 'iwb-btn iwb-btn-sm', text: '显示更多(' + (total - items.length) + ' 张)' })
@@ -377,9 +453,21 @@
}
}
- function itemNode (it) {
+ // v1.9.3:卡片节点复用。列数切换时不再重建这几十张卡(重建会重新解码缩略图,实测停顿约 1 秒),
+ // 只把已有节点 appendChild 到新列里(DOM 移动,图片和事件都保留)。
+ var nodeCache = {}
+ var nodeOrder = []
+ function itemNode (it, seq) {
+ var hit = nodeCache[it.name]
+ if (hit && hit.__iwbItem === it) {
+ // 复用时把上轮可能还停在 display:none 的缩略图复位(否则看起来「没图」)
+ var hi = hit.querySelector('img')
+ if (hi && hi.style.display === 'none' && hi.complete && hi.naturalWidth > 0) hi.style.display = ''
+ return hit
+ }
var on = !!picked[it.name]
var box = el('div', { class: 'iwb-history-item' + (count() ? ' iwb-history-managed' : '') + (on ? ' iwb-history-selected' : '') })
+ box.setAttribute('data-name', it.name)
// 缩略图是**异步**的(ctx.gallery.thumb 返回 Promise):先占位,拿到地址再挂 img。
// v1.2.0:加载失败自动重试 2 次(图片还没落盘/临时不可读),仍失败才显示可点击重试的占位。
box.title = it.name + '(单击单选 · Shift+单击多选 · 双击放大 · 拖到画布=参考图节点)'
@@ -388,7 +476,10 @@
origBadge = el('span', { class: 'iwb-gal-origbadge', text: it.orig === 'off' ? '未备份' : '仅缩略图' })
origBadge.title = it.orig === 'off' ? '原图入库已关闭:这张只有缩略图' : '原图没有写进本地:右键可「补存原图」'
}
- var holder = el('div', { class: 'iwb-history-missing', text: '加载中…' })
+ // v1.9.4:卡片先按宽高比占位 —— 否则缩略图出现的瞬间卡片从「一行字高」长成整图高,
+ // 整列跟着重排,滚动时就表现为闪动。
+ if (it.w && it.h) { try { box.style.aspectRatio = it.w + ' / ' + it.h } catch (e0) { /* ignore */ } }
+ var holder = el('div', { class: 'iwb-history-missing', text: it.w && it.h ? '' : '加载中…' })
box.appendChild(holder)
var tries = 0
function fail (text) {
@@ -410,7 +501,12 @@
if (thumbCache[key]) { var u0 = thumbCache[key]; Promise.resolve().then(function () { paint(u0) }).catch(function () { /* ignore */ }); return }
if (!thumbPending[key]) {
thumbPending[key] = Promise.resolve(ctx.gallery.thumb(key)).then(function (url) {
- if (url && typeof url === 'string') thumbCache[key] = url
+ if (url && typeof url === 'string') {
+ thumbCache[key] = url
+ thumbOrder.push(key)
+ // 上限 400:200+ 张的图库来回滚会把 objectURL 一直攒在内存里
+ while (thumbOrder.length > 400) { var oldK = thumbOrder.shift(); if (oldK && oldK !== key) { try { delete thumbCache[oldK] } catch (e2) { /* ignore */ } } }
+ }
delete thumbPending[key]
return url
}, function (e) { delete thumbPending[key]; throw e })
@@ -419,9 +515,11 @@
}
function paint (url) {
if (!url || typeof url !== 'string') { fail('图片已丢失'); return }
- if (!box.isConnected) return
- var img = el('img', { src: url, alt: '', loading: 'eager', draggable: 'true' })
+ // v1.9.1:不再因为「此刻不在文档里」直接放弃 —— 虚拟列表滚动时会先离屏再挂载,
+ // 放弃会导致某些卡片永远停在「加载中…」(缩略图缓存已存,只是没人把它挂上去)。
+ var img = el('img', { src: url, alt: '', loading: 'eager', decoding: 'async', draggable: 'true' })
if (it.w && it.h) img.setAttribute('style', 'aspect-ratio:' + it.w + ' / ' + it.h)
+ try { if (typeof img.decode === 'function') img.decode().catch(function () {}) } catch (e4) { /* ignore */ }
img.addEventListener('load', function () {
// naturalWidth=0 说明拿到的是坏图(空 data URL / 截断文件):按失败处理,别留白块
if (!img.naturalWidth) { tries++; if (tries <= 2) { setTimeout(boot, 400 * tries); return } if (img.parentNode === box) box.replaceChild(holder, img); fail('缩略图加载失败(点击重试)'); return }
@@ -435,7 +533,6 @@
fail('缩略图加载失败(点击重试)')
})
img.addEventListener('click', function (e) { pick(it.name, !!(e && e.shiftKey)) })
- img.addEventListener('dblclick', function () { ctx.gallery.preview(it.name) })
img.addEventListener('dragstart', function (e) {
try {
var names = (picked[it.name] && count() > 1) ? pickedNames() : [it.name]
@@ -449,7 +546,6 @@
e.dataTransfer.effectAllowed = 'copy'
} catch (err) { /* ignore */ }
})
- img.style.display = 'none'
box.appendChild(img)
// v1.6.9:坏图/超时兜底 —— 某些坏字节既不触发 load 也不触发 error,700ms 后直接判定失败(可点击重试)
setTimeout(function () {
@@ -464,6 +560,9 @@
if (img.complete && img.naturalWidth > 0) { img.style.display = ''; if (holder.parentNode === box) box.replaceChild(img, holder) }
else if (img.complete && !img.naturalWidth) { /* 立即失败(坏图)*/ tries++; if (tries <= 2) setTimeout(boot, 400 * tries); else { if (img.parentNode === box) box.replaceChild(holder, img); fail('缩略图加载失败(点击重试)') } }
}
+ // v1.8.0:缩略图按可见性懒加载(IntersectionObserver,上下预取 300px)——
+ // 原来一次性对全部条目发 IPC 取缩略图,列表一长首屏就慢。
+ // v1.8.1:撤销懒加载——IntersectionObserver 在停靠栏里不稳定,大量卡片停在「加载中…」
boot()
box.addEventListener('contextmenu', function (e) { openMenu(e, it) })
var acts = el('div', { class: 'iwb-history-actions' })
@@ -478,6 +577,10 @@
// 角标/勾选最后挂:不要 z-index(插件层级闸门禁止裸值),靠 DOM 顺序盖在图片上
if (origBadge) box.appendChild(origBadge)
if (on) box.appendChild(el('span', { class: 'iwb-history-check', title: '已选中' }))
+ box.__iwbItem = it
+ nodeCache[it.name] = box
+ nodeOrder.push(it.name)
+ while (nodeOrder.length > 400) { var oldN = nodeOrder.shift(); if (oldN && oldN !== it.name) { try { delete nodeCache[oldN] } catch (e3) { /* ignore */ } } }
return box
}
@@ -508,12 +611,44 @@
}).catch(function () { setStatus('下载失败,可再点一次重试') })
}
+ // v1.8.1:双击打开改成在 grid 上做事件委托 —— 原来监听在
上,一旦卡片被重绘替换,
+ // dblclick 就永远落不到同一个元素(用户反馈「双击打不开」)。委托到容器后按 data-name 处理。
+ grid.addEventListener('dblclick', function (e) {
+ var node = e.target
+ while (node && node !== grid && !(node.getAttribute && node.getAttribute('data-name'))) node = node.parentNode
+ if (!node || node === grid) return
+ var nm = node.getAttribute('data-name')
+ if (!nm) return
+ e.preventDefault()
+ e.stopPropagation()
+ try { ctx.gallery.preview(nm) } catch (err) { /* ignore */ }
+ })
+
function pick (name, shift) {
if (shift) { if (picked[name]) delete picked[name]; else picked[name] = 1 } else { picked = {}; picked[name] = 1 }
- render()
+ // v1.8.0:选中只就地改 class/勾选角标 —— 原来整个网格重建,滚动条被顶回顶部,
+ // 而且正在双击的那张
被换掉,双击因此经常打不开。
+ syncSelection()
+ renderHead()
+ // 顺手量一次宽度:面板被拖窄后如果没有其它触发条件,列数会停在旧值上(卡片被窗口裁掉)
+ try { measure() } catch (e) { /* ignore */ }
+ }
+ function syncSelection () {
+ var managed = !!count()
+ var boxes = grid.querySelectorAll('[data-name]')
+ for (var i = 0; i < boxes.length; i++) {
+ var b = boxes[i]
+ var nm = b.getAttribute('data-name')
+ var on = !!picked[nm]
+ if (b.classList.contains('iwb-history-selected') !== on) b.classList.toggle('iwb-history-selected', on)
+ if (b.classList.contains('iwb-history-managed') !== managed) b.classList.toggle('iwb-history-managed', managed)
+ var check = b.querySelector('.iwb-history-check')
+ if (on && !check) b.appendChild(el('span', { class: 'iwb-history-check', title: '已选中' }))
+ else if (!on && check && check.parentNode === b) b.removeChild(check)
+ }
}
- function render () { renderHead(); renderGrid(); global.requestAnimationFrame(function () { try { measure() } catch (e) {} }); setTimeout(function () { try { measure() } catch (e) {} }, 150) }
+ function render () { var sc = scrollerOf(); var top = sc ? sc.scrollTop : 0; renderHead(); layoutState = null; winState.top = -1; renderGrid(true); if (sc) sc.scrollTop = top; global.requestAnimationFrame(function () { try { measure() } catch (e) {} }); setTimeout(function () { try { measure() } catch (e) {} }, 150) }
function load (force) {
if (force) setStatus('刷新中…')
@@ -536,6 +671,23 @@
// 宽度测量:列数只由「面板宽 / 图幅」决定
// v1.6.5:面板刚挂载时 grid 宽度可能是 0,而 grid 宽度又取决于列宽 → RO 不会触发,图库一直空白。
+ // v1.8.2:可用宽度按「真正滚动的容器」算,扣掉内边距和滚动条余量。
+ // 原来用 wrap.clientWidth(面板全宽),右侧有滚动条/内边距时 4 列总宽会超出,最右一列被裁掉。
+ function usableW () {
+ var sc = scrollerOf()
+ var w = 0
+ if (sc) {
+ // 内边距缓存:拖动时每帧 getComputedStyle 会强制样式重算(这是每帧的固定开销)
+ if (!padCache) {
+ var cs = null
+ try { cs = global.getComputedStyle ? global.getComputedStyle(sc) : null } catch (e) { cs = null }
+ padCache = { l: cs ? (parseFloat(cs.paddingLeft) || 0) : 0, r: cs ? (parseFloat(cs.paddingRight) || 0) : 0 }
+ }
+ w = sc.clientWidth - padCache.l - padCache.r
+ }
+ if (!w || w < 80) w = availableW()
+ return Math.max(80, Math.floor(w) - 4)
+ }
function availableW () {
// v1.6.6:优先量「会随面板拉伸的外层容器」,而不是 grid 自身
// (grid 现在是 flex-start + 内容宽度,面板变宽它不会变宽 → RO 不触发 → 列数永不补齐)
@@ -544,22 +696,61 @@
if (!w) w = grid.clientWidth
return w || 0
}
+ var renderRaf = 0
+ function scheduleRender () {
+ if (renderRaf) return
+ renderRaf = global.requestAnimationFrame(function () { renderRaf = 0; try { layoutState = null; winState.top = -1; renderGrid(true) } catch (e) { /* ignore */ } })
+ }
+ var measureTimer = 0
+ function measureNow () {
+ padCache = null // 尺寸/样式可能变了,重新量一次内边距
+ var w = usableW()
+ if (w > 0 && Math.abs(w - gridW) >= 4) { gridW = w; scheduleRender() }
+ }
+ // 拖动中的廉价重排:列数没变就只改进已有的列宽(几条 style 写入),不重建卡片
+ function quickWidth () {
+ var w = usableW()
+ if (!w || !layoutState) return false
+ var gap = 6
+ var tileW = Math.max(40, Number(cfg.tile) || 110)
+ var n = colsFor(w, layoutState.n)
+ if (n !== layoutState.n) return false
+ var colW = Math.max(40, Math.floor((w - gap * (n - 1)) / n))
+ var cols = grid.children
+ for (var i = 0; i < cols.length; i++) { try { cols[i].style.width = colW + 'px' } catch (e) { /* ignore */ } }
+ gridW = w
+ return true
+ }
function measure () {
- var w = availableW()
- if (w > 0 && Math.abs(w - gridW) > 1) { gridW = w; renderGrid() }
+ var w = usableW()
+ if (!w) return
+ // 列数变了立刻重排(合并到一帧;节点复用后代价很小,列数能跟着拖动实时变)
+ if (layoutState && colsFor(w, 0) !== layoutState.n) {
+ gridW = w
+ clearTimeout(measureTimer)
+ scheduleRender()
+ return
+ }
+ // 列数不变:只改列宽,不重建卡片
+ if (quickWidth()) return
+ clearTimeout(measureTimer)
+ measureTimer = setTimeout(measureNow, 120)
+ }
+ if (global.document && global.document.addEventListener) {
+ global.document.addEventListener('pointerup', function () { clearTimeout(measureTimer); measureNow() }, true)
}
var ro = typeof ResizeObserver === 'function' ? new ResizeObserver(function () { measure() }) : null
if (ro) { if (wrap) ro.observe(wrap); if (wrap && wrap.parentNode) ro.observe(wrap.parentNode); ro.observe(grid) }
measure()
var tries = 0
function retry () {
- if (gridW > 0 || tries++ > 40) { if (gridW <= 0) { gridW = Math.max(160, Number(cfg.tile) || 110) * 2; renderGrid() } return }
+ if (gridW > 0 || tries++ > 40) { if (gridW <= 0) { gridW = Math.max(160, Number(cfg.tile) || 110) * 2; layoutState = null; winState.top = -1; renderGrid(true) } return }
measure()
if (gridW <= 0) global.requestAnimationFrame(retry)
}
global.requestAnimationFrame(retry)
// v1.6.7:再补几次延时重测(停靠栏展开动画、首帧布局未完成时能在 1s 内自愈)
- ;[120, 400, 900].forEach(function (ms) { setTimeout(function () { try { measure(); if (gridW > 0) renderGrid() } catch (e) { /* ignore */ } }, ms) })
+ ;[120, 400, 900].forEach(function (ms) { setTimeout(function () { try { measure(); if (gridW > 0) { layoutState = null; winState.top = -1; renderGrid(true) } } catch (e) { /* ignore */ } }, ms) })
// v1.3.0:自动恢复 —— 面板重新可见(切回 tab / 窗口聚焦 / 后台回来)且距上次拉取 >5s 时重拉一次,
// 这样图床恢复、后台补图后不必手动刷新;同时保留底部「刷新」按钮做即时重试。
@@ -588,7 +779,7 @@
for (var i = 0; i < entries.length; i++) {
if (entries[i].isIntersecting) {
// v1.6.7:面板真正可见后再量一次宽度并重排(首帧可能还是 0 宽)
- try { measure(); renderGrid() } catch (e) { /* ignore */ }
+ try { measure(); layoutState = null; winState.top = -1; renderGrid(true) } catch (e) { /* ignore */ }
autoRefresh()
}
}
@@ -620,7 +811,7 @@
global.IWBPluginHost.register({
id: 'gallery',
name: '图库',
- version: '1.7.5',
+ version: '1.9.5',
apiVersion: 1,
capabilities: ['panels', 'gallery'],
data: { schemaVersion: 1, maxBytes: 65536 },
diff --git a/gallery/styles.css b/gallery/styles.css
index 898a699..8f088eb 100644
--- a/gallery/styles.css
+++ b/gallery/styles.css
@@ -65,7 +65,7 @@
/* ---- 图片墙 ---- */
.iwb-history-grid { overscroll-behavior: contain; }
-.iwb-history-embedded .iwb-history-item { position: relative; flex: none; width: 100%; }
+.iwb-history-embedded .iwb-history-item { position: relative; flex: none; width: 100%; contain: layout style; }
.iwb-history-embedded .iwb-history-item img {
width: 100%; height: auto; display: block; object-fit: contain; margin: 0 auto;
border-radius: 6px; border: 1px solid var(--iwb-border); background: var(--iwb-layer2); cursor: pointer;
@@ -80,6 +80,8 @@
border-color: var(--iwb-hover-border, var(--iwb-brand));
box-shadow: var(--iwb-hover-shadow, 0 5px 16px rgba(0, 0, 0, .22));
}
+/* v1.9.4:卡片按宽高比占位后,占位层要铺满卡片 —— 否则缩略图出现时仍会有一次高度跳变(滚动时表现为闪动) */
+.iwb-history-embedded .iwb-history-item .iwb-history-missing { position: absolute; inset: 0; min-height: 0; }
.iwb-history-missing {
display: flex; align-items: center; justify-content: center; text-align: center;
min-height: 84px; padding: 8px; border-radius: 6px; border: 1px dashed var(--iwb-border);
diff --git a/promptlib/package.json b/promptlib/package.json
index 7c67660..c75d511 100644
--- a/promptlib/package.json
+++ b/promptlib/package.json
@@ -1,7 +1,7 @@
{
"name": "@iwb-plugin/promptlib",
"private": true,
- "version": "1.13.1",
+ "version": "1.14.9",
"description": "提示词库:右栏提示词列表(搜索/分组/收藏/新建编辑/插入画布/复制/删除),数据由宿主 promptlib 能力提供",
"ibwPlugin": {
"id": "promptlib",
diff --git a/promptlib/src/index.js b/promptlib/src/index.js
index f992b37..0f4b30e 100644
--- a/promptlib/src/index.js
+++ b/promptlib/src/index.js
@@ -2201,12 +2201,40 @@
}
}
+ // ===== 收藏(v1.14.0:宿主不再提供收藏入口,由插件自己注册)=====
+ function plpNotifyCtx (ctx, t, ty) { try { if (ctx.promptlib && ctx.promptlib.notify) ctx.promptlib.notify(t, ty || 'ok') } catch (e) { /* ignore */ } }
+ function plpCollect (ctx, nodeId) {
+ var nodes = []
+ try { nodes = (ctx.canvas && typeof ctx.canvas.getNodes === 'function') ? (ctx.canvas.getNodes() || []) : [] } catch (e) { nodes = [] }
+ var n = null
+ for (var i = 0; i < nodes.length; i++) if (nodes[i] && nodes[i].id === nodeId) { n = nodes[i]; break }
+ var d0 = (n && n.data) || {}
+ var text = String(d0.text || '').trim()
+ var ttl = String(d0.title || '').trim()
+ if (!text) { plpNotifyCtx(ctx, '提示词为空,无法收藏', 'err'); return Promise.resolve({ ok: false }) }
+ var read = (ctx.data && typeof ctx.data.read === 'function') ? Promise.resolve(ctx.data.read()).catch(function () { return {} }) : Promise.resolve({})
+ return read.then(function (d) {
+ if (d && Array.isArray(d.prompts) && d.prompts.length) return { prompts: d.prompts, groups: Array.isArray(d.groups) ? d.groups : [] }
+ return Promise.resolve(ctx.promptlib.list()).then(function (r) { return { prompts: (r && r.prompts) || [], groups: (r && r.groups) || [] } })
+ }).then(function (cur) {
+ var list = cur.prompts.slice()
+ list.push({ id: 'q' + Date.now() + '_' + Math.floor(Math.random() * 1e6), name: ttl || ('提示词 ' + text.slice(0, 8) + '…'), text: text, tags: [], group: '' })
+ var payload = { schemaVersion: 3, prompts: list, groups: cur.groups, updatedAt: Date.now() }
+ var jobs = []
+ if (ctx.data && typeof ctx.data.write === 'function') jobs.push(Promise.resolve(ctx.data.write(payload)).catch(function () {}))
+ if (ctx.promptlib && typeof ctx.promptlib.save === 'function') jobs.push(Promise.resolve(ctx.promptlib.save({ prompts: list, groups: cur.groups })).catch(function () {}))
+ return Promise.all(jobs)
+ }).then(function () { plpNotifyCtx(ctx, '已收藏到未分组'); return { ok: true } })
+ .catch(function () { plpNotifyCtx(ctx, '收藏失败,请重试', 'err'); return { ok: false } })
+ }
+
+
global.IWBPluginHost.register({
id: 'promptlib',
name: '提示词库',
- version: '1.13.1',
+ version: '1.14.9',
apiVersion: 1,
- capabilities: ['panels', 'promptlib', 'nodeTypes', 'canvas', 'canvasWrite'],
+ capabilities: ['panels', 'promptlib', 'nodeTypes', 'canvas', 'canvasWrite', 'nodeActions', 'commands'],
data: { schemaVersion: 3, maxBytes: 4 * 1024 * 1024 },
settings: {
panel: { type: 'custom', label: '分组与备份', render: renderPluginSettings },
@@ -2289,15 +2317,18 @@
titleBox.appendChild(title); titleBox.appendChild(meta)
head.appendChild(thumb); head.appendChild(titleBox)
var vars = el('div', { class: 'iwb-plp-nvars' })
+ // v1.14.2:参考图开关移到头部(title 下面、变量列表上面)——与样式节点位置一致。
+ // 原来放在节点底部,变量一多就要滚到底才点得到。
var refRow = el('label', { class: 'iwb-plp-nref' })
var refChk = el('input', { type: 'checkbox' })
var refTxt = el('span', { text: '封面作参考图' })
var refNum = el('em', { text: '0' })
refRow.appendChild(refChk); refRow.appendChild(refTxt); refRow.appendChild(refNum)
var warn = el('div', { class: 'iwb-plp-nwarn' })
- root.appendChild(head); root.appendChild(vars); root.appendChild(refRow); root.appendChild(warn)
+ titleBox.appendChild(refRow)
+ root.appendChild(head); root.appendChild(vars); root.appendChild(warn)
host.appendChild(root)
- var st = { root: root, thumb: thumb, title: title, meta: meta, vars: vars, warn: warn, refChk: refChk, refNum: refNum, inputs: {}, key: '' }
+ var st = { root: root, thumb: thumb, title: title, meta: meta, vars: vars, warn: warn, refChk: refChk, refNum: refNum, refRow: refRow, inputs: {}, key: '' }
refChk.addEventListener('change', function () {
var on = Boolean(refChk.checked)
var cover = st.node && st.node.data ? st.node.data.cover : ''
@@ -2403,6 +2434,7 @@
if (!coverKey) st.thumb.style.display = 'none'
var refOn = d.refOn === true
if (st.refChk.checked !== refOn) st.refChk.checked = refOn
+ try { if (st.refRow) st.refRow.classList.toggle('is-on', refOn) } catch (e) { /* ignore */ }
st.refNum.textContent = refOn ? '1 张' : '0'
// 未填提示(v1.12.3 语义变了):输入框空但「内容」有值 ⇒ 用内容兜底,不算缺;
// 只有既没填、内容也空,这段占位才会在提示词里被去掉 —— 那才值得提醒。
@@ -2433,6 +2465,29 @@
}
}
+ // v1.14.0:收藏入口归插件 —— 节点气泡(nodeAction)+ 右键「插件命令」;插件停用即消失
+ if (ctx.nodeActions && typeof ctx.nodeActions.register === 'function') {
+ ctx.nodeActions.register({
+ id: 'collect-prompt',
+ title: '收藏为提示词',
+ icon: 'star',
+ appliesTo: function (node) { return !!node && node.type === 'prompt' && String((node.data && node.data.text) || '').trim() !== '' },
+ run: function (node) { if (node && node.id) plpCollect(ctx, node.id) },
+ })
+ }
+ if (ctx.commands && typeof ctx.commands.register === 'function') {
+ ctx.commands.register({
+ id: 'collect-selected',
+ title: '收藏选中的提示词',
+ icon: 'star',
+ run: function () {
+ var sel = (ctx.canvas && typeof ctx.canvas.getSelectedNode === 'function') ? ctx.canvas.getSelectedNode() : null
+ if (!sel || !sel.id) { plpNotifyCtx(ctx, '先选中一个提示词节点', 'err'); return }
+ plpCollect(ctx, sel.id)
+ },
+ })
+ }
+
return {}
})
})(typeof window !== 'undefined' ? window : globalThis)
\ No newline at end of file
diff --git a/promptlib/styles.css b/promptlib/styles.css
index fa2ee0a..7c96a8d 100644
--- a/promptlib/styles.css
+++ b/promptlib/styles.css
@@ -151,8 +151,17 @@
.iwb-plp-nrow{display:flex;align-items:flex-start;gap:6px;min-height:26px}
.iwb-plp-nk{flex:0 0 56px;width:56px;max-width:56px;padding-top:4px;color:var(--iwb-text2,#5b6472);font-size: 12px;line-height:1.35;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.iwb-plp-nin{flex:1 1 auto;min-width:0;height:auto;min-height:24px;padding:2px 8px;line-height:1.5;font-size: 12px;resize:none;overflow-y:hidden}
-.iwb-plp-nref{display:flex;align-items:center;gap:6px;font-size: 12px;color:var(--iwb-text2,#5b6472);border-top:1px dashed var(--iwb-border,#e3e5e9);padding-top:6px}
+/* v1.14.2:参考图开关移到头部(与样式节点一致)——做成浅色药丸,不再是底部分隔行 */
+.iwb-plp-nref{display:inline-flex;align-items:center;gap:6px;margin-top:6px;padding:2px 8px;border-radius:6px;background:var(--iwb-layer,#f0f1f4);color:var(--iwb-text2,#4d5668);font-size: 12px;cursor:pointer;align-self:flex-start}
.iwb-plp-nref em{font-style:normal;color:var(--iwb-text2,#8b929c)}
+/* v1.14.3:勾选框改成自绘的蓝色实心勾(与样式节点视觉一致;原生 macOS 勾选框在不同外观下不一致) */
+.iwb-plp-nref input[type="checkbox"]{appearance:none;-webkit-appearance:none;margin:0;width:15px;height:15px;flex:0 0 auto;border-radius:var(--iwb-set-check-radius,4px);border:1.5px solid color-mix(in srgb, var(--iwb-border2) 70%, var(--iwb-text2));background:var(--iwb-field,var(--iwb-plugin-surface,#fff));cursor:pointer;position:relative;transition:background .12s ease,border-color .12s ease}
+.iwb-plp-nref input[type="checkbox"]:checked{background:var(--iwb-brand,#1677ff);border-color:var(--iwb-brand,#1677ff)}
+.iwb-plp-nref input[type="checkbox"]:checked::after{content:"";position:absolute;left:50%;top:50%;width:4px;height:8px;border:solid var(--iwb-on-brand,#ffffff);border-width:0 2px 2px 0;transform:translate(-50%,-58%) rotate(45deg)}
+/* v1.14.6:强调色当文字用时必须和正文色混合 —— 直接用 --iwb-brand 在暗色下对比度不够(蓝字压深灰底)。
+ 亮色混深(更沉),暗色混浅(更亮),两端都过 4.5:1。 */
+.iwb-plp-nref.is-on{background:var(--iwb-accent-tint, color-mix(in srgb, var(--iwb-brand) 18%, transparent));color:var(--iwb-accent-on-surface, color-mix(in srgb, var(--iwb-brand) 45%, var(--iwb-text)))}
+.iwb-plp-nref.is-on em{color:inherit;opacity:.8}
.iwb-plp-nprev{margin-top:2px;border-top:1px dashed var(--iwb-border,#e3e5e9);padding-top:6px;color:var(--iwb-text2,#5b6472);font-size: 12px;line-height:1.6;max-height:88px;overflow:hidden}
/* v1.5.0:变量编辑器 / 详情变量 */
diff --git a/scripts/validate.mjs b/scripts/validate.mjs
index 2e89ca0..1308052 100644
--- a/scripts/validate.mjs
+++ b/scripts/validate.mjs
@@ -37,19 +37,28 @@ export const checkPlugin = (dir) => {
if (src.indexOf('IWBPluginHost.register(') < 0) errors.push('entry 未调用 IWBPluginHost.register(manifest, factory)')
- const idMatch = /(?:^|[\s{,])id:\s*'([^']+)'/.exec(src)
+ // v1.0.2:只在 register(...) 的 manifest 块里找字段。
+ // 旧写法在整份源码里找第一个 id:/version:,会被业务代码里的 { id: 'q' + Date.now() } 误命中
+ // (promptlib 就因此被判「entry 内 id (q) 与 ibwPlugin.id 不一致」)。
+ const regAt = src.indexOf('IWBPluginHost.register(')
+ // 从 register( 开始截到文件末尾:manifest 一定在 factory 之前,而业务代码里的同名键都在 register 之前
+ const regBlock = regAt >= 0 ? src.slice(regAt) : src
+ // 两段扫描:优先 register( 之后(避开业务代码里的同名键),找不到字面量再回退整份源码——
+ // image-annotate / image-vectorize 是构建产物,manifest 用 __IWB_XXX_MANIFEST__ 常量传入。
+ const pick = (re) => re.exec(regBlock) || re.exec(src)
+ const idMatch = pick(/(?:^|[\s{,])id:\s*'([^']+)'/)
if (!idMatch) errors.push("entry 内未找到 id: '' 字面量(manifest 必须显式声明 id)")
else if (idMatch[1] !== id) errors.push('entry 内 id (' + idMatch[1] + ') 与 ibwPlugin.id (' + id + ') 不一致')
- const apiMatch = /apiVersion:\s*(\d+)/.exec(src)
+ const apiMatch = pick(/apiVersion:\s*(\d+)/)
if (!apiMatch) errors.push('entry 内未找到 apiVersion 字面量')
else if (Number(apiMatch[1]) !== meta.apiVersion) errors.push('entry 内 apiVersion (' + apiMatch[1] + ') 与 ibwPlugin.apiVersion (' + meta.apiVersion + ') 不一致')
- const versionMatch = /version:\s*'([^']+)'/.exec(src)
+ const versionMatch = pick(/version:\s*'([^']+)'/)
if (!versionMatch) errors.push("entry 内未找到 version: '' 字面量")
else if (versionMatch[1] !== String(pkg.version)) errors.push('entry 内 version (' + versionMatch[1] + ') 与 package.json version (' + pkg.version + ') 不一致')
- if (!/name:\s*'[^']+'/.test(src)) errors.push("entry 内未找到 name: '' 字面量")
- if (!/capabilities:\s*\[/.test(src)) errors.push('entry 内未找到 capabilities 数组')
+ if (!/name:\s*'[^']+'/.test(regBlock) && !/name:\s*'[^']+'/.test(src)) errors.push("entry 内未找到 name: '' 字面量")
+ if (!/capabilities:\s*\[/.test(regBlock) && !/capabilities:\s*\[/.test(src)) errors.push('entry 内未找到 capabilities 数组')
return errors
}