misc_pterodactyl-panel/resources/scripts/state/server/files.ts

84 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-11-25 20:25:03 +00:00
import type { Action } from 'easy-peasy';
import { action } from 'easy-peasy';
import { cleanDirectoryPath } from '@/helpers';
2022-11-25 20:25:03 +00:00
interface FileUploadData {
loaded: number;
readonly abort: AbortController;
readonly total: number;
}
2022-11-25 20:25:03 +00:00
interface ServerFileStore {
directory: string;
selectedFiles: string[];
uploads: Record<string, FileUploadData>;
setDirectory: Action<ServerFileStore, string>;
setSelectedFiles: Action<ServerFileStore, string[]>;
appendSelectedFile: Action<ServerFileStore, string>;
removeSelectedFile: Action<ServerFileStore, string>;
pushFileUpload: Action<ServerFileStore, { name: string; data: FileUploadData }>;
setUploadProgress: Action<ServerFileStore, { name: string; loaded: number }>;
2022-07-24 22:50:47 +00:00
clearFileUploads: Action<ServerFileStore>;
removeFileUpload: Action<ServerFileStore, string>;
}
const files: ServerFileStore = {
directory: '/',
selectedFiles: [],
uploads: {},
setDirectory: action((state, payload) => {
state.directory = cleanDirectoryPath(payload);
}),
setSelectedFiles: action((state, payload) => {
state.selectedFiles = payload;
}),
appendSelectedFile: action((state, payload) => {
2022-11-25 20:25:03 +00:00
state.selectedFiles = state.selectedFiles.filter(f => f !== payload).concat(payload);
}),
removeSelectedFile: action((state, payload) => {
2022-11-25 20:25:03 +00:00
state.selectedFiles = state.selectedFiles.filter(f => f !== payload);
}),
2022-11-25 20:25:03 +00:00
clearFileUploads: action(state => {
Object.values(state.uploads).forEach(upload => upload.abort.abort());
state.uploads = {};
}),
pushFileUpload: action((state, payload) => {
state.uploads[payload.name] = payload.data;
2022-07-24 22:50:47 +00:00
}),
setUploadProgress: action((state, { name, loaded }) => {
2022-11-25 20:25:03 +00:00
const upload = state.uploads[name];
if (upload === undefined) {
return;
2022-07-24 22:50:47 +00:00
}
2022-11-25 20:25:03 +00:00
upload.loaded = loaded;
}),
removeFileUpload: action((state, payload) => {
2022-11-25 20:25:03 +00:00
const upload = state.uploads[payload];
if (upload === undefined) {
return;
}
2022-11-25 20:25:03 +00:00
// Abort the request if it is still in flight. If it already completed this is
// a no-op.
upload.abort.abort();
delete state.uploads[payload];
}),
};
2022-11-25 20:25:03 +00:00
export type { FileUploadData, ServerFileStore };
export default files;