2023-07-01 06:50:47 +02:00
|
|
|
import { derived, writable } from 'svelte/store';
|
2022-06-03 18:04:30 +02:00
|
|
|
|
2023-07-15 03:25:13 +02:00
|
|
|
export interface DownloadProgress {
|
|
|
|
progress: number;
|
|
|
|
total: number;
|
|
|
|
percentage: number;
|
|
|
|
abort: AbortController | null;
|
|
|
|
}
|
|
|
|
|
|
|
|
export const downloadAssets = writable<Record<string, DownloadProgress>>({});
|
2022-06-03 18:04:30 +02:00
|
|
|
|
|
|
|
export const isDownloading = derived(downloadAssets, ($downloadAssets) => {
|
2024-02-02 04:18:00 +01:00
|
|
|
if (Object.keys($downloadAssets).length === 0) {
|
2023-07-01 06:50:47 +02:00
|
|
|
return false;
|
|
|
|
}
|
2022-06-03 18:04:30 +02:00
|
|
|
|
2023-07-01 06:50:47 +02:00
|
|
|
return true;
|
2022-07-26 19:28:07 +02:00
|
|
|
});
|
2023-06-30 18:24:28 +02:00
|
|
|
|
2023-07-15 03:25:13 +02:00
|
|
|
const update = (key: string, value: Partial<DownloadProgress> | null) => {
|
2023-07-01 06:50:47 +02:00
|
|
|
downloadAssets.update((state) => {
|
|
|
|
const newState = { ...state };
|
2023-07-15 03:25:13 +02:00
|
|
|
|
2023-07-01 06:50:47 +02:00
|
|
|
if (value === null) {
|
|
|
|
delete newState[key];
|
2023-07-15 03:25:13 +02:00
|
|
|
return newState;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!newState[key]) {
|
|
|
|
newState[key] = { progress: 0, total: 0, percentage: 0, abort: null };
|
2023-07-01 06:50:47 +02:00
|
|
|
}
|
2023-07-15 03:25:13 +02:00
|
|
|
|
|
|
|
const item = newState[key];
|
|
|
|
Object.assign(item, value);
|
|
|
|
item.percentage = Math.min(Math.floor((item.progress / item.total) * 100), 100);
|
|
|
|
|
2023-07-01 06:50:47 +02:00
|
|
|
return newState;
|
|
|
|
});
|
2023-06-30 18:24:28 +02:00
|
|
|
};
|
|
|
|
|
2023-07-15 03:25:13 +02:00
|
|
|
export const downloadManager = {
|
|
|
|
add: (key: string, total: number, abort?: AbortController) => update(key, { total, abort }),
|
|
|
|
clear: (key: string) => update(key, null),
|
|
|
|
update: (key: string, progress: number, total?: number) => {
|
|
|
|
const download: Partial<DownloadProgress> = { progress };
|
|
|
|
if (total !== undefined) {
|
|
|
|
download.total = total;
|
|
|
|
}
|
|
|
|
update(key, download);
|
|
|
|
},
|
|
|
|
};
|