gradio-pr-bot commited on
Commit
5bef25b
·
verified ·
1 Parent(s): 237a77e

Upload folder using huggingface_hub

Browse files
6.16.0/upload/package.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@gradio/upload",
3
+ "version": "0.17.10",
4
+ "description": "Gradio UI packages",
5
+ "type": "module",
6
+ "main": "src/index.ts",
7
+ "author": "",
8
+ "license": "ISC",
9
+ "dependencies": {
10
+ "@gradio/atoms": "workspace:^",
11
+ "@gradio/icons": "workspace:^",
12
+ "@gradio/client": "workspace:^",
13
+ "@gradio/utils": "workspace:^"
14
+ },
15
+ "main_changeset": true,
16
+ "exports": {
17
+ ".": {
18
+ "gradio": "./src/index.ts",
19
+ "svelte": "./dist/src/index.js",
20
+ "types": "./dist/src/index.d.ts"
21
+ }
22
+ },
23
+ "peerDependencies": {
24
+ "svelte": "^5.48.0"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/gradio-app/gradio.git",
29
+ "directory": "js/upload"
30
+ }
31
+ }
6.16.0/upload/src/ModifyUpload.svelte ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { IconButton, IconButtonWrapper } from "@gradio/atoms";
3
+ import type { I18nFormatter } from "@gradio/utils";
4
+ import { Edit, Clear, Undo, Download } from "@gradio/icons";
5
+ import { DownloadLink } from "@gradio/atoms";
6
+
7
+ let {
8
+ editable = false,
9
+ undoable = false,
10
+ download = null,
11
+ i18n,
12
+ onedit,
13
+ onclear,
14
+ onundo,
15
+ children
16
+ }: {
17
+ editable?: boolean;
18
+ undoable?: boolean;
19
+ download?: string | null;
20
+ i18n: I18nFormatter;
21
+ onedit?: () => void;
22
+ onclear?: () => void;
23
+ onundo?: () => void;
24
+ children?: import("svelte").Snippet;
25
+ } = $props();
26
+ </script>
27
+
28
+ <IconButtonWrapper>
29
+ {#if editable}
30
+ <IconButton
31
+ Icon={Edit}
32
+ label={i18n("common.edit")}
33
+ onclick={() => onedit?.()}
34
+ />
35
+ {/if}
36
+
37
+ {#if undoable}
38
+ <IconButton
39
+ Icon={Undo}
40
+ label={i18n("common.undo")}
41
+ onclick={() => onundo?.()}
42
+ />
43
+ {/if}
44
+
45
+ {#if download}
46
+ <DownloadLink href={download} download>
47
+ <IconButton Icon={Download} label={i18n("common.download")} />
48
+ </DownloadLink>
49
+ {/if}
50
+
51
+ {#if children}{@render children()}{/if}
52
+
53
+ <IconButton
54
+ Icon={Clear}
55
+ label={i18n("common.clear")}
56
+ onclick={(event) => {
57
+ onclear?.();
58
+ event.stopPropagation();
59
+ }}
60
+ />
61
+ </IconButtonWrapper>
6.16.0/upload/src/Upload.svelte ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { tick } from "svelte";
3
+ import type { FileData } from "@gradio/client";
4
+ import { prepare_files, type Client } from "@gradio/client";
5
+ import UploadProgress from "./UploadProgress.svelte";
6
+ import { create_drag, is_valid_mimetype } from "./utils";
7
+
8
+ const { drag, open_file_upload: _open_file_upload } = create_drag();
9
+
10
+ let {
11
+ filetype = null,
12
+ dragging = $bindable(false),
13
+ boundedheight = true,
14
+ center = true,
15
+ flex = true,
16
+ file_count = "single",
17
+ disable_click = false,
18
+ root,
19
+ hidden = false,
20
+ format = "file",
21
+ uploading = $bindable(false),
22
+ show_progress = true,
23
+ max_file_size = null,
24
+ upload,
25
+ stream_handler,
26
+ icon_upload = false,
27
+ height = undefined,
28
+ aria_label = undefined,
29
+ upload_promise = $bindable(),
30
+ onload,
31
+ onerror,
32
+ children
33
+ }: {
34
+ filetype?: string | string[] | null;
35
+ dragging?: boolean;
36
+ boundedheight?: boolean;
37
+ center?: boolean;
38
+ flex?: boolean;
39
+ file_count?: "single" | "multiple" | "directory";
40
+ disable_click?: boolean;
41
+ root: string;
42
+ hidden?: boolean;
43
+ format?: "blob" | "file";
44
+ uploading?: boolean;
45
+ show_progress?: boolean;
46
+ max_file_size?: number | null;
47
+ upload: Client["upload"];
48
+ stream_handler: Client["stream"];
49
+ icon_upload?: boolean;
50
+ height?: number | string | undefined;
51
+ aria_label?: string | undefined;
52
+ upload_promise?: Promise<(FileData | null)[]>;
53
+ onload?: (data: FileData | FileData[] | Blob | File) => void;
54
+ onerror?: (error: string) => void;
55
+ children?: import("svelte").Snippet;
56
+ } = $props();
57
+
58
+ export function open_upload(): void {
59
+ _open_file_upload();
60
+ }
61
+
62
+ let upload_id: string = "";
63
+ let file_data: FileData[];
64
+ let accept_file_types: string | null = $state(null);
65
+ let use_post_upload_validation: boolean | null = null;
66
+
67
+ const get_ios = (): boolean => {
68
+ if (typeof navigator !== "undefined") {
69
+ const userAgent = navigator.userAgent.toLowerCase();
70
+ return userAgent.indexOf("iphone") > -1 || userAgent.indexOf("ipad") > -1;
71
+ }
72
+ return false;
73
+ };
74
+
75
+ let ios = get_ios();
76
+
77
+ const validFileTypes = ["image", "video", "audio", "text", "file"];
78
+ const process_file_type = (type: string): string => {
79
+ if (ios && type.startsWith(".")) {
80
+ use_post_upload_validation = true;
81
+ return type;
82
+ }
83
+ if (ios && type.includes("file/*")) {
84
+ return "*";
85
+ }
86
+ if (type.startsWith(".") || type.endsWith("/*")) {
87
+ return type;
88
+ }
89
+ if (validFileTypes.includes(type)) {
90
+ return type + "/*";
91
+ }
92
+ return "." + type;
93
+ };
94
+
95
+ $effect(() => {
96
+ if (filetype == null) {
97
+ accept_file_types = null;
98
+ } else if (typeof filetype === "string") {
99
+ accept_file_types = process_file_type(filetype);
100
+ } else if (ios && filetype.includes("file/*")) {
101
+ accept_file_types = "*";
102
+ } else {
103
+ const processed = filetype.map(process_file_type);
104
+ accept_file_types = processed.join(", ");
105
+ }
106
+ });
107
+
108
+ export function paste_clipboard(): void {
109
+ navigator.clipboard.read().then(async (items) => {
110
+ for (let i = 0; i < items.length; i++) {
111
+ const type = items[i].types.find((t) => t.startsWith("image/"));
112
+ if (type) {
113
+ items[i].getType(type).then(async (blob) => {
114
+ const file = new File(
115
+ [blob],
116
+ `clipboard.${type.replace("image/", "")}`
117
+ );
118
+ await load_files([file]);
119
+ });
120
+ break;
121
+ }
122
+ }
123
+ });
124
+ }
125
+
126
+ export function open_file_upload(): void {
127
+ _open_file_upload();
128
+ }
129
+
130
+ async function handle_upload(
131
+ file_data: FileData[],
132
+ _upload_id?: string
133
+ ): Promise<(FileData | null)[]> {
134
+ if (!_upload_id) {
135
+ upload_id = Math.random().toString(36).substring(2, 15);
136
+ } else {
137
+ upload_id = _upload_id;
138
+ }
139
+
140
+ await tick();
141
+ uploading = true;
142
+ upload_promise = new Promise(async (resolve) => {
143
+ try {
144
+ const _file_data = await upload(
145
+ file_data,
146
+ root,
147
+ upload_id,
148
+ max_file_size ?? Infinity
149
+ );
150
+ onload?.(file_count === "single" ? _file_data?.[0] : _file_data);
151
+ resolve(_file_data || []);
152
+ uploading = false;
153
+ } catch (e) {
154
+ onerror?.((e as Error).message);
155
+ uploading = false;
156
+ resolve([]);
157
+ }
158
+ });
159
+
160
+ return upload_promise;
161
+ }
162
+
163
+ export async function load_files(
164
+ files: File[] | Blob[],
165
+ upload_id?: string
166
+ ): Promise<(FileData | null)[] | void> {
167
+ if (!files.length) {
168
+ return;
169
+ }
170
+ let _files: File[] = files.map(
171
+ (f) =>
172
+ new File([f], f instanceof File ? f.name : "file", { type: f.type })
173
+ );
174
+
175
+ if (ios && use_post_upload_validation) {
176
+ _files = _files.filter((file) => {
177
+ if (is_valid_file(file)) {
178
+ return true;
179
+ }
180
+ onerror?.(`Invalid file type: ${file.name}. Only ${filetype} allowed.`);
181
+ return false;
182
+ });
183
+
184
+ if (_files.length === 0) {
185
+ return [];
186
+ }
187
+ }
188
+
189
+ file_data = await prepare_files(_files);
190
+ return await handle_upload(file_data, upload_id);
191
+ }
192
+
193
+ function is_valid_file(file: File): boolean {
194
+ if (!filetype) return true;
195
+
196
+ const allowed_types = Array.isArray(filetype) ? filetype : [filetype];
197
+
198
+ return allowed_types.some((type) => {
199
+ const processed_type = process_file_type(type);
200
+
201
+ if (processed_type.startsWith(".")) {
202
+ return file.name.toLowerCase().endsWith(processed_type.toLowerCase());
203
+ }
204
+
205
+ if (processed_type === "*") {
206
+ return true;
207
+ }
208
+
209
+ if (processed_type.endsWith("/*")) {
210
+ const [category] = processed_type.split("/");
211
+ return file.type.startsWith(category + "/");
212
+ }
213
+
214
+ return file.type === processed_type;
215
+ });
216
+ }
217
+
218
+ async function load_files_from_upload(files: File[]): Promise<void> {
219
+ const files_to_load = files.filter((file) => {
220
+ const file_extension = "." + file.name.toLowerCase().split(".").pop();
221
+ if (
222
+ file_extension &&
223
+ is_valid_mimetype(accept_file_types, file_extension, file.type)
224
+ ) {
225
+ return true;
226
+ }
227
+ if (
228
+ file_extension && Array.isArray(filetype)
229
+ ? filetype.includes(file_extension)
230
+ : file_extension === filetype
231
+ ) {
232
+ return true;
233
+ }
234
+ onerror?.(`Invalid file type only ${filetype} allowed.`);
235
+ return false;
236
+ });
237
+ if (format != "blob") {
238
+ await load_files(files_to_load);
239
+ } else {
240
+ if (file_count === "single") {
241
+ onload?.(files_to_load[0]);
242
+ return;
243
+ }
244
+ onload?.(files_to_load);
245
+ }
246
+ }
247
+
248
+ export async function load_files_from_drop(e: DragEvent): Promise<void> {
249
+ dragging = false;
250
+ if (!e.dataTransfer?.files) return;
251
+ const files_to_load = Array.from(e.dataTransfer.files).filter(
252
+ is_valid_file
253
+ );
254
+
255
+ if (format != "blob") {
256
+ await load_files(files_to_load);
257
+ } else {
258
+ if (file_count === "single") {
259
+ onload?.(files_to_load[0]);
260
+ return;
261
+ }
262
+ onload?.(files_to_load);
263
+ }
264
+ }
265
+ </script>
266
+
267
+ {#if filetype === "clipboard"}
268
+ <button
269
+ class:hidden
270
+ class:center
271
+ class:boundedheight
272
+ class:flex
273
+ class:icon-mode={icon_upload}
274
+ style:height={icon_upload
275
+ ? ""
276
+ : height
277
+ ? typeof height === "number"
278
+ ? height + "px"
279
+ : height
280
+ : "100%"}
281
+ tabindex={hidden ? -1 : 0}
282
+ onclick={paste_clipboard}
283
+ aria-label={aria_label || "Paste from clipboard"}
284
+ >
285
+ {#if children}{@render children()}{/if}
286
+ </button>
287
+ {:else if uploading && show_progress}
288
+ {#if !hidden}
289
+ <UploadProgress {root} {upload_id} files={file_data} {stream_handler} />
290
+ {/if}
291
+ {:else}
292
+ <button
293
+ class:hidden
294
+ class:center
295
+ class:boundedheight
296
+ class:flex
297
+ class:disable_click
298
+ class:icon-mode={icon_upload}
299
+ style:height={icon_upload
300
+ ? ""
301
+ : height
302
+ ? typeof height === "number"
303
+ ? height + "px"
304
+ : height
305
+ : "100%"}
306
+ tabindex={hidden ? -1 : 0}
307
+ use:drag={{
308
+ on_drag_change: (d) => (dragging = d),
309
+ on_files: (files) => load_files_from_upload(files),
310
+ accepted_types: accept_file_types,
311
+ mode: file_count,
312
+ disable_click
313
+ }}
314
+ aria-label={aria_label || "Click to upload or drop files"}
315
+ aria-dropeffect="copy"
316
+ >
317
+ {#if children}{@render children()}{/if}
318
+ </button>
319
+ {/if}
320
+
321
+ <style>
322
+ button {
323
+ cursor: pointer;
324
+ width: var(--size-full);
325
+ }
326
+
327
+ .center {
328
+ display: flex;
329
+ justify-content: center;
330
+ }
331
+ .flex {
332
+ display: flex;
333
+ flex-direction: column;
334
+ justify-content: center;
335
+ align-items: center;
336
+ }
337
+ .hidden {
338
+ display: none;
339
+ position: absolute;
340
+ flex-grow: 0;
341
+ }
342
+
343
+ .hidden :global(svg) {
344
+ display: none;
345
+ }
346
+
347
+ .disable_click {
348
+ cursor: default;
349
+ }
350
+
351
+ .icon-mode {
352
+ position: absolute !important;
353
+ width: var(--size-4);
354
+ height: var(--size-4);
355
+ padding: 0;
356
+ min-height: 0;
357
+ border-radius: var(--radius-circle);
358
+ }
359
+
360
+ .icon-mode :global(svg) {
361
+ width: var(--size-4);
362
+ height: var(--size-4);
363
+ }
364
+ </style>
6.16.0/upload/src/UploadProgress.svelte ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { FileData, type Client } from "@gradio/client";
3
+ import { onMount, onDestroy } from "svelte";
4
+
5
+ type FileDataWithProgress = FileData & { progress: number };
6
+
7
+ let {
8
+ upload_id,
9
+ root,
10
+ files,
11
+ stream_handler,
12
+ ondone
13
+ }: {
14
+ upload_id: string;
15
+ root: string;
16
+ files: FileData[];
17
+ stream_handler: Client["stream"];
18
+ ondone?: () => void;
19
+ } = $props();
20
+
21
+ let stream: Awaited<ReturnType<Client["stream"]>>;
22
+ let progress = $state(false);
23
+ let current_file_upload = $state<FileDataWithProgress>();
24
+ let file_to_display = $derived(current_file_upload || files_with_progress[0]);
25
+
26
+ let files_with_progress = $state<FileDataWithProgress[]>(
27
+ files.map((file) => {
28
+ return {
29
+ ...file,
30
+ progress: 0
31
+ };
32
+ })
33
+ );
34
+
35
+ function handleProgress(filename: string, chunk_size: number): void {
36
+ // Find the corresponding file in the array and update its progress
37
+ files_with_progress = files_with_progress.map((file) => {
38
+ if (file.orig_name === filename) {
39
+ file.progress += chunk_size;
40
+ }
41
+ return file;
42
+ });
43
+ }
44
+
45
+ function getProgress(file: FileDataWithProgress): number {
46
+ return (file.progress * 100) / (file.size || 0) || 0;
47
+ }
48
+
49
+ onMount(async () => {
50
+ stream = await stream_handler(
51
+ new URL(`${root}/gradio_api/upload_progress?upload_id=${upload_id}`)
52
+ );
53
+
54
+ if (stream == null) {
55
+ throw new Error("Event source is not defined");
56
+ }
57
+ // Event listener for progress updates
58
+ stream.onmessage = async function (event) {
59
+ const _data = JSON.parse(event.data);
60
+ if (!progress) progress = true;
61
+ if (_data.msg === "done") {
62
+ // the stream will close itself but is here for clarity; remove .close() in 5.0
63
+ stream?.close();
64
+ ondone?.();
65
+ } else {
66
+ current_file_upload = _data;
67
+ handleProgress(_data.orig_name, _data.chunk_size);
68
+ }
69
+ };
70
+ });
71
+
72
+ onDestroy(() => {
73
+ // the stream will close itself but is here for clarity; remove .close() in 5.0
74
+ if (stream != null || stream != undefined) stream.close();
75
+ });
76
+
77
+ function calculateTotalProgress(files: FileDataWithProgress[]): number {
78
+ let totalProgress = 0;
79
+ files.forEach((file) => {
80
+ totalProgress += getProgress(file);
81
+ });
82
+
83
+ document.documentElement.style.setProperty(
84
+ "--upload-progress-width",
85
+ (totalProgress / files.length).toFixed(2) + "%"
86
+ );
87
+
88
+ return totalProgress / files.length;
89
+ }
90
+
91
+ $effect(() => {
92
+ calculateTotalProgress(files_with_progress);
93
+ });
94
+ </script>
95
+
96
+ <div class="wrap" class:progress>
97
+ <span class="uploading"
98
+ >Uploading {files_with_progress.length}
99
+ {files_with_progress.length > 1 ? "files" : "file"}...</span
100
+ >
101
+
102
+ {#if file_to_display}
103
+ <div class="file">
104
+ <span>
105
+ <div class="progress-bar">
106
+ <progress
107
+ style="visibility:hidden;height:0;width:0;"
108
+ value={getProgress(file_to_display)}
109
+ max="100">{getProgress(file_to_display)}</progress
110
+ >
111
+ </div>
112
+ </span>
113
+ <span class="file-name">
114
+ {file_to_display.orig_name}
115
+ </span>
116
+ </div>
117
+ {/if}
118
+ </div>
119
+
120
+ <style>
121
+ .wrap {
122
+ overflow-y: auto;
123
+ transition: opacity 0.5s ease-in-out;
124
+ background: var(--block-background-fill);
125
+ position: relative;
126
+ display: flex;
127
+ flex-direction: column;
128
+ align-items: center;
129
+ justify-content: center;
130
+ min-height: var(--size-40);
131
+ width: var(--size-full);
132
+ }
133
+
134
+ .wrap::after {
135
+ content: "";
136
+ position: absolute;
137
+ top: 0;
138
+ left: 0;
139
+ width: var(--upload-progress-width);
140
+ height: 100%;
141
+ transition: all 0.5s ease-in-out;
142
+ z-index: 1;
143
+ }
144
+
145
+ .uploading {
146
+ font-size: var(--text-lg);
147
+ font-family: var(--font);
148
+ z-index: 2;
149
+ }
150
+
151
+ .file-name {
152
+ margin: var(--spacing-md);
153
+ font-size: var(--text-lg);
154
+ color: var(--body-text-color-subdued);
155
+ }
156
+
157
+ .file {
158
+ font-size: var(--text-md);
159
+ z-index: 2;
160
+ display: flex;
161
+ align-items: center;
162
+ }
163
+
164
+ .file progress {
165
+ display: inline;
166
+ height: var(--size-1);
167
+ width: 100%;
168
+ transition: all 0.5s ease-in-out;
169
+ color: var(--color-accent);
170
+ border: none;
171
+ }
172
+
173
+ .file progress[value]::-webkit-progress-value {
174
+ background-color: var(--color-accent);
175
+ border-radius: 20px;
176
+ }
177
+
178
+ .file progress[value]::-webkit-progress-bar {
179
+ background-color: var(--border-color-accent);
180
+ border-radius: 20px;
181
+ }
182
+
183
+ .progress-bar {
184
+ width: 14px;
185
+ height: 14px;
186
+ border-radius: 50%;
187
+ background:
188
+ radial-gradient(
189
+ closest-side,
190
+ var(--block-background-fill) 64%,
191
+ transparent 53% 100%
192
+ ),
193
+ conic-gradient(
194
+ var(--color-accent) var(--upload-progress-width),
195
+ var(--border-color-accent) 0
196
+ );
197
+ transition: all 0.5s ease-in-out;
198
+ }
199
+ </style>
6.16.0/upload/src/index.ts ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ export { default as Upload } from "./Upload.svelte";
2
+ export { default as ModifyUpload } from "./ModifyUpload.svelte";
3
+ export { default as UploadProgress } from "./UploadProgress.svelte";
4
+ export { create_drag, is_valid_mimetype } from "./utils";
6.16.0/upload/src/utils.ts ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export function is_valid_mimetype(
2
+ file_accept: string | string[] | null,
3
+ uploaded_file_extension: string,
4
+ uploaded_file_type: string
5
+ ): boolean {
6
+ if (
7
+ !file_accept ||
8
+ file_accept === "*" ||
9
+ file_accept === "file/*" ||
10
+ (Array.isArray(file_accept) &&
11
+ file_accept.some((accept) => accept === "*" || accept === "file/*"))
12
+ ) {
13
+ return true;
14
+ }
15
+ let acceptArray: string[];
16
+ if (typeof file_accept === "string") {
17
+ acceptArray = file_accept.split(",").map((s) => s.trim());
18
+ } else if (Array.isArray(file_accept)) {
19
+ acceptArray = file_accept;
20
+ } else {
21
+ return false;
22
+ }
23
+
24
+ return (
25
+ acceptArray.includes(uploaded_file_extension) ||
26
+ acceptArray.some((type) => {
27
+ const [category] = type.split("/").map((s) => s.trim());
28
+ return (
29
+ type.endsWith("/*") && uploaded_file_type.startsWith(category + "/")
30
+ );
31
+ })
32
+ );
33
+ }
34
+
35
+ interface DragActionOptions {
36
+ disable_click?: boolean;
37
+ accepted_types?: string | string[] | null;
38
+ mode?: "single" | "multiple" | "directory";
39
+ on_drag_change?: (dragging: boolean) => void;
40
+ on_files?: (files: File[]) => void;
41
+ }
42
+
43
+ type ActionReturn = {
44
+ update: (new_options: DragActionOptions) => void;
45
+ destroy: () => void;
46
+ };
47
+
48
+ export function create_drag(): {
49
+ drag: (node: HTMLElement, options: DragActionOptions) => ActionReturn;
50
+ open_file_upload: () => void;
51
+ } {
52
+ let hidden_input: HTMLInputElement;
53
+ let _options: DragActionOptions;
54
+ return {
55
+ drag(
56
+ node: HTMLElement,
57
+ options: DragActionOptions = {}
58
+ ): {
59
+ update: (new_options: DragActionOptions) => void;
60
+ destroy: () => void;
61
+ } {
62
+ _options = options;
63
+
64
+ // Create and configure hidden file input
65
+ function setup_hidden_input(): void {
66
+ hidden_input = document.createElement("input");
67
+ hidden_input.type = "file";
68
+ hidden_input.style.display = "none";
69
+ hidden_input.setAttribute("aria-label", "File upload");
70
+ hidden_input.setAttribute("data-testid", "file-upload");
71
+ const accept_options = Array.isArray(_options.accepted_types)
72
+ ? _options.accepted_types.join(",")
73
+ : _options.accepted_types || undefined;
74
+
75
+ if (accept_options) {
76
+ hidden_input.accept = accept_options;
77
+ }
78
+
79
+ hidden_input.multiple = _options.mode === "multiple" || false;
80
+ if (_options.mode === "directory") {
81
+ hidden_input.webkitdirectory = true;
82
+ hidden_input.setAttribute("directory", "");
83
+ hidden_input.setAttribute("mozdirectory", "");
84
+ }
85
+ node.appendChild(hidden_input);
86
+ }
87
+
88
+ setup_hidden_input();
89
+
90
+ function handle_drag(e: DragEvent): void {
91
+ e.preventDefault();
92
+ e.stopPropagation();
93
+ }
94
+
95
+ function handle_drag_enter(e: DragEvent): void {
96
+ e.preventDefault();
97
+ e.stopPropagation();
98
+ _options.on_drag_change?.(true);
99
+ }
100
+
101
+ function handle_drag_leave(e: DragEvent): void {
102
+ e.preventDefault();
103
+ e.stopPropagation();
104
+ _options.on_drag_change?.(false);
105
+ }
106
+
107
+ function handle_drop(e: DragEvent): void {
108
+ e.preventDefault();
109
+ e.stopPropagation();
110
+ _options.on_drag_change?.(false);
111
+
112
+ if (!e.dataTransfer?.files) return;
113
+ const files = Array.from(e.dataTransfer.files);
114
+ if (files.length > 0) {
115
+ _options.on_files?.(files);
116
+ }
117
+ }
118
+
119
+ function handle_click(): void {
120
+ if (!_options.disable_click) {
121
+ hidden_input.value = "";
122
+ hidden_input.click();
123
+ }
124
+ }
125
+
126
+ function handle_file_input_change(): void {
127
+ if (hidden_input.files) {
128
+ const files = Array.from(hidden_input.files);
129
+ if (files.length > 0) {
130
+ _options.on_files?.(files);
131
+ }
132
+ }
133
+ }
134
+
135
+ // Add all event listeners
136
+ node.addEventListener("drag", handle_drag);
137
+ node.addEventListener("dragstart", handle_drag);
138
+ node.addEventListener("dragend", handle_drag);
139
+ node.addEventListener("dragover", handle_drag);
140
+ node.addEventListener("dragenter", handle_drag_enter);
141
+ node.addEventListener("dragleave", handle_drag_leave);
142
+ node.addEventListener("drop", handle_drop);
143
+ node.addEventListener("click", handle_click);
144
+ hidden_input!.addEventListener("change", handle_file_input_change);
145
+
146
+ return {
147
+ update(new_options: DragActionOptions) {
148
+ _options = new_options;
149
+ // Recreate hidden input with new options
150
+ hidden_input.remove();
151
+ setup_hidden_input();
152
+ hidden_input.addEventListener("change", handle_file_input_change);
153
+ },
154
+ destroy() {
155
+ node.removeEventListener("drag", handle_drag);
156
+ node.removeEventListener("dragstart", handle_drag);
157
+ node.removeEventListener("dragend", handle_drag);
158
+ node.removeEventListener("dragover", handle_drag);
159
+ node.removeEventListener("dragenter", handle_drag_enter);
160
+ node.removeEventListener("dragleave", handle_drag_leave);
161
+ node.removeEventListener("drop", handle_drop);
162
+ node.removeEventListener("click", handle_click);
163
+ hidden_input.removeEventListener("change", handle_file_input_change);
164
+ hidden_input.remove();
165
+ }
166
+ };
167
+ },
168
+ open_file_upload(): void {
169
+ if (hidden_input) {
170
+ hidden_input.value = "";
171
+ hidden_input.click();
172
+ }
173
+ }
174
+ };
175
+ }