misc_pterodactyl-panel/resources/scripts/components/server/files/UploadButton.tsx

155 lines
5.8 KiB
TypeScript
Raw Normal View History

import axios from 'axios';
import getFileUploadUrl from '@/api/server/files/getFileUploadUrl';
2020-07-12 21:20:37 +00:00
import tw from 'twin.macro';
2022-06-20 18:16:42 +00:00
import { Button } from '@/components/elements/button/index';
import React, { useEffect, useRef } from 'react';
import { ModalMask } from '@/components/elements/Modal';
import Fade from '@/components/elements/Fade';
import useEventListener from '@/plugins/useEventListener';
import { useFlashKey } from '@/plugins/useFlash';
2020-08-23 05:36:53 +00:00
import useFileManagerSwr from '@/plugins/useFileManagerSwr';
2020-08-24 17:26:05 +00:00
import { ServerContext } from '@/state/server';
import { WithClassname } from '@/components/types';
2022-06-20 18:16:42 +00:00
import Portal from '@/components/elements/Portal';
2022-07-24 22:59:20 +00:00
import { CloudUploadIcon } from '@heroicons/react/outline';
import { useSignal } from '@preact/signals-react';
2020-07-12 21:20:37 +00:00
function isFileOrDirectory(event: DragEvent): boolean {
if (!event.dataTransfer?.types) {
return false;
}
return event.dataTransfer.types.some((value) => value.toLowerCase() === 'files');
}
export default ({ className }: WithClassname) => {
const fileUploadInput = useRef<HTMLInputElement>(null);
const visible = useSignal(false);
const timeouts = useSignal<NodeJS.Timeout[]>([]);
2020-08-23 05:36:53 +00:00
const { mutate } = useFileManagerSwr();
const { addError, clearAndAddHttpError } = useFlashKey('files');
const uuid = ServerContext.useStoreState((state) => state.server.data!.uuid);
const directory = ServerContext.useStoreState((state) => state.files.directory);
const { clearFileUploads, removeFileUpload, pushFileUpload, setUploadProgress } = ServerContext.useStoreActions(
2022-07-24 22:50:47 +00:00
(actions) => actions.files
);
2020-07-12 21:20:37 +00:00
useEventListener(
'dragenter',
(e) => {
e.preventDefault();
e.stopPropagation();
if (isFileOrDirectory(e)) {
visible.value = true;
}
},
{ capture: true }
);
useEventListener('dragexit', () => (visible.value = false), { capture: true });
useEventListener('keydown', () => (visible.value = false));
2020-07-12 21:20:37 +00:00
useEffect(() => {
return () => timeouts.value.forEach(clearTimeout);
}, []);
2022-07-24 22:50:47 +00:00
const onUploadProgress = (data: ProgressEvent, name: string) => {
setUploadProgress({ name, loaded: data.loaded });
2022-07-24 22:50:47 +00:00
};
2022-07-24 22:50:47 +00:00
const onFileSubmission = (files: FileList) => {
clearAndAddHttpError();
const list = Array.from(files);
if (list.some((file) => !file.size || (!file.type && file.size === 4096))) {
return addError('Folder uploads are not supported at this time.', 'Error');
}
2022-07-24 22:50:47 +00:00
const uploads = list.map((file) => {
const controller = new AbortController();
pushFileUpload({
name: file.name,
data: { abort: controller, loaded: 0, total: file.size },
});
2022-07-24 22:50:47 +00:00
return () =>
getFileUploadUrl(uuid).then((url) =>
axios
.post(
url,
{ files: file },
{
signal: controller.signal,
headers: { 'Content-Type': 'multipart/form-data' },
params: { directory },
onUploadProgress: (data) => onUploadProgress(data, file.name),
}
)
.then(() => timeouts.value.push(setTimeout(() => removeFileUpload(file.name), 500)))
2022-07-24 22:50:47 +00:00
);
});
Promise.all(uploads.map((fn) => fn()))
2020-08-23 05:36:53 +00:00
.then(() => mutate())
2022-07-24 22:50:47 +00:00
.catch((error) => {
clearFileUploads();
clearAndAddHttpError(error);
});
2020-07-12 21:20:37 +00:00
};
return (
<>
2022-06-20 18:16:42 +00:00
<Portal>
<Fade appear in={visible.value} timeout={75} key={'upload_modal_mask'} unmountOnExit>
2022-06-20 18:16:42 +00:00
<ModalMask
onClick={() => (visible.value = false)}
onDragOver={(e) => e.preventDefault()}
onDrop={(e) => {
2022-06-20 18:16:42 +00:00
e.preventDefault();
e.stopPropagation();
visible.value = false;
2022-06-20 18:16:42 +00:00
if (!e.dataTransfer?.files.length) return;
2022-06-20 18:16:42 +00:00
onFileSubmission(e.dataTransfer.files);
}}
>
2022-07-24 22:59:20 +00:00
<div className={'w-full flex items-center justify-center pointer-events-none'}>
<div
className={
'flex items-center space-x-4 bg-black w-full ring-4 ring-blue-200 ring-opacity-60 rounded p-6 mx-10 max-w-sm'
}
>
<CloudUploadIcon className={'w-10 h-10 flex-shrink-0'} />
<p className={'font-header flex-1 text-lg text-neutral-100 text-center'}>
Drag and drop files to upload.
</p>
</div>
2022-06-20 18:16:42 +00:00
</div>
</ModalMask>
</Fade>
</Portal>
<input
type={'file'}
ref={fileUploadInput}
css={tw`hidden`}
onChange={(e) => {
if (!e.currentTarget.files) return;
onFileSubmission(e.currentTarget.files);
if (fileUploadInput.current) {
fileUploadInput.current.files = null;
}
}}
multiple
/>
<Button className={className} onClick={() => fileUploadInput.current && fileUploadInput.current.click()}>
2020-07-12 21:20:37 +00:00
Upload
</Button>
</>
);
};