/* image-remote-cache.js —— 远程参考图本地缓存(v3.25.80) * * 目的:远程参考图(如 ibb.co)每次打开画布都重新下载,慢且耗流量。 * 做法:空闲时下载一次,写入本地引用存储,节点上只记 data.localRef(显示用)。 * * 约束(用户裁定):节点 data.url 保持原样 ⇒ **提交生成时仍然用链接**。 */ ;(function (global) { 'use strict' const React = global.React || {} function useRemoteRefCache (opts) { const o = opts || {} const tried = React.useRef(new Set()) React.useEffect(() => { if (!o.enabled) return undefined const pend = (o.nodes || []).filter((n) => n && n.type === 'ref' && n.data && !n.data.data && !n.data.localRef && /^https?:\/\//i.test(String(n.data.url || '')) && !tried.current.has(n.id)) if (!pend.length) return undefined const timer = setTimeout(() => { (async () => { for (const n of pend) { tried.current.add(n.id) try { const url = String((n.data && n.data.url) || '') if (!url) continue const resp = await fetch(url, { credentials: 'omit' }) if (!resp || !resp.ok) continue const blob = await resp.blob() if (!blob || !blob.size) continue const dataUrl = await new Promise((res, rej) => { const rd = new FileReader() rd.onload = () => res(String(rd.result || '')) rd.onerror = () => rej(new Error('read-failed')) rd.readAsDataURL(blob) }) if (!dataUrl) continue const ref = await o.writeRef(dataUrl) if (ref) { o.updateNode(n.id, { localRef: ref }); break } } catch (e) { /* 跨域/离线:保留 url 显示,不重试 */ } } })() }, 2500) return () => clearTimeout(timer) }, [o.enabled, o.activeWsId, o.nodes]) } // 非 Hook 版本:宿主在自己的 effect 里调用,返回 stop()。 function startRemoteRefCache (opts) { const o = opts || {} const tried = new Set() const timer = setInterval(() => { let st = null try { st = typeof o.getState === 'function' ? o.getState() : null } catch (e) { st = null } if (!st || !st.enabled || !Array.isArray(st.nodes)) return const next = st.nodes.find((n) => n && n.type === 'ref' && n.data && !n.data.data && !n.data.localRef && /^https?:\/\//i.test(String(n.data.url || '')) && !tried.has(n.id)) if (!next) return tried.add(next.id) const url = String((next.data && next.data.url) || '') if (!url) return ;(async () => { try { const resp = await fetch(url, { credentials: 'omit' }) if (!resp || !resp.ok) return const blob = await resp.blob() if (!blob || !blob.size) return const dataUrl = await new Promise((res, rej) => { const rd = new FileReader() rd.onload = () => res(String(rd.result || '')) rd.onerror = () => rej(new Error('read-failed')) rd.readAsDataURL(blob) }) if (!dataUrl) return const ref = await o.writeRef(dataUrl) if (ref && typeof o.updateNode === 'function') o.updateNode(next.id, { localRef: ref }) } catch (e) { /* 跨域/离线:保留 url 显示,不重试 */ } })() }, 4000) return () => clearInterval(timer) } function attach (opts) { return startRemoteRefCache(opts) } global.IWBImageRemoteCache = { useRemoteRefCache, startRemoteRefCache, attach } })(typeof window !== 'undefined' ? window : globalThis)