@masa-dev/react-signage
Version:
This is a react library for signage.
56 lines (55 loc) • 1.99 kB
JavaScript
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useRef, useState } from "react";
import { useCacher } from "./useCacher";
export function Cacher(props) {
const { items } = props;
const { fetchAndCache, getStatus } = useCacher();
const [queue, setQueue] = useState([]);
const processing = useRef(false);
const [progress, setProgress] = useState();
const itemsJson = JSON.stringify(items);
useEffect(() => {
setQueue(prev => [...prev, ...items]);
}, [itemsJson]);
useEffect(() => {
const interval = setInterval(() => process(), 1000);
return () => clearInterval(interval);
}, [queue]);
async function process() {
if (processing.current)
return;
processing.current = true;
try {
const item = queue.shift();
setQueue([...queue]);
if (!item)
throw new Error('no item');
setProgress({ src: item.src, progress: 0 });
const status = await getStatus(item.src);
if (status?.status != 'success' && status?.status != 'downloading') {
await fetchAndCache(item.src, {
onDownloadProgress: (p) => {
setProgress({ src: item.src, progress: p.progress });
}
});
}
else {
}
setProgress(undefined);
processing.current = false;
process();
}
catch (err) {
}
finally {
processing.current = false;
setProgress(undefined);
}
}
;
if (props.renderProgress)
return props.renderProgress({ progress, queue });
return _jsx(_Fragment, { children: progress
? _jsxs(_Fragment, { children: ["loading...", (progress?.progress ?? 0) * 100, "%", _jsx("br", {}), progress.src] })
: 'done' });
}