Support canceling file uploads (#4441)

Closes #4440
This commit is contained in:
Dane Everitt 2022-11-21 12:58:55 -08:00 committed by GitHub
parent a4f6870518
commit df9a7f71f9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 92 additions and 50 deletions

View file

@ -11,6 +11,7 @@
"@headlessui/react": "^1.6.4", "@headlessui/react": "^1.6.4",
"@heroicons/react": "^1.0.6", "@heroicons/react": "^1.0.6",
"@hot-loader/react-dom": "^16.14.0", "@hot-loader/react-dom": "^16.14.0",
"@preact/signals-react": "^1.2.1",
"@tailwindcss/forms": "^0.5.2", "@tailwindcss/forms": "^0.5.2",
"@tailwindcss/line-clamp": "^0.4.0", "@tailwindcss/line-clamp": "^0.4.0",
"axios": "^0.27.2", "axios": "^0.27.2",

View file

@ -90,7 +90,7 @@ export default ({
> >
<div className={'flex p-6 pb-0 overflow-y-auto'}> <div className={'flex p-6 pb-0 overflow-y-auto'}>
{iconPosition === 'container' && icon} {iconPosition === 'container' && icon}
<div className={'flex-1 max-h-[70vh]'}> <div className={'flex-1 max-h-[70vh] min-w-0'}>
<div className={'flex items-center'}> <div className={'flex items-center'}>
{iconPosition !== 'container' && icon} {iconPosition !== 'container' && icon}
<div> <div>

View file

@ -1,11 +1,12 @@
import React, { useContext, useEffect, useState } from 'react'; import React, { useContext, useEffect } from 'react';
import { ServerContext } from '@/state/server'; import { ServerContext } from '@/state/server';
import { CloudUploadIcon } from '@heroicons/react/solid'; import { CloudUploadIcon, XIcon } from '@heroicons/react/solid';
import asDialog from '@/hoc/asDialog'; import asDialog from '@/hoc/asDialog';
import { Dialog, DialogWrapperContext } from '@/components/elements/dialog'; import { Dialog, DialogWrapperContext } from '@/components/elements/dialog';
import { Button } from '@/components/elements/button/index'; import { Button } from '@/components/elements/button/index';
import Tooltip from '@/components/elements/tooltip/Tooltip'; import Tooltip from '@/components/elements/tooltip/Tooltip';
import Code from '@/components/elements/Code'; import Code from '@/components/elements/Code';
import { useSignal } from '@preact/signals-react';
const svgProps = { const svgProps = {
cx: 16, cx: 16,
@ -31,23 +32,34 @@ const Spinner = ({ progress, className }: { progress: number; className?: string
const FileUploadList = () => { const FileUploadList = () => {
const { close } = useContext(DialogWrapperContext); const { close } = useContext(DialogWrapperContext);
const removeFileUpload = ServerContext.useStoreActions((actions) => actions.files.removeFileUpload);
const clearFileUploads = ServerContext.useStoreActions((actions) => actions.files.clearFileUploads);
const uploads = ServerContext.useStoreState((state) => const uploads = ServerContext.useStoreState((state) =>
state.files.uploads.sort((a, b) => a.name.localeCompare(b.name)) Object.entries(state.files.uploads).sort(([a], [b]) => a.localeCompare(b))
); );
return ( return (
<div className={'space-y-2 mt-6'}> <div className={'space-y-2 mt-6'}>
{uploads.map((file) => ( {uploads.map(([name, file]) => (
<div key={file.name} className={'flex items-center space-x-3 bg-gray-700 p-3 rounded'}> <div key={name} className={'flex items-center space-x-3 bg-gray-700 p-3 rounded'}>
<Tooltip content={`${Math.floor((file.loaded / file.total) * 100)}%`} placement={'left'}> <Tooltip content={`${Math.floor((file.loaded / file.total) * 100)}%`} placement={'left'}>
<div className={'flex-shrink-0'}> <div className={'flex-shrink-0'}>
<Spinner progress={(file.loaded / file.total) * 100} className={'w-6 h-6'} /> <Spinner progress={(file.loaded / file.total) * 100} className={'w-6 h-6'} />
</div> </div>
</Tooltip> </Tooltip>
<Code>{file.name}</Code> <Code className={'flex-1 truncate'}>{name}</Code>
<button
onClick={removeFileUpload.bind(this, name)}
className={'text-gray-500 hover:text-gray-200 transition-colors duration-75'}
>
<XIcon className={'w-5 h-5'} />
</button>
</div> </div>
))} ))}
<Dialog.Footer> <Dialog.Footer>
<Button.Danger variant={Button.Variants.Secondary} onClick={() => clearFileUploads()}>
Cancel Uploads
</Button.Danger>
<Button.Text onClick={close}>Close</Button.Text> <Button.Text onClick={close}>Close</Button.Text>
</Dialog.Footer> </Dialog.Footer>
</div> </div>
@ -60,17 +72,17 @@ const FileUploadListDialog = asDialog({
})(FileUploadList); })(FileUploadList);
export default () => { export default () => {
const [open, setOpen] = useState(false); const open = useSignal(false);
const count = ServerContext.useStoreState((state) => state.files.uploads.length); const count = ServerContext.useStoreState((state) => Object.keys(state.files.uploads).length);
const progress = ServerContext.useStoreState((state) => ({ const progress = ServerContext.useStoreState((state) => ({
uploaded: state.files.uploads.reduce((count, file) => count + file.loaded, 0), uploaded: Object.values(state.files.uploads).reduce((count, file) => count + file.loaded, 0),
total: state.files.uploads.reduce((count, file) => count + file.total, 0), total: Object.values(state.files.uploads).reduce((count, file) => count + file.total, 0),
})); }));
useEffect(() => { useEffect(() => {
if (count === 0) { if (count === 0) {
setOpen(false); open.value = false;
} }
}, [count]); }, [count]);
@ -78,13 +90,16 @@ export default () => {
<> <>
{count > 0 && ( {count > 0 && (
<Tooltip content={`${count} files are uploading, click to view`}> <Tooltip content={`${count} files are uploading, click to view`}>
<button className={'flex items-center justify-center w-10 h-10'} onClick={setOpen.bind(this, true)}> <button
className={'flex items-center justify-center w-10 h-10'}
onClick={() => (open.value = true)}
>
<Spinner progress={(progress.uploaded / progress.total) * 100} className={'w-8 h-8'} /> <Spinner progress={(progress.uploaded / progress.total) * 100} className={'w-8 h-8'} />
<CloudUploadIcon className={'h-3 absolute mx-auto animate-pulse'} /> <CloudUploadIcon className={'h-3 absolute mx-auto animate-pulse'} />
</button> </button>
</Tooltip> </Tooltip>
)} )}
<FileUploadListDialog open={open} onClose={setOpen.bind(this, false)} /> <FileUploadListDialog open={open.value} onClose={() => (open.value = false)} />
</> </>
); );
}; };

View file

@ -2,7 +2,7 @@ import axios from 'axios';
import getFileUploadUrl from '@/api/server/files/getFileUploadUrl'; import getFileUploadUrl from '@/api/server/files/getFileUploadUrl';
import tw from 'twin.macro'; import tw from 'twin.macro';
import { Button } from '@/components/elements/button/index'; import { Button } from '@/components/elements/button/index';
import React, { useEffect, useRef, useState } from 'react'; import React, { useEffect, useRef } from 'react';
import { ModalMask } from '@/components/elements/Modal'; import { ModalMask } from '@/components/elements/Modal';
import Fade from '@/components/elements/Fade'; import Fade from '@/components/elements/Fade';
import useEventListener from '@/plugins/useEventListener'; import useEventListener from '@/plugins/useEventListener';
@ -12,6 +12,7 @@ import { ServerContext } from '@/state/server';
import { WithClassname } from '@/components/types'; import { WithClassname } from '@/components/types';
import Portal from '@/components/elements/Portal'; import Portal from '@/components/elements/Portal';
import { CloudUploadIcon } from '@heroicons/react/outline'; import { CloudUploadIcon } from '@heroicons/react/outline';
import { useSignal } from '@preact/signals-react';
function isFileOrDirectory(event: DragEvent): boolean { function isFileOrDirectory(event: DragEvent): boolean {
if (!event.dataTransfer?.types) { if (!event.dataTransfer?.types) {
@ -23,14 +24,16 @@ function isFileOrDirectory(event: DragEvent): boolean {
export default ({ className }: WithClassname) => { export default ({ className }: WithClassname) => {
const fileUploadInput = useRef<HTMLInputElement>(null); const fileUploadInput = useRef<HTMLInputElement>(null);
const [timeouts, setTimeouts] = useState<NodeJS.Timeout[]>([]);
const [visible, setVisible] = useState(false); const visible = useSignal(false);
const timeouts = useSignal<NodeJS.Timeout[]>([]);
const { mutate } = useFileManagerSwr(); const { mutate } = useFileManagerSwr();
const { addError, clearAndAddHttpError } = useFlashKey('files'); const { addError, clearAndAddHttpError } = useFlashKey('files');
const uuid = ServerContext.useStoreState((state) => state.server.data!.uuid); const uuid = ServerContext.useStoreState((state) => state.server.data!.uuid);
const directory = ServerContext.useStoreState((state) => state.files.directory); const directory = ServerContext.useStoreState((state) => state.files.directory);
const { clearFileUploads, appendFileUpload, removeFileUpload } = ServerContext.useStoreActions( const { clearFileUploads, removeFileUpload, pushFileUpload, setUploadProgress } = ServerContext.useStoreActions(
(actions) => actions.files (actions) => actions.files
); );
@ -40,27 +43,24 @@ export default ({ className }: WithClassname) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
if (isFileOrDirectory(e)) { if (isFileOrDirectory(e)) {
return setVisible(true); visible.value = true;
} }
}, },
{ capture: true } { capture: true }
); );
useEventListener('dragexit', () => setVisible(false), { capture: true }); useEventListener('dragexit', () => (visible.value = false), { capture: true });
useEventListener('keydown', () => { useEventListener('keydown', () => (visible.value = false));
visible && setVisible(false);
});
useEffect(() => { useEffect(() => {
return () => timeouts.forEach(clearTimeout); return () => timeouts.value.forEach(clearTimeout);
}, []); }, []);
const onUploadProgress = (data: ProgressEvent, name: string) => { const onUploadProgress = (data: ProgressEvent, name: string) => {
appendFileUpload({ name, loaded: data.loaded, total: data.total }); setUploadProgress({ name, loaded: data.loaded });
if (data.loaded >= data.total) { if (data.loaded >= data.total) {
const timeout = setTimeout(() => removeFileUpload(name), 500); timeouts.value.push(setTimeout(() => removeFileUpload(name), 500));
setTimeouts((t) => [...t, timeout]);
} }
}; };
@ -71,23 +71,20 @@ export default ({ className }: WithClassname) => {
return addError('Folder uploads are not supported at this time.', 'Error'); return addError('Folder uploads are not supported at this time.', 'Error');
} }
if (!list.length) {
return;
}
const uploads = list.map((file) => { const uploads = list.map((file) => {
appendFileUpload({ name: file.name, loaded: 0, total: file.size }); const controller = new AbortController();
pushFileUpload({ name: file.name, data: { abort: controller, loaded: 0, total: file.size } });
return () => return () =>
getFileUploadUrl(uuid).then((url) => getFileUploadUrl(uuid).then((url) =>
axios.post( axios.post(
url, url,
{ files: file }, { files: file },
{ {
signal: controller.signal,
headers: { 'Content-Type': 'multipart/form-data' }, headers: { 'Content-Type': 'multipart/form-data' },
params: { directory }, params: { directory },
onUploadProgress: (data) => { onUploadProgress: (data) => onUploadProgress(data, file.name),
onUploadProgress(data, file.name);
},
} }
) )
); );
@ -104,15 +101,15 @@ export default ({ className }: WithClassname) => {
return ( return (
<> <>
<Portal> <Portal>
<Fade appear in={visible} timeout={75} key={'upload_modal_mask'} unmountOnExit> <Fade appear in={visible.value} timeout={75} key={'upload_modal_mask'} unmountOnExit>
<ModalMask <ModalMask
onClick={() => setVisible(false)} onClick={() => (visible.value = false)}
onDragOver={(e) => e.preventDefault()} onDragOver={(e) => e.preventDefault()}
onDrop={(e) => { onDrop={(e) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
setVisible(false); visible.value = false;
if (!e.dataTransfer?.files.length) return; if (!e.dataTransfer?.files.length) return;
onFileSubmission(e.dataTransfer.files); onFileSubmission(e.dataTransfer.files);

View file

@ -1,31 +1,32 @@
import { action, Action } from 'easy-peasy'; import { action, Action } from 'easy-peasy';
import { cleanDirectoryPath } from '@/helpers'; import { cleanDirectoryPath } from '@/helpers';
export interface FileUpload { export interface FileUploadData {
name: string;
loaded: number; loaded: number;
readonly abort: AbortController;
readonly total: number; readonly total: number;
} }
export interface ServerFileStore { export interface ServerFileStore {
directory: string; directory: string;
selectedFiles: string[]; selectedFiles: string[];
uploads: FileUpload[]; uploads: Record<string, FileUploadData>;
setDirectory: Action<ServerFileStore, string>; setDirectory: Action<ServerFileStore, string>;
setSelectedFiles: Action<ServerFileStore, string[]>; setSelectedFiles: Action<ServerFileStore, string[]>;
appendSelectedFile: Action<ServerFileStore, string>; appendSelectedFile: Action<ServerFileStore, string>;
removeSelectedFile: Action<ServerFileStore, string>; removeSelectedFile: Action<ServerFileStore, string>;
pushFileUpload: Action<ServerFileStore, { name: string; data: FileUploadData }>;
setUploadProgress: Action<ServerFileStore, { name: string; loaded: number }>;
clearFileUploads: Action<ServerFileStore>; clearFileUploads: Action<ServerFileStore>;
appendFileUpload: Action<ServerFileStore, FileUpload>;
removeFileUpload: Action<ServerFileStore, string>; removeFileUpload: Action<ServerFileStore, string>;
} }
const files: ServerFileStore = { const files: ServerFileStore = {
directory: '/', directory: '/',
selectedFiles: [], selectedFiles: [],
uploads: [], uploads: {},
setDirectory: action((state, payload) => { setDirectory: action((state, payload) => {
state.directory = cleanDirectoryPath(payload); state.directory = cleanDirectoryPath(payload);
@ -44,19 +45,29 @@ const files: ServerFileStore = {
}), }),
clearFileUploads: action((state) => { clearFileUploads: action((state) => {
state.uploads = []; Object.values(state.uploads).forEach((upload) => upload.abort.abort());
state.uploads = {};
}), }),
appendFileUpload: action((state, payload) => { pushFileUpload: action((state, payload) => {
if (!state.uploads.some(({ name }) => name === payload.name)) { state.uploads[payload.name] = payload.data;
state.uploads = [...state.uploads, payload]; }),
} else {
state.uploads = state.uploads.map((file) => (file.name === payload.name ? payload : file)); setUploadProgress: action((state, { name, loaded }) => {
if (state.uploads[name]) {
state.uploads[name].loaded = loaded;
} }
}), }),
removeFileUpload: action((state, payload) => { removeFileUpload: action((state, payload) => {
state.uploads = state.uploads.filter(({ name }) => name !== payload); if (state.uploads[payload]) {
// Abort the request if it is still in flight. If it already completed this is
// a no-op.
state.uploads[payload].abort.abort();
delete state.uploads[payload];
}
}), }),
}; };

View file

@ -1493,6 +1493,19 @@
mkdirp "^1.0.4" mkdirp "^1.0.4"
rimraf "^3.0.2" rimraf "^3.0.2"
"@preact/signals-core@^1.2.2":
version "1.2.2"
resolved "https://registry.yarnpkg.com/@preact/signals-core/-/signals-core-1.2.2.tgz#279dcc5ab249de2f2e8f6e6779b1958256ba843e"
integrity sha512-z3/bCj7rRA21RJb4FeJ4guCrD1CQbaURHkCTunUWQpxUMAFOPXCD8tSFqERyGrrcSb4T3Hrmdc1OAl0LXBHwiw==
"@preact/signals-react@^1.2.1":
version "1.2.1"
resolved "https://registry.yarnpkg.com/@preact/signals-react/-/signals-react-1.2.1.tgz#6d5d305ebdb38c879043acebc65c0d9351e663c1"
integrity sha512-73J8sL1Eru7Ot4yBYOCPj1izEZjzCEXlembRgk6C7PkwsqoAVbCxMlDOFfCLoPFuJ6qeGatrJzRkcycXppMqVQ==
dependencies:
"@preact/signals-core" "^1.2.2"
use-sync-external-store "^1.2.0"
"@sinclair/typebox@^0.23.3": "@sinclair/typebox@^0.23.3":
version "0.23.5" version "0.23.5"
resolved "https://registry.yarnpkg.com/@sinclair/typebox/-/typebox-0.23.5.tgz#93f7b9f4e3285a7a9ade7557d9a8d36809cbc47d" resolved "https://registry.yarnpkg.com/@sinclair/typebox/-/typebox-0.23.5.tgz#93f7b9f4e3285a7a9ade7557d9a8d36809cbc47d"
@ -9121,6 +9134,11 @@ use-memo-one@^1.1.1:
resolved "https://registry.yarnpkg.com/use-memo-one/-/use-memo-one-1.1.1.tgz#39e6f08fe27e422a7d7b234b5f9056af313bd22c" resolved "https://registry.yarnpkg.com/use-memo-one/-/use-memo-one-1.1.1.tgz#39e6f08fe27e422a7d7b234b5f9056af313bd22c"
integrity sha512-oFfsyun+bP7RX8X2AskHNTxu+R3QdE/RC5IefMbqptmACAA/gfol1KDD5KRzPsGMa62sWxGZw+Ui43u6x4ddoQ== integrity sha512-oFfsyun+bP7RX8X2AskHNTxu+R3QdE/RC5IefMbqptmACAA/gfol1KDD5KRzPsGMa62sWxGZw+Ui43u6x4ddoQ==
use-sync-external-store@^1.2.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz#7dbefd6ef3fe4e767a0cf5d7287aacfb5846928a"
integrity sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==
use@^3.1.0: use@^3.1.0:
version "3.1.0" version "3.1.0"
resolved "https://registry.yarnpkg.com/use/-/use-3.1.0.tgz#14716bf03fdfefd03040aef58d8b4b85f3a7c544" resolved "https://registry.yarnpkg.com/use/-/use-3.1.0.tgz#14716bf03fdfefd03040aef58d8b4b85f3a7c544"