553 lines
27 KiB
JavaScript
553 lines
27 KiB
JavaScript
// 相册节点(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
|
||
|
||
const DENSITY = { S: 64, M: 48, L: 100 }
|
||
const GAP = 5
|
||
const PAD_X = 16 // 宫格左右 padding 合计(与 styles.css 对齐)
|
||
const PAD_Y = 8 // 上下 padding 合计
|
||
const BAR_H = 26 // 状态栏
|
||
const TOOLS_H = 27 // 工具条
|
||
const PAGER_H = 26 // 分页条 / 一页提示条
|
||
const HINT_H = 24 // 批量模式提示行
|
||
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
|
||
}
|
||
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(/^.*[\\/]/, '')
|
||
const str = (v) => (v == null ? '' : String(v))
|
||
|
||
// ── 缩略图(插件私有缓存,几十 KB/张,不碰画布存储)────────────
|
||
const thumbNameOf = (key) => 't-' + hash32(key) + '.jpg'
|
||
|
||
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)
|
||
resolve(cv.toDataURL('image/jpeg', THUMB_Q))
|
||
} catch (e) { resolve('') }
|
||
}
|
||
img.onerror = () => resolve('')
|
||
img.src = dataUrl
|
||
} catch (e) { resolve('') }
|
||
})
|
||
}
|
||
|
||
// ── 容量:随节点宽高实时算(放大 = 一页装更多)────────────────
|
||
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(内存缓存)
|
||
missing: new Set(), // 失联文件的 key
|
||
busy: '',
|
||
checkedMissing: false,
|
||
sig: '',
|
||
}
|
||
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('一图一任务'))
|
||
modeLabel.addEventListener('pointerdown', (e) => e.stopPropagation())
|
||
modeLabel.addEventListener('click', (e) => {
|
||
e.stopPropagation()
|
||
const d = (node && node.data) || {}
|
||
const next = d.albumMode === 'batch' ? 'per-image' : 'batch'
|
||
update(props, node, { albumMode: next })
|
||
})
|
||
const count = el('span', { className: 'iwb-album-count' })
|
||
bar.appendChild(modeLabel); bar.appendChild(count)
|
||
|
||
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: '把引用复制进画布存储(删源文件/分享画布前用)' }, '固化')
|
||
const seg = el('span', { className: 'iwb-album-seg' })
|
||
const segs = {}
|
||
for (const key of ['S', 'M', 'L']) {
|
||
const s = el('span', { title: key === 'S' ? '小格(默认)' : (key === 'M' ? '中格' : '大格') }, key)
|
||
s.addEventListener('click', (e) => { e.stopPropagation(); update(props, node, { density: key }) })
|
||
segs[key] = s; seg.appendChild(s)
|
||
}
|
||
const tools = el('div', { className: 'iwb-album-tools' }, [btnAdd, btnDir, btnSettle, 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' }, '全部图片一页展示')
|
||
|
||
host.textContent = ''
|
||
const root = el('div', { className: 'iwb-album' }, [bar, tools, hint, grid, empty, pager, onepage])
|
||
host.appendChild(root)
|
||
Object.assign(st, { root, bar, track, count, btnAdd, btnDir, btnSettle, segs, grid, empty, pager, onepage, hint })
|
||
|
||
// 按钮绑定(用闭包里的当前 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) })
|
||
|
||
// 拖拽入图:桌面端拿不到绝对路径 ⇒ 按「方案 1」复制进画布存储
|
||
host.addEventListener('dragover', (e) => { e.preventDefault(); e.stopPropagation() })
|
||
host.addEventListener('drop', (e) => {
|
||
e.preventDefault(); e.stopPropagation()
|
||
const files = Array.from((e.dataTransfer && e.dataTransfer.files) || [])
|
||
if (files.length) importDropped(ctx, st, files)
|
||
})
|
||
return 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'
|
||
// 尺寸来源:节点显式 w/h → 宿主实测高度 → 插件默认值。
|
||
// ⚠ 不能用 host.getBoundingClientRect() 当高度:插件节点体是内容撑开的(auto),
|
||
// 量到的是「当前内容」而不是「卡片能有多高」⇒ 容量永远算成 1 行。
|
||
const measured = measure(st.root)
|
||
const cardW = Number(node.w) || Number(d.width) || measured.width || 300
|
||
const cardH = Number(node.h) || Number(props.measuredH) || 470
|
||
st.root.style.height = Math.max(120, Math.round(cardH) - 4) + 'px'
|
||
const cap = capacityOf(cardW, cardH, density, mode === 'batch')
|
||
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' : '')
|
||
const hasFileRef = items.some((it) => fileRefOf(it && it.src))
|
||
st.btnSettle.style.display = hasFileRef ? '' : 'none'
|
||
st.btnDir.style.display = (ctx.images && ctx.images.canReference()) || true ? '' : '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'
|
||
|
||
// 分页条 / 一页展示
|
||
const showPager = pages > 1
|
||
st.pager.style.display = showPager ? '' : 'none'
|
||
st.onepage.style.display = showPager ? 'none' : ''
|
||
if (!showPager) st.onepage.textContent = '全部 ' + items.length + ' 张一页展示 · 无需翻页'
|
||
if (showPager) {
|
||
st.pager.innerHTML = ''
|
||
const pg = el('span', { className: 'iwb-album-pg' })
|
||
const prev = el('span', { title: '上一页' }, '‹')
|
||
const next = el('span', { title: '下一页' }, '›')
|
||
prev.addEventListener('click', (e) => { e.stopPropagation(); if (page > 0) update(st.props, st.node, { page: page - 1 }) })
|
||
next.addEventListener('click', (e) => { e.stopPropagation(); 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) => (it && (fileRefOf(it.src) || it.name)) || '').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) {
|
||
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 */ } } })
|
||
}
|
||
}
|
||
|
||
// ── 单元格 ──────────────────────────────────────────────
|
||
function cellOf (ctx, st, it, index, mode) {
|
||
const src = it && it.src
|
||
const path = fileRefOf(src)
|
||
const key = path || str(it && it.name) || String(index)
|
||
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' })
|
||
const cached = st.thumbs.get(key)
|
||
if (cached) img.src = cached
|
||
else {
|
||
img.src = ''
|
||
loadThumb(ctx, st, it, key).then((url) => { if (url) img.src = url })
|
||
}
|
||
btn.appendChild(img)
|
||
btn.appendChild(el('span', { className: 'iwb-album-idx' }, String(index + 1)))
|
||
if (mode === 'batch' && on) btn.appendChild(el('span', { className: 'iwb-album-batch' }, String(Math.floor(index / 12) + 1)))
|
||
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()
|
||
items.splice(index, 1)
|
||
update(st.props, st.node, { items, page: 0 }, true)
|
||
})
|
||
btn.appendChild(del)
|
||
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()
|
||
const cellCount = st.grid.querySelectorAll('.iwb-album-cell').length
|
||
const pageStart = (Number((st.node.data || {}).page) || 0) * cellCount
|
||
const from = pageStart
|
||
const srcIndex = index
|
||
let dest = from + target.index
|
||
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 }, true)
|
||
}
|
||
document.addEventListener('pointermove', onMove)
|
||
document.addEventListener('pointerup', onUp)
|
||
})
|
||
return btn
|
||
}
|
||
|
||
// ── 缩略图取用:内存 → 插件文件 → 现做 ───────────────────
|
||
async function loadThumb (ctx, st, it, key) {
|
||
if (st.thumbs.has(key)) return st.thumbs.get(key)
|
||
const name = thumbNameOf(key)
|
||
try {
|
||
if (ctx.files) {
|
||
const got = await ctx.files.get(name)
|
||
if (got && got.ok && got.url) { st.thumbs.set(key, got.url); return got.url }
|
||
}
|
||
} catch (e) { /* 没缓存就现做 */ }
|
||
let dataUrl = ''
|
||
const src = it && it.src
|
||
try {
|
||
if (fileRefOf(src)) dataUrl = await ctx.images.dataUrl(src)
|
||
else if (typeof src === 'string') dataUrl = src
|
||
else dataUrl = await ctx.images.dataUrl(src)
|
||
} catch (e) { dataUrl = '' }
|
||
if (!dataUrl) return ''
|
||
const thumb = await makeThumb(dataUrl)
|
||
if (!thumb) return ''
|
||
st.thumbs.set(key, thumb)
|
||
try { if (ctx.files) await ctx.files.put(name, thumb) } catch (e) { /* 配额满就只留内存 */ }
|
||
return thumb
|
||
}
|
||
|
||
// ── 导入:选择器 / 文件夹 / 拖入 / 固化 / 重新定位 ──────────
|
||
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 paths = await ctx.images.pick({ multiple: true, directory: !!directory })
|
||
st.busy = ''
|
||
if (paths.length) await addPaths(ctx, st, paths)
|
||
else { st.sig = ''; sync(ctx, st, st.node, st.props) }
|
||
} 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()
|
||
const keep = (st.node.data && st.node.data.keepOriginal !== false)
|
||
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
|
||
items.push({ src: { __file: ref.item.path }, name: ref.item.name, size: ref.item.size, mtime: ref.item.mtime, on: true })
|
||
}
|
||
st.busy = ''
|
||
update(st.props, st.node, { items }, true)
|
||
st.sig = ''
|
||
sync(ctx, st, st.node, st.props)
|
||
// 顺序生成缩略图(避免一次读几十张原图造成内存尖峰)
|
||
for (const it of items) {
|
||
const key = fileRefOf(it.src) || it.name
|
||
if (key) await loadThumb(ctx, st, it, key)
|
||
}
|
||
st.sig = ''
|
||
sync(ctx, st, st.node, st.props)
|
||
}
|
||
|
||
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, size: f.size || 0, on: true })
|
||
const thumb = await makeThumb(dataUrl)
|
||
if (thumb) { st.thumbs.set(name, thumb); try { if (ctx.files) await ctx.files.put(thumbNameOf(name), thumb) } catch (e) { /* ignore */ } }
|
||
}
|
||
st.busy = ''
|
||
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
|
||
for (let i = 0; i < items.length; i++) {
|
||
const it = items[i]
|
||
const path = fileRefOf(it && it.src)
|
||
if (!path) 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)
|
||
}
|
||
|
||
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], fileRefOf(items[index].src)).then(() => { st.sig = ''; try { sync(ctx, st, st.node, st.props) } catch (e) { /* ignore */ } })
|
||
}
|
||
|
||
// ── 注册 ────────────────────────────────────────────────
|
||
global.IWBPluginHost.register({
|
||
id: 'album',
|
||
name: '相册',
|
||
version: '1.0.0',
|
||
apiVersion: 1,
|
||
capabilities: ['nodeTypes', 'images', 'files'],
|
||
settings: {
|
||
keepOriginal: { type: 'boolean', label: '默认保留原图(不压缩)', desc: '开启后导入不进 1600 长边压缩,分辨率不损失(占用更高)。节点内可单独改。', default: true },
|
||
},
|
||
}, function (ctx) {
|
||
ctx.nodes.register({
|
||
id: 'album',
|
||
title: '相册',
|
||
width: 300,
|
||
height: 470,
|
||
color: '#8a8a8a',
|
||
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) {
|
||
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)
|