74 lines
3.2 KiB
JavaScript
74 lines
3.2 KiB
JavaScript
/* plugin-api-gallery.js —— 宿主 gallery capability(M5)
|
||
*
|
||
* 给插件一块**只读为主**的图库访问面:列表 / 缩略图 / 预览 / 下载 / 插入画布 / 删除。
|
||
* 图片字节仍留在宿主(桌面端 = images/gallery + images/thumbs 文件,浏览器 = IndexedDB),
|
||
* 插件拿不到文件路径,只能拿元数据与缩略图 URL。
|
||
*
|
||
* 为什么要这层「impl 桥」:
|
||
* capability 在 PluginHost.init 时创建(早于组件渲染),拿不到 Workbench 的 state/refs。
|
||
* 所以这里只保存一组**稳定的代理函数**,真正的实现由 Workbench 每次渲染时 setImpl 注入。
|
||
*
|
||
* v1.7.0(2026-11-24):补 onChanged —— 此前只有「拉」没有「推」,出图后图库面板要等
|
||
* 可见性变化/5s 节流才刷新,用户看到的是「生成了但图库没图」。宿主在归档、删除、恢复后
|
||
* emit 一次,插件订阅后自己 load()。
|
||
*/
|
||
;(function (global) {
|
||
'use strict'
|
||
|
||
let impl = null
|
||
const listeners = []
|
||
|
||
function setImpl (next) {
|
||
impl = (next && typeof next === 'object') ? next : null
|
||
}
|
||
|
||
function call (name) {
|
||
return function () {
|
||
const fn = impl && impl[name]
|
||
if (typeof fn !== 'function') return Promise.reject(new Error('图库能力未就绪'))
|
||
try { return Promise.resolve(fn.apply(null, arguments)) } catch (e) { return Promise.reject(e) }
|
||
}
|
||
}
|
||
|
||
// 图库数据变了下发一次(生成结果逐张归档 / 删除 / 恢复 / 清空 / 保留策略剪枝)
|
||
function emit (reason) {
|
||
for (const fn of listeners.slice()) {
|
||
try { fn(reason || 'changed') } catch (e) { /* 插件回调异常不影响宿主 */ }
|
||
}
|
||
}
|
||
|
||
// 稳定代理:插件拿到的对象永不变,内部每次都取最新的 impl
|
||
const API = {
|
||
list: call('list'),
|
||
thumb: call('thumb'),
|
||
preview: call('preview'),
|
||
download: call('download'),
|
||
insert: call('insert'),
|
||
remove: call('remove'),
|
||
backfill: call('backfill'),
|
||
openFolder: call('openFolder'),
|
||
onChanged: function (fn) {
|
||
if (typeof fn !== 'function') return function () {}
|
||
listeners.push(fn)
|
||
return function () { const i = listeners.indexOf(fn); if (i >= 0) listeners.splice(i, 1) }
|
||
},
|
||
}
|
||
|
||
// 纯函数:把宿主 outputs + 查询参数变成插件要的条目(不含 data,避免把 base64 递给插件)
|
||
function query (outputs, opt) {
|
||
const o = opt || {}
|
||
const Q = global.IWBGalleryQuery
|
||
const list = Array.isArray(outputs) ? outputs : []
|
||
const limit = Math.min(500, Math.max(1, Number(o.limit) || 200))
|
||
const res = (Q && typeof Q.queryOutputs === 'function')
|
||
? Q.queryOutputs(list, { query: o.query || '', range: o.range || '', limit, width: 320, tile: 130 })
|
||
: { filtered: list, visible: list.slice(0, limit), total: list.length }
|
||
const items = (res.visible || []).map(function (f) {
|
||
return { name: f.name, label: f.label || '', w: f.w || 0, h: f.h || 0, mtime: f.mtime || 0, orig: f.orig || (f.origIdb ? 'ok' : 'missing') }
|
||
})
|
||
return { items: items, total: res.total || items.length }
|
||
}
|
||
|
||
global.IWBPluginGallery = { setImpl: setImpl, api: function () { return API }, query: query, emit: emit }
|
||
})(typeof window !== 'undefined' ? window : globalThis)
|