-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathDropzone.svelte
365 lines (316 loc) · 9.44 KB
/
Dropzone.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
<script>
import { fromEvent } from "file-selector";
import {
fileAccepted,
fileMatchSize,
isEvtWithFiles,
isIeOrEdge,
isPropagationStopped,
TOO_MANY_FILES_REJECTION
} from "../utils/index";
import { onMount, onDestroy, createEventDispatcher } from "svelte";
//props
/**
* Set accepted file types.
* See https://github.com/okonet/attr-accept for more information.
*/
/**
* @type {string | Array<string>}
*/
export let accept = undefined;
export let disabled = false;
export let getFilesFromEvent = fromEvent;
export let maxSize = Infinity;
export let minSize = 0;
export let multiple = true;
export let preventDropOnDocument = true;
export let noClick = false;
export let noKeyboard = false;
export let noDrag = false;
export let noDragEventsBubbling = false;
export let containerClasses = "";
export let containerStyles = "";
export let disableDefaultStyles = false;
export let name = "";
export let inputElement = undefined;
export let required = false;
const dispatch = createEventDispatcher();
//state
let state = {
isFocused: false,
isFileDialogActive: false,
isDragActive: false,
isDragAccept: false,
isDragReject: false,
draggedFiles: [],
acceptedFiles: [],
fileRejections: []
};
let rootRef;
function resetState() {
state.isFileDialogActive = false;
state.isDragActive = false;
state.draggedFiles = [];
state.acceptedFiles = [];
state.fileRejections = [];
}
// Fn for opening the file dialog programmatically
function openFileDialog() {
if (inputElement) {
inputElement.value = null; // TODO check if null needs to be set
state.isFileDialogActive = true;
inputElement.click();
}
}
// Cb to open the file dialog when SPACE/ENTER occurs on the dropzone
function onKeyDownCb(event) {
// Ignore keyboard events bubbling up the DOM tree
if (!rootRef || !rootRef.isEqualNode(event.target)) {
return;
}
if (event.keyCode === 32 || event.keyCode === 13) {
event.preventDefault();
openFileDialog();
}
}
// Update focus state for the dropzone
function onFocusCb() {
state.isFocused = true;
}
function onBlurCb() {
state.isFocused = false;
}
// Cb to open the file dialog when click occurs on the dropzone
function onClickCb() {
if (noClick) {
return;
}
// In IE11/Edge the file-browser dialog is blocking, therefore, use setTimeout()
// to ensure React can handle state changes
// See: https://github.com/react-dropzone/react-dropzone/issues/450
if (isIeOrEdge()) {
setTimeout(openFileDialog, 0);
} else {
openFileDialog();
}
}
function onDragEnterCb(event) {
event.preventDefault();
stopPropagation(event);
dragTargetsRef = [...dragTargetsRef, event.target];
if (isEvtWithFiles(event)) {
Promise.resolve(getFilesFromEvent(event)).then(draggedFiles => {
if (isPropagationStopped(event) && !noDragEventsBubbling) {
return;
}
state.draggedFiles = draggedFiles;
state.isDragActive = true;
dispatch("dragenter", {
dragEvent: event
});
});
}
}
function onDragOverCb(event) {
event.preventDefault();
stopPropagation(event);
if (event.dataTransfer) {
try {
event.dataTransfer.dropEffect = "copy";
} catch {} /* eslint-disable-line no-empty */
}
if (isEvtWithFiles(event)) {
dispatch("dragover", {
dragEvent: event
});
}
return false;
}
function onDragLeaveCb(event) {
event.preventDefault();
stopPropagation(event);
// Only deactivate once the dropzone and all children have been left
const targets = dragTargetsRef.filter(target => rootRef && rootRef.contains(target));
// Make sure to remove a target present multiple times only once
// (Firefox may fire dragenter/dragleave multiple times on the same element)
const targetIdx = targets.indexOf(event.target);
if (targetIdx !== -1) {
targets.splice(targetIdx, 1);
}
dragTargetsRef = targets;
if (targets.length > 0) {
return;
}
state.isDragActive = false;
state.draggedFiles = [];
if (isEvtWithFiles(event)) {
dispatch("dragleave", {
dragEvent: event
});
}
}
function onDropCb(event) {
event.preventDefault();
stopPropagation(event);
dragTargetsRef = [];
if (isEvtWithFiles(event)) {
dispatch("filedropped", {
event
});
Promise.resolve(getFilesFromEvent(event)).then(files => {
if (isPropagationStopped(event) && !noDragEventsBubbling) {
return;
}
const acceptedFiles = [];
const fileRejections = [];
files.forEach(file => {
const [accepted, acceptError] = fileAccepted(file, accept);
const [sizeMatch, sizeError] = fileMatchSize(file, minSize, maxSize);
if (accepted && sizeMatch) {
acceptedFiles.push(file);
} else {
const errors = [acceptError, sizeError].filter(e => e);
fileRejections.push({ file, errors });
}
});
if (!multiple && acceptedFiles.length > 1) {
// Reject everything and empty accepted files
acceptedFiles.forEach(file => {
fileRejections.push({ file, errors: [TOO_MANY_FILES_REJECTION] });
});
acceptedFiles.splice(0);
}
// Files dropped keep input in sync
if (event.dataTransfer) {
inputElement.files = event.dataTransfer.files;
}
state.acceptedFiles = acceptedFiles;
state.fileRejections = fileRejections;
dispatch("drop", {
acceptedFiles,
fileRejections,
event
});
if (fileRejections.length > 0) {
dispatch("droprejected", {
fileRejections,
event
});
}
if (acceptedFiles.length > 0) {
dispatch("dropaccepted", {
acceptedFiles,
event
});
}
});
}
resetState();
}
$: composeHandler = fn => (disabled ? null : fn);
$: composeKeyboardHandler = fn => (noKeyboard ? null : composeHandler(fn));
$: composeDragHandler = fn => (noDrag ? null : composeHandler(fn));
$: defaultPlaceholderString = multiple
? "Drag 'n' drop some files here, or click to select files"
: "Drag 'n' drop a file here, or click to select a file";
function stopPropagation(event) {
if (noDragEventsBubbling) {
event.stopPropagation();
}
}
// allow the entire document to be a drag target
function onDocumentDragOver(event) {
if (preventDropOnDocument) {
event.preventDefault();
}
}
let dragTargetsRef = [];
function onDocumentDrop(event) {
if (!preventDropOnDocument) {
return;
}
if (rootRef && rootRef.contains(event.target)) {
// If we intercepted an event for our instance, let it propagate down to the instance's onDrop handler
return;
}
event.preventDefault();
dragTargetsRef = [];
}
// Update file dialog active state when the window is focused on
function onWindowFocus() {
// Execute the timeout only if the file dialog is opened in the browser
if (state.isFileDialogActive) {
setTimeout(() => {
if (inputElement) {
const { files } = inputElement;
if (!files.length) {
state.isFileDialogActive = false;
dispatch("filedialogcancel");
}
}
}, 300);
}
}
onDestroy(() => {
// This is critical for canceling the timeout behaviour on `onWindowFocus()`
inputElement = null;
});
function onInputElementClick(event) {
event.stopPropagation();
}
</script>
<svelte:window on:focus={onWindowFocus} on:dragover={onDocumentDragOver} on:drop={onDocumentDrop} />
<div
bind:this={rootRef}
tabindex="0"
role="button"
class="{disableDefaultStyles ? '' : 'dropzone'}
{containerClasses}"
style={containerStyles}
on:keydown={composeKeyboardHandler(onKeyDownCb)}
on:focus={composeKeyboardHandler(onFocusCb)}
on:blur={composeKeyboardHandler(onBlurCb)}
on:click={composeHandler(onClickCb)}
on:dragenter={composeDragHandler(onDragEnterCb)}
on:dragover={composeDragHandler(onDragOverCb)}
on:dragleave={composeDragHandler(onDragLeaveCb)}
on:drop={composeDragHandler(onDropCb)}
{...$$restProps}
>
<input
accept={accept?.toString()}
{multiple}
{required}
type="file"
{name}
autocomplete="off"
tabindex="-1"
on:change={onDropCb}
on:click={onInputElementClick}
bind:this={inputElement}
style="display: none;"
/>
<slot>
<p>{defaultPlaceholderString}</p>
</slot>
</div>
<style>
.dropzone {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
border-width: 2px;
border-radius: 2px;
border-color: #eeeeee;
border-style: dashed;
background-color: #fafafa;
color: #bdbdbd;
outline: none;
transition: border 0.24s ease-in-out;
}
.dropzone:focus {
border-color: #2196f3;
}
</style>