gradio-pr-bot commited on
Commit
1a91a53
·
verified ·
1 Parent(s): 145e067

Upload folder using huggingface_hub

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