index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
  2. 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."); }
  3. function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
  4. function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
  5. 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; }
  6. 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; }
  7. 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; }
  8. function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
  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. import accepts from "attr-accept"; // Error codes
  16. export var FILE_INVALID_TYPE = "file-invalid-type";
  17. export var FILE_TOO_LARGE = "file-too-large";
  18. export var FILE_TOO_SMALL = "file-too-small";
  19. export var TOO_MANY_FILES = "too-many-files";
  20. export var ErrorCode = {
  21. FileInvalidType: FILE_INVALID_TYPE,
  22. FileTooLarge: FILE_TOO_LARGE,
  23. FileTooSmall: FILE_TOO_SMALL,
  24. TooManyFiles: TOO_MANY_FILES
  25. }; // File Errors
  26. export var getInvalidTypeRejectionErr = function getInvalidTypeRejectionErr(accept) {
  27. accept = Array.isArray(accept) && accept.length === 1 ? accept[0] : accept;
  28. var messageSuffix = Array.isArray(accept) ? "one of ".concat(accept.join(", ")) : accept;
  29. return {
  30. code: FILE_INVALID_TYPE,
  31. message: "File type must be ".concat(messageSuffix)
  32. };
  33. };
  34. export var getTooLargeRejectionErr = function getTooLargeRejectionErr(maxSize) {
  35. return {
  36. code: FILE_TOO_LARGE,
  37. message: "File is larger than ".concat(maxSize, " ").concat(maxSize === 1 ? "byte" : "bytes")
  38. };
  39. };
  40. export var getTooSmallRejectionErr = function getTooSmallRejectionErr(minSize) {
  41. return {
  42. code: FILE_TOO_SMALL,
  43. message: "File is smaller than ".concat(minSize, " ").concat(minSize === 1 ? "byte" : "bytes")
  44. };
  45. };
  46. export var TOO_MANY_FILES_REJECTION = {
  47. code: TOO_MANY_FILES,
  48. message: "Too many files"
  49. }; // Firefox versions prior to 53 return a bogus MIME type for every file drag, so dragovers with
  50. // that MIME type will always be accepted
  51. export function fileAccepted(file, accept) {
  52. var isAcceptable = file.type === "application/x-moz-file" || accepts(file, accept);
  53. return [isAcceptable, isAcceptable ? null : getInvalidTypeRejectionErr(accept)];
  54. }
  55. export function fileMatchSize(file, minSize, maxSize) {
  56. if (isDefined(file.size)) {
  57. if (isDefined(minSize) && isDefined(maxSize)) {
  58. if (file.size > maxSize) return [false, getTooLargeRejectionErr(maxSize)];
  59. if (file.size < minSize) return [false, getTooSmallRejectionErr(minSize)];
  60. } else if (isDefined(minSize) && file.size < minSize) return [false, getTooSmallRejectionErr(minSize)];else if (isDefined(maxSize) && file.size > maxSize) return [false, getTooLargeRejectionErr(maxSize)];
  61. }
  62. return [true, null];
  63. }
  64. function isDefined(value) {
  65. return value !== undefined && value !== null;
  66. }
  67. /**
  68. *
  69. * @param {object} options
  70. * @param {File[]} options.files
  71. * @param {string|string[]} [options.accept]
  72. * @param {number} [options.minSize]
  73. * @param {number} [options.maxSize]
  74. * @param {boolean} [options.multiple]
  75. * @param {number} [options.maxFiles]
  76. * @param {(f: File) => FileError|FileError[]|null} [options.validator]
  77. * @returns
  78. */
  79. export function allFilesAccepted(_ref) {
  80. var files = _ref.files,
  81. accept = _ref.accept,
  82. minSize = _ref.minSize,
  83. maxSize = _ref.maxSize,
  84. multiple = _ref.multiple,
  85. maxFiles = _ref.maxFiles,
  86. validator = _ref.validator;
  87. if (!multiple && files.length > 1 || multiple && maxFiles >= 1 && files.length > maxFiles) {
  88. return false;
  89. }
  90. return files.every(function (file) {
  91. var _fileAccepted = fileAccepted(file, accept),
  92. _fileAccepted2 = _slicedToArray(_fileAccepted, 1),
  93. accepted = _fileAccepted2[0];
  94. var _fileMatchSize = fileMatchSize(file, minSize, maxSize),
  95. _fileMatchSize2 = _slicedToArray(_fileMatchSize, 1),
  96. sizeMatch = _fileMatchSize2[0];
  97. var customErrors = validator ? validator(file) : null;
  98. return accepted && sizeMatch && !customErrors;
  99. });
  100. } // React's synthetic events has event.isPropagationStopped,
  101. // but to remain compatibility with other libs (Preact) fall back
  102. // to check event.cancelBubble
  103. export function isPropagationStopped(event) {
  104. if (typeof event.isPropagationStopped === "function") {
  105. return event.isPropagationStopped();
  106. } else if (typeof event.cancelBubble !== "undefined") {
  107. return event.cancelBubble;
  108. }
  109. return false;
  110. }
  111. export function isEvtWithFiles(event) {
  112. if (!event.dataTransfer) {
  113. return !!event.target && !!event.target.files;
  114. } // https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/types
  115. // https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types#file
  116. return Array.prototype.some.call(event.dataTransfer.types, function (type) {
  117. return type === "Files" || type === "application/x-moz-file";
  118. });
  119. }
  120. export function isKindFile(item) {
  121. return _typeof(item) === "object" && item !== null && item.kind === "file";
  122. } // allow the entire document to be a drag target
  123. export function onDocumentDragOver(event) {
  124. event.preventDefault();
  125. }
  126. function isIe(userAgent) {
  127. return userAgent.indexOf("MSIE") !== -1 || userAgent.indexOf("Trident/") !== -1;
  128. }
  129. function isEdge(userAgent) {
  130. return userAgent.indexOf("Edge/") !== -1;
  131. }
  132. export function isIeOrEdge() {
  133. var userAgent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window.navigator.userAgent;
  134. return isIe(userAgent) || isEdge(userAgent);
  135. }
  136. /**
  137. * This is intended to be used to compose event handlers
  138. * They are executed in order until one of them calls `event.isPropagationStopped()`.
  139. * Note that the check is done on the first invoke too,
  140. * meaning that if propagation was stopped before invoking the fns,
  141. * no handlers will be executed.
  142. *
  143. * @param {Function} fns the event hanlder functions
  144. * @return {Function} the event handler to add to an element
  145. */
  146. export function composeEventHandlers() {
  147. for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {
  148. fns[_key] = arguments[_key];
  149. }
  150. return function (event) {
  151. for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  152. args[_key2 - 1] = arguments[_key2];
  153. }
  154. return fns.some(function (fn) {
  155. if (!isPropagationStopped(event) && fn) {
  156. fn.apply(void 0, [event].concat(args));
  157. }
  158. return isPropagationStopped(event);
  159. });
  160. };
  161. }
  162. /**
  163. * canUseFileSystemAccessAPI checks if the [File System Access API](https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API)
  164. * is supported by the browser.
  165. * @returns {boolean}
  166. */
  167. export function canUseFileSystemAccessAPI() {
  168. return "showOpenFilePicker" in window;
  169. }
  170. /**
  171. * Convert the `{accept}` dropzone prop to the
  172. * `{types}` option for https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker
  173. *
  174. * @param {AcceptProp} accept
  175. * @returns {{accept: string[]}[]}
  176. */
  177. export function pickerOptionsFromAccept(accept) {
  178. if (isDefined(accept)) {
  179. var acceptForPicker = Object.entries(accept).filter(function (_ref2) {
  180. var _ref3 = _slicedToArray(_ref2, 2),
  181. mimeType = _ref3[0],
  182. ext = _ref3[1];
  183. var ok = true;
  184. if (!isMIMEType(mimeType)) {
  185. console.warn("Skipped \"".concat(mimeType, "\" because it is not a valid MIME type. Check https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types for a list of valid MIME types."));
  186. ok = false;
  187. }
  188. if (!Array.isArray(ext) || !ext.every(isExt)) {
  189. console.warn("Skipped \"".concat(mimeType, "\" because an invalid file extension was provided."));
  190. ok = false;
  191. }
  192. return ok;
  193. }).reduce(function (agg, _ref4) {
  194. var _ref5 = _slicedToArray(_ref4, 2),
  195. mimeType = _ref5[0],
  196. ext = _ref5[1];
  197. return _objectSpread(_objectSpread({}, agg), {}, _defineProperty({}, mimeType, ext));
  198. }, {});
  199. return [{
  200. accept: acceptForPicker
  201. }];
  202. }
  203. return accept;
  204. }
  205. /**
  206. * Convert the `{accept}` dropzone prop to an array of MIME types/extensions.
  207. * @param {AcceptProp} accept
  208. * @returns {string}
  209. */
  210. export function acceptPropAsAcceptAttr(accept) {
  211. if (isDefined(accept)) {
  212. return Object.entries(accept).reduce(function (a, _ref6) {
  213. var _ref7 = _slicedToArray(_ref6, 2),
  214. mimeType = _ref7[0],
  215. ext = _ref7[1];
  216. return [].concat(_toConsumableArray(a), [mimeType], _toConsumableArray(ext));
  217. }, []) // Silently discard invalid entries as pickerOptionsFromAccept warns about these
  218. .filter(function (v) {
  219. return isMIMEType(v) || isExt(v);
  220. }).join(",");
  221. }
  222. return undefined;
  223. }
  224. /**
  225. * Check if v is an exception caused by aborting a request (e.g window.showOpenFilePicker()).
  226. *
  227. * See https://developer.mozilla.org/en-US/docs/Web/API/DOMException.
  228. * @param {any} v
  229. * @returns {boolean} True if v is an abort exception.
  230. */
  231. export function isAbort(v) {
  232. return v instanceof DOMException && (v.name === "AbortError" || v.code === v.ABORT_ERR);
  233. }
  234. /**
  235. * Check if v is a security error.
  236. *
  237. * See https://developer.mozilla.org/en-US/docs/Web/API/DOMException.
  238. * @param {any} v
  239. * @returns {boolean} True if v is a security error.
  240. */
  241. export function isSecurityError(v) {
  242. return v instanceof DOMException && (v.name === "SecurityError" || v.code === v.SECURITY_ERR);
  243. }
  244. /**
  245. * Check if v is a MIME type string.
  246. *
  247. * See accepted format: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#unique_file_type_specifiers.
  248. *
  249. * @param {string} v
  250. */
  251. export function isMIMEType(v) {
  252. return v === "audio/*" || v === "video/*" || v === "image/*" || v === "text/*" || /\w+\/[-+.\w]+/g.test(v);
  253. }
  254. /**
  255. * Check if v is a file extension.
  256. * @param {string} v
  257. */
  258. export function isExt(v) {
  259. return /^.*\.[\w]+$/.test(v);
  260. }
  261. /**
  262. * @typedef {Object.<string, string[]>} AcceptProp
  263. */
  264. /**
  265. * @typedef {object} FileError
  266. * @property {string} message
  267. * @property {ErrorCode|string} code
  268. */
  269. /**
  270. * @typedef {"file-invalid-type"|"file-too-large"|"file-too-small"|"too-many-files"} ErrorCode
  271. */