Dynamic file sizes
This commit is contained in:
+29
-3
@@ -18,6 +18,20 @@ const IconMap: Record<string, any> = {
|
||||
"FileText": FileText
|
||||
};
|
||||
|
||||
const fetchFileSize = async (url: string) => {
|
||||
try {
|
||||
const res = await fetch(url, { method: 'HEAD' });
|
||||
const bytes = res.headers.get('content-length');
|
||||
if (bytes) {
|
||||
const mb = (parseInt(bytes) / (1024 * 1024)).toFixed(2);
|
||||
return `${mb} MB`;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Kunde inte hämta filstorlek för", url);
|
||||
}
|
||||
return "Okänd";
|
||||
};
|
||||
|
||||
export default function Documents() {
|
||||
const [isHydrated, setIsHydrated] = useState(false);
|
||||
const [isOffline, setIsOffline] = useState(false);
|
||||
@@ -48,10 +62,22 @@ export default function Documents() {
|
||||
if (navigator.onLine) {
|
||||
const res = await readJsonFile('documents.json');
|
||||
if (res.success && res.data) {
|
||||
setDocs(res.data.docs || []);
|
||||
const docsWithSizes = await Promise.all(
|
||||
(res.data.docs || []).map(async (doc: DocumentItem) => {
|
||||
if (!doc.size || doc.size === "") {
|
||||
const calculatedSize = await fetchFileSize(doc.file);
|
||||
return { ...doc, size: calculatedSize };
|
||||
}
|
||||
return doc;
|
||||
})
|
||||
);
|
||||
|
||||
setDocs(docsWithSizes);
|
||||
setLinks(res.data.links || []);
|
||||
localStorage.setItem('kullaberg_documents_cache', JSON.stringify(res.data));
|
||||
checkCacheStatus(res.data.docs || []);
|
||||
const dataToCache = { ...res.data, docs: docsWithSizes };
|
||||
localStorage.setItem('kullaberg_documents_cache', JSON.stringify(dataToCache));
|
||||
|
||||
checkCacheStatus(docsWithSizes);
|
||||
}
|
||||
} else {
|
||||
const cachedData = localStorage.getItem('kullaberg_documents_cache');
|
||||
|
||||
Reference in New Issue
Block a user