Debian Codegraph @

node/react-dropzone/src/index.js

raw
1 /* eslint prefer-template: 0 */
2 import React, {
3 forwardRef,
4 Fragment,
5 useCallback,
6 useEffect,
7 useImperativeHandle,
8 useMemo,
9 useReducer,
10 useRef,
11 } from "react";
12 import PropTypes from "prop-types";
13 import { fromEvent } from "file-selector";
14 import {
15 acceptPropAsAcceptAttr,
16 allFilesAccepted,
17 composeEventHandlers,
18 fileAccepted,
19 fileMatchSize,
20 canUseFileSystemAccessAPI,
21 isAbort,
22 isEvtWithFiles,
23 isIeOrEdge,
24 isPropagationStopped,
25 isSecurityError,
26 onDocumentDragOver,
27 pickerOptionsFromAccept,
28 TOO_MANY_FILES_REJECTION,
29 } from "./utils/index.js";
30
31 /**
32 * Convenience wrapper component for the `useDropzone` hook
33 *
34 * ```jsx
35 * <Dropzone>
36 * {({getRootProps, getInputProps}) => (
37 * <div {...getRootProps()}>
38 * <input {...getInputProps()} />
39 * <p>Drag 'n' drop some files here, or click to select files</p>
40 * </div>
41 * )}
42 * </Dropzone>
43 * ```
44 */
45 const Dropzone = forwardRef(({ children, ...params }, ref) => {
46 const { open, ...props } = useDropzone(params);
47
48 useImperativeHandle(ref, () => ({ open }), [open]);
49
50 // TODO: Figure out why react-styleguidist cannot create docs if we don't return a jsx element
51 return <Fragment>{children({ ...props, open })}</Fragment>;
52 });
53
54 Dropzone.displayName = "Dropzone";
55
56 // Add default props for react-docgen
57 const defaultProps = {
58 disabled: false,
59 getFilesFromEvent: fromEvent,
60 maxSize: Infinity,
61 minSize: 0,
62 multiple: true,
63 maxFiles: 0,
64 preventDropOnDocument: true,
65 noClick: false,
66 noKeyboard: false,
67 noDrag: false,
68 noDragEventsBubbling: false,
69 validator: null,
70 useFsAccessApi: false,
71 autoFocus: false,
72 };
73
74 Dropzone.defaultProps = defaultProps;
75
76 Dropzone.propTypes = {
77 /**
78 * Render function that exposes the dropzone state and prop getter fns
79 *
80 * @param {object} params
81 * @param {Function} params.getRootProps Returns the props you should apply to the root drop container you render
82 * @param {Function} params.getInputProps Returns the props you should apply to hidden file input you render
83 * @param {Function} params.open Open the native file selection dialog
84 * @param {boolean} params.isFocused Dropzone area is in focus
85 * @param {boolean} params.isFileDialogActive File dialog is opened
86 * @param {boolean} params.isDragActive Active drag is in progress
87 * @param {boolean} params.isDragAccept Dragged files are accepted
88 * @param {boolean} params.isDragReject Some dragged files are rejected
89 * @param {boolean} params.isDragGlobal Files are being dragged anywhere on the document
90 * @param {File[]} params.acceptedFiles Accepted files
91 * @param {FileRejection[]} params.fileRejections Rejected files and why they were rejected
92 */
93 children: PropTypes.func,
94
95 /**
96 * Set accepted file types.
97 * Checkout https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker types option for more information.
98 * Keep in mind that mime type determination is not reliable across platforms. CSV files,
99 * for example, are reported as text/plain under macOS but as application/vnd.ms-excel under
100 * Windows. In some cases there might not be a mime type set at all (https://github.com/react-dropzone/react-dropzone/issues/276).
101 */
102 accept: PropTypes.objectOf(PropTypes.arrayOf(PropTypes.string)),
103
104 /**
105 * Allow drag 'n' drop (or selection from the file dialog) of multiple files
106 */
107 multiple: PropTypes.bool,
108
109 /**
110 * If false, allow dropped items to take over the current browser window
111 */
112 preventDropOnDocument: PropTypes.bool,
113
114 /**
115 * If true, disables click to open the native file selection dialog
116 */
117 noClick: PropTypes.bool,
118
119 /**
120 * If true, disables SPACE/ENTER to open the native file selection dialog.
121 * Note that it also stops tracking the focus state.
122 */
123 noKeyboard: PropTypes.bool,
124
125 /**
126 * If true, disables drag 'n' drop
127 */
128 noDrag: PropTypes.bool,
129
130 /**
131 * If true, stops drag event propagation to parents
132 */
133 noDragEventsBubbling: PropTypes.bool,
134
135 /**
136 * Minimum file size (in bytes)
137 */
138 minSize: PropTypes.number,
139
140 /**
141 * Maximum file size (in bytes)
142 */
143 maxSize: PropTypes.number,
144 /**
145 * Maximum accepted number of files
146 * The default value is 0 which means there is no limitation to how many files are accepted.
147 */
148 maxFiles: PropTypes.number,
149
150 /**
151 * Enable/disable the dropzone
152 */
153 disabled: PropTypes.bool,
154
155 /**
156 * Use this to provide a custom file aggregator
157 *
158 * @param {(DragEvent|Event|Array<FileSystemFileHandle>)} event A drag event or input change event (if files were selected via the file dialog)
159 */
160 getFilesFromEvent: PropTypes.func,
161
162 /**
163 * Cb for when closing the file dialog with no selection
164 */
165 onFileDialogCancel: PropTypes.func,
166
167 /**
168 * Cb for when opening the file dialog
169 */
170 onFileDialogOpen: PropTypes.func,
171
172 /**
173 * Set to true to use the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API
174 * to open the file picker instead of using an `<input type="file">` click event.
175 */
176 useFsAccessApi: PropTypes.bool,
177
178 /**
179 * Set to true to focus the root element on render
180 */
181 autoFocus: PropTypes.bool,
182
183 /**
184 * Cb for when the `dragenter` event occurs.
185 *
186 * @param {DragEvent} event
187 */
188 onDragEnter: PropTypes.func,
189
190 /**
191 * Cb for when the `dragleave` event occurs
192 *
193 * @param {DragEvent} event
194 */
195 onDragLeave: PropTypes.func,
196
197 /**
198 * Cb for when the `dragover` event occurs
199 *
200 * @param {DragEvent} event
201 */
202 onDragOver: PropTypes.func,
203
204 /**
205 * Cb for when the `drop` event occurs.
206 * Note that this callback is invoked after the `getFilesFromEvent` callback is done.
207 *
208 * Files are accepted or rejected based on the `accept`, `multiple`, `minSize` and `maxSize` props.
209 * `accept` must be a valid [MIME type](http://www.iana.org/assignments/media-types/media-types.xhtml) according to [input element specification](https://www.w3.org/wiki/HTML/Elements/input/file) or a valid file extension.
210 * If `multiple` is set to false and additional files are dropped,
211 * all files besides the first will be rejected.
212 * Any file which does not have a size in the [`minSize`, `maxSize`] range, will be rejected as well.
213 *
214 * Note that the `onDrop` callback will always be invoked regardless if the dropped files were accepted or rejected.
215 * If you'd like to react to a specific scenario, use the `onDropAccepted`/`onDropRejected` props.
216 *
217 * `onDrop` will provide you with an array of [File](https://developer.mozilla.org/en-US/docs/Web/API/File) objects which you can then process and send to a server.
218 * For example, with [SuperAgent](https://github.com/visionmedia/superagent) as a http/ajax library:
219 *
220 * ```js
221 * function onDrop(acceptedFiles) {
222 * const req = request.post('/upload')
223 * acceptedFiles.forEach(file => {
224 * req.attach(file.name, file)
225 * })
226 * req.end(callback)
227 * }
228 * ```
229 *
230 * @param {File[]} acceptedFiles
231 * @param {FileRejection[]} fileRejections
232 * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
233 */
234 onDrop: PropTypes.func,
235
236 /**
237 * Cb for when the `drop` event occurs.
238 * Note that if no files are accepted, this callback is not invoked.
239 *
240 * @param {File[]} files
241 * @param {(DragEvent|Event)} event
242 */
243 onDropAccepted: PropTypes.func,
244
245 /**
246 * Cb for when the `drop` event occurs.
247 * Note that if no files are rejected, this callback is not invoked.
248 *
249 * @param {FileRejection[]} fileRejections
250 * @param {(DragEvent|Event)} event
251 */
252 onDropRejected: PropTypes.func,
253
254 /**
255 * Cb for when there's some error from any of the promises.
256 *
257 * @param {Error} error
258 */
259 onError: PropTypes.func,
260
261 /**
262 * Custom validation function. It must return null if there's no errors.
263 * @param {File} file
264 * @returns {FileError|FileError[]|null}
265 */
266 validator: PropTypes.func,
267 };
268
269 export default Dropzone;
270
271 /**
272 * A function that is invoked for the `dragenter`,
273 * `dragover` and `dragleave` events.
274 * It is not invoked if the items are not files (such as link, text, etc.).
275 *
276 * @callback dragCb
277 * @param {DragEvent} event
278 */
279
280 /**
281 * A function that is invoked for the `drop` or input change event.
282 * It is not invoked if the items are not files (such as link, text, etc.).
283 *
284 * @callback dropCb
285 * @param {File[]} acceptedFiles List of accepted files
286 * @param {FileRejection[]} fileRejections List of rejected files and why they were rejected
287 * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
288 */
289
290 /**
291 * A function that is invoked for the `drop` or input change event.
292 * It is not invoked if the items are files (such as link, text, etc.).
293 *
294 * @callback dropAcceptedCb
295 * @param {File[]} files List of accepted files that meet the given criteria
296 * (`accept`, `multiple`, `minSize`, `maxSize`)
297 * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
298 */
299
300 /**
301 * A function that is invoked for the `drop` or input change event.
302 *
303 * @callback dropRejectedCb
304 * @param {File[]} files List of rejected files that do not meet the given criteria
305 * (`accept`, `multiple`, `minSize`, `maxSize`)
306 * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
307 */
308
309 /**
310 * A function that is used aggregate files,
311 * in a asynchronous fashion, from drag or input change events.
312 *
313 * @callback getFilesFromEvent
314 * @param {(DragEvent|Event|Array<FileSystemFileHandle>)} event A drag event or input change event (if files were selected via the file dialog)
315 * @returns {(File[]|Promise<File[]>)}
316 */
317
318 /**
319 * An object with the current dropzone state.
320 *
321 * @typedef {object} DropzoneState
322 * @property {boolean} isFocused Dropzone area is in focus
323 * @property {boolean} isFileDialogActive File dialog is opened
324 * @property {boolean} isDragActive Active drag is in progress
325 * @property {boolean} isDragAccept Dragged files are accepted
326 * @property {boolean} isDragReject Some dragged files are rejected
327 * @property {boolean} isDragGlobal Files are being dragged anywhere on the document
328 * @property {File[]} acceptedFiles Accepted files
329 * @property {FileRejection[]} fileRejections Rejected files and why they were rejected
330 */
331
332 /**
333 * An object with the dropzone methods.
334 *
335 * @typedef {object} DropzoneMethods
336 * @property {Function} getRootProps Returns the props you should apply to the root drop container you render
337 * @property {Function} getInputProps Returns the props you should apply to hidden file input you render
338 * @property {Function} open Open the native file selection dialog
339 */
340
341 const initialState = {
342 isFocused: false,
343 isFileDialogActive: false,
344 isDragActive: false,
345 isDragAccept: false,
346 isDragReject: false,
347 isDragGlobal: false,
348 acceptedFiles: [],
349 fileRejections: [],
350 };
351
352 /**
353 * A React hook that creates a drag 'n' drop area.
354 *
355 * ```jsx
356 * function MyDropzone(props) {
357 * const {getRootProps, getInputProps} = useDropzone({
358 * onDrop: acceptedFiles => {
359 * // do something with the File objects, e.g. upload to some server
360 * }
361 * });
362 * return (
363 * <div {...getRootProps()}>
364 * <input {...getInputProps()} />
365 * <p>Drag and drop some files here, or click to select files</p>
366 * </div>
367 * )
368 * }
369 * ```
370 *
371 * @function useDropzone
372 *
373 * @param {object} props
374 * @param {import("./utils").AcceptProp} [props.accept] Set accepted file types.
375 * Checkout https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker types option for more information.
376 * Keep in mind that mime type determination is not reliable across platforms. CSV files,
377 * for example, are reported as text/plain under macOS but as application/vnd.ms-excel under
378 * Windows. In some cases there might not be a mime type set at all (https://github.com/react-dropzone/react-dropzone/issues/276).
379 * @param {boolean} [props.multiple=true] Allow drag 'n' drop (or selection from the file dialog) of multiple files
380 * @param {boolean} [props.preventDropOnDocument=true] If false, allow dropped items to take over the current browser window
381 * @param {boolean} [props.noClick=false] If true, disables click to open the native file selection dialog
382 * @param {boolean} [props.noKeyboard=false] If true, disables SPACE/ENTER to open the native file selection dialog.
383 * Note that it also stops tracking the focus state.
384 * @param {boolean} [props.noDrag=false] If true, disables drag 'n' drop
385 * @param {boolean} [props.noDragEventsBubbling=false] If true, stops drag event propagation to parents
386 * @param {number} [props.minSize=0] Minimum file size (in bytes)
387 * @param {number} [props.maxSize=Infinity] Maximum file size (in bytes)
388 * @param {boolean} [props.disabled=false] Enable/disable the dropzone
389 * @param {getFilesFromEvent} [props.getFilesFromEvent] Use this to provide a custom file aggregator
390 * @param {Function} [props.onFileDialogCancel] Cb for when closing the file dialog with no selection
391 * @param {boolean} [props.useFsAccessApi] Set to true to use the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API
392 * to open the file picker instead of using an `<input type="file">` click event.
393 * @param {boolean} autoFocus Set to true to auto focus the root element.
394 * @param {Function} [props.onFileDialogOpen] Cb for when opening the file dialog
395 * @param {dragCb} [props.onDragEnter] Cb for when the `dragenter` event occurs.
396 * @param {dragCb} [props.onDragLeave] Cb for when the `dragleave` event occurs
397 * @param {dragCb} [props.onDragOver] Cb for when the `dragover` event occurs
398 * @param {dropCb} [props.onDrop] Cb for when the `drop` event occurs.
399 * Note that this callback is invoked after the `getFilesFromEvent` callback is done.
400 *
401 * Files are accepted or rejected based on the `accept`, `multiple`, `minSize` and `maxSize` props.
402 * `accept` must be an object with keys as a valid [MIME type](http://www.iana.org/assignments/media-types/media-types.xhtml) according to [input element specification](https://www.w3.org/wiki/HTML/Elements/input/file) and the value an array of file extensions (optional).
403 * If `multiple` is set to false and additional files are dropped,
404 * all files besides the first will be rejected.
405 * Any file which does not have a size in the [`minSize`, `maxSize`] range, will be rejected as well.
406 *
407 * Note that the `onDrop` callback will always be invoked regardless if the dropped files were accepted or rejected.
408 * If you'd like to react to a specific scenario, use the `onDropAccepted`/`onDropRejected` props.
409 *
410 * `onDrop` will provide you with an array of [File](https://developer.mozilla.org/en-US/docs/Web/API/File) objects which you can then process and send to a server.
411 * For example, with [SuperAgent](https://github.com/visionmedia/superagent) as a http/ajax library:
412 *
413 * ```js
414 * function onDrop(acceptedFiles) {
415 * const req = request.post('/upload')
416 * acceptedFiles.forEach(file => {
417 * req.attach(file.name, file)
418 * })
419 * req.end(callback)
420 * }
421 * ```
422 * @param {dropAcceptedCb} [props.onDropAccepted]
423 * @param {dropRejectedCb} [props.onDropRejected]
424 * @param {(error: Error) => void} [props.onError]
425 *
426 * @returns {DropzoneState & DropzoneMethods}
427 */
428 export function useDropzone(props = {}) {
429 const {
430 accept,
431 disabled,
432 getFilesFromEvent,
433 maxSize,
434 minSize,
435 multiple,
436 maxFiles,
437 onDragEnter,
438 onDragLeave,
439 onDragOver,
440 onDrop,
441 onDropAccepted,
442 onDropRejected,
443 onFileDialogCancel,
444 onFileDialogOpen,
445 useFsAccessApi,
446 autoFocus,
447 preventDropOnDocument,
448 noClick,
449 noKeyboard,
450 noDrag,
451 noDragEventsBubbling,
452 onError,
453 validator,
454 } = {
455 ...defaultProps,
456 ...props,
457 };
458
459 const acceptAttr = useMemo(() => acceptPropAsAcceptAttr(accept), [accept]);
460 const pickerTypes = useMemo(() => pickerOptionsFromAccept(accept), [accept]);
461
462 const onFileDialogOpenCb = useMemo(
463 () => (typeof onFileDialogOpen === "function" ? onFileDialogOpen : noop),
464 [onFileDialogOpen]
465 );
466 const onFileDialogCancelCb = useMemo(
467 () =>
468 typeof onFileDialogCancel === "function" ? onFileDialogCancel : noop,
469 [onFileDialogCancel]
470 );
471
472 /**
473 * @constant
474 * @type {React.MutableRefObject<HTMLElement>}
475 */
476 const rootRef = useRef(null);
477
478 const inputRef = useRef(null);
479
480 const [state, dispatch] = useReducer(reducer, initialState);
481 const { isFocused, isFileDialogActive } = state;
482
483 const fsAccessApiWorksRef = useRef(
484 typeof window !== "undefined" &&
485 window.isSecureContext &&
486 useFsAccessApi &&
487 canUseFileSystemAccessAPI()
488 );
489
490 // Update file dialog active state when the window is focused on
491 const onWindowFocus = () => {
492 // Execute the timeout only if the file dialog is opened in the browser
493 if (!fsAccessApiWorksRef.current && isFileDialogActive) {
494 setTimeout(() => {
495 if (inputRef.current) {
496 const { files } = inputRef.current;
497
498 if (!files.length) {
499 dispatch({ type: "closeDialog" });
500 onFileDialogCancelCb();
501 }
502 }
503 }, 300);
504 }
505 };
506 useEffect(() => {
507 window.addEventListener("focus", onWindowFocus, false);
508 return () => {
509 window.removeEventListener("focus", onWindowFocus, false);
510 };
511 }, [inputRef, isFileDialogActive, onFileDialogCancelCb, fsAccessApiWorksRef]);
512
513 const dragTargetsRef = useRef([]);
514 const globalDragTargetsRef = useRef([]);
515 const onDocumentDrop = (event) => {
516 if (rootRef.current && rootRef.current.contains(event.target)) {
517 // If we intercepted an event for our instance, let it propagate down to the instance's onDrop handler
518 return;
519 }
520 event.preventDefault();
521 dragTargetsRef.current = [];
522 };
523
524 useEffect(() => {
525 if (preventDropOnDocument) {
526 document.addEventListener("dragover", onDocumentDragOver, false);
527 document.addEventListener("drop", onDocumentDrop, false);
528 }
529
530 return () => {
531 if (preventDropOnDocument) {
532 document.removeEventListener("dragover", onDocumentDragOver);
533 document.removeEventListener("drop", onDocumentDrop);
534 }
535 };
536 }, [rootRef, preventDropOnDocument]);
537
538 // Track global drag state for document-level drag events
539 useEffect(() => {
540 const onDocumentDragEnter = (event) => {
541 globalDragTargetsRef.current = [
542 ...globalDragTargetsRef.current,
543 event.target,
544 ];
545
546 if (isEvtWithFiles(event)) {
547 dispatch({ isDragGlobal: true, type: "setDragGlobal" });
548 }
549 };
550
551 const onDocumentDragLeave = (event) => {
552 // Only deactivate once we've left all children
553 globalDragTargetsRef.current = globalDragTargetsRef.current.filter(
554 (el) => el !== event.target && el !== null
555 );
556
557 if (globalDragTargetsRef.current.length > 0) {
558 return;
559 }
560
561 dispatch({ isDragGlobal: false, type: "setDragGlobal" });
562 };
563
564 const onDocumentDragEnd = () => {
565 globalDragTargetsRef.current = [];
566 dispatch({ isDragGlobal: false, type: "setDragGlobal" });
567 };
568
569 const onDocumentDropGlobal = () => {
570 globalDragTargetsRef.current = [];
571 dispatch({ isDragGlobal: false, type: "setDragGlobal" });
572 };
573
574 document.addEventListener("dragenter", onDocumentDragEnter, false);
575 document.addEventListener("dragleave", onDocumentDragLeave, false);
576 document.addEventListener("dragend", onDocumentDragEnd, false);
577 document.addEventListener("drop", onDocumentDropGlobal, false);
578
579 return () => {
580 document.removeEventListener("dragenter", onDocumentDragEnter);
581 document.removeEventListener("dragleave", onDocumentDragLeave);
582 document.removeEventListener("dragend", onDocumentDragEnd);
583 document.removeEventListener("drop", onDocumentDropGlobal);
584 };
585 }, [rootRef]);
586
587 // Auto focus the root when autoFocus is true
588 useEffect(() => {
589 if (!disabled && autoFocus && rootRef.current) {
590 rootRef.current.focus();
591 }
592 return () => {};
593 }, [rootRef, autoFocus, disabled]);
594
595 const onErrCb = useCallback(
596 (e) => {
597 if (onError) {
598 onError(e);
599 } else {
600 // Let the user know something's gone wrong if they haven't provided the onError cb.
601 console.error(e);
602 }
603 },
604 [onError]
605 );
606
607 const onDragEnterCb = useCallback(
608 (event) => {
609 event.preventDefault();
610 // Persist here because we need the event later after getFilesFromEvent() is done
611 event.persist();
612 stopPropagation(event);
613
614 dragTargetsRef.current = [...dragTargetsRef.current, event.target];
615
616 if (isEvtWithFiles(event)) {
617 Promise.resolve(getFilesFromEvent(event))
618 .then((files) => {
619 if (isPropagationStopped(event) && !noDragEventsBubbling) {
620 return;
621 }
622
623 const fileCount = files.length;
624 const isDragAccept =
625 fileCount > 0 &&
626 allFilesAccepted({
627 files,
628 accept: acceptAttr,
629 minSize,
630 maxSize,
631 multiple,
632 maxFiles,
633 validator,
634 });
635 const isDragReject = fileCount > 0 && !isDragAccept;
636
637 dispatch({
638 isDragAccept,
639 isDragReject,
640 isDragActive: true,
641 type: "setDraggedFiles",
642 });
643
644 if (onDragEnter) {
645 onDragEnter(event);
646 }
647 })
648 .catch((e) => onErrCb(e));
649 }
650 },
651 [
652 getFilesFromEvent,
653 onDragEnter,
654 onErrCb,
655 noDragEventsBubbling,
656 acceptAttr,
657 minSize,
658 maxSize,
659 multiple,
660 maxFiles,
661 validator,
662 ]
663 );
664
665 const onDragOverCb = useCallback(
666 (event) => {
667 event.preventDefault();
668 event.persist();
669 stopPropagation(event);
670
671 const hasFiles = isEvtWithFiles(event);
672 if (hasFiles && event.dataTransfer) {
673 try {
674 event.dataTransfer.dropEffect = "copy";
675 } catch {} /* eslint-disable-line no-empty */
676 }
677
678 if (hasFiles && onDragOver) {
679 onDragOver(event);
680 }
681
682 return false;
683 },
684 [onDragOver, noDragEventsBubbling]
685 );
686
687 const onDragLeaveCb = useCallback(
688 (event) => {
689 event.preventDefault();
690 event.persist();
691 stopPropagation(event);
692
693 // Only deactivate once the dropzone and all children have been left
694 const targets = dragTargetsRef.current.filter(
695 (target) => rootRef.current && rootRef.current.contains(target)
696 );
697 // Make sure to remove a target present multiple times only once
698 // (Firefox may fire dragenter/dragleave multiple times on the same element)
699 const targetIdx = targets.indexOf(event.target);
700 if (targetIdx !== -1) {
701 targets.splice(targetIdx, 1);
702 }
703 dragTargetsRef.current = targets;
704 if (targets.length > 0) {
705 return;
706 }
707
708 dispatch({
709 type: "setDraggedFiles",
710 isDragActive: false,
711 isDragAccept: false,
712 isDragReject: false,
713 });
714
715 if (isEvtWithFiles(event) && onDragLeave) {
716 onDragLeave(event);
717 }
718 },
719 [rootRef, onDragLeave, noDragEventsBubbling]
720 );
721
722 const setFiles = useCallback(
723 (files, event) => {
724 const acceptedFiles = [];
725 const fileRejections = [];
726
727 files.forEach((file) => {
728 const [accepted, acceptError] = fileAccepted(file, acceptAttr);
729 const [sizeMatch, sizeError] = fileMatchSize(file, minSize, maxSize);
730 const customErrors = validator ? validator(file) : null;
731
732 if (accepted && sizeMatch && !customErrors) {
733 acceptedFiles.push(file);
734 } else {
735 let errors = [acceptError, sizeError];
736
737 if (customErrors) {
738 errors = errors.concat(customErrors);
739 }
740
741 fileRejections.push({ file, errors: errors.filter((e) => e) });
742 }
743 });
744
745 if (
746 (!multiple && acceptedFiles.length > 1) ||
747 (multiple && maxFiles >= 1 && acceptedFiles.length > maxFiles)
748 ) {
749 // Reject everything and empty accepted files
750 acceptedFiles.forEach((file) => {
751 fileRejections.push({ file, errors: [TOO_MANY_FILES_REJECTION] });
752 });
753 acceptedFiles.splice(0);
754 }
755
756 dispatch({
757 acceptedFiles,
758 fileRejections,
759 isDragReject: fileRejections.length > 0,
760 type: "setFiles",
761 });
762
763 if (onDrop) {
764 onDrop(acceptedFiles, fileRejections, event);
765 }
766
767 if (fileRejections.length > 0 && onDropRejected) {
768 onDropRejected(fileRejections, event);
769 }
770
771 if (acceptedFiles.length > 0 && onDropAccepted) {
772 onDropAccepted(acceptedFiles, event);
773 }
774 },
775 [
776 dispatch,
777 multiple,
778 acceptAttr,
779 minSize,
780 maxSize,
781 maxFiles,
782 onDrop,
783 onDropAccepted,
784 onDropRejected,
785 validator,
786 ]
787 );
788
789 const onDropCb = useCallback(
790 (event) => {
791 event.preventDefault();
792 // Persist here because we need the event later after getFilesFromEvent() is done
793 event.persist();
794 stopPropagation(event);
795
796 dragTargetsRef.current = [];
797
798 if (isEvtWithFiles(event)) {
799 Promise.resolve(getFilesFromEvent(event))
800 .then((files) => {
801 if (isPropagationStopped(event) && !noDragEventsBubbling) {
802 return;
803 }
804 setFiles(files, event);
805 })
806 .catch((e) => onErrCb(e));
807 }
808 dispatch({ type: "reset" });
809 },
810 [getFilesFromEvent, setFiles, onErrCb, noDragEventsBubbling]
811 );
812
813 // Fn for opening the file dialog programmatically
814 const openFileDialog = useCallback(() => {
815 // No point to use FS access APIs if context is not secure
816 // https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts#feature_detection
817 if (fsAccessApiWorksRef.current) {
818 dispatch({ type: "openDialog" });
819 onFileDialogOpenCb();
820 // https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker
821 const opts = {
822 multiple,
823 types: pickerTypes,
824 };
825 window
826 .showOpenFilePicker(opts)
827 .then((handles) => getFilesFromEvent(handles))
828 .then((files) => {
829 setFiles(files, null);
830 dispatch({ type: "closeDialog" });
831 })
832 .catch((e) => {
833 // AbortError means the user canceled
834 if (isAbort(e)) {
835 onFileDialogCancelCb(e);
836 dispatch({ type: "closeDialog" });
837 } else if (isSecurityError(e)) {
838 fsAccessApiWorksRef.current = false;
839 // CORS, so cannot use this API
840 // Try using the input
841 if (inputRef.current) {
842 inputRef.current.value = null;
843 inputRef.current.click();
844 } else {
845 onErrCb(
846 new Error(
847 "Cannot open the file picker because the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API is not supported and no <input> was provided."
848 )
849 );
850 }
851 } else {
852 onErrCb(e);
853 }
854 });
855 return;
856 }
857
858 if (inputRef.current) {
859 dispatch({ type: "openDialog" });
860 onFileDialogOpenCb();
861 inputRef.current.value = null;
862 inputRef.current.click();
863 }
864 }, [
865 dispatch,
866 onFileDialogOpenCb,
867 onFileDialogCancelCb,
868 useFsAccessApi,
869 setFiles,
870 onErrCb,
871 pickerTypes,
872 multiple,
873 ]);
874
875 // Cb to open the file dialog when SPACE/ENTER occurs on the dropzone
876 const onKeyDownCb = useCallback(
877 (event) => {
878 // Ignore keyboard events bubbling up the DOM tree
879 if (!rootRef.current || !rootRef.current.isEqualNode(event.target)) {
880 return;
881 }
882
883 if (
884 event.key === " " ||
885 event.key === "Enter" ||
886 event.keyCode === 32 ||
887 event.keyCode === 13
888 ) {
889 event.preventDefault();
890 openFileDialog();
891 }
892 },
893 [rootRef, openFileDialog]
894 );
895
896 // Update focus state for the dropzone
897 const onFocusCb = useCallback(() => {
898 dispatch({ type: "focus" });
899 }, []);
900 const onBlurCb = useCallback(() => {
901 dispatch({ type: "blur" });
902 }, []);
903
904 // Cb to open the file dialog when click occurs on the dropzone
905 const onClickCb = useCallback(() => {
906 if (noClick) {
907 return;
908 }
909
910 // In IE11/Edge the file-browser dialog is blocking, therefore, use setTimeout()
911 // to ensure React can handle state changes
912 // See: https://github.com/react-dropzone/react-dropzone/issues/450
913 if (isIeOrEdge()) {
914 setTimeout(openFileDialog, 0);
915 } else {
916 openFileDialog();
917 }
918 }, [noClick, openFileDialog]);
919
920 const composeHandler = (fn) => {
921 return disabled ? null : fn;
922 };
923
924 const composeKeyboardHandler = (fn) => {
925 return noKeyboard ? null : composeHandler(fn);
926 };
927
928 const composeDragHandler = (fn) => {
929 return noDrag ? null : composeHandler(fn);
930 };
931
932 const stopPropagation = (event) => {
933 if (noDragEventsBubbling) {
934 event.stopPropagation();
935 }
936 };
937
938 const getRootProps = useMemo(
939 () =>
940 ({
941 refKey = "ref",
942 role,
943 onKeyDown,
944 onFocus,
945 onBlur,
946 onClick,
947 onDragEnter,
948 onDragOver,
949 onDragLeave,
950 onDrop,
951 ...rest
952 } = {}) => ({
953 onKeyDown: composeKeyboardHandler(
954 composeEventHandlers(onKeyDown, onKeyDownCb)
955 ),
956 onFocus: composeKeyboardHandler(
957 composeEventHandlers(onFocus, onFocusCb)
958 ),
959 onBlur: composeKeyboardHandler(composeEventHandlers(onBlur, onBlurCb)),
960 onClick: composeHandler(composeEventHandlers(onClick, onClickCb)),
961 onDragEnter: composeDragHandler(
962 composeEventHandlers(onDragEnter, onDragEnterCb)
963 ),
964 onDragOver: composeDragHandler(
965 composeEventHandlers(onDragOver, onDragOverCb)
966 ),
967 onDragLeave: composeDragHandler(
968 composeEventHandlers(onDragLeave, onDragLeaveCb)
969 ),
970 onDrop: composeDragHandler(composeEventHandlers(onDrop, onDropCb)),
971 role: typeof role === "string" && role !== "" ? role : "presentation",
972 [refKey]: rootRef,
973 ...(!disabled && !noKeyboard ? { tabIndex: 0 } : {}),
974 ...rest,
975 }),
976 [
977 rootRef,
978 onKeyDownCb,
979 onFocusCb,
980 onBlurCb,
981 onClickCb,
982 onDragEnterCb,
983 onDragOverCb,
984 onDragLeaveCb,
985 onDropCb,
986 noKeyboard,
987 noDrag,
988 disabled,
989 ]
990 );
991
992 const onInputElementClick = useCallback((event) => {
993 event.stopPropagation();
994 }, []);
995
996 const getInputProps = useMemo(
997 () =>
998 ({ refKey = "ref", onChange, onClick, ...rest } = {}) => {
999 const inputProps = {
1000 accept: acceptAttr,
1001 multiple,
1002 type: "file",
1003 style: {
1004 border: 0,
1005 clip: "rect(0, 0, 0, 0)",
1006 clipPath: "inset(50%)",
1007 height: "1px",
1008 margin: "0 -1px -1px 0",
1009 overflow: "hidden",
1010 padding: 0,
1011 position: "absolute",
1012 width: "1px",
1013 whiteSpace: "nowrap",
1014 },
1015 onChange: composeHandler(composeEventHandlers(onChange, onDropCb)),
1016 onClick: composeHandler(
1017 composeEventHandlers(onClick, onInputElementClick)
1018 ),
1019 tabIndex: -1,
1020 [refKey]: inputRef,
1021 };
1022
1023 return {
1024 ...inputProps,
1025 ...rest,
1026 };
1027 },
1028 [inputRef, accept, multiple, onDropCb, disabled]
1029 );
1030
1031 return {
1032 ...state,
1033 isFocused: isFocused && !disabled,
1034 getRootProps,
1035 getInputProps,
1036 rootRef,
1037 inputRef,
1038 open: composeHandler(openFileDialog),
1039 };
1040 }
1041
1042 /**
1043 * @param {DropzoneState} state
1044 * @param {{type: string} & DropzoneState} action
1045 * @returns {DropzoneState}
1046 */
1047 function reducer(state, action) {
1048 /* istanbul ignore next */
1049 switch (action.type) {
1050 case "focus":
1051 return {
1052 ...state,
1053 isFocused: true,
1054 };
1055 case "blur":
1056 return {
1057 ...state,
1058 isFocused: false,
1059 };
1060 case "openDialog":
1061 return {
1062 ...initialState,
1063 isFileDialogActive: true,
1064 };
1065 case "closeDialog":
1066 return {
1067 ...state,
1068 isFileDialogActive: false,
1069 };
1070 case "setDraggedFiles":
1071 return {
1072 ...state,
1073 isDragActive: action.isDragActive,
1074 isDragAccept: action.isDragAccept,
1075 isDragReject: action.isDragReject,
1076 };
1077 case "setFiles":
1078 return {
1079 ...state,
1080 acceptedFiles: action.acceptedFiles,
1081 fileRejections: action.fileRejections,
1082 isDragReject: action.isDragReject,
1083 };
1084 case "setDragGlobal":
1085 return {
1086 ...state,
1087 isDragGlobal: action.isDragGlobal,
1088 };
1089 case "reset":
1090 return {
1091 ...initialState,
1092 };
1093 default:
1094 return state;
1095 }
1096 }
1097
1098 function noop() {}
1099
1100 export { ErrorCode } from "./utils/index.js";