Skip to content

Commit 1224284

Browse files
authored
File upload status (v2 backport) (pterodactyl#4219)
1 parent 2eda199 commit 1224284

File tree

4 files changed

+156
-25
lines changed

4 files changed

+156
-25
lines changed

resources/scripts/components/server/files/FileManagerContainer.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import tw from 'twin.macro';
1313
import { Button } from '@/components/elements/button/index';
1414
import { ServerContext } from '@/state/server';
1515
import useFileManagerSwr from '@/plugins/useFileManagerSwr';
16+
import FileManagerStatus from '@/components/server/files/FileManagerStatus';
1617
import MassActionsBar from '@/components/server/files/MassActionsBar';
1718
import UploadButton from '@/components/server/files/UploadButton';
1819
import ServerContentBlock from '@/components/elements/ServerContentBlock';
@@ -104,6 +105,7 @@ export default () => {
104105
<FileObjectRow key={file.key} file={file} />
105106
))}
106107
<MassActionsBar />
108+
<FileManagerStatus />
107109
</div>
108110
</CSSTransition>
109111
)}
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import React from 'react';
2+
import tw, { styled } from 'twin.macro';
3+
import { ServerContext } from '@/state/server';
4+
import { bytesToString } from '@/lib/formatters';
5+
6+
const SpinnerCircle = styled.circle`
7+
transition: stroke-dashoffset 0.35s;
8+
transform: rotate(-90deg);
9+
transform-origin: 50% 50%;
10+
`;
11+
12+
function Spinner({ progress }: { progress: number }) {
13+
const stroke = 3;
14+
const radius = 20;
15+
const normalizedRadius = radius - stroke * 2;
16+
const circumference = normalizedRadius * 2 * Math.PI;
17+
18+
return (
19+
<svg width={radius * 2 - 8} height={radius * 2 - 8}>
20+
<circle
21+
stroke={'rgba(255, 255, 255, 0.07)'}
22+
fill={'none'}
23+
strokeWidth={stroke}
24+
r={normalizedRadius}
25+
cx={radius - 4}
26+
cy={radius - 4}
27+
/>
28+
<SpinnerCircle
29+
stroke={'white'}
30+
fill={'none'}
31+
strokeDasharray={circumference}
32+
strokeWidth={stroke}
33+
r={normalizedRadius}
34+
cx={radius - 4}
35+
cy={radius - 4}
36+
style={{ strokeDashoffset: ((100 - progress) / 100) * circumference }}
37+
/>
38+
</svg>
39+
);
40+
}
41+
42+
function FileManagerStatus() {
43+
const uploads = ServerContext.useStoreState((state) => state.files.uploads);
44+
45+
return (
46+
<div css={tw`pointer-events-none fixed right-0 bottom-0 z-20 flex justify-center`}>
47+
{uploads.length > 0 && (
48+
<div
49+
css={tw`flex flex-col justify-center bg-neutral-700 rounded shadow mb-2 mr-2 pointer-events-auto px-3 py-1`}
50+
>
51+
{uploads
52+
.sort((a, b) => a.total - b.total)
53+
.map((f) => (
54+
<div key={f.name} css={tw`h-10 flex flex-row items-center`}>
55+
<div css={tw`mr-2`}>
56+
<Spinner progress={Math.round((100 * f.loaded) / f.total)} />
57+
</div>
58+
59+
<div css={tw`block`}>
60+
<span css={tw`text-base font-normal leading-none text-neutral-300`}>
61+
{f.name} ({bytesToString(f.loaded)}/{bytesToString(f.total)})
62+
</span>
63+
</div>
64+
</div>
65+
))}
66+
</div>
67+
)}
68+
</div>
69+
);
70+
}
71+
72+
export default FileManagerStatus;

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

Lines changed: 63 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import styled from 'styled-components/macro';
77
import { ModalMask } from '@/components/elements/Modal';
88
import Fade from '@/components/elements/Fade';
99
import useEventListener from '@/plugins/useEventListener';
10-
import SpinnerOverlay from '@/components/elements/SpinnerOverlay';
1110
import useFlash from '@/plugins/useFlash';
1211
import useFileManagerSwr from '@/plugins/useFileManagerSwr';
1312
import { ServerContext } from '@/state/server';
@@ -19,18 +18,40 @@ const InnerContainer = styled.div`
1918
${tw`bg-black w-full border-4 border-primary-500 border-dashed rounded p-10 mx-10`}
2019
`;
2120

21+
function isFileOrDirectory(event: DragEvent): boolean {
22+
if (!event.dataTransfer?.types) {
23+
return false;
24+
}
25+
26+
for (let i = 0; i < event.dataTransfer.types.length; i++) {
27+
// Check if the item being dragged is not a file.
28+
// On Firefox a file of type "application/x-moz-file" is also in the array.
29+
if (event.dataTransfer.types[i] !== 'Files' && event.dataTransfer.types[i] !== 'application/x-moz-file') {
30+
return false;
31+
}
32+
}
33+
34+
return true;
35+
}
36+
2237
export default ({ className }: WithClassname) => {
2338
const fileUploadInput = useRef<HTMLInputElement>(null);
24-
const uuid = ServerContext.useStoreState((state) => state.server.data!.uuid);
39+
const [timeouts, setTimeouts] = useState<NodeJS.Timeout[]>([]);
2540
const [visible, setVisible] = useState(false);
26-
const [loading, setLoading] = useState(false);
2741
const { mutate } = useFileManagerSwr();
2842
const { clearFlashes, clearAndAddHttpError } = useFlash();
43+
44+
const uuid = ServerContext.useStoreState((state) => state.server.data!.uuid);
2945
const directory = ServerContext.useStoreState((state) => state.files.directory);
46+
const appendFileUpload = ServerContext.useStoreActions((actions) => actions.files.appendFileUpload);
47+
const removeFileUpload = ServerContext.useStoreActions((actions) => actions.files.removeFileUpload);
3048

3149
useEventListener(
3250
'dragenter',
3351
(e) => {
52+
if (!isFileOrDirectory(e)) {
53+
return;
54+
}
3455
e.stopPropagation();
3556
setVisible(true);
3657
},
@@ -40,6 +61,9 @@ export default ({ className }: WithClassname) => {
4061
useEventListener(
4162
'dragexit',
4263
(e) => {
64+
if (!isFileOrDirectory(e)) {
65+
return;
66+
}
4367
e.stopPropagation();
4468
setVisible(false);
4569
},
@@ -57,27 +81,47 @@ export default ({ className }: WithClassname) => {
5781
};
5882
}, [visible]);
5983

60-
const onFileSubmission = (files: FileList) => {
61-
const form = new FormData();
62-
Array.from(files).forEach((file) => form.append('files', file));
84+
useEffect(() => {
85+
return () => timeouts.forEach(clearTimeout);
86+
}, []);
6387

64-
setLoading(true);
88+
const onFileSubmission = (files: FileList) => {
89+
const formData: FormData[] = [];
90+
Array.from(files).forEach((file) => {
91+
const form = new FormData();
92+
form.append('files', file);
93+
formData.push(form);
94+
});
6595
clearFlashes('files');
66-
getFileUploadUrl(uuid)
67-
.then((url) =>
68-
axios.post(`${url}&directory=${directory}`, form, {
69-
headers: {
70-
'Content-Type': 'multipart/form-data',
71-
},
72-
})
96+
Promise.all(
97+
Array.from(formData).map((f) =>
98+
getFileUploadUrl(uuid).then((url) =>
99+
axios.post(`${url}&directory=${directory}`, f, {
100+
headers: { 'Content-Type': 'multipart/form-data' },
101+
onUploadProgress: (data: ProgressEvent) => {
102+
// @ts-expect-error this is valid
103+
const name = f.getAll('files')[0].name;
104+
105+
appendFileUpload({
106+
name: name,
107+
loaded: data.loaded,
108+
total: data.total,
109+
});
110+
111+
if (data.loaded === data.total) {
112+
const timeout = setTimeout(() => removeFileUpload(name), 2000);
113+
setTimeouts((t) => [...t, timeout]);
114+
}
115+
},
116+
})
117+
)
73118
)
119+
)
74120
.then(() => mutate())
75121
.catch((error) => {
76122
console.error(error);
77123
clearAndAddHttpError({ error, key: 'files' });
78-
})
79-
.then(() => setVisible(false))
80-
.then(() => setLoading(false));
124+
});
81125
};
82126

83127
return (
@@ -97,14 +141,13 @@ export default ({ className }: WithClassname) => {
97141
onFileSubmission(e.dataTransfer.files);
98142
}}
99143
>
100-
<div css={tw`w-full flex items-center justify-center`} style={{ pointerEvents: 'none' }}>
144+
<div css={tw`w-full flex items-center justify-center pointer-events-none`}>
101145
<InnerContainer>
102146
<p css={tw`text-lg text-neutral-200 text-center`}>Drag and drop files to upload.</p>
103147
</InnerContainer>
104148
</div>
105149
</ModalMask>
106150
</Fade>
107-
<SpinnerOverlay visible={loading} size={'large'} fixed />
108151
</Portal>
109152
<input
110153
type={'file'}
@@ -119,12 +162,7 @@ export default ({ className }: WithClassname) => {
119162
}
120163
}}
121164
/>
122-
<Button
123-
className={className}
124-
onClick={() => {
125-
fileUploadInput.current ? fileUploadInput.current.click() : setVisible(true);
126-
}}
127-
>
165+
<Button className={className} onClick={() => fileUploadInput.current && fileUploadInput.current.click()}>
128166
Upload
129167
</Button>
130168
</>

resources/scripts/state/server/files.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,30 @@
11
import { action, Action } from 'easy-peasy';
22
import { cleanDirectoryPath } from '@/helpers';
33

4+
export interface FileUpload {
5+
name: string;
6+
loaded: number;
7+
readonly total: number;
8+
}
9+
410
export interface ServerFileStore {
511
directory: string;
612
selectedFiles: string[];
13+
uploads: FileUpload[];
714

815
setDirectory: Action<ServerFileStore, string>;
916
setSelectedFiles: Action<ServerFileStore, string[]>;
1017
appendSelectedFile: Action<ServerFileStore, string>;
1118
removeSelectedFile: Action<ServerFileStore, string>;
19+
20+
appendFileUpload: Action<ServerFileStore, FileUpload>;
21+
removeFileUpload: Action<ServerFileStore, string>;
1222
}
1323

1424
const files: ServerFileStore = {
1525
directory: '/',
1626
selectedFiles: [],
27+
uploads: [],
1728

1829
setDirectory: action((state, payload) => {
1930
state.directory = cleanDirectoryPath(payload);
@@ -30,6 +41,14 @@ const files: ServerFileStore = {
3041
removeSelectedFile: action((state, payload) => {
3142
state.selectedFiles = state.selectedFiles.filter((f) => f !== payload);
3243
}),
44+
45+
appendFileUpload: action((state, payload) => {
46+
state.uploads = state.uploads.filter((f) => f.name !== payload.name).concat(payload);
47+
}),
48+
49+
removeFileUpload: action((state, payload) => {
50+
state.uploads = state.uploads.filter((f) => f.name !== payload);
51+
}),
3352
};
3453

3554
export default files;

0 commit comments

Comments
 (0)