index.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  1. var _excluded = ["children"],
  2. _excluded2 = ["open"],
  3. _excluded3 = ["refKey", "role", "onKeyDown", "onFocus", "onBlur", "onClick", "onDragEnter", "onDragOver", "onDragLeave", "onDrop"],
  4. _excluded4 = ["refKey", "onChange", "onClick"];
  5. function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
  6. function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
  7. function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
  8. function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
  9. function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
  10. function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
  11. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  12. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  13. function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
  14. function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
  15. function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
  16. function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
  17. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  18. function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
  19. function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
  20. /* eslint prefer-template: 0 */
  21. import React, { forwardRef, Fragment, useCallback, useEffect, useImperativeHandle, useMemo, useReducer, useRef } from "react";
  22. import PropTypes from "prop-types";
  23. import { fromEvent } from "file-selector";
  24. import { acceptPropAsAcceptAttr, allFilesAccepted, composeEventHandlers, fileAccepted, fileMatchSize, canUseFileSystemAccessAPI, isAbort, isEvtWithFiles, isIeOrEdge, isPropagationStopped, isSecurityError, onDocumentDragOver, pickerOptionsFromAccept, TOO_MANY_FILES_REJECTION } from "./utils/index";
  25. /**
  26. * Convenience wrapper component for the `useDropzone` hook
  27. *
  28. * ```jsx
  29. * <Dropzone>
  30. * {({getRootProps, getInputProps}) => (
  31. * <div {...getRootProps()}>
  32. * <input {...getInputProps()} />
  33. * <p>Drag 'n' drop some files here, or click to select files</p>
  34. * </div>
  35. * )}
  36. * </Dropzone>
  37. * ```
  38. */
  39. var Dropzone = /*#__PURE__*/forwardRef(function (_ref, ref) {
  40. var children = _ref.children,
  41. params = _objectWithoutProperties(_ref, _excluded);
  42. var _useDropzone = useDropzone(params),
  43. open = _useDropzone.open,
  44. props = _objectWithoutProperties(_useDropzone, _excluded2);
  45. useImperativeHandle(ref, function () {
  46. return {
  47. open: open
  48. };
  49. }, [open]); // TODO: Figure out why react-styleguidist cannot create docs if we don't return a jsx element
  50. return /*#__PURE__*/React.createElement(Fragment, null, children(_objectSpread(_objectSpread({}, props), {}, {
  51. open: open
  52. })));
  53. });
  54. Dropzone.displayName = "Dropzone"; // Add default props for react-docgen
  55. var defaultProps = {
  56. disabled: false,
  57. getFilesFromEvent: fromEvent,
  58. maxSize: Infinity,
  59. minSize: 0,
  60. multiple: true,
  61. maxFiles: 0,
  62. preventDropOnDocument: true,
  63. noClick: false,
  64. noKeyboard: false,
  65. noDrag: false,
  66. noDragEventsBubbling: false,
  67. validator: null,
  68. useFsAccessApi: true,
  69. autoFocus: false
  70. };
  71. Dropzone.defaultProps = defaultProps;
  72. Dropzone.propTypes = {
  73. /**
  74. * Render function that exposes the dropzone state and prop getter fns
  75. *
  76. * @param {object} params
  77. * @param {Function} params.getRootProps Returns the props you should apply to the root drop container you render
  78. * @param {Function} params.getInputProps Returns the props you should apply to hidden file input you render
  79. * @param {Function} params.open Open the native file selection dialog
  80. * @param {boolean} params.isFocused Dropzone area is in focus
  81. * @param {boolean} params.isFileDialogActive File dialog is opened
  82. * @param {boolean} params.isDragActive Active drag is in progress
  83. * @param {boolean} params.isDragAccept Dragged files are accepted
  84. * @param {boolean} params.isDragReject Some dragged files are rejected
  85. * @param {File[]} params.acceptedFiles Accepted files
  86. * @param {FileRejection[]} params.fileRejections Rejected files and why they were rejected
  87. */
  88. children: PropTypes.func,
  89. /**
  90. * Set accepted file types.
  91. * Checkout https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker types option for more information.
  92. * Keep in mind that mime type determination is not reliable across platforms. CSV files,
  93. * for example, are reported as text/plain under macOS but as application/vnd.ms-excel under
  94. * Windows. In some cases there might not be a mime type set at all (https://github.com/react-dropzone/react-dropzone/issues/276).
  95. */
  96. accept: PropTypes.objectOf(PropTypes.arrayOf(PropTypes.string)),
  97. /**
  98. * Allow drag 'n' drop (or selection from the file dialog) of multiple files
  99. */
  100. multiple: PropTypes.bool,
  101. /**
  102. * If false, allow dropped items to take over the current browser window
  103. */
  104. preventDropOnDocument: PropTypes.bool,
  105. /**
  106. * If true, disables click to open the native file selection dialog
  107. */
  108. noClick: PropTypes.bool,
  109. /**
  110. * If true, disables SPACE/ENTER to open the native file selection dialog.
  111. * Note that it also stops tracking the focus state.
  112. */
  113. noKeyboard: PropTypes.bool,
  114. /**
  115. * If true, disables drag 'n' drop
  116. */
  117. noDrag: PropTypes.bool,
  118. /**
  119. * If true, stops drag event propagation to parents
  120. */
  121. noDragEventsBubbling: PropTypes.bool,
  122. /**
  123. * Minimum file size (in bytes)
  124. */
  125. minSize: PropTypes.number,
  126. /**
  127. * Maximum file size (in bytes)
  128. */
  129. maxSize: PropTypes.number,
  130. /**
  131. * Maximum accepted number of files
  132. * The default value is 0 which means there is no limitation to how many files are accepted.
  133. */
  134. maxFiles: PropTypes.number,
  135. /**
  136. * Enable/disable the dropzone
  137. */
  138. disabled: PropTypes.bool,
  139. /**
  140. * Use this to provide a custom file aggregator
  141. *
  142. * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
  143. */
  144. getFilesFromEvent: PropTypes.func,
  145. /**
  146. * Cb for when closing the file dialog with no selection
  147. */
  148. onFileDialogCancel: PropTypes.func,
  149. /**
  150. * Cb for when opening the file dialog
  151. */
  152. onFileDialogOpen: PropTypes.func,
  153. /**
  154. * Set to true to use the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API
  155. * to open the file picker instead of using an `<input type="file">` click event.
  156. */
  157. useFsAccessApi: PropTypes.bool,
  158. /**
  159. * Set to true to focus the root element on render
  160. */
  161. autoFocus: PropTypes.bool,
  162. /**
  163. * Cb for when the `dragenter` event occurs.
  164. *
  165. * @param {DragEvent} event
  166. */
  167. onDragEnter: PropTypes.func,
  168. /**
  169. * Cb for when the `dragleave` event occurs
  170. *
  171. * @param {DragEvent} event
  172. */
  173. onDragLeave: PropTypes.func,
  174. /**
  175. * Cb for when the `dragover` event occurs
  176. *
  177. * @param {DragEvent} event
  178. */
  179. onDragOver: PropTypes.func,
  180. /**
  181. * Cb for when the `drop` event occurs.
  182. * Note that this callback is invoked after the `getFilesFromEvent` callback is done.
  183. *
  184. * Files are accepted or rejected based on the `accept`, `multiple`, `minSize` and `maxSize` props.
  185. * `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.
  186. * If `multiple` is set to false and additional files are dropped,
  187. * all files besides the first will be rejected.
  188. * Any file which does not have a size in the [`minSize`, `maxSize`] range, will be rejected as well.
  189. *
  190. * Note that the `onDrop` callback will always be invoked regardless if the dropped files were accepted or rejected.
  191. * If you'd like to react to a specific scenario, use the `onDropAccepted`/`onDropRejected` props.
  192. *
  193. * `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.
  194. * For example, with [SuperAgent](https://github.com/visionmedia/superagent) as a http/ajax library:
  195. *
  196. * ```js
  197. * function onDrop(acceptedFiles) {
  198. * const req = request.post('/upload')
  199. * acceptedFiles.forEach(file => {
  200. * req.attach(file.name, file)
  201. * })
  202. * req.end(callback)
  203. * }
  204. * ```
  205. *
  206. * @param {File[]} acceptedFiles
  207. * @param {FileRejection[]} fileRejections
  208. * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
  209. */
  210. onDrop: PropTypes.func,
  211. /**
  212. * Cb for when the `drop` event occurs.
  213. * Note that if no files are accepted, this callback is not invoked.
  214. *
  215. * @param {File[]} files
  216. * @param {(DragEvent|Event)} event
  217. */
  218. onDropAccepted: PropTypes.func,
  219. /**
  220. * Cb for when the `drop` event occurs.
  221. * Note that if no files are rejected, this callback is not invoked.
  222. *
  223. * @param {FileRejection[]} fileRejections
  224. * @param {(DragEvent|Event)} event
  225. */
  226. onDropRejected: PropTypes.func,
  227. /**
  228. * Cb for when there's some error from any of the promises.
  229. *
  230. * @param {Error} error
  231. */
  232. onError: PropTypes.func,
  233. /**
  234. * Custom validation function. It must return null if there's no errors.
  235. * @param {File} file
  236. * @returns {FileError|FileError[]|null}
  237. */
  238. validator: PropTypes.func
  239. };
  240. export default Dropzone;
  241. /**
  242. * A function that is invoked for the `dragenter`,
  243. * `dragover` and `dragleave` events.
  244. * It is not invoked if the items are not files (such as link, text, etc.).
  245. *
  246. * @callback dragCb
  247. * @param {DragEvent} event
  248. */
  249. /**
  250. * A function that is invoked for the `drop` or input change event.
  251. * It is not invoked if the items are not files (such as link, text, etc.).
  252. *
  253. * @callback dropCb
  254. * @param {File[]} acceptedFiles List of accepted files
  255. * @param {FileRejection[]} fileRejections List of rejected files and why they were rejected
  256. * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
  257. */
  258. /**
  259. * A function that is invoked for the `drop` or input change event.
  260. * It is not invoked if the items are files (such as link, text, etc.).
  261. *
  262. * @callback dropAcceptedCb
  263. * @param {File[]} files List of accepted files that meet the given criteria
  264. * (`accept`, `multiple`, `minSize`, `maxSize`)
  265. * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
  266. */
  267. /**
  268. * A function that is invoked for the `drop` or input change event.
  269. *
  270. * @callback dropRejectedCb
  271. * @param {File[]} files List of rejected files that do not meet the given criteria
  272. * (`accept`, `multiple`, `minSize`, `maxSize`)
  273. * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
  274. */
  275. /**
  276. * A function that is used aggregate files,
  277. * in a asynchronous fashion, from drag or input change events.
  278. *
  279. * @callback getFilesFromEvent
  280. * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
  281. * @returns {(File[]|Promise<File[]>)}
  282. */
  283. /**
  284. * An object with the current dropzone state.
  285. *
  286. * @typedef {object} DropzoneState
  287. * @property {boolean} isFocused Dropzone area is in focus
  288. * @property {boolean} isFileDialogActive File dialog is opened
  289. * @property {boolean} isDragActive Active drag is in progress
  290. * @property {boolean} isDragAccept Dragged files are accepted
  291. * @property {boolean} isDragReject Some dragged files are rejected
  292. * @property {File[]} acceptedFiles Accepted files
  293. * @property {FileRejection[]} fileRejections Rejected files and why they were rejected
  294. */
  295. /**
  296. * An object with the dropzone methods.
  297. *
  298. * @typedef {object} DropzoneMethods
  299. * @property {Function} getRootProps Returns the props you should apply to the root drop container you render
  300. * @property {Function} getInputProps Returns the props you should apply to hidden file input you render
  301. * @property {Function} open Open the native file selection dialog
  302. */
  303. var initialState = {
  304. isFocused: false,
  305. isFileDialogActive: false,
  306. isDragActive: false,
  307. isDragAccept: false,
  308. isDragReject: false,
  309. acceptedFiles: [],
  310. fileRejections: []
  311. };
  312. /**
  313. * A React hook that creates a drag 'n' drop area.
  314. *
  315. * ```jsx
  316. * function MyDropzone(props) {
  317. * const {getRootProps, getInputProps} = useDropzone({
  318. * onDrop: acceptedFiles => {
  319. * // do something with the File objects, e.g. upload to some server
  320. * }
  321. * });
  322. * return (
  323. * <div {...getRootProps()}>
  324. * <input {...getInputProps()} />
  325. * <p>Drag and drop some files here, or click to select files</p>
  326. * </div>
  327. * )
  328. * }
  329. * ```
  330. *
  331. * @function useDropzone
  332. *
  333. * @param {object} props
  334. * @param {import("./utils").AcceptProp} [props.accept] Set accepted file types.
  335. * Checkout https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker types option for more information.
  336. * Keep in mind that mime type determination is not reliable across platforms. CSV files,
  337. * for example, are reported as text/plain under macOS but as application/vnd.ms-excel under
  338. * Windows. In some cases there might not be a mime type set at all (https://github.com/react-dropzone/react-dropzone/issues/276).
  339. * @param {boolean} [props.multiple=true] Allow drag 'n' drop (or selection from the file dialog) of multiple files
  340. * @param {boolean} [props.preventDropOnDocument=true] If false, allow dropped items to take over the current browser window
  341. * @param {boolean} [props.noClick=false] If true, disables click to open the native file selection dialog
  342. * @param {boolean} [props.noKeyboard=false] If true, disables SPACE/ENTER to open the native file selection dialog.
  343. * Note that it also stops tracking the focus state.
  344. * @param {boolean} [props.noDrag=false] If true, disables drag 'n' drop
  345. * @param {boolean} [props.noDragEventsBubbling=false] If true, stops drag event propagation to parents
  346. * @param {number} [props.minSize=0] Minimum file size (in bytes)
  347. * @param {number} [props.maxSize=Infinity] Maximum file size (in bytes)
  348. * @param {boolean} [props.disabled=false] Enable/disable the dropzone
  349. * @param {getFilesFromEvent} [props.getFilesFromEvent] Use this to provide a custom file aggregator
  350. * @param {Function} [props.onFileDialogCancel] Cb for when closing the file dialog with no selection
  351. * @param {boolean} [props.useFsAccessApi] Set to true to use the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API
  352. * to open the file picker instead of using an `<input type="file">` click event.
  353. * @param {boolean} autoFocus Set to true to auto focus the root element.
  354. * @param {Function} [props.onFileDialogOpen] Cb for when opening the file dialog
  355. * @param {dragCb} [props.onDragEnter] Cb for when the `dragenter` event occurs.
  356. * @param {dragCb} [props.onDragLeave] Cb for when the `dragleave` event occurs
  357. * @param {dragCb} [props.onDragOver] Cb for when the `dragover` event occurs
  358. * @param {dropCb} [props.onDrop] Cb for when the `drop` event occurs.
  359. * Note that this callback is invoked after the `getFilesFromEvent` callback is done.
  360. *
  361. * Files are accepted or rejected based on the `accept`, `multiple`, `minSize` and `maxSize` props.
  362. * `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).
  363. * If `multiple` is set to false and additional files are dropped,
  364. * all files besides the first will be rejected.
  365. * Any file which does not have a size in the [`minSize`, `maxSize`] range, will be rejected as well.
  366. *
  367. * Note that the `onDrop` callback will always be invoked regardless if the dropped files were accepted or rejected.
  368. * If you'd like to react to a specific scenario, use the `onDropAccepted`/`onDropRejected` props.
  369. *
  370. * `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.
  371. * For example, with [SuperAgent](https://github.com/visionmedia/superagent) as a http/ajax library:
  372. *
  373. * ```js
  374. * function onDrop(acceptedFiles) {
  375. * const req = request.post('/upload')
  376. * acceptedFiles.forEach(file => {
  377. * req.attach(file.name, file)
  378. * })
  379. * req.end(callback)
  380. * }
  381. * ```
  382. * @param {dropAcceptedCb} [props.onDropAccepted]
  383. * @param {dropRejectedCb} [props.onDropRejected]
  384. * @param {(error: Error) => void} [props.onError]
  385. *
  386. * @returns {DropzoneState & DropzoneMethods}
  387. */
  388. export function useDropzone() {
  389. var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  390. var _defaultProps$props = _objectSpread(_objectSpread({}, defaultProps), props),
  391. accept = _defaultProps$props.accept,
  392. disabled = _defaultProps$props.disabled,
  393. getFilesFromEvent = _defaultProps$props.getFilesFromEvent,
  394. maxSize = _defaultProps$props.maxSize,
  395. minSize = _defaultProps$props.minSize,
  396. multiple = _defaultProps$props.multiple,
  397. maxFiles = _defaultProps$props.maxFiles,
  398. onDragEnter = _defaultProps$props.onDragEnter,
  399. onDragLeave = _defaultProps$props.onDragLeave,
  400. onDragOver = _defaultProps$props.onDragOver,
  401. onDrop = _defaultProps$props.onDrop,
  402. onDropAccepted = _defaultProps$props.onDropAccepted,
  403. onDropRejected = _defaultProps$props.onDropRejected,
  404. onFileDialogCancel = _defaultProps$props.onFileDialogCancel,
  405. onFileDialogOpen = _defaultProps$props.onFileDialogOpen,
  406. useFsAccessApi = _defaultProps$props.useFsAccessApi,
  407. autoFocus = _defaultProps$props.autoFocus,
  408. preventDropOnDocument = _defaultProps$props.preventDropOnDocument,
  409. noClick = _defaultProps$props.noClick,
  410. noKeyboard = _defaultProps$props.noKeyboard,
  411. noDrag = _defaultProps$props.noDrag,
  412. noDragEventsBubbling = _defaultProps$props.noDragEventsBubbling,
  413. onError = _defaultProps$props.onError,
  414. validator = _defaultProps$props.validator;
  415. var acceptAttr = useMemo(function () {
  416. return acceptPropAsAcceptAttr(accept);
  417. }, [accept]);
  418. var pickerTypes = useMemo(function () {
  419. return pickerOptionsFromAccept(accept);
  420. }, [accept]);
  421. var onFileDialogOpenCb = useMemo(function () {
  422. return typeof onFileDialogOpen === "function" ? onFileDialogOpen : noop;
  423. }, [onFileDialogOpen]);
  424. var onFileDialogCancelCb = useMemo(function () {
  425. return typeof onFileDialogCancel === "function" ? onFileDialogCancel : noop;
  426. }, [onFileDialogCancel]);
  427. /**
  428. * @constant
  429. * @type {React.MutableRefObject<HTMLElement>}
  430. */
  431. var rootRef = useRef(null);
  432. var inputRef = useRef(null);
  433. var _useReducer = useReducer(reducer, initialState),
  434. _useReducer2 = _slicedToArray(_useReducer, 2),
  435. state = _useReducer2[0],
  436. dispatch = _useReducer2[1];
  437. var isFocused = state.isFocused,
  438. isFileDialogActive = state.isFileDialogActive;
  439. var fsAccessApiWorksRef = useRef(typeof window !== "undefined" && window.isSecureContext && useFsAccessApi && canUseFileSystemAccessAPI()); // Update file dialog active state when the window is focused on
  440. var onWindowFocus = function onWindowFocus() {
  441. // Execute the timeout only if the file dialog is opened in the browser
  442. if (!fsAccessApiWorksRef.current && isFileDialogActive) {
  443. setTimeout(function () {
  444. if (inputRef.current) {
  445. var files = inputRef.current.files;
  446. if (!files.length) {
  447. dispatch({
  448. type: "closeDialog"
  449. });
  450. onFileDialogCancelCb();
  451. }
  452. }
  453. }, 300);
  454. }
  455. };
  456. useEffect(function () {
  457. window.addEventListener("focus", onWindowFocus, false);
  458. return function () {
  459. window.removeEventListener("focus", onWindowFocus, false);
  460. };
  461. }, [inputRef, isFileDialogActive, onFileDialogCancelCb, fsAccessApiWorksRef]);
  462. var dragTargetsRef = useRef([]);
  463. var onDocumentDrop = function onDocumentDrop(event) {
  464. if (rootRef.current && rootRef.current.contains(event.target)) {
  465. // If we intercepted an event for our instance, let it propagate down to the instance's onDrop handler
  466. return;
  467. }
  468. event.preventDefault();
  469. dragTargetsRef.current = [];
  470. };
  471. useEffect(function () {
  472. if (preventDropOnDocument) {
  473. document.addEventListener("dragover", onDocumentDragOver, false);
  474. document.addEventListener("drop", onDocumentDrop, false);
  475. }
  476. return function () {
  477. if (preventDropOnDocument) {
  478. document.removeEventListener("dragover", onDocumentDragOver);
  479. document.removeEventListener("drop", onDocumentDrop);
  480. }
  481. };
  482. }, [rootRef, preventDropOnDocument]); // Auto focus the root when autoFocus is true
  483. useEffect(function () {
  484. if (!disabled && autoFocus && rootRef.current) {
  485. rootRef.current.focus();
  486. }
  487. return function () {};
  488. }, [rootRef, autoFocus, disabled]);
  489. var onErrCb = useCallback(function (e) {
  490. if (onError) {
  491. onError(e);
  492. } else {
  493. // Let the user know something's gone wrong if they haven't provided the onError cb.
  494. console.error(e);
  495. }
  496. }, [onError]);
  497. var onDragEnterCb = useCallback(function (event) {
  498. event.preventDefault(); // Persist here because we need the event later after getFilesFromEvent() is done
  499. event.persist();
  500. stopPropagation(event);
  501. dragTargetsRef.current = [].concat(_toConsumableArray(dragTargetsRef.current), [event.target]);
  502. if (isEvtWithFiles(event)) {
  503. Promise.resolve(getFilesFromEvent(event)).then(function (files) {
  504. if (isPropagationStopped(event) && !noDragEventsBubbling) {
  505. return;
  506. }
  507. var fileCount = files.length;
  508. var isDragAccept = fileCount > 0 && allFilesAccepted({
  509. files: files,
  510. accept: acceptAttr,
  511. minSize: minSize,
  512. maxSize: maxSize,
  513. multiple: multiple,
  514. maxFiles: maxFiles,
  515. validator: validator
  516. });
  517. var isDragReject = fileCount > 0 && !isDragAccept;
  518. dispatch({
  519. isDragAccept: isDragAccept,
  520. isDragReject: isDragReject,
  521. isDragActive: true,
  522. type: "setDraggedFiles"
  523. });
  524. if (onDragEnter) {
  525. onDragEnter(event);
  526. }
  527. }).catch(function (e) {
  528. return onErrCb(e);
  529. });
  530. }
  531. }, [getFilesFromEvent, onDragEnter, onErrCb, noDragEventsBubbling, acceptAttr, minSize, maxSize, multiple, maxFiles, validator]);
  532. var onDragOverCb = useCallback(function (event) {
  533. event.preventDefault();
  534. event.persist();
  535. stopPropagation(event);
  536. var hasFiles = isEvtWithFiles(event);
  537. if (hasFiles && event.dataTransfer) {
  538. try {
  539. event.dataTransfer.dropEffect = "copy";
  540. } catch (_unused) {}
  541. /* eslint-disable-line no-empty */
  542. }
  543. if (hasFiles && onDragOver) {
  544. onDragOver(event);
  545. }
  546. return false;
  547. }, [onDragOver, noDragEventsBubbling]);
  548. var onDragLeaveCb = useCallback(function (event) {
  549. event.preventDefault();
  550. event.persist();
  551. stopPropagation(event); // Only deactivate once the dropzone and all children have been left
  552. var targets = dragTargetsRef.current.filter(function (target) {
  553. return rootRef.current && rootRef.current.contains(target);
  554. }); // Make sure to remove a target present multiple times only once
  555. // (Firefox may fire dragenter/dragleave multiple times on the same element)
  556. var targetIdx = targets.indexOf(event.target);
  557. if (targetIdx !== -1) {
  558. targets.splice(targetIdx, 1);
  559. }
  560. dragTargetsRef.current = targets;
  561. if (targets.length > 0) {
  562. return;
  563. }
  564. dispatch({
  565. type: "setDraggedFiles",
  566. isDragActive: false,
  567. isDragAccept: false,
  568. isDragReject: false
  569. });
  570. if (isEvtWithFiles(event) && onDragLeave) {
  571. onDragLeave(event);
  572. }
  573. }, [rootRef, onDragLeave, noDragEventsBubbling]);
  574. var setFiles = useCallback(function (files, event) {
  575. var acceptedFiles = [];
  576. var fileRejections = [];
  577. files.forEach(function (file) {
  578. var _fileAccepted = fileAccepted(file, acceptAttr),
  579. _fileAccepted2 = _slicedToArray(_fileAccepted, 2),
  580. accepted = _fileAccepted2[0],
  581. acceptError = _fileAccepted2[1];
  582. var _fileMatchSize = fileMatchSize(file, minSize, maxSize),
  583. _fileMatchSize2 = _slicedToArray(_fileMatchSize, 2),
  584. sizeMatch = _fileMatchSize2[0],
  585. sizeError = _fileMatchSize2[1];
  586. var customErrors = validator ? validator(file) : null;
  587. if (accepted && sizeMatch && !customErrors) {
  588. acceptedFiles.push(file);
  589. } else {
  590. var errors = [acceptError, sizeError];
  591. if (customErrors) {
  592. errors = errors.concat(customErrors);
  593. }
  594. fileRejections.push({
  595. file: file,
  596. errors: errors.filter(function (e) {
  597. return e;
  598. })
  599. });
  600. }
  601. });
  602. if (!multiple && acceptedFiles.length > 1 || multiple && maxFiles >= 1 && acceptedFiles.length > maxFiles) {
  603. // Reject everything and empty accepted files
  604. acceptedFiles.forEach(function (file) {
  605. fileRejections.push({
  606. file: file,
  607. errors: [TOO_MANY_FILES_REJECTION]
  608. });
  609. });
  610. acceptedFiles.splice(0);
  611. }
  612. dispatch({
  613. acceptedFiles: acceptedFiles,
  614. fileRejections: fileRejections,
  615. type: "setFiles"
  616. });
  617. if (onDrop) {
  618. onDrop(acceptedFiles, fileRejections, event);
  619. }
  620. if (fileRejections.length > 0 && onDropRejected) {
  621. onDropRejected(fileRejections, event);
  622. }
  623. if (acceptedFiles.length > 0 && onDropAccepted) {
  624. onDropAccepted(acceptedFiles, event);
  625. }
  626. }, [dispatch, multiple, acceptAttr, minSize, maxSize, maxFiles, onDrop, onDropAccepted, onDropRejected, validator]);
  627. var onDropCb = useCallback(function (event) {
  628. event.preventDefault(); // Persist here because we need the event later after getFilesFromEvent() is done
  629. event.persist();
  630. stopPropagation(event);
  631. dragTargetsRef.current = [];
  632. if (isEvtWithFiles(event)) {
  633. Promise.resolve(getFilesFromEvent(event)).then(function (files) {
  634. if (isPropagationStopped(event) && !noDragEventsBubbling) {
  635. return;
  636. }
  637. setFiles(files, event);
  638. }).catch(function (e) {
  639. return onErrCb(e);
  640. });
  641. }
  642. dispatch({
  643. type: "reset"
  644. });
  645. }, [getFilesFromEvent, setFiles, onErrCb, noDragEventsBubbling]); // Fn for opening the file dialog programmatically
  646. var openFileDialog = useCallback(function () {
  647. // No point to use FS access APIs if context is not secure
  648. // https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts#feature_detection
  649. if (fsAccessApiWorksRef.current) {
  650. dispatch({
  651. type: "openDialog"
  652. });
  653. onFileDialogOpenCb(); // https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker
  654. var opts = {
  655. multiple: multiple,
  656. types: pickerTypes
  657. };
  658. window.showOpenFilePicker(opts).then(function (handles) {
  659. return getFilesFromEvent(handles);
  660. }).then(function (files) {
  661. setFiles(files, null);
  662. dispatch({
  663. type: "closeDialog"
  664. });
  665. }).catch(function (e) {
  666. // AbortError means the user canceled
  667. if (isAbort(e)) {
  668. onFileDialogCancelCb(e);
  669. dispatch({
  670. type: "closeDialog"
  671. });
  672. } else if (isSecurityError(e)) {
  673. fsAccessApiWorksRef.current = false; // CORS, so cannot use this API
  674. // Try using the input
  675. if (inputRef.current) {
  676. inputRef.current.value = null;
  677. inputRef.current.click();
  678. } else {
  679. onErrCb(new Error("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."));
  680. }
  681. } else {
  682. onErrCb(e);
  683. }
  684. });
  685. return;
  686. }
  687. if (inputRef.current) {
  688. dispatch({
  689. type: "openDialog"
  690. });
  691. onFileDialogOpenCb();
  692. inputRef.current.value = null;
  693. inputRef.current.click();
  694. }
  695. }, [dispatch, onFileDialogOpenCb, onFileDialogCancelCb, useFsAccessApi, setFiles, onErrCb, pickerTypes, multiple]); // Cb to open the file dialog when SPACE/ENTER occurs on the dropzone
  696. var onKeyDownCb = useCallback(function (event) {
  697. // Ignore keyboard events bubbling up the DOM tree
  698. if (!rootRef.current || !rootRef.current.isEqualNode(event.target)) {
  699. return;
  700. }
  701. if (event.key === " " || event.key === "Enter" || event.keyCode === 32 || event.keyCode === 13) {
  702. event.preventDefault();
  703. openFileDialog();
  704. }
  705. }, [rootRef, openFileDialog]); // Update focus state for the dropzone
  706. var onFocusCb = useCallback(function () {
  707. dispatch({
  708. type: "focus"
  709. });
  710. }, []);
  711. var onBlurCb = useCallback(function () {
  712. dispatch({
  713. type: "blur"
  714. });
  715. }, []); // Cb to open the file dialog when click occurs on the dropzone
  716. var onClickCb = useCallback(function () {
  717. if (noClick) {
  718. return;
  719. } // In IE11/Edge the file-browser dialog is blocking, therefore, use setTimeout()
  720. // to ensure React can handle state changes
  721. // See: https://github.com/react-dropzone/react-dropzone/issues/450
  722. if (isIeOrEdge()) {
  723. setTimeout(openFileDialog, 0);
  724. } else {
  725. openFileDialog();
  726. }
  727. }, [noClick, openFileDialog]);
  728. var composeHandler = function composeHandler(fn) {
  729. return disabled ? null : fn;
  730. };
  731. var composeKeyboardHandler = function composeKeyboardHandler(fn) {
  732. return noKeyboard ? null : composeHandler(fn);
  733. };
  734. var composeDragHandler = function composeDragHandler(fn) {
  735. return noDrag ? null : composeHandler(fn);
  736. };
  737. var stopPropagation = function stopPropagation(event) {
  738. if (noDragEventsBubbling) {
  739. event.stopPropagation();
  740. }
  741. };
  742. var getRootProps = useMemo(function () {
  743. return function () {
  744. var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
  745. _ref2$refKey = _ref2.refKey,
  746. refKey = _ref2$refKey === void 0 ? "ref" : _ref2$refKey,
  747. role = _ref2.role,
  748. onKeyDown = _ref2.onKeyDown,
  749. onFocus = _ref2.onFocus,
  750. onBlur = _ref2.onBlur,
  751. onClick = _ref2.onClick,
  752. onDragEnter = _ref2.onDragEnter,
  753. onDragOver = _ref2.onDragOver,
  754. onDragLeave = _ref2.onDragLeave,
  755. onDrop = _ref2.onDrop,
  756. rest = _objectWithoutProperties(_ref2, _excluded3);
  757. return _objectSpread(_objectSpread(_defineProperty({
  758. onKeyDown: composeKeyboardHandler(composeEventHandlers(onKeyDown, onKeyDownCb)),
  759. onFocus: composeKeyboardHandler(composeEventHandlers(onFocus, onFocusCb)),
  760. onBlur: composeKeyboardHandler(composeEventHandlers(onBlur, onBlurCb)),
  761. onClick: composeHandler(composeEventHandlers(onClick, onClickCb)),
  762. onDragEnter: composeDragHandler(composeEventHandlers(onDragEnter, onDragEnterCb)),
  763. onDragOver: composeDragHandler(composeEventHandlers(onDragOver, onDragOverCb)),
  764. onDragLeave: composeDragHandler(composeEventHandlers(onDragLeave, onDragLeaveCb)),
  765. onDrop: composeDragHandler(composeEventHandlers(onDrop, onDropCb)),
  766. role: typeof role === "string" && role !== "" ? role : "presentation"
  767. }, refKey, rootRef), !disabled && !noKeyboard ? {
  768. tabIndex: 0
  769. } : {}), rest);
  770. };
  771. }, [rootRef, onKeyDownCb, onFocusCb, onBlurCb, onClickCb, onDragEnterCb, onDragOverCb, onDragLeaveCb, onDropCb, noKeyboard, noDrag, disabled]);
  772. var onInputElementClick = useCallback(function (event) {
  773. event.stopPropagation();
  774. }, []);
  775. var getInputProps = useMemo(function () {
  776. return function () {
  777. var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
  778. _ref3$refKey = _ref3.refKey,
  779. refKey = _ref3$refKey === void 0 ? "ref" : _ref3$refKey,
  780. onChange = _ref3.onChange,
  781. onClick = _ref3.onClick,
  782. rest = _objectWithoutProperties(_ref3, _excluded4);
  783. var inputProps = _defineProperty({
  784. accept: acceptAttr,
  785. multiple: multiple,
  786. type: "file",
  787. style: {
  788. display: "none"
  789. },
  790. onChange: composeHandler(composeEventHandlers(onChange, onDropCb)),
  791. onClick: composeHandler(composeEventHandlers(onClick, onInputElementClick)),
  792. tabIndex: -1
  793. }, refKey, inputRef);
  794. return _objectSpread(_objectSpread({}, inputProps), rest);
  795. };
  796. }, [inputRef, accept, multiple, onDropCb, disabled]);
  797. return _objectSpread(_objectSpread({}, state), {}, {
  798. isFocused: isFocused && !disabled,
  799. getRootProps: getRootProps,
  800. getInputProps: getInputProps,
  801. rootRef: rootRef,
  802. inputRef: inputRef,
  803. open: composeHandler(openFileDialog)
  804. });
  805. }
  806. /**
  807. * @param {DropzoneState} state
  808. * @param {{type: string} & DropzoneState} action
  809. * @returns {DropzoneState}
  810. */
  811. function reducer(state, action) {
  812. /* istanbul ignore next */
  813. switch (action.type) {
  814. case "focus":
  815. return _objectSpread(_objectSpread({}, state), {}, {
  816. isFocused: true
  817. });
  818. case "blur":
  819. return _objectSpread(_objectSpread({}, state), {}, {
  820. isFocused: false
  821. });
  822. case "openDialog":
  823. return _objectSpread(_objectSpread({}, initialState), {}, {
  824. isFileDialogActive: true
  825. });
  826. case "closeDialog":
  827. return _objectSpread(_objectSpread({}, state), {}, {
  828. isFileDialogActive: false
  829. });
  830. case "setDraggedFiles":
  831. return _objectSpread(_objectSpread({}, state), {}, {
  832. isDragActive: action.isDragActive,
  833. isDragAccept: action.isDragAccept,
  834. isDragReject: action.isDragReject
  835. });
  836. case "setFiles":
  837. return _objectSpread(_objectSpread({}, state), {}, {
  838. acceptedFiles: action.acceptedFiles,
  839. fileRejections: action.fileRejections
  840. });
  841. case "reset":
  842. return _objectSpread({}, initialState);
  843. default:
  844. return state;
  845. }
  846. }
  847. function noop() {}
  848. export { ErrorCode } from "./utils";