/* image-ingest-store.js —— 落地队列的持久化 + 状态视图(2026-12-02) * * 两个职责,都很薄: * 1) store:把 ingest 的记录存在 localStorage(只存元数据与引用,不存字节;字节在 blob 引用存储里) * —— 断点恢复靠它;上限 500 条,超出按最旧淘汰(pinned 不动) * 2) view:url → 状态的内存索引,供结果图组件按 url 查「下载中 / 失败 / 已就绪」 * —— 组件订阅 notify 后重渲染,不需要把状态灌进画布节点数据 * * 与 image-ingest.js 的分工:那边是执行器(下载/重试),这边只管「记账」和「给 UI 看」。 */ ;(function (global) { 'use strict' const KEY = 'iwb_ingest_idx' const MAX = 500 function createStore (deps) { const d = deps || {} const lsGet = typeof d.get === 'function' ? d.get : () => null const lsSet = typeof d.set === 'function' ? d.set : () => {} let cache = null function load () { if (cache) return cache let arr = null try { arr = lsGet(KEY) } catch (e) { arr = null } cache = Array.isArray(arr) ? arr.filter((x) => x && x.id && x.url) : [] return cache } function save (entry) { if (!entry || !entry.id) return const arr = load() const at = arr.findIndex((x) => x.id === entry.id) if (at >= 0) arr[at] = entry else arr.push(entry) if (arr.length > MAX) { // 淘汰最旧的非 pinned 记录(pinned = 被画布/图库引用) const drop = arr.filter((x) => !x.pinned).sort((a, b) => (a.createdAt || 0) - (b.createdAt || 0)) while (arr.length > MAX && drop.length) { const victim = drop.shift() const i = arr.indexOf(victim) if (i >= 0) arr.splice(i, 1) } } try { lsSet(KEY, arr) } catch (e) { /* 配额满:保留内存态,下次启动丢,不影响当前会话 */ } } function remove (id) { const arr = load() const i = arr.findIndex((x) => x.id === id) if (i >= 0) arr.splice(i, 1) try { lsSet(KEY, arr) } catch (e) { /* ignore */ } } function list () { return load().slice() } return { load, save, remove, list, KEY, MAX } } // 视图:url → { status, localUrl, bytes, error };订阅者用于 React 重渲染 function createView () { const byUrl = new Map() const subs = new Set() function set (entry) { if (!entry || !entry.url) return const prev = byUrl.get(entry.url) || {} byUrl.set(entry.url, { id: entry.id, status: entry.status, ref: entry.ref || prev.ref || null, displayRef: entry.displayRef || prev.displayRef || null, localUrl: entry.localUrl || prev.localUrl || '', bytes: entry.bytes || 0, error: entry.lastError || '', }) } function byUrlOf (url) { return byUrl.get(String(url || '')) || null } function hydrate (entries) { for (const e of (entries || [])) set(e) } function subscribe (fn) { if (typeof fn === 'function') { subs.add(fn); return () => subs.delete(fn) } return () => {} } function notify () { for (const fn of [...subs]) { try { fn() } catch (e) { /* ignore */ } } } return { set, get: byUrlOf, hydrate, subscribe, notify } } global.IWBImageIngestStore = { createStore, createView, KEY } })(typeof window !== 'undefined' ? window : globalThis)