PteroTheme/resources/scripts/components/server/files/UploadButton.tsx

110 lines
3.2 KiB
TypeScript
Raw Normal View History

import axios from 'axios';
import getFileUploadUrl from '@/api/server/files/getFileUploadUrl';
import useServer from '@/plugins/useServer';
2020-07-12 22:20:37 +01:00
import tw from 'twin.macro';
import Button from '@/components/elements/Button';
import React, { useEffect, useState } from 'react';
2020-07-12 22:20:37 +01:00
import styled from 'styled-components/macro';
import { ModalMask } from '@/components/elements/Modal';
import Fade from '@/components/elements/Fade';
import useEventListener from '@/plugins/useEventListener';
2020-07-12 22:20:37 +01:00
const InnerContainer = styled.div`
max-width: 600px;
${tw`bg-black w-full border-4 border-primary-500 border-dashed rounded p-10 mx-10`}
2020-07-12 22:20:37 +01:00
`;
export default () => {
const { uuid } = useServer();
2020-07-12 22:20:37 +01:00
const [ visible, setVisible ] = useState(false);
useEventListener('dragenter', e => {
e.stopPropagation();
setVisible(true);
}, true);
useEventListener('dragexit', e => {
e.stopPropagation();
setVisible(false);
}, true);
useEffect(() => {
if (!visible) return;
const hide = () => setVisible(false);
window.addEventListener('keydown', hide);
return () => {
window.removeEventListener('keydown', hide);
};
}, [ visible ]);
2020-07-12 22:20:37 +01:00
const onFileDrop = (e: React.DragEvent<HTMLDivElement>) => {
2020-07-12 22:20:37 +01:00
e.preventDefault();
if (e.dataTransfer === undefined || e.dataTransfer === null) {
return;
}
const files: FileList = e.dataTransfer.files;
2020-07-12 22:20:37 +01:00
console.log(files);
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
console.log(files[i]);
// @ts-ignore
formData.append('files', files[i]);
}
getFileUploadUrl(uuid)
.then(url => {
console.log(url);
axios.post(url, formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
.then(res => {
console.log(res);
setVisible(false);
})
.catch(error => {
console.error(error);
});
})
.catch(error => {
console.error(error);
});
2020-07-12 22:20:37 +01:00
};
return (
<>
<Fade
appear
in={visible}
timeout={75}
key={'upload_modal_mask'}
unmountOnExit
>
<ModalMask
onClick={() => setVisible(false)}
onDrop={onFileDrop}
>
<div css={tw`w-full flex items-center justify-center`} style={{ pointerEvents: 'none' }}>
<InnerContainer>
<p css={tw`text-lg text-neutral-200 text-center`}>
Drag and drop files to upload.
</p>
</InnerContainer>
</div>
</ModalMask>
</Fade>
2020-07-12 22:20:37 +01:00
<Button css={tw`mr-2`} onClick={() => setVisible(true)}>
Upload
</Button>
</>
);
};