/
Upload.svelte
250 lines (232 loc) 路 6.18 KB
/
Upload.svelte
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
<script lang="ts">
import { createEventDispatcher, tick, getContext } from "svelte";
import type { FileData } from "@gradio/client";
import { upload_files, upload, prepare_files } from "@gradio/client";
import { _ } from "svelte-i18n";
import UploadProgress from "./UploadProgress.svelte";
export let filetype: string | string[] | null = null;
export let dragging = false;
export let boundedheight = true;
export let center = true;
export let flex = true;
export let file_count = "single";
export let disable_click = false;
export let root: string;
export let hidden = false;
export let format: "blob" | "file" = "file";
export let uploading = false;
let upload_id: string;
let file_data: FileData[];
let accept_file_types: string | null;
// Needed for wasm support
const upload_fn = getContext<typeof upload_files>("upload_files");
let hidden_upload: HTMLInputElement;
const dispatch = createEventDispatcher();
const validFileTypes = ["image", "video", "audio", "text", "file"];
const processFileType = (type: string): string => {
if (type.startsWith(".") || type.endsWith("/*")) {
return type;
}
if (validFileTypes.includes(type)) {
return type + "/*";
}
return "." + type;
};
$: if (filetype == null) {
accept_file_types = null;
} else if (typeof filetype === "string") {
accept_file_types = processFileType(filetype);
} else {
filetype = filetype.map(processFileType);
accept_file_types = filetype.join(", ");
}
function updateDragging(): void {
dragging = !dragging;
}
export function paste_clipboard(): void {
navigator.clipboard.read().then(async (items) => {
for (let i = 0; i < items.length; i++) {
const type = items[i].types.find((t) => t.startsWith("image/"));
if (type) {
items[i].getType(type).then(async (blob) => {
const file = new File(
[blob],
`clipboard.${type.replace("image/", "")}`
);
await load_files([file]);
});
break;
}
}
});
}
export function open_file_upload(): void {
if (disable_click) return;
hidden_upload.value = "";
hidden_upload.click();
}
async function handle_upload(
file_data: FileData[]
): Promise<(FileData | null)[]> {
await tick();
upload_id = Math.random().toString(36).substring(2, 15);
uploading = true;
const _file_data = await upload(file_data, root, upload_id, upload_fn);
dispatch("load", file_count === "single" ? _file_data?.[0] : _file_data);
uploading = false;
return _file_data || [];
}
export async function load_files(
files: File[] | Blob[]
): Promise<(FileData | null)[] | void> {
if (!files.length) {
return;
}
let _files: File[] = files.map((f) => new File([f], f.name));
file_data = await prepare_files(_files);
return await handle_upload(file_data);
}
async function load_files_from_upload(e: Event): Promise<void> {
const target = e.target as HTMLInputElement;
if (!target.files) return;
if (format != "blob") {
await load_files(Array.from(target.files));
} else {
if (file_count === "single") {
dispatch("load", target.files[0]);
return;
}
dispatch("load", target.files);
}
}
function is_valid_mimetype(
file_accept: string | string[] | null,
uploaded_file_extension: string,
uploaded_file_type: string
): boolean {
if (
!file_accept ||
file_accept === "*" ||
file_accept === "file/*" ||
(Array.isArray(file_accept) &&
file_accept.some((accept) => accept === "*" || accept === "file/*"))
) {
return true;
}
let acceptArray: string[];
if (typeof file_accept === "string") {
acceptArray = file_accept.split(",").map((s) => s.trim());
} else if (Array.isArray(file_accept)) {
acceptArray = file_accept;
} else {
return false;
}
return (
acceptArray.includes(uploaded_file_extension) ||
acceptArray.some((type) => {
const [category] = type.split("/").map((s) => s.trim());
return (
type.endsWith("/*") && uploaded_file_type.startsWith(category + "/")
);
})
);
}
async function loadFilesFromDrop(e: DragEvent): Promise<void> {
dragging = false;
if (!e.dataTransfer?.files) return;
const files_to_load = Array.from(e.dataTransfer.files).filter((file) => {
const file_extension = "." + file.name.split(".").pop();
if (
file_extension &&
is_valid_mimetype(accept_file_types, file_extension, file.type)
) {
return true;
}
if (
file_extension && Array.isArray(filetype)
? filetype.includes(file_extension)
: file_extension === filetype
) {
return true;
}
dispatch("error", `Invalid file type only ${filetype} allowed.`);
return false;
});
await load_files(files_to_load);
}
</script>
{#if filetype === "clipboard"}
<button
class:hidden
class:center
class:boundedheight
class:flex
style:height="100%"
tabindex={hidden ? -1 : 0}
on:click={paste_clipboard}
>
<slot />
</button>
{:else if uploading}
{#if !hidden}
<UploadProgress {root} {upload_id} files={file_data} />
{/if}
{:else}
<button
class:hidden
class:center
class:boundedheight
class:flex
style:height="100%"
tabindex={hidden ? -1 : 0}
on:drag|preventDefault|stopPropagation
on:dragstart|preventDefault|stopPropagation
on:dragend|preventDefault|stopPropagation
on:dragover|preventDefault|stopPropagation
on:dragenter|preventDefault|stopPropagation
on:dragleave|preventDefault|stopPropagation
on:drop|preventDefault|stopPropagation
on:click={open_file_upload}
on:drop={loadFilesFromDrop}
on:dragenter={updateDragging}
on:dragleave={updateDragging}
>
<slot />
<input
aria-label="file upload"
data-testid="file-upload"
type="file"
bind:this={hidden_upload}
on:change={load_files_from_upload}
accept={accept_file_types}
multiple={file_count === "multiple" || undefined}
webkitdirectory={file_count === "directory" || undefined}
mozdirectory={file_count === "directory" || undefined}
/>
</button>
{/if}
<style>
button {
cursor: pointer;
width: var(--size-full);
}
.hidden {
display: none;
height: 0 !important;
position: absolute;
width: 0;
flex-grow: 0;
}
.center {
display: flex;
justify-content: center;
}
.flex {
display: flex;
justify-content: center;
align-items: center;
}
input {
display: none;
}
</style>