Files
image-workbench-desktop/plugins/album/main.js
T
2026-12-01 07:01:36 +08:00

1187 lines
66 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.
// 相册节点(2026-11-26,iwb-plugin: album)
//
// 一件事:把「多个图片节点」收成一个节点——宫格装 N 张本地图,接提示词/组合做批量生图。
//
// 三条关键设计(都对宿主有依赖,别在插件里重造):
// ① 只引用不复制:item.src = { __file: '/abs/a.png' };宿主生成时才读盘(ctx.images.reference / dataUrl)
// ② 任务展开由宿主任务图做:data.outKind='images' + data.items,宿主按 albumMode 展开成 N 个任务
// (一图一任务)或分批(批量,每组 ≤12 张);本插件只负责「数据 + 界面」
// ③ 分页容量随节点尺寸实时算:拖大 = 一页装更多(装得下就隐藏分页条),缩小 = 自动多页;
// 只有 data.onlyPage 打开时才把可见区间写进 data.pageRange 交给宿主过滤
;(function (global) {
'use strict'
if (!global.IWBPluginHost) return
// 密度档位 = 目标单元格边长(px)。1.1.0 修正:旧值 {S:64, M:48, L:100} 里 M 比 S 还小,
// 于是「中格」每页装 30 张(比小格的 20 张还多),档位语义是反的。现在 S < M < L 严格递增。
const DENSITY = { S: 64, M: 80, L: 104 }
// ⚠ 下面这一组必须与 styles.css 逐个对齐(换了 box-sizing / padding 就会算错容量 ⇒ 最后一行被裁)。
// 宿主全局 * { box-sizing: border-box },所以 CSS 里写的 height 已含 padding。
const GAP = 4 // .iwb-album-grid 的 gap = --iwb-space-4
const PAD_X = 16 // 宫格左右 padding 合计(.iwb-album-grid 左右各 --iwb-space-8)
const PAD_Y = 8 // 上下 padding 合计(.iwb-album-grid 2px + 6px)
const BAR_H = 26 // 状态栏
const TOOLS_H = 25 // 工具条(padding 2+2 + 按钮 21)
const PAGER_H = 26 // 分页条 / 一页提示条
const HINT_H = 28 // 批量模式提示行(含 margin-bottom 4)
const DEFAULT_H = 470 // 注册时声明的默认高度(与 height 字段保持一致)
const THUMB_EDGE = 256
const THUMB_Q = 0.8
const IMG_EXT = ['png', 'jpg', 'jpeg', 'webp', 'gif', 'avif', 'bmp', 'svg']
const STATE = new WeakMap() // host 元素 → 渲染状态(一个容器一个实例)
// ── 小工具 ──────────────────────────────────────────────
function el (tag, attrs, kids) {
const node = document.createElement(tag)
if (attrs) for (const k in attrs) {
const v = attrs[k]
if (v === null || v === undefined || v === false) continue
if (k === 'className') node.className = v
else if (k === 'text') node.textContent = v
else if (k === 'style' && typeof v === 'object') Object.assign(node.style, v)
else if (k.slice(0, 2) === 'on' && typeof v === 'function') node.addEventListener(k.slice(2).toLowerCase(), v)
else node.setAttribute(k, v === true ? '' : String(v))
}
for (const kid of (Array.isArray(kids) ? kids : (kids ? [kids] : []))) {
if (kid === null || kid === undefined || kid === false) continue
node.appendChild(typeof kid === 'string' ? document.createTextNode(kid) : kid)
}
return node
}
// 可点击元素:宿主在节点体上的 pointerdown 会启动「拖动节点」,单击事件因此被吞。
// 所有可点击的非 input/button 元素都必须挡住 pointerdown(与 ui-node-bodies 里 stop 的用法一致)。
function onTap (el0, fn) {
el0.addEventListener('pointerdown', (e) => e.stopPropagation())
el0.addEventListener('click', (e) => { e.stopPropagation(); fn(e) })
return el0
}
function hash32 (s) {
let h = 0x811c9dc5
const str = String(s || '')
for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0 }
return ('00000000' + h.toString(16)).slice(-8)
}
const extOf = (p) => { const m = /\.([a-z0-9]{1,5})$/i.exec(String(p || '')); return m ? m[1].toLowerCase() : '' }
const isImagePath = (p) => IMG_EXT.indexOf(extOf(p)) >= 0
const fileRefOf = (src) => (src && typeof src === 'object' && typeof src.__file === 'string') ? src.__file : ''
const nameOf = (p) => String(p || '').replace(/^.*[\\/]/, '')
// Windows 路径大小写不敏感;重选同一文件夹时 dialog 可能回不同大小写,必须按平台归一化后再去重
const WIN = typeof navigator !== 'undefined' && /Windows/i.test(String(navigator.userAgent || ''))
const normPath = (p) => { const s = String(p || '').replace(/\\/g, '/'); return WIN ? s.toLowerCase() : s }
const str = (v) => (v == null ? '' : String(v))
// ── 缩略图(插件私有缓存,几十 KB/张,不碰画布存储)────────────
// 编码代号(1.1.6):
// · 1.1.5 及以前一律 JPEG —— 而 JPEG 没有 alpha,canvas 的透明像素编码后是**纯黑**
// (Chromium 实测 rgba(0,0,0,255))⇒ 抠图/透明 PNG 在相册里是一格格黑方块。
// · 现在「含 alpha 走 PNG,否则 JPEG 0.85」;代号进文件名,旧黑底缓存自然不再命中。
const THUMB_REV = '2'
const thumbBase = (key) => 't' + THUMB_REV + '-' + hash32(key)
// 宿主文件白名单只认 jpg/jpeg/png/webp,后缀必须与实际字节一致(读回时按文件头嗅探 mime)
const thumbNameOf = (key, ext) => thumbBase(key) + '.' + (ext === 'png' ? 'png' : 'jpg')
const thumbNames = (key) => [thumbNameOf(key, 'png'), thumbNameOf(key, 'jpg')]
// 1.1.5 及以前的缓存名(永远是 JPEG),写新图时顺手清掉,别让黑底缩略图在磁盘里越积越多
const oldThumbName = (key) => 't-' + hash32(key) + '.jpg'
// keepExt:刚写成功的那一份不能删(png/jpg 只留一个),其余变体清掉
function dropThumbFile (ctx, key, keepExt) {
if (!ctx || !ctx.files || !key) return
const keep = keepExt ? thumbNameOf(key, keepExt) : ''
for (const n of thumbNames(key).concat([oldThumbName(key)])) {
if (keep && n === keep) continue
try { const p = ctx.files.remove(n); if (p && typeof p.catch === 'function') p.catch(() => {}) } catch (e) { /* ignore */ }
}
}
// 缩略图缓存键(1.1.0 修「串味」):旧实现是 `fileRefOf(src) || it.name`,一旦固化(src 变成
// {__blob})或从别处导入,路径就没了 ⇒ 键退化成纯文件名 ⇒ 不同目录下的 1.png 共用同一张缩略图。
// 现在按引用本身取键:路径 → 路径;blob/cache → 各自 id;dataURL → 内容哈希;只有都没有才退回文件名。
function thumbKeyOf (it) {
const src = (it && it.src) != null ? it.src : it
const path = fileRefOf(src)
if (path) return 'f:' + path
if (src && typeof src === 'object') {
if (typeof src.__blob === 'string' && src.__blob) return 'b:' + src.__blob
if (typeof src.__cache === 'string' && src.__cache) return 'c:' + src.__cache
}
if (typeof src === 'string' && src) {
if (src.length > 4096) return 'd:' + hash32(src.slice(0, 2048) + src.slice(-2048) + ':' + src.length)
return 'd:' + hash32(src)
}
const n = (it && (it.name || it.size)) || ''
return 'n:' + str(n)
}
// 返回 { url, ext };失败返回 null。
// alpha 判定:缩放后隔 4 个像素采样 alpha 通道(256² 画布全读也就 256KB 一次性缓冲)。
// 只有确实含透明像素才付 PNG 的体积代价 —— 照片仍走 JPEG,缓存总量不会膨胀。
function makeThumb (dataUrl) {
return new Promise((resolve) => {
try {
const img = new Image()
img.onload = () => {
try {
const scale = Math.min(1, THUMB_EDGE / Math.max(img.naturalWidth || 1, img.naturalHeight || 1))
const w = Math.max(1, Math.round((img.naturalWidth || 1) * scale))
const h = Math.max(1, Math.round((img.naturalHeight || 1) * scale))
const cv = document.createElement('canvas')
cv.width = w; cv.height = h
const c2 = cv.getContext('2d')
c2.drawImage(img, 0, 0, w, h)
let alpha = false
try {
const d = c2.getImageData(0, 0, w, h).data
for (let i = 3; i < d.length; i += 16) { if (d[i] < 250) { alpha = true; break } }
} catch (e) { /* 读不出像素就按不透明处理(IMG 被污染时 JPEG 也不会更糟) */ }
if (alpha) resolve({ url: cv.toDataURL('image/png'), ext: 'png' })
else resolve({ url: cv.toDataURL('image/jpeg', THUMB_Q), ext: 'jpg' })
} catch (e) { resolve(null) }
}
img.onerror = () => resolve(null)
img.src = dataUrl
} catch (e) { resolve(null) }
})
}
// ── 容量:随节点宽高实时算(放大 = 一页装更多)────────────────
function capacityOf (width, height, density, hasHint) {
const target = DENSITY[density] || DENSITY.S
const innerW = Math.max(0, width - 4 - PAD_X)
const innerH = Math.max(0, height - 4 - BAR_H - TOOLS_H - PAGER_H - (hasHint ? HINT_H : 0) - PAD_Y)
const cols = Math.max(1, Math.floor((innerW + GAP) / (target + GAP)))
const cell = Math.floor((innerW - (cols - 1) * GAP) / cols) || target
const rows = Math.max(1, Math.floor((innerH + GAP) / (cell + GAP)))
return { cols, rows, cell: Math.max(20, cell), capacity: Math.max(1, cols * rows) }
}
function measure (host) {
const rect = host.getBoundingClientRect()
return { width: Math.round(rect.width || 0), height: Math.round(rect.height || 0) }
}
// ── 数据读写 ────────────────────────────────────────────
function itemsOf (node) {
const d = (node && node.data) || {}
return Array.isArray(d.items) ? d.items : []
}
function update (props, node, patch, snapshot) {
try { if (snapshot && typeof props.onSnapshot === 'function') props.onSnapshot() } catch (e) { /* 撤销快照失败不影响写入 */ }
try { props.onUpdate(node.id, patch) } catch (e) { /* 宿主不可写时保持只读 */ }
}
// ── 外壳 ────────────────────────────────────────────────
function buildShell (ctx, node, props, host) {
const st = {
nodeId: node.id,
thumbs: new Map(), // key → dataURL(内存缓存)
forceThumbs: new Set(), // 需要绕过旧缩略图缓存、重新读原图的 key(重选文件夹/缩略图损坏)
pending: new Map(), // key → Promise(并发去重:格子挂载和预生成会同时要同一张)
missing: new Set(), // 失联文件的 key
busy: '',
checkedMissing: false,
sig: '',
cap: null, // 最近一次容量计算(拖拽排序换算页码要用)
}
const bar = el('div', { className: 'iwb-album-bar' })
const track = el('span', { className: 'iwb-album-track' }, el('i', null))
const modeLabel = el('label', { className: 'iwb-album-toggle' }, track, document.createTextNode('单图任务'))
// v1.2.0:文件夹监控开关(桌面端才有路径能力)
const fTrack = el('span', { className: 'iwb-album-track' }, el('i', null))
const folderLabel = el('label', { className: 'iwb-album-toggle iwb-album-folder-toggle' }, fTrack, document.createTextNode('文件夹监控'))
folderLabel.addEventListener('pointerdown', (e) => e.stopPropagation())
folderLabel.addEventListener('click', (e) => {
e.stopPropagation()
const cur = st.node || node
const d = (cur && cur.data) || {}
const next = d.sourceMode === 'folder' ? 'mixed' : 'folder'
update(st.props || props, cur, { sourceMode: next })
if (next === 'folder' && !folderOf(cur)) pickFolderForMonitor(ctx, st)
})
modeLabel.addEventListener('pointerdown', (e) => e.stopPropagation())
modeLabel.addEventListener('click', (e) => {
e.stopPropagation()
// ⚠ 必须读 st.node(每次 sync 更新),不能读 buildShell 捕获的 node ——
// 那是**挂载时**的旧数据,连点两次会一直算出同一个 next(实测:永远停在批量)。
const cur = st.node || node
const d = (cur && cur.data) || {}
const next = d.albumMode === 'batch' ? 'per-image' : 'batch'
update(st.props || props, cur, { albumMode: next })
})
const count = el('span', { className: 'iwb-album-count' })
// 一键清空(2026-11-26 用户需求):只清本节点持有的 items,删源文件与画布存储一概不碰。
// 走 snapshot:true ⇒ ⌘Z 能整批恢复,所以不加二次确认弹窗(多一步点击反而更烦)。
const btnClear = el('button', { className: 'iwb-album-btn iwb-album-clear', title: '清空相册(⌘Z 可撤销;不会删除磁盘上的原文件)' }, '清空')
bar.appendChild(modeLabel); bar.appendChild(folderLabel); bar.appendChild(count); bar.appendChild(btnClear)
const btnAdd = el('button', { className: 'iwb-album-btn', title: '选择本地图片(桌面端只引用,不复制字节)' }, '+ 添加图片')
const btnDir = el('button', { className: 'iwb-album-btn', title: '按文件夹批量添加' }, '文件夹')
const btnSettle = el('button', { className: 'iwb-album-btn', title: '把引用复制进画布存储(删源文件/分享画布前用)' }, '固化')
// v1.2.0:文件夹模式专用(手动刷新,不做自动监听)
const btnPaste = el('button', { className: 'iwb-album-btn', title: '从剪贴板粘贴图片(截图 / 网页复制 / 访达复制文件都行)' }, '粘贴')
const btnRefresh = el('button', { className: 'iwb-album-btn', title: '重新读取文件夹:新增的加入、消失的移除(尊重忽略名单)' }, '刷新')
const btnReload = el('button', { className: 'iwb-album-btn', title: '清空忽略名单并整本重新读取(会重置勾选)' }, '全部重载')
const folderNote = el('div', { className: 'iwb-album-foldernote' }, '文件夹监控:只读该目录第一层 · 最多 500 张 · 拖拽 / 粘贴 / 添加已隐藏')
const folderMsg = el('div', { className: 'iwb-album-foldermsg' })
const folderPath = el('div', { className: 'iwb-album-folderpath' })
const seg = el('span', { className: 'iwb-album-seg' })
const segs = {}
for (const key of ['S', 'M', 'L']) {
const s = onTap(el('span', { title: key === 'S' ? '小格(默认)' : (key === 'M' ? '中格' : '大格') }, key), () => update(st.props || props, st.node || node, { density: key }))
segs[key] = s; seg.appendChild(s)
}
const tools = el('div', { className: 'iwb-album-tools' }, [btnAdd, btnDir, btnPaste, btnSettle, btnRefresh, btnReload, seg])
const hint = el('div', { className: 'iwb-album-hint' })
const grid = el('div', { className: 'iwb-album-grid' })
const empty = el('div', { className: 'iwb-album-empty' }, [
el('div', { className: 'box' }, '+'),
el('div', null, '把图片拖到这里,或点「添加图片」选本地文件'),
el('div', { style: { fontSize: '10px', opacity: '.85' } }, '支持 PNG / JPG / WebP / GIF / AVIF / SVG'),
])
const pager = el('div', { className: 'iwb-album-pager' })
const onepage = el('div', { className: 'iwb-album-onepage' }, '全部图片一页展示')
// 节点内 hover 预览层已于 1.1.1 移除(用户实测:鼠标移到放大镜上时预览层盖住图标,反而点不到)。
// 现在只看大图走「点击放大镜 → 宿主全屏预览(props.onPreview)」,点图片外或 Esc 自动退出。
host.textContent = ''
const root = el('div', { className: 'iwb-album' }, [bar, folderNote, folderMsg, tools, hint, grid, empty, pager, onepage, folderPath])
host.appendChild(root)
Object.assign(st, { root, bar, track, count, btnClear, btnAdd, btnDir, btnPaste, btnSettle, segs, grid, empty, pager, onepage, hint, modeLabel, folderLabel, fTrack, btnRefresh, btnReload, folderNote, folderMsg, folderPath })
// 按钮绑定(用闭包里的当前 node/props:每次 sync 会更新 st.node/st.props)
btnAdd.addEventListener('pointerdown', (e) => e.stopPropagation())
btnAdd.addEventListener('click', (e) => { e.stopPropagation(); pickFiles(ctx, st, host, false) })
btnDir.addEventListener('pointerdown', (e) => e.stopPropagation())
btnDir.addEventListener('click', (e) => { e.stopPropagation(); pickFiles(ctx, st, host, true) })
btnSettle.addEventListener('pointerdown', (e) => e.stopPropagation())
btnSettle.addEventListener('click', (e) => { e.stopPropagation(); settleAll(ctx, st) })
btnPaste.addEventListener('pointerdown', (e) => e.stopPropagation())
btnPaste.addEventListener('click', (e) => { e.stopPropagation(); pasteFromClipboard(ctx, st) })
btnRefresh.addEventListener('pointerdown', (e) => e.stopPropagation())
btnRefresh.addEventListener('click', (e) => { e.stopPropagation(); refreshFolder(ctx, st) })
btnReload.addEventListener('pointerdown', (e) => e.stopPropagation())
btnReload.addEventListener('click', (e) => { e.stopPropagation(); reloadFolder(ctx, st) })
btnClear.addEventListener('pointerdown', (e) => e.stopPropagation())
btnClear.addEventListener('click', (e) => { e.stopPropagation(); clearAll(ctx, st) })
// 拖拽入图:桌面端拿不到绝对路径 ⇒ 按「方案 1」复制进画布存储
host.addEventListener('dragover', (e) => { e.preventDefault(); e.stopPropagation() })
host.addEventListener('drop', (e) => {
e.preventDefault(); e.stopPropagation()
if (isFolderMode(st.node)) return // 文件夹模式禁止其它来源,避免混源
const files = Array.from((e.dataTransfer && e.dataTransfer.files) || [])
if (files.length) importDropped(ctx, st, files)
})
return st
}
// ── 文件夹模式(v1.2.0)──────────────────────────────────
// 只做手动刷新:不做文件监听(用户已确认,避免性能开销)。
// 宿主 listImages 的硬上限:只递归 1 层、最多 500 张。超限必须中止,
// 否则一次性渲染/引用几百张会把界面拖死(用户明确要求“超了要阻止执行”)。
const FOLDER_MAX = 500
function isFolderMode (node) { return ((node && node.data) || {}).sourceMode === 'folder' }
function folderOf (node) { const f = ((node && node.data) || {}).folder; return (f && typeof f.path === 'string') ? f.path : '' }
function skipOf (node) { const v = ((node && node.data) || {}).folderSkip; return Array.isArray(v) ? v.filter((x) => typeof x === 'string') : [] }
// 文件夹模式的提示统一走 folderMsg:原来的 st.hint 会被 sync 的“批量模式提示”逻辑隐藏,
// 结果就是用户看不到任何原因(实测:选了目录仍显示 0 张且无提示)。
function setFolderMsg (st, text) {
if (!st || !st.folderMsg) return
st.folderMsg.textContent = text || ''
st.folderMsg.style.display = text ? '' : 'none'
}
async function pickFolderForMonitor (ctx, st) {
try {
const picked = await ctx.images.pick({ multiple: false, directory: true })
const dir = (picked && picked[0]) || ''
if (!dir) return
update(st.props, st.node, { folder: { path: dir } }, true)
// 本地先合并一次:宿主 re-render 前 st.node 还是旧的,refreshFolder 会读不到目录
try {
const cur = st.node || {}
st.node = Object.assign({}, cur, { data: Object.assign({}, cur.data || {}, { folder: { path: dir } }) })
} catch (e) { /* ignore */ }
st.sig = ''
sync(ctx, st, st.node, st.props)
await refreshFolder(ctx, st, dir)
} catch (e) { /* 用户取消 */ }
}
// 刷新 = 增量 diff:按文件名排序、尊重忽略名单、保留勾选与当前页
async function refreshFolder (ctx, st, dirOverride) {
if (st.busy) return
const node = st.node
const dir = dirOverride || folderOf(node)
if (!dir) { setFolderMsg(st, '尚未选择文件夹'); return }
st.busy = '刷新…'; st.sig = ''; sync(ctx, st, node, st.props)
let files = []
try { files = await ctx.images.listImages(dir) } catch (e) { files = [] }
st.busy = ''
if (files && files.length >= FOLDER_MAX) {
st.sig = ''; sync(ctx, st, node, st.props)
setFolderMsg(st, '该文件夹图片达到 ' + FOLDER_MAX + ' 张上限,已中止刷新(未改动现有条目)。请拆分目录或只放需要的图。')
return
}
if (!files || !files.length) {
st.sig = ''; sync(ctx, st, node, st.props)
setFolderMsg(st, '该目录第一层没有图片,或目录不可用(未改动现有条目)')
return
}
setFolderMsg(st, '')
const skip = new Set(skipOf(node).map((x) => normPath(x)))
const want = files.filter((f) => !skip.has(normPath(f))).sort((a, b) => normPath(a).localeCompare(normPath(b)))
const items = itemsOf(node).slice()
const byPath = new Map()
for (const it of items) { const p0 = fileRefOf(it && it.src); if (p0) byPath.set(normPath(p0), it) }
const next = []
for (const f of want) {
const hit = byPath.get(normPath(f))
if (hit) { next.push(hit); continue }
const ref = await ctx.images.reference(f)
if (ref && ref.ok) next.push({ src: { __file: ref.item.path }, name: ref.item.name, size: ref.item.size, mtime: ref.item.mtime, on: true })
}
const capNow = (st.cap && st.cap.capacity) || 20
const pageNow = Math.max(0, Number(((node && node.data) || {}).page) || 0)
const pagesNow = Math.max(1, Math.ceil(next.length / capNow))
update(st.props, node, { items: next, page: Math.min(pageNow, pagesNow - 1) }, true)
st.checkedMissing = false
st.sig = ''
sync(ctx, st, node, st.props)
}
// 全部重载 = 清空忽略名单 + 整本重读(会重置勾选与页码)
async function reloadFolder (ctx, st) {
const node = st.node
const dir = folderOf(node)
if (!dir) return
if (typeof confirm === 'function' && !confirm('将清空忽略名单并重新读取文件夹,确定?')) return
const files = await ctx.images.listImages(dir).catch(() => [])
if (files && files.length >= FOLDER_MAX) { setFolderMsg(st, '该文件夹图片达到 ' + FOLDER_MAX + ' 张上限,已中止重载(未改动现有条目)'); return }
if (!files || !files.length) { setFolderMsg(st, '文件夹不可用,未改动现有条目'); return }
update(st.props, node, { folderSkip: [], items: [], page: 0 }, true)
st.checkedMissing = false
st.sig = ''
sync(ctx, st, node, st.props)
await refreshFolder(ctx, st)
}
// ── 同步(宿主每次重渲染都会调用;必须可增量)──────────────────
function sync (ctx, st, node, props) {
st.node = node; st.props = props
const d = (node && node.data) || {}
const items = itemsOf(node)
const density = DENSITY[d.density] ? d.density : 'S'
const mode = d.albumMode === 'batch' ? 'batch' : 'per-image'
// 尺寸来源:**只认显式 node.h 或变体默认高度**(2026-11-26 修"插入后慢慢变矮")。
// ⚠ 绝不能用 props.measuredH / 自身 getBoundingClientRect():插件节点体是内容撑开的,
// 我们按它写回高度 ⇒ 卡片变矮 ⇒ 下次量到更矮 ⇒ 一路缩水。
// 拖拽调整尺寸时宿主会把新高度写进 node.h,那才是权威值。
const measured = measure(st.root)
const cardW = Number(node.w) || measured.width || 300
const cardH = Number(node.h) || DEFAULT_H
const wantH = Math.max(120, Math.round(cardH) - 4) + 'px'
if (st.root.style.height !== wantH) st.root.style.height = wantH
const cap = capacityOf(cardW, cardH, density, mode === 'batch')
st.cap = cap // 拖拽排序换算「本页第 i 格 → 全局第几格」要用(旧代码用格子数,把「+添加」也算进去了)
const pages = Math.max(1, Math.ceil(items.length / cap.capacity))
const page = Math.max(0, Math.min(pages - 1, Number(d.page) || 0))
const from = page * cap.capacity
const to = Math.min(items.length, from + cap.capacity)
const selected = items.filter((it) => it && it.on !== false).length
// 一图一任务开关 / 计数 / 密度高亮 / 固化可用性
st.track.className = 'iwb-album-track' + (mode === 'per-image' ? ' on' : '')
st.count.innerHTML = ''
st.count.appendChild(document.createTextNode('已选 '))
st.count.appendChild(el('b', null, String(selected)))
st.count.appendChild(document.createTextNode('/' + items.length + ' · 每页 ' + cap.capacity))
for (const k in st.segs) st.segs[k].className = (density === k ? 'on' : '')
// v1.2.0:按模式切换可见控件(不适用的一律隐藏,不置灰)
const folderMode = isFolderMode(node)
const fileCount = items.filter((it) => fileRefOf(it && it.src)).length
st.btnSettle.textContent = fileCount ? ('固化 ' + fileCount) : '固化'
st.btnSettle.style.display = (!folderMode && fileCount) ? '' : 'none'
st.btnAdd.style.display = folderMode ? 'none' : ''
// v1.2.3:粘贴按钮只在混合模式显示;没有剪贴板能力(网页端/无 Rust 桥)时也隐藏
const canPaste = !folderMode && !!(window.IWBNativeClipboard && typeof window.IWBNativeClipboard.readImage === 'function')
st.btnPaste.style.display = canPaste ? '' : 'none'
st.btnRefresh.style.display = folderMode ? '' : 'none'
st.btnReload.style.display = folderMode ? '' : 'none'
st.btnDir.textContent = folderMode ? '更换文件夹' : '文件夹'
st.folderNote.style.display = folderMode ? '' : 'none'
st.folderLabel.classList.toggle('on', folderMode)
if (st.fTrack) st.fTrack.className = 'iwb-album-track' + (folderMode ? ' on' : '')
st.folderPath.style.display = folderMode ? '' : 'none'
if (!folderMode && !st.folderMsg.textContent) st.folderMsg.style.display = 'none'
if (folderMode) {
const dir = folderOf(node)
const skipped = skipOf(node).length
st.folderPath.textContent = '文件夹:' + (dir || '(未选择)') + (skipped ? (' · 已忽略 ' + skipped + ' 张') : '')
}
// 「文件夹」只在能做路径引用的宿主里有意义(桌面端)。旧写法 `canReference() || true` 恒真,
// 于是在不支持路径引用的宿主里点它永远没反应(这类宿主仍可用「+ 添加图片」走文件选择器)。
const canRef = !!(ctx.images && typeof ctx.images.canReference === 'function' && ctx.images.canReference())
st.btnDir.style.display = canRef ? '' : 'none'
st.btnClear.style.display = items.length ? '' : 'none'
if (st.busy) { st.btnAdd.textContent = st.busy } else { st.btnAdd.textContent = '+ 添加图片' }
// 批量模式提示:N 张 → M 个任务(每组 ≤ 12)
if (mode === 'batch' && items.length) {
st.hint.style.display = ''
st.hint.innerHTML = ''
st.hint.appendChild(document.createTextNode('整本一次请求:'))
st.hint.appendChild(el('b', null, items.length + ' 张 → ' + Math.ceil(items.length / 12) + ' 个任务'))
st.hint.appendChild(document.createTextNode('(每组 ≤ 12 张)'))
} else st.hint.style.display = 'none'
// 分页条 / 一页展示
// 空节点不再显示「全部 0 张一页展示」那条灰条(2026-11-26):它压着空态提示,说的还是废话。
const showPager = pages > 1
const showOne = !showPager && items.length > 0
st.pager.style.display = showPager ? '' : 'none'
st.onepage.style.display = showOne ? '' : 'none'
if (showOne) st.onepage.textContent = '全部 ' + items.length + ' 张一页展示 · 无需翻页'
if (showPager) {
st.pager.innerHTML = ''
const pg = el('span', { className: 'iwb-album-pg' })
const prev = onTap(el('span', { title: '上一页' }, '‹'), () => { if (page > 0) update(st.props, st.node, { page: page - 1 }) })
const next = onTap(el('span', { title: '下一页' }, '›'), () => { if (page < pages - 1) update(st.props, st.node, { page: page + 1 }) })
pg.appendChild(prev); pg.appendChild(el('b', null, (page + 1) + '/' + pages)); pg.appendChild(next)
st.pager.appendChild(pg)
const only = el('label', { className: 'iwb-album-mini' }, [
el('span', { className: 'iwb-album-track' + (d.onlyPage === true ? ' on' : '') }, el('i', null)),
document.createTextNode('仅本页参与'),
])
only.addEventListener('pointerdown', (e) => e.stopPropagation())
only.addEventListener('click', (e) => {
e.stopPropagation()
update(st.props, st.node, { onlyPage: !(d.onlyPage === true) })
})
st.pager.appendChild(only)
}
// 仅本页参与:把可见区间写回 data.pageRange(宿主任务图据此过滤;关闭时清掉)
const wantRange = (d.onlyPage === true) ? [from, to] : null
const curRange = Array.isArray(d.pageRange) ? d.pageRange : null
const rangeChanged = (!!wantRange !== !!curRange) || (wantRange && curRange && (wantRange[0] !== curRange[0] || wantRange[1] !== curRange[1]))
if (rangeChanged || (Number(d.page) || 0) !== page) {
update(st.props, st.node, { page: page, pageRange: wantRange })
}
// 宫格(签名不变就不重建:避免每帧重排导致闪烁/丢拖拽态)
const sig = [node.id, density, page, cap.capacity, mode, items.length, d.onlyPage === true ? 1 : 0,
items.map((it) => thumbKeyOf(it) + (it && it.on === false ? ':0' : ':1')).join(','), Array.from(st.missing).join(',')].join('|')
if (sig !== st.sig) {
st.sig = sig
st.grid.innerHTML = ''
st.grid.style.gridTemplateColumns = 'repeat(' + cap.cols + ', 1fr)'
if (!items.length) {
st.grid.style.display = 'none'; st.empty.style.display = ''
} else {
st.grid.style.display = ''; st.empty.style.display = 'none'
for (let i = from; i < to; i++) st.grid.appendChild(cellOf(ctx, st, items[i], i, mode))
if (to - from < cap.capacity && !isFolderMode(st.node)) {
const add = el('button', { className: 'iwb-album-cell iwb-album-add', title: '添加图片' }, [el('b', null, '+'), el('span', null, '添加')])
add.addEventListener('click', (e) => { e.stopPropagation(); pickFiles(ctx, st, st.root, false) })
st.grid.appendChild(add)
}
}
} else {
st.grid.style.gridTemplateColumns = 'repeat(' + cap.cols + ', 1fr)'
}
// 失联检测(每个节点一次;文件被移动/删除时给出明确提示)
if (!st.checkedMissing && items.some((it) => fileRefOf(it && it.src))) {
st.checkedMissing = true
checkMissing(ctx, st, items).then((changed) => { if (changed) { st.sig = ''; try { sync(ctx, st, st.node, st.props) } catch (e) { /* ignore */ } } })
}
}
// ── 单元格 ──────────────────────────────────────────────
// 放大镜图标(内联 SVG,CSP 禁外部资源):圆 + 手柄,10px 下仍看得清
function zoomIcon () {
const NS = 'http://www.w3.org/2000/svg'
const mk = (tag, attrs) => {
const n = document.createElementNS(NS, tag)
for (const k in attrs) n.setAttribute(k, attrs[k])
return n
}
const svg = mk('svg', { viewBox: '0 0 24 24', 'aria-hidden': 'true' })
svg.appendChild(mk('circle', { cx: 10, cy: 10, r: 7, fill: 'none', stroke: 'currentColor', 'stroke-width': 2.4 }))
svg.appendChild(mk('path', { d: 'M15.2 15.2 21 21', fill: 'none', stroke: 'currentColor', 'stroke-width': 2.4, 'stroke-linecap': 'round' }))
return svg
}
function cellOf (ctx, st, it, index, mode) {
const src = it && it.src
const path = fileRefOf(src)
const key = thumbKeyOf(it)
const on = !(it && it.on === false)
const missing = path && st.missing.has(path)
const btn = el('button', {
className: 'iwb-album-cell' + (on ? ' sel' : ' off') + (missing ? ' missing' : ''),
title: (it && it.name ? it.name : ('图 ' + (index + 1))) + (missing ? '(文件已不在原位置:点一下重新定位)' : ''),
})
const img = el('img', { alt: '', draggable: 'false' })
// 缩略图缓存可能来自旧路径/旧版本,dataURL 本身坏了也会命中;onerror 时绕过缓存重读原图一次。
let thumbRetried = false
const applyThumb = (url) => {
if (!url) return
img.onerror = () => {
if (thumbRetried) return
thumbRetried = true
st.thumbs.delete(key)
if (st.forceThumbs) st.forceThumbs.add(key)
dropThumbFile(ctx, key)
loadThumb(ctx, st, it, key, true).then((next) => { if (next) applyThumb(next) })
}
img.src = url
}
const cached = st.thumbs.get(key)
// ⚠ 命中内存缓存时 img **还没** appendChild(本函数末尾才挂),所以这里不能判存活:
// 1.1.5 把「存活判断」提进了 applyThumb,于是同步分支永远 isConnected === false ⇒ 直接 return,
// 每次「导入 / 翻页 / 切密度 / 拖拽排序」引发宫格重建后,内存里已有的缩略图全都赋不上 src,
// 格子一片空白(切走再切回来才正常 —— 那时内存缓存是空的,走异步分支)。
// 存活判断只对异步回来的那一支有意义:那时格子可能已被下一次重建丢掉。
if (cached) applyThumb(cached)
// 不设 img.src = '':空字符串会向页面 URL 发一次请求(控制台 ERR_UNKNOWN_URL_SCHEME)。
// 不设 src 属性时 <img> 什么都不做,缩略图到了再赋上即可。
// 异步分支才判存活(等图期间宫格可能已被下一次重建丢掉,旧 img 不该再赋值)
else loadThumb(ctx, st, it, key).then((u) => { if (u && img.isConnected) applyThumb(u) })
btn.appendChild(img)
btn.appendChild(el('span', { className: 'iwb-album-idx' }, String(index + 1)))
// v1.2.0:来源徽标(左下角)。让“是否已固化”可见,避免用户靠按钮有无去猜。
const srcState = missing ? '丢失'
: (path ? '引用'
: ((typeof src === 'string' && /^https?:/i.test(src)) ? '网络' : '已固化'))
btn.appendChild(el('span', { className: 'iwb-album-src' + (missing ? ' is-missing' : '') }, srcState))
// 批次角标(右上角那个「1」)已删除:顶栏「N 张 → M 个任务」已经说清楚,角标是重复信息,
// 还会和删除按钮抢同一个角。位置让给了 ×。
const del = el('span', { className: 'iwb-album-del', title: '移除(不删除磁盘上的原文件)' }, '×')
del.addEventListener('pointerdown', (e) => e.stopPropagation())
del.addEventListener('click', (e) => {
e.stopPropagation()
const items = itemsOf(st.node).slice()
const removed = items[index]
items.splice(index, 1)
// 删除后留在当前页(旧实现硬编码 page:0,第 2 页删一张直接跳回第 1 页)。
// 只做「页数变少时往回收」,正常情况 page 不动。
const capNow = st.cap || { capacity: 20 }
const pagesNow = Math.max(1, Math.ceil(items.length / capNow.capacity))
const pageNow = Math.max(0, Number((st.node.data || {}).page) || 0)
const patch = { items: items, page: Math.min(pageNow, pagesNow - 1) }
// v1.2.0:文件夹模式下手动删除要记进忽略名单,否则下次刷新又回来
const rmPath = fileRefOf(removed && removed.src)
if (isFolderMode(st.node) && rmPath) {
const skip = skipOf(st.node).slice()
if (skip.indexOf(rmPath) < 0) skip.push(rmPath)
patch.folderSkip = skip.slice(-500)
}
// v1.2.0:清掉该条目的缩略图文件(原来只删条目,ctx.files 里会越积越多)
try { dropThumbFile(ctx, thumbKeyOf(removed)) } catch (e) { /* ignore */ }
st.thumbs.delete(thumbKeyOf(removed))
update(st.props, st.node, patch, true)
})
btn.appendChild(del)
// 放大镜(右下角):点开插件自带的全屏查看器,可 ← → 切换整本相册(1.1.2)。
// 1.1.1 的 hover 预览已废(那层会盖住放大镜本身)。
const zoom = el('span', { className: 'iwb-album-zoom', title: '查看大图(← → 切换,点击空白处或 Esc 关闭)' }, zoomIcon())
zoom.addEventListener('pointerdown', (e) => e.stopPropagation())
zoom.addEventListener('click', (e) => { e.stopPropagation(); openFull(ctx, st, index) })
btn.appendChild(zoom)
btn.addEventListener('pointerdown', (e) => e.stopPropagation())
btn.addEventListener('click', (e) => {
e.stopPropagation()
if (missing) { relocate(ctx, st, index); return }
const items = itemsOf(st.node).slice()
if (!items[index]) return
items[index] = Object.assign({}, items[index], { on: !on })
update(st.props, st.node, { items })
})
// 拖拽排序
btn.addEventListener('pointerdown', (e) => {
if (e.button !== 0) return
const startX = e.clientX, startY = e.clientY
let moved = false
const target = { index: index }
const onMove = (ev) => {
const dx = ev.clientX - startX, dy = ev.clientY - startY
if (!moved && Math.abs(dx) + Math.abs(dy) < 5) return
moved = true
btn.classList.add('dragging')
const cells = Array.from(st.grid.querySelectorAll('.iwb-album-cell'))
let hit = cells.length - 1
for (let i = 0; i < cells.length; i++) {
const r = cells[i].getBoundingClientRect()
if (ev.clientX < r.left + r.width / 2 + (r.width * 0.1) && ev.clientY < r.bottom && ev.clientX > r.left - r.width) { hit = i; break }
}
cells.forEach((c, i) => c.classList.toggle('dropbefore', i === hit))
target.index = hit
}
const onUp = () => {
document.removeEventListener('pointermove', onMove)
document.removeEventListener('pointerup', onUp)
btn.classList.remove('dragging')
Array.from(st.grid.querySelectorAll('.dropbefore')).forEach((c) => c.classList.remove('dropbefore'))
if (!moved) return
const items = itemsOf(st.node).slice()
// 1.1.0 修跨页错位:本页起点 = page × **每页容量**(旧代码乘的是「本页格子数」,而格子数里
// 还含末尾那个「+添加」格 ⇒ 第 2 页永远算少一格,把 21 号拖到第 2 位会插到全局第 13 位)。
const capNow = st.cap || { capacity: 20 }
const pageNow = Math.max(0, Number((st.node.data || {}).page) || 0)
const pageStart = pageNow * capNow.capacity
const realCount = Math.min(capNow.capacity, Math.max(0, items.length - pageStart))
const srcIndex = index
let dest = pageStart + Math.min(target.index, realCount)
if (dest === srcIndex || dest < 0) return
const [movedItem] = items.splice(srcIndex, 1)
if (dest > srcIndex) dest -= 1
items.splice(Math.max(0, Math.min(items.length, dest)), 0, movedItem)
update(st.props, st.node, { items: items }, true)
}
document.addEventListener('pointermove', onMove)
document.addEventListener('pointerup', onUp)
})
return btn
}
// ── 缩略图取用:内存 → 插件文件 → 现做 ───────────────────
// 并发去重(1.1.0):格子一挂载就各自要缩略图,而 addPaths 又顺序预热一遍 ⇒ 同一张图会被读两次盘。
// 用 pending 表把同 key 的请求合成一个 Promise(否则导入 30 张会解 60 次原图,内存直接翻倍)。
async function loadThumb (ctx, st, it, key, force) {
const forced = !!force || !!(st.forceThumbs && st.forceThumbs.has(key))
if (!forced && st.thumbs.has(key)) return st.thumbs.get(key)
const flight = st.pending && st.pending.get(key)
if (flight && !forced) return flight
const p = loadThumbInner(ctx, st, it, key, forced).finally(() => { if (st.pending) st.pending.delete(key) })
if (st.pending) st.pending.set(key, p)
return p
}
async function loadThumbInner (ctx, st, it, key, force) {
if (!force && st.thumbs.has(key)) return st.thumbs.get(key)
// 读缓存要试两个后缀:同一个 key 可能存成 png(含透明)或 jpg(照片)。
// 先 png 不会误命中 —— 透明图只可能存 png,照片只可能存 jpg。
try {
if (!force && ctx.files) {
for (const name of thumbNames(key)) {
const got = await ctx.files.get(name)
if (got && got.ok && got.url) { st.thumbs.set(key, got.url); return got.url }
}
}
} catch (e) { /* 没缓存就现做 */ }
// v1.2.4(图片策略 v2):先让**宿主原生**出 320 小图 —— 不再把整幅原图读成 dataURL
// 再在 webview 里 canvas 缩放(那是 WebKit 上每次 21MB 的整幅解码,一夹 100 张就是 GB 级)。
const src = it && it.src
try {
if (ctx.images && typeof ctx.images.thumb === 'function') {
const u = await ctx.images.thumb(src, { max: 320 })
if (u && typeof u === 'string' && u.length < 512 * 1024) {
st.thumbs.set(key, u)
if (st.forceThumbs) st.forceThumbs.delete(key)
// 不再往 plugin-data 另存一份:宿主已在 thumbs/ 里按 hash 落了 tier,重复存等于两份
return u
}
}
} catch (e) { /* 回退到本地缩放 */ }
let dataUrl = ''
try {
if (typeof src === 'string' && src.indexOf('data:') === 0) dataUrl = src
else dataUrl = await ctx.images.dataUrl(src)
} catch (e) { dataUrl = '' }
if (!dataUrl) return ''
const made = await makeThumb(dataUrl)
if (!made || !made.url) return ''
st.thumbs.set(key, made.url)
if (st.forceThumbs) st.forceThumbs.delete(key)
// 内存里已经有一张就够本会话用了;写盘失败(配额满)不影响显示
try {
if (ctx.files) {
const put = await ctx.files.put(thumbNameOf(key, made.ext), made.url)
// 写成功才清旧:换格式留下的另一份、以及 1.1.5 的黑底 JPEG。
// 写失败(如 64MB 配额满)就先都留着,别把唯一一份也删了。
if (!put || put.ok !== false) dropThumbFile(ctx, key, made.ext)
}
} catch (e) { /* ignore */ }
return made.url
}
// ── 看大图:插件自带全屏查看器(1.1.2 起支持 ← → 切换)──────────
// 历史:1.1.0 做过「hover 节点内浮大图 + 点击全屏」两套,hover 层把放大镜盖住了 ⇒ 1.1.1 删掉。
// 1.1.2:宿主 props.onPreview 只收「已解析好的 URL 列表」,一本 30 张的相册要左右切换,
// 就得开窗前把 30 张原图全转成 dataURL(几十上百 MB,还可能卡住主线程)。所以改成自建查看器:
// 只解码当前这张 + 预取左右各一张(最多 3 张常驻),切换即时、内存可控。
// 交互沿用宿主那套肌肉记忆:点图片外的空白 / Esc 退出,← → 切换,滚轮也切。
const FS_KEEP = 3 // 同时保留的原图张数(当前 + 左右各一)
function closeViewer (st) {
const v = st && st.viewer
if (!v) return
st.viewer = null
try { window.removeEventListener('keydown', v.onKey, true) } catch (e) { /* ignore */ }
try { window.removeEventListener('wheel', v.onWheel, true) } catch (e) { /* ignore */ }
if (v.root && v.root.parentNode) v.root.parentNode.removeChild(v.root)
}
function openFull (ctx, st, index) {
closeViewer(st)
const items = itemsOf(st.node)
const total = items.length
if (!total) return
const pick = (i) => items[((i % total) + total) % total]
const keyAt = (i) => thumbKeyOf(pick(i))
let cur = Math.max(0, Math.min(total - 1, Number(index) || 0))
let curUrl = '' // 当前显示图的地址(复制/下载用)
let token = 0
const cache = new Map() // key → 原图 URL
const pending = new Map() // key → Promise(预取与切页会同时要同一张)
const img = el('img', { alt: '', draggable: 'false' })
const count = el('span', { className: 'iwb-album-fs-count' })
const name = el('span', { className: 'iwb-album-fs-name' })
const btnCopy = el('button', { className: 'iwb-album-fs-btn', title: '复制当前图片到剪贴板(PNG)' }, '复制')
const btnDl = el('button', { className: 'iwb-album-fs-btn', title: '下载当前图片' }, '下载')
const bar = el('div', { className: 'iwb-album-fs-bar' }, [count, name, btnCopy, btnDl])
const hint = el('div', { className: 'iwb-album-fs-hint' }, '点击空白处或按 Esc 关闭 · ← → 切换')
const btnPrev = el('button', { className: 'iwb-album-fs-nav prev', title: '上一张(←)' }, '‹')
const btnNext = el('button', { className: 'iwb-album-fs-nav next', title: '下一张(→)' }, '›')
const root = el('div', { className: 'iwb-album-fs' + (total > 1 ? '' : ' single') }, [img, btnPrev, btnNext, bar, hint])
// 原图按需读:命中缓存直接用;读盘失败就保持缩略图(不白屏、不报错)
const fullOf = (i) => {
const it = pick(i)
const key = keyAt(i)
if (cache.has(key)) return Promise.resolve(cache.get(key))
const flight = pending.get(key)
if (flight) return flight
if (!ctx.images || typeof ctx.images.dataUrl !== 'function') return Promise.resolve('')
// v1.2.4:大图也只取 2048 长边的预览(原生缩放),避免整幅解码 4K 原图
const ask = (ctx.images && typeof ctx.images.preview === 'function')
? Promise.resolve(ctx.images.preview(it && it.src, { max: 2048 })).then((r) => (r && r.dataUrl) || '')
: Promise.resolve(ctx.images.dataUrl(it && it.src))
const p = ask.then((u) => {
pending.delete(key)
if (!u) return ''
cache.set(key, u)
// 只留当前 + 左右各一张:4K 图的 dataURL 一张就几 MB,全书缓存直接爆内存
const keep = new Set([keyAt(cur), keyAt(cur + 1), keyAt(cur - 1)])
if (cache.size > FS_KEEP) for (const k of Array.from(cache.keys())) if (!keep.has(k)) cache.delete(k)
return u
}).catch(() => { pending.delete(key); return '' })
pending.set(key, p)
return p
}
const paint = (i) => {
const it = pick(i)
const my = ++token
const cached = cache.get(keyAt(i))
const thumb = st.thumbs.get(keyAt(i)) || ''
// 先用缩略图占位(切换时不会闪一块黑),原图到了再换上;缩略图也还没好就现做
if (cached) { img.src = cached; curUrl = cached }
else if (thumb) { img.src = thumb; curUrl = thumb }
else {
img.removeAttribute('src'); curUrl = ''
loadThumb(ctx, st, it, keyAt(i)).then((u) => { if (u && my === token) { img.src = u; curUrl = u } }).catch(() => {})
}
fullOf(i).then((u) => { if (u && my === token) { img.src = u; curUrl = u } }).catch(() => {})
count.textContent = (i + 1) + ' / ' + total
name.textContent = (it && it.name) || ('图 ' + (i + 1))
if (total > 1) { fullOf(i + 1).catch(() => {}); fullOf(i - 1).catch(() => {}) }
}
const go = (delta) => { cur = ((cur + delta) % total + total) % total; paint(cur) }
const close = () => closeViewer(st)
img.addEventListener('pointerdown', (e) => e.stopPropagation())
img.addEventListener('click', (e) => e.stopPropagation())
for (const [btn, delta] of [[btnPrev, -1], [btnNext, 1]]) {
btn.addEventListener('pointerdown', (e) => e.stopPropagation())
btn.addEventListener('click', (e) => { e.stopPropagation(); go(delta) })
}
// 复制 / 下载:宿主预览层原本有这两个按钮,不能因为换成自建查看器就丢掉
const flash = (msg) => {
hint.textContent = msg
clearTimeout(flash.timer)
flash.timer = setTimeout(() => { hint.textContent = '点击空白处或按 Esc 关闭 · ← → 切换' }, 1800)
}
const toPngBlob = (url) => new Promise((resolve, reject) => {
const im = new Image()
im.onload = () => {
try {
const cv = document.createElement('canvas')
cv.width = im.naturalWidth || 1; cv.height = im.naturalHeight || 1
cv.getContext('2d').drawImage(im, 0, 0)
cv.toBlob((b) => b ? resolve(b) : reject(new Error('toBlob 失败')), 'image/png')
} catch (e) { reject(e) }
}
im.onerror = () => reject(new Error('图片加载失败'))
im.src = url
})
for (const btn of [btnCopy, btnDl]) btn.addEventListener('pointerdown', (e) => e.stopPropagation())
btnDl.addEventListener('click', (e) => {
e.stopPropagation()
if (!curUrl) return
try {
const a = document.createElement('a')
a.href = curUrl
a.download = (pick(cur) && pick(cur).name) || ('image-' + (cur + 1) + '.png')
document.body.appendChild(a); a.click()
if (a.parentNode) a.parentNode.removeChild(a)
} catch (err) { flash('下载失败:' + String((err && err.message) || err)) }
})
btnCopy.addEventListener('click', async (e) => {
e.stopPropagation()
if (!curUrl) return
try {
const png = await toPngBlob(curUrl)
if (navigator.clipboard && typeof navigator.clipboard.write === 'function' && typeof ClipboardItem !== 'undefined') {
await navigator.clipboard.write([new ClipboardItem({ 'image/png': png })])
} else {
// WKWebView 常没有 ClipboardItem ⇒ 走宿主的原生 arboard 通道(与图库预览同一实现)
const D = window.IWBDesktop
if (!D || !D.clipboardWriteImage || !(await D.clipboardWriteImage(png))) throw new Error('当前环境不支持图片剪贴板')
}
flash('已复制图片到剪贴板(PNG)')
} catch (err) { flash('复制失败:' + String((err && err.message) || err)) }
})
// 整个浮层吃掉指针事件:否则点空白会把画布的「取消选中/框选」一起触发
root.addEventListener('pointerdown', (e) => { e.stopPropagation(); if (e.target === root || e.target === bar) close() })
root.addEventListener('click', (e) => e.stopPropagation())
root.addEventListener('pointerup', (e) => e.stopPropagation())
root.addEventListener('dblclick', (e) => e.stopPropagation())
// 键盘:捕获阶段吃掉,避免宿主把 ← → 当成「微调节点」
const onKey = (e) => {
if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); close() }
else if (e.key === 'ArrowLeft') { e.preventDefault(); e.stopPropagation(); go(-1) }
else if (e.key === 'ArrowRight') { e.preventDefault(); e.stopPropagation(); go(1) }
}
// 滚轮也切(大图查看器的通用手势);40ms 节流,避免一次滑到底翻好几张
let wheelLock = 0
const onWheel = (e) => {
if (total < 2) return
e.preventDefault(); e.stopPropagation()
const now = Date.now()
if (now - wheelLock < 40) return
const d = Math.abs(e.deltaY) > Math.abs(e.deltaX) ? e.deltaY : e.deltaX
if (Math.abs(d) < 2) return
wheelLock = now
go(d > 0 ? 1 : -1)
}
document.body.appendChild(root)
paint(cur)
window.addEventListener('keydown', onKey, true)
window.addEventListener('wheel', onWheel, { passive: false, capture: true })
st.viewer = { root, onKey, onWheel }
}
// ── 一键清空 ────────────────────────────────────────────
function clearAll (ctx, st) {
const items = itemsOf(st.node)
if (!items.length) return
for (const it of items) { try { dropThumbFile(ctx, thumbKeyOf(it)) } catch (e) { /* ignore */ } }
st.thumbs.clear(); st.pending.clear(); st.missing.clear(); if (st.forceThumbs) st.forceThumbs.clear()
st.checkedMissing = false // 清空后再导入要重新做一次失联检测
closeViewer(st) // 正在看大图时清空 ⇒ 先把浮层收掉(别留个没有数据的空查看器)
update(st.props, st.node, { items: [], page: 0, pageRange: null }, true)
st.sig = ''
sync(ctx, st, st.node, st.props)
}
// ── 导入:选择器 / 文件夹 / 拖入 / 固化 / 重新定位 ──────────
async function pickFiles (ctx, st, host, directory) {
if (st.busy) return
const items = itemsOf(st.node).slice()
// 桌面端:系统选择器给绝对路径 ⇒ 只引用(不复制字节)
if (ctx.images && ctx.images.canReference()) {
st.busy = '选择中…'; st.sig = ''; sync(ctx, st, st.node, st.props)
try {
const picked = await ctx.images.pick({ multiple: true, directory: !!directory })
st.busy = ''
if (!picked.length) { st.sig = ''; sync(ctx, st, st.node, st.props); return }
// 目录要展开成图片文件:pick 返回目录路径本身不是图片,之前直接过滤 ⇒ 「文件夹」点了没反应
let paths = []
if (directory) {
for (const dir of picked) {
try { const got = await ctx.images.listImages(dir); for (const f of (got || [])) paths.push(f) } catch (e) { /* 单个目录失败不阻断 */ }
}
if (paths.length >= FOLDER_MAX) {
st.busy = ''
st.hint.textContent = '该文件夹图片达到 ' + FOLDER_MAX + ' 张上限,已中止导入(未添加任何图)'
st.hint.style.display = ''
st.sig = ''; sync(ctx, st, st.node, st.props)
return
}
} else paths = picked.slice()
if (!paths.length) { st.sig = ''; sync(ctx, st, st.node, st.props); return }
await addPaths(ctx, st, paths)
} catch (e) { st.busy = ''; st.sig = ''; sync(ctx, st, st.node, st.props) }
return
}
// 不支持路径引用的宿主:退回文件选择 + 复制进画布存储
const input = document.createElement('input')
input.type = 'file'; input.accept = 'image/*'; input.multiple = true
input.style.display = 'none'
document.body.appendChild(input)
input.addEventListener('change', () => {
const files = Array.from(input.files || [])
document.body.removeChild(input)
if (files.length) importDropped(ctx, st, files)
})
input.click()
}
async function addPaths (ctx, st, paths) {
const list = paths.filter(isImagePath)
const items = itemsOf(st.node).slice()
for (let i = 0; i < list.length; i++) {
st.busy = '导入 ' + (i + 1) + '/' + list.length; st.sig = ''; sync(ctx, st, st.node, st.props)
const ref = await ctx.images.reference(list[i])
if (!ref || !ref.ok) continue
const nextSrc = { __file: ref.item.path }
// 重选同一文件夹:按归一化路径就地更新,不追加重复项(旧实现会让坏格一直留在前面,
// 新加的重复项排到后面/下一页,看起来就是「重新选择也不出缩略图」)。
let at = -1
for (let k = 0; k < items.length; k++) {
const p0 = fileRefOf(items[k] && items[k].src)
if (p0 && normPath(p0) === normPath(ref.item.path)) { at = k; break }
}
if (at >= 0) {
const old = items[at]
const oldKey = thumbKeyOf(old)
items[at] = Object.assign({}, old, { src: nextSrc, name: ref.item.name, size: ref.item.size, mtime: ref.item.mtime, on: true })
st.missing.delete(fileRefOf(old && old.src))
st.missing.delete(ref.item.path)
st.thumbs.delete(oldKey)
if (st.forceThumbs) st.forceThumbs.add(oldKey)
dropThumbFile(ctx, oldKey)
// 路径大小写/分隔符不同 ⇒ 新 key 也要清掉旧缓存并强制重读
const newKey = thumbKeyOf(items[at])
if (newKey !== oldKey) {
st.thumbs.delete(newKey)
if (st.forceThumbs) st.forceThumbs.add(newKey)
dropThumbFile(ctx, newKey)
}
} else {
items.push({ src: nextSrc, name: ref.item.name, size: ref.item.size, mtime: ref.item.mtime, on: true })
}
}
st.busy = ''
st.checkedMissing = false // 新图要重新做一次失联检测(否则清空后再导入,检测永远不再跑)
update(st.props, st.node, { items }, true)
st.sig = ''
sync(ctx, st, st.node, st.props)
// 顺序预生成缩略图(避免一次读几十张原图造成内存尖峰)。
// 1.1.0:进度写进「+ 添加图片」按钮(旧实现 busy 在这里已经清空 ⇒ 导入 500 张时界面像卡死);
// 只改按钮文字、不重置 sig ⇒ 不触发整块宫格重建(重建 500 次比读盘本身还慢)。
for (let i = 0; i < items.length; i++) {
const it = items[i]
const key = thumbKeyOf(it)
if (!key || st.thumbs.has(key)) continue
st.busy = '缩略图 ' + (i + 1) + '/' + items.length
st.btnAdd.textContent = st.busy
await loadThumb(ctx, st, it, key)
}
st.busy = ''
st.btnAdd.textContent = '+ 添加图片'
// 预生成只是「提前把缩略图做进缓存」:格子自己的 loadThumb 早在上面那次 sync 里就发起了,
// pending 表已把同一张合成一个 Promise。这里**不再**置空 sig 强制整块重建 ——
// 1.1.5 每次导入末尾都会多建一遍全部格子(500 张导入 = 白建 500 个 DOM),是肉眼可见的卡顿;
// 而它当年还掩盖了缩略图赋值的问题(重建恰好把所有格子都变成「命中缓存 → 空白」)。
}
async function importDropped (ctx, st, files) {
const items = itemsOf(st.node).slice()
for (let i = 0; i < files.length; i++) {
const f = files[i]
if (!f || !/^image\//i.test(f.type || '')) continue
st.busy = '复制 ' + (i + 1) + '/' + files.length; st.sig = ''; sync(ctx, st, st.node, st.props)
const dataUrl = await new Promise((resolve) => {
try { const r = new FileReader(); r.onload = () => resolve(String(r.result || '')); r.onerror = () => resolve(''); r.readAsDataURL(f) } catch (e) { resolve('') }
})
if (!dataUrl) continue
let res = null
try { res = await ctx.images.importDataUrl(dataUrl, { keepOriginal: (st.node.data && st.node.data.keepOriginal !== false) }) } catch (e) { res = null }
if (!res || !res.ok) continue
const src = res.ref || res.data
if (!src) continue
const name = f.name || ('图 ' + (items.length + 1))
items.push({ src, name: name, size: f.size || 0, on: true })
const made = await makeThumb(dataUrl)
// 键必须和 cellOf / loadThumb 完全一致(thumbKeyOf),否则写进缓存也命中不到
if (made && made.url) {
const key = thumbKeyOf(items[items.length - 1])
st.thumbs.set(key, made.url)
try { if (ctx.files) await ctx.files.put(thumbNameOf(key, made.ext), made.url) } catch (e) { /* ignore */ }
}
}
st.busy = ''
st.checkedMissing = false
update(st.props, st.node, { items }, true)
st.sig = ''
sync(ctx, st, st.node, st.props)
}
// ── 粘贴(v1.2.3)──────────────────────────────────────
// 走宿主已有的 IWBNativeClipboard(桌面端 = Rust arboard,能读截图 / 网页复制 / 访达复制文件)。
// 插件与宿主同窗口,直接取全局即可,不需要新增宿主 API;网页端回落 navigator.clipboard.read()。
function fileToDataUrl (file) {
return new Promise((resolve) => {
try {
const r = new FileReader()
r.onload = () => resolve(String(r.result || ''))
r.onerror = () => resolve('')
r.readAsDataURL(file)
} catch (e) { resolve('') }
})
}
async function readClipboardFile () {
const C = (typeof window !== 'undefined') ? window.IWBNativeClipboard : null
if (C && typeof C.readImage === 'function') {
try { const f = await C.readImage(); if (f) return { file: f, reason: '' } } catch (e) { /* 落到下面的文案 */ }
const why = (typeof C.lastReason === 'function') ? String(C.lastReason() || '') : ''
return { file: null, reason: why }
}
// 网页端兜底:navigator.clipboard.read()(需要权限,失败就按“没有图片”处理)
try {
const nav = window.navigator
if (nav && nav.clipboard && typeof nav.clipboard.read === 'function') {
const items = await nav.clipboard.read()
for (const it of (items || [])) {
const type = (it.types || []).find((t) => /^image\//i.test(t))
if (!type) continue
const blob = await it.getType(type)
return { file: new File([blob], 'clipboard-' + Date.now() + '.png', { type: blob.type || type }), reason: '' }
}
}
} catch (e) { /* ignore */ }
return { file: null, reason: '' }
}
async function pasteFromClipboard (ctx, st) {
if (st.busy) return
st.busy = '粘贴…'; st.sig = ''; sync(ctx, st, st.node, st.props)
const got = await readClipboardFile()
st.busy = ''
if (!got.file) {
setFolderMsg(st, '剪贴板里没有图片' + (got.reason ? '(' + got.reason + ')' : '(截图或 ⌘C 复制图片后再试)'))
st.sig = ''; sync(ctx, st, st.node, st.props)
return
}
const dataUrl = await fileToDataUrl(got.file)
if (!dataUrl) { setFolderMsg(st, '读取剪贴板图片失败'); st.sig = ''; sync(ctx, st, st.node, st.props); return }
let res = null
try { res = await ctx.images.importDataUrl(dataUrl, { keepOriginal: (st.node.data && st.node.data.keepOriginal !== false) }) } catch (e) { res = null }
if (!res || !res.ok || !(res.ref || res.data)) { setFolderMsg(st, '粘贴失败:图片没能写入画布存储'); st.sig = ''; sync(ctx, st, st.node, st.props); return }
const items = itemsOf(st.node).slice()
items.push({ src: res.ref || res.data, name: got.file.name || ('粘贴 ' + (items.length + 1)), size: got.file.size || 0, on: true })
// 缩略图:与「添加图片」同一条链路
const made = await makeThumb(dataUrl)
if (made && made.url) {
const key = thumbKeyOf(items[items.length - 1])
st.thumbs.set(key, made.url)
try { if (ctx.files) await ctx.files.put(thumbNameOf(key, made.ext), made.url) } catch (e) { /* ignore */ }
}
setFolderMsg(st, '')
update(st.props, st.node, { items }, true)
st.sig = ''
sync(ctx, st, st.node, st.props)
}
// 固化:把 __file 引用换成宿主存储引用(删源文件/分享画布前用)
async function settleAll (ctx, st) {
const items = itemsOf(st.node).slice()
let done = 0
let skipped = 0
for (let i = 0; i < items.length; i++) {
const it = items[i]
const path = fileRefOf(it && it.src)
if (!path) { skipped++; continue } // 已固化/网络图:跳过,不重复读字节
st.busy = '固化 ' + (++done) + '…'; st.sig = ''; sync(ctx, st, st.node, st.props)
try {
const res = await ctx.images.importPath(path, { keepOriginal: (st.node.data && st.node.data.keepOriginal !== false) })
if (res && res.ok && (res.ref || res.data)) items[i] = Object.assign({}, it, { src: res.ref || res.data })
} catch (e) { /* 单张失败不打断整批 */ }
}
st.busy = ''
update(st.props, st.node, { items }, true)
st.sig = ''
sync(ctx, st, st.node, st.props)
if (skipped) { st.hint.textContent = '已跳过 ' + skipped + ' 张(已固化或非本地引用)'; st.hint.style.display = '' }
}
async function checkMissing (ctx, st, items) {
let changed = false
for (const it of items) {
const path = fileRefOf(it && it.src)
if (!path) continue
try {
const r = await ctx.images.stat(path)
const missing = !(r && r.ok && r.exists)
if (missing && !st.missing.has(path)) { st.missing.add(path); changed = true }
if (!missing && st.missing.has(path)) { st.missing.delete(path); changed = true }
} catch (e) { /* 检测失败按存在处理 */ }
}
return changed
}
// 失联重定位:点失联格 → 选一张同名/任意图片替换
async function relocate (ctx, st, index) {
if (!ctx.images || !ctx.images.canReference()) return
const items = itemsOf(st.node).slice()
const cur = items[index]
if (!cur) return
const paths = await ctx.images.pick({ multiple: false })
if (!paths || !paths.length) return
const ref = await ctx.images.reference(paths[0])
if (!ref || !ref.ok) return
const oldPath = fileRefOf(cur.src)
st.missing.delete(oldPath)
items[index] = Object.assign({}, cur, { src: { __file: ref.item.path }, name: ref.item.name, size: ref.item.size, mtime: ref.item.mtime })
update(st.props, st.node, { items }, true)
st.sig = ''
sync(ctx, st, st.node, st.props)
loadThumb(ctx, st, items[index], thumbKeyOf(items[index])).then(() => { st.sig = ''; try { sync(ctx, st, st.node, st.props) } catch (e) { /* ignore */ } })
}
// ── 注册 ────────────────────────────────────────────────
global.IWBPluginHost.register({
id: 'album',
name: '相册',
version: '1.2.5',
apiVersion: 1,
capabilities: ['nodeTypes', 'images', 'files'],
settings: {
keepOriginal: { type: 'boolean', label: '默认保留原图(不压缩)', desc: '开启后导入不进 1600 长边压缩,分辨率不损失(占用更高)。节点内可单独改。', default: true },
},
}, function (ctx) {
ctx.nodes.register({
id: 'album',
title: '相册',
icon: 'puzzle',
width: 300,
height: 470,
ports: { in: true, out: true },
defaults: { outKind: 'images', items: [], albumMode: 'per-image', density: 'S', page: 0, onlyPage: false, keepOriginal: ctx.settings.get('keepOriginal') !== false },
render: function (node, props, host) {
// 自愈(2026-11-26):旧版本/兜底路径建出来的节点可能没有 outKind,
// 那样连线规则会把相册当普通插件节点(只能连中继)。这里补写一次默认值。
try {
const d0 = node && node.data
if (d0 && d0.outKind !== 'images') {
props.onUpdate(node.id, { outKind: 'images', items: Array.isArray(d0.items) ? d0.items : [] })
}
} catch (e) { /* ignore */ }
let st = STATE.get(host)
if (!st || st.nodeId !== node.id) { st = buildShell(ctx, node, props, host); STATE.set(host, st) }
try { sync(ctx, st, node, props) } catch (e) {
// 渲染失败降级成一行可读文本(绝不让整块画布白屏)
try { host.textContent = ''; const tip = document.createElement('div'); tip.className = 'iwb-hint'; tip.textContent = '相册渲染失败:' + String((e && e.message) || e); host.appendChild(tip) } catch (e2) { /* ignore */ }
}
},
})
return {}
})
})(typeof window !== 'undefined' ? window : globalThis)