|
| 1 | +import { image as polliImage } from '../polliLib/src/image.js'; |
| 2 | + |
| 3 | +let imageFn = polliImage; |
| 4 | +let pollIntervalMs = 2000; |
| 5 | +let timeoutMs = 20000; |
| 6 | +let fallbackSrc = 'https://via.placeholder.com/512?text=Image+Unavailable'; |
| 7 | + |
| 8 | +const pending = new Map(); |
| 9 | +let timer = null; |
| 10 | + |
| 11 | +export function trackPlaceholder(img, { prompt, model, width, height } = {}) { |
| 12 | + if (!img) return; |
| 13 | + pending.set(img, { prompt, model, width, height, start: Date.now() }); |
| 14 | + if (!timer) { |
| 15 | + timer = setInterval(() => { |
| 16 | + checkPending().catch(() => {}); |
| 17 | + }, pollIntervalMs); |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +async function checkPending() { |
| 22 | + for (const [img, info] of pending) { |
| 23 | + if (Date.now() - info.start > timeoutMs) { |
| 24 | + img.src = fallbackSrc; |
| 25 | + img.classList?.remove?.('placeholder'); |
| 26 | + pending.delete(img); |
| 27 | + continue; |
| 28 | + } |
| 29 | + try { |
| 30 | + const data = await imageFn(info.prompt, { model: info.model, width: info.width, height: info.height, json: true }); |
| 31 | + if (data && data.url) { |
| 32 | + img.src = data.url; |
| 33 | + img.classList?.remove?.('placeholder'); |
| 34 | + pending.delete(img); |
| 35 | + } |
| 36 | + } catch (err) { |
| 37 | + img.src = fallbackSrc; |
| 38 | + img.classList?.remove?.('placeholder'); |
| 39 | + pending.delete(img); |
| 40 | + } |
| 41 | + } |
| 42 | + if (pending.size === 0 && timer) { |
| 43 | + clearInterval(timer); |
| 44 | + timer = null; |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +export function _setImageFn(fn) { |
| 49 | + imageFn = fn; |
| 50 | +} |
| 51 | + |
| 52 | +export function _configure({ intervalMs, timeout, fallback } = {}) { |
| 53 | + if (intervalMs != null) pollIntervalMs = intervalMs; |
| 54 | + if (timeout != null) timeoutMs = timeout; |
| 55 | + if (fallback != null) fallbackSrc = fallback; |
| 56 | + if (timer) { |
| 57 | + clearInterval(timer); |
| 58 | + timer = setInterval(() => { |
| 59 | + checkPending().catch(() => {}); |
| 60 | + }, pollIntervalMs); |
| 61 | + } |
| 62 | +} |
0 commit comments