36 lines
1.5 KiB
JavaScript
36 lines
1.5 KiB
JavaScript
;(function (global) {
|
|
'use strict'
|
|
|
|
function createHydrator(options) {
|
|
const opt = options || {}
|
|
const get = typeof opt.get === 'function' ? opt.get : (() => Promise.resolve(null))
|
|
// 文件存储:清单只留 thumbHash,缩略图按需从 images/thumbs/ 读
|
|
const thumb = typeof opt.thumb === 'function' ? opt.thumb : null
|
|
let sequence = 0
|
|
let disposed = false
|
|
async function hydrate(items, requestId) {
|
|
const id = requestId == null ? ++sequence : requestId
|
|
if (id > sequence) sequence = id
|
|
const list = Array.isArray(items) ? items : []
|
|
const values = await Promise.all(list.map(async (item) => {
|
|
if (!item) return item
|
|
if (item.data) return item
|
|
if (thumb && item.thumbHash) {
|
|
try { const v = await thumb(item.thumbHash); if (v) return Object.assign({}, item, { data: v }) } catch (e) { /* 读文件失败退回 idb */ }
|
|
}
|
|
if (!item.idb) return item
|
|
try {
|
|
const value = await get(item.idb)
|
|
return value == null ? item : Object.assign({}, item, { data: value })
|
|
} catch (e) { return item }
|
|
}))
|
|
return { requestId: id, stale: disposed || id !== sequence, items: values }
|
|
}
|
|
function nextRequest() { return ++sequence }
|
|
function dispose() { disposed = true; sequence++ }
|
|
return { hydrate, nextRequest, dispose, get currentRequestId() { return sequence } }
|
|
}
|
|
|
|
global.IWBGalleryHydration = { create: createHydrator }
|
|
})(typeof window !== 'undefined' ? window : globalThis)
|