@jobber/components 9.16.7 → 9.16.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,1441 +3,1222 @@
3
3
  var tslib_es6 = require('./tslib.es6-cjs.js');
4
4
  var React = require('react');
5
5
  var classnames = require('classnames');
6
- var index = require('./index-cjs.js');
6
+ var jsxRuntime = require('react/jsx-runtime');
7
7
  var axios = require('axios');
8
8
  var Text = require('./Text-cjs.js');
9
9
  var Button = require('./Button-cjs.js');
10
10
  var InputValidation = require('./InputValidation-cjs.js');
11
+ var useAtlantisI18n = require('./useAtlantisI18n-cjs.js');
12
+ require('./AtlantisContext-cjs.js');
11
13
  var Content = require('./Content-cjs.js');
12
14
 
13
- var COMMON_MIME_TYPES = new Map([
14
- // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
15
- ['aac', 'audio/aac'],
16
- ['abw', 'application/x-abiword'],
17
- ['arc', 'application/x-freearc'],
18
- ['avif', 'image/avif'],
19
- ['avi', 'video/x-msvideo'],
20
- ['azw', 'application/vnd.amazon.ebook'],
21
- ['bin', 'application/octet-stream'],
22
- ['bmp', 'image/bmp'],
23
- ['bz', 'application/x-bzip'],
24
- ['bz2', 'application/x-bzip2'],
25
- ['cda', 'application/x-cdf'],
26
- ['csh', 'application/x-csh'],
27
- ['css', 'text/css'],
28
- ['csv', 'text/csv'],
29
- ['doc', 'application/msword'],
30
- ['docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
31
- ['eot', 'application/vnd.ms-fontobject'],
32
- ['epub', 'application/epub+zip'],
33
- ['gz', 'application/gzip'],
34
- ['gif', 'image/gif'],
35
- ['htm', 'text/html'],
36
- ['html', 'text/html'],
37
- ['ico', 'image/vnd.microsoft.icon'],
38
- ['ics', 'text/calendar'],
39
- ['jar', 'application/java-archive'],
40
- ['jpeg', 'image/jpeg'],
41
- ['jpg', 'image/jpeg'],
42
- ['js', 'text/javascript'],
43
- ['json', 'application/json'],
44
- ['jsonld', 'application/ld+json'],
45
- ['mid', 'audio/midi'],
46
- ['midi', 'audio/midi'],
47
- ['mjs', 'text/javascript'],
48
- ['mp3', 'audio/mpeg'],
49
- ['mp4', 'video/mp4'],
50
- ['mpeg', 'video/mpeg'],
51
- ['mpkg', 'application/vnd.apple.installer+xml'],
52
- ['odp', 'application/vnd.oasis.opendocument.presentation'],
53
- ['ods', 'application/vnd.oasis.opendocument.spreadsheet'],
54
- ['odt', 'application/vnd.oasis.opendocument.text'],
55
- ['oga', 'audio/ogg'],
56
- ['ogv', 'video/ogg'],
57
- ['ogx', 'application/ogg'],
58
- ['opus', 'audio/opus'],
59
- ['otf', 'font/otf'],
60
- ['png', 'image/png'],
61
- ['pdf', 'application/pdf'],
62
- ['php', 'application/x-httpd-php'],
63
- ['ppt', 'application/vnd.ms-powerpoint'],
64
- ['pptx', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'],
65
- ['rar', 'application/vnd.rar'],
66
- ['rtf', 'application/rtf'],
67
- ['sh', 'application/x-sh'],
68
- ['svg', 'image/svg+xml'],
69
- ['swf', 'application/x-shockwave-flash'],
70
- ['tar', 'application/x-tar'],
71
- ['tif', 'image/tiff'],
72
- ['tiff', 'image/tiff'],
73
- ['ts', 'video/mp2t'],
74
- ['ttf', 'font/ttf'],
75
- ['txt', 'text/plain'],
76
- ['vsd', 'application/vnd.visio'],
77
- ['wav', 'audio/wav'],
78
- ['weba', 'audio/webm'],
79
- ['webm', 'video/webm'],
80
- ['webp', 'image/webp'],
81
- ['woff', 'font/woff'],
82
- ['woff2', 'font/woff2'],
83
- ['xhtml', 'application/xhtml+xml'],
84
- ['xls', 'application/vnd.ms-excel'],
85
- ['xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
86
- ['xml', 'application/xml'],
87
- ['xul', 'application/vnd.mozilla.xul+xml'],
88
- ['zip', 'application/zip'],
89
- ['7z', 'application/x-7z-compressed'],
90
- // Others
91
- ['mkv', 'video/x-matroska'],
92
- ['mov', 'video/quicktime'],
93
- ['msg', 'application/vnd.ms-outlook']
15
+ //#region src/mime-default.ts
16
+ /**
17
+ * A small set of the most common file extensions, bundled into the main entry so that
18
+ * {@link fromEvent} guesses a MIME type for typeless files out of the box.
19
+ *
20
+ * This is the single source of truth for these defaults: the full extension-to-MIME table
21
+ * (`COMMON_MIME_TYPES`, exposed via the `file-selector/mime` subpath) spreads this map in
22
+ * rather than redefining these entries, so no value is duplicated across modules.
23
+ *
24
+ * See https://github.com/react-dropzone/file-selector/issues/127
25
+ */
26
+ const DEFAULT_MIME_TYPES = /* @__PURE__ */ new Map([
27
+ ["avif", "image/avif"],
28
+ ["bmp", "image/bmp"],
29
+ ["css", "text/css"],
30
+ ["csv", "text/csv"],
31
+ ["doc", "application/msword"],
32
+ ["docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"],
33
+ ["gif", "image/gif"],
34
+ ["gz", "application/gzip"],
35
+ ["htm", "text/html"],
36
+ ["html", "text/html"],
37
+ ["ico", "image/x-icon"],
38
+ ["jpeg", "image/jpeg"],
39
+ ["jpg", "image/jpeg"],
40
+ ["js", "application/javascript"],
41
+ ["json", "application/json"],
42
+ ["md", "text/markdown"],
43
+ ["mjs", "application/javascript"],
44
+ ["mp3", "audio/mpeg"],
45
+ ["mp4", "video/mp4"],
46
+ ["ogg", "audio/ogg"],
47
+ ["pdf", "application/pdf"],
48
+ ["png", "image/png"],
49
+ ["ppt", "application/powerpoint"],
50
+ ["pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"],
51
+ ["svg", "image/svg+xml"],
52
+ ["tif", "image/tiff"],
53
+ ["tiff", "image/tiff"],
54
+ ["txt", "text/plain"],
55
+ ["wasm", "application/wasm"],
56
+ ["wav", "audio/x-wav"],
57
+ ["weba", "audio/webm"],
58
+ ["webm", "video/webm"],
59
+ ["webp", "image/webp"],
60
+ ["xls", "application/vnd.ms-excel"],
61
+ ["xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
62
+ ["xml", "application/xml"],
63
+ ["zip", "application/zip"]
94
64
  ]);
95
- function toFileWithPath(file, path) {
96
- var f = withMimeType(file);
97
- if (typeof f.path !== 'string') { // on electron, path is already set to the absolute path
98
- var webkitRelativePath = file.webkitRelativePath;
99
- Object.defineProperty(f, 'path', {
100
- value: typeof path === 'string'
101
- ? path
102
- // If <input webkitdirectory> is set,
103
- // the File will have a {webkitRelativePath} property
104
- // https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory
105
- : typeof webkitRelativePath === 'string' && webkitRelativePath.length > 0
106
- ? webkitRelativePath
107
- : file.name,
108
- writable: false,
109
- configurable: false,
110
- enumerable: true
111
- });
112
- }
113
- return f;
114
- }
115
- function withMimeType(file) {
116
- var name = file.name;
117
- var hasExtension = name && name.lastIndexOf('.') !== -1;
118
- if (hasExtension && !file.type) {
119
- var ext = name.split('.')
120
- .pop().toLowerCase();
121
- var type = COMMON_MIME_TYPES.get(ext);
122
- if (type) {
123
- Object.defineProperty(file, 'type', {
124
- value: type,
125
- writable: false,
126
- configurable: false,
127
- enumerable: true
128
- });
129
- }
130
- }
131
- return file;
132
- }
133
65
 
134
- var FILES_TO_IGNORE = [
135
- // Thumbnail cache files for macOS and Windows
136
- '.DS_Store',
137
- 'Thumbs.db' // Windows
138
- ];
66
+ //#region src/error.ts
67
+ var UnexpectedObjectError = class extends Error {
68
+ constructor(item) {
69
+ super("DataTransferItem is not a file");
70
+ this.item = item;
71
+ this.name = "UnexpectedObjectError";
72
+ }
73
+ };
74
+ //#endregion
75
+ //#region src/file.ts
76
+ function toFileWithPath(file, path, h) {
77
+ const f = file;
78
+ const { webkitRelativePath } = file;
79
+ const p = typeof path === "string" ? path : typeof webkitRelativePath === "string" && webkitRelativePath.length > 0 ? webkitRelativePath : `./${file.name}`;
80
+ if (typeof f.path !== "string") setObjProp(f, "path", p);
81
+ if (h !== void 0) Object.defineProperty(f, "handle", {
82
+ value: h,
83
+ writable: false,
84
+ configurable: false,
85
+ enumerable: true
86
+ });
87
+ setObjProp(f, "relativePath", p);
88
+ return f;
89
+ }
139
90
  /**
140
- * Convert a DragEvent's DataTrasfer object to a list of File objects
141
- * NOTE: If some of the items are folders,
142
- * everything will be flattened and placed in the same list but the paths will be kept as a {path} property.
143
- *
144
- * EXPERIMENTAL: A list of https://developer.mozilla.org/en-US/docs/Web/API/FileSystemHandle objects can also be passed as an arg
145
- * and a list of File objects will be returned.
146
- *
147
- * @param evt
148
- */
149
- function fromEvent(evt) {
150
- return tslib_es6.__awaiter(this, void 0, void 0, function () {
151
- return tslib_es6.__generator(this, function (_a) {
152
- if (isObject(evt) && isDataTransfer(evt)) {
153
- return [2 /*return*/, getDataTransferFiles(evt.dataTransfer, evt.type)];
154
- }
155
- else if (isChangeEvt(evt)) {
156
- return [2 /*return*/, getInputFiles(evt)];
157
- }
158
- else if (Array.isArray(evt) && evt.every(function (item) { return 'getFile' in item && typeof item.getFile === 'function'; })) {
159
- return [2 /*return*/, getFsHandleFiles(evt)];
160
- }
161
- return [2 /*return*/, []];
162
- });
163
- });
91
+ * Sets a File's `type` from its extension using the provided `mimeTypes` lookup,
92
+ * but only when the browser didn't already set a type. Returns the same File.
93
+ */
94
+ function withMimeType(file, mimeTypes = DEFAULT_MIME_TYPES) {
95
+ const { name } = file;
96
+ if (name && name.lastIndexOf(".") !== -1 && !file.type) {
97
+ const ext = name.split(".").pop().toLowerCase();
98
+ const type = mimeTypes.get(ext);
99
+ if (type) Object.defineProperty(file, "type", {
100
+ value: type,
101
+ writable: false,
102
+ configurable: false,
103
+ enumerable: true
104
+ });
105
+ }
106
+ return file;
107
+ }
108
+ function setObjProp(f, key, value) {
109
+ Object.defineProperty(f, key, {
110
+ value,
111
+ writable: false,
112
+ configurable: false,
113
+ enumerable: true
114
+ });
115
+ }
116
+ //#endregion
117
+ //#region src/file-selector.ts
118
+ const FILES_TO_IGNORE = [".DS_Store", "Thumbs.db"];
119
+ /**
120
+ * Convert a DragEvent's DataTrasfer object to a list of File objects
121
+ * NOTE: If some of the items are folders,
122
+ * everything will be flattened and placed in the same list but the paths will be kept as a {path} property.
123
+ *
124
+ * A https://developer.mozilla.org/en-US/docs/Web/API/ClipboardEvent (e.g. a paste of a screenshot)
125
+ * is also supported: its files are read from {clipboardData}.
126
+ *
127
+ * EXPERIMENTAL: A list of https://developer.mozilla.org/en-US/docs/Web/API/FileSystemHandle objects can also be passed as an arg
128
+ * and a list of File objects will be returned.
129
+ *
130
+ * @param evt
131
+ * @param options
132
+ */
133
+ async function fromEvent(evt, { mimeTypes = DEFAULT_MIME_TYPES } = {}) {
134
+ return (await getFilesOrItems(evt)).map((item) => item instanceof File ? withMimeType(item, mimeTypes) : item);
135
+ }
136
+ async function getFilesOrItems(evt) {
137
+ if (isObject(evt) && isDataTransfer(evt.dataTransfer)) return getDataTransferFiles(evt.dataTransfer, evt.type);
138
+ else if (isClipboardEvt(evt)) return getClipboardFiles(evt.clipboardData);
139
+ else if (isChangeEvt(evt)) return getInputFiles(evt);
140
+ else if (Array.isArray(evt) && evt.every((item) => "getFile" in item && typeof item.getFile === "function")) return getFsHandleFiles(evt);
141
+ return [];
164
142
  }
165
143
  function isDataTransfer(value) {
166
- return isObject(value.dataTransfer);
144
+ return isObject(value);
145
+ }
146
+ function isClipboardEvt(value) {
147
+ return isObject(value) && isDataTransfer(value.clipboardData);
167
148
  }
168
149
  function isChangeEvt(value) {
169
- return isObject(value) && isObject(value.target);
150
+ return isObject(value) && isObject(value.target);
170
151
  }
171
152
  function isObject(v) {
172
- return typeof v === 'object' && v !== null;
153
+ return typeof v === "object" && v !== null;
173
154
  }
174
155
  function getInputFiles(evt) {
175
- return fromList(evt.target.files).map(function (file) { return toFileWithPath(file); });
176
- }
177
- // Ee expect each handle to be https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileHandle
178
- function getFsHandleFiles(handles) {
179
- return tslib_es6.__awaiter(this, void 0, void 0, function () {
180
- var files;
181
- return tslib_es6.__generator(this, function (_a) {
182
- switch (_a.label) {
183
- case 0: return [4 /*yield*/, Promise.all(handles.map(function (h) { return h.getFile(); }))];
184
- case 1:
185
- files = _a.sent();
186
- return [2 /*return*/, files.map(function (file) { return toFileWithPath(file); })];
187
- }
188
- });
189
- });
156
+ return fromList(evt.target.files).map((file) => toFileWithPath(file));
190
157
  }
191
- function getDataTransferFiles(dt, type) {
192
- return tslib_es6.__awaiter(this, void 0, void 0, function () {
193
- var items, files;
194
- return tslib_es6.__generator(this, function (_a) {
195
- switch (_a.label) {
196
- case 0:
197
- if (dt === null) {
198
- return [2 /*return*/, []];
199
- }
200
- if (!dt.items) return [3 /*break*/, 2];
201
- items = fromList(dt.items)
202
- .filter(function (item) { return item.kind === 'file'; });
203
- // According to https://html.spec.whatwg.org/multipage/dnd.html#dndevents,
204
- // only 'dragstart' and 'drop' has access to the data (source node)
205
- if (type !== 'drop') {
206
- return [2 /*return*/, items];
207
- }
208
- return [4 /*yield*/, Promise.all(items.map(toFilePromises))];
209
- case 1:
210
- files = _a.sent();
211
- return [2 /*return*/, noIgnoredFiles(flatten(files))];
212
- case 2: return [2 /*return*/, noIgnoredFiles(fromList(dt.files)
213
- .map(function (file) { return toFileWithPath(file); }))];
214
- }
215
- });
216
- });
158
+ async function getFsHandleFiles(handles) {
159
+ return (await Promise.all(handles.map((h) => h.getFile()))).map((file) => toFileWithPath(file));
160
+ }
161
+ async function getDataTransferFiles(dt, type) {
162
+ const items = fromList(dt.items).filter((item) => item.kind === "file");
163
+ if (type !== "drop") return items;
164
+ return noIgnoredFiles(flatten(await Promise.all(items.map(toFilePromises))));
165
+ }
166
+ function getClipboardFiles(dt) {
167
+ const fromItems = fromList(dt.items).filter((item) => item.kind === "file").map((item) => item.getAsFile()).filter((file) => file !== null);
168
+ return noIgnoredFiles((fromItems.length > 0 ? fromItems : fromList(dt.files)).map((file) => toFileWithPath(file)));
217
169
  }
218
170
  function noIgnoredFiles(files) {
219
- return files.filter(function (file) { return FILES_TO_IGNORE.indexOf(file.name) === -1; });
171
+ return files.filter((file) => FILES_TO_IGNORE.indexOf(file.name) === -1);
220
172
  }
221
- // IE11 does not support Array.from()
222
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from#Browser_compatibility
223
- // https://developer.mozilla.org/en-US/docs/Web/API/FileList
224
- // https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItemList
225
173
  function fromList(items) {
226
- if (items === null) {
227
- return [];
228
- }
229
- var files = [];
230
- // tslint:disable: prefer-for-of
231
- for (var i = 0; i < items.length; i++) {
232
- var file = items[i];
233
- files.push(file);
234
- }
235
- return files;
174
+ if (items === null) return [];
175
+ return Array.from(items);
236
176
  }
237
- // https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem
238
- function toFilePromises(item) {
239
- if (typeof item.webkitGetAsEntry !== 'function') {
240
- return fromDataTransferItem(item);
241
- }
242
- var entry = item.webkitGetAsEntry();
243
- // Safari supports dropping an image node from a different window and can be retrieved using
244
- // the DataTransferItem.getAsFile() API
245
- // NOTE: FileSystemEntry.file() throws if trying to get the file
246
- if (entry && entry.isDirectory) {
247
- return fromDirEntry(entry);
248
- }
249
- return fromDataTransferItem(item);
177
+ async function toFilePromises(item) {
178
+ if (typeof item.webkitGetAsEntry !== "function") return fromDataTransferItem(item);
179
+ const entry = item.webkitGetAsEntry();
180
+ if (entry?.isDirectory) {
181
+ const handle = await getFsHandle(item);
182
+ if (handle?.kind === "directory") return fromDirHandle(handle, `/${handle.name}`);
183
+ return fromDirEntry(entry);
184
+ }
185
+ return fromDataTransferItem(item, entry);
250
186
  }
251
187
  function flatten(items) {
252
- return items.reduce(function (acc, files) { return tslib_es6.__spread(acc, (Array.isArray(files) ? flatten(files) : [files])); }, []);
188
+ const result = [];
189
+ for (const item of items) if (Array.isArray(item)) result.push(...flatten(item));
190
+ else result.push(item);
191
+ return result;
253
192
  }
254
- function fromDataTransferItem(item) {
255
- var file = item.getAsFile();
256
- if (!file) {
257
- return Promise.reject(item + " is not a File");
258
- }
259
- var fwp = toFileWithPath(file);
260
- return Promise.resolve(fwp);
261
- }
262
- // https://developer.mozilla.org/en-US/docs/Web/API/FileSystemEntry
263
- function fromEntry(entry) {
264
- return tslib_es6.__awaiter(this, void 0, void 0, function () {
265
- return tslib_es6.__generator(this, function (_a) {
266
- return [2 /*return*/, entry.isDirectory ? fromDirEntry(entry) : fromFileEntry(entry)];
267
- });
268
- });
193
+ async function fromDataTransferItem(item, entry) {
194
+ const syncFile = item.getAsFile();
195
+ const h = await getFsHandle(item);
196
+ if (h !== null && h !== void 0) {
197
+ const file = syncFile ?? await h.getFile();
198
+ file.handle = h;
199
+ return toFileWithPath(file);
200
+ }
201
+ if (!syncFile) throw new UnexpectedObjectError(item);
202
+ return toFileWithPath(syncFile, entry?.fullPath ?? void 0);
203
+ }
204
+ async function getFsHandle(item) {
205
+ if (globalThis.isSecureContext && typeof item.getAsFileSystemHandle === "function") return item.getAsFileSystemHandle();
206
+ }
207
+ async function fromDirHandle(handle, path) {
208
+ const files = [];
209
+ for await (const child of handle.values()) {
210
+ const childPath = `${path}/${child.name}`;
211
+ if (child.kind === "directory") files.push(...await fromDirHandle(child, childPath));
212
+ else {
213
+ const file = await child.getFile();
214
+ files.push(toFileWithPath(file, childPath, child));
215
+ }
216
+ }
217
+ return files;
218
+ }
219
+ async function fromEntry(entry) {
220
+ return entry.isDirectory ? fromDirEntry(entry) : fromFileEntry(entry);
269
221
  }
270
- // https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryEntry
271
222
  function fromDirEntry(entry) {
272
- var reader = entry.createReader();
273
- return new Promise(function (resolve, reject) {
274
- var entries = [];
275
- function readEntries() {
276
- var _this = this;
277
- // https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryEntry/createReader
278
- // https://developer.mozilla.org/en-US/docs/Web/API/FileSystemDirectoryReader/readEntries
279
- reader.readEntries(function (batch) { return tslib_es6.__awaiter(_this, void 0, void 0, function () {
280
- var files, err_1, items;
281
- return tslib_es6.__generator(this, function (_a) {
282
- switch (_a.label) {
283
- case 0:
284
- if (!!batch.length) return [3 /*break*/, 5];
285
- _a.label = 1;
286
- case 1:
287
- _a.trys.push([1, 3, , 4]);
288
- return [4 /*yield*/, Promise.all(entries)];
289
- case 2:
290
- files = _a.sent();
291
- resolve(files);
292
- return [3 /*break*/, 4];
293
- case 3:
294
- err_1 = _a.sent();
295
- reject(err_1);
296
- return [3 /*break*/, 4];
297
- case 4: return [3 /*break*/, 6];
298
- case 5:
299
- items = Promise.all(batch.map(fromEntry));
300
- entries.push(items);
301
- // Continue reading
302
- readEntries();
303
- _a.label = 6;
304
- case 6: return [2 /*return*/];
305
- }
306
- });
307
- }); }, function (err) {
308
- reject(err);
309
- });
310
- }
311
- readEntries();
312
- });
223
+ const reader = entry.createReader();
224
+ return new Promise((resolve, reject) => {
225
+ const entries = [];
226
+ function readEntries() {
227
+ reader.readEntries(async (batch) => {
228
+ if (!batch.length) try {
229
+ resolve(await Promise.all(entries));
230
+ } catch (err) {
231
+ reject(err);
232
+ }
233
+ else {
234
+ const items = Promise.all(batch.map(fromEntry));
235
+ entries.push(items);
236
+ readEntries();
237
+ }
238
+ }, (err) => {
239
+ reject(err);
240
+ });
241
+ }
242
+ readEntries();
243
+ });
313
244
  }
314
- // https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileEntry
315
- function fromFileEntry(entry) {
316
- return tslib_es6.__awaiter(this, void 0, void 0, function () {
317
- return tslib_es6.__generator(this, function (_a) {
318
- return [2 /*return*/, new Promise(function (resolve, reject) {
319
- entry.file(function (file) {
320
- var fwp = toFileWithPath(file, entry.fullPath);
321
- resolve(fwp);
322
- }, function (err) {
323
- reject(err);
324
- });
325
- })];
326
- });
327
- });
245
+ async function fromFileEntry(entry) {
246
+ return new Promise((resolve, reject) => {
247
+ entry.file((file) => {
248
+ resolve(toFileWithPath(file, entry.fullPath));
249
+ }, (err) => {
250
+ reject(err);
251
+ });
252
+ });
328
253
  }
329
254
 
330
- var _default = function (file, acceptedFiles) {
331
- if (file && acceptedFiles) {
332
- var acceptedFilesArray = Array.isArray(acceptedFiles) ? acceptedFiles : acceptedFiles.split(',');
333
- var fileName = file.name || '';
334
- var mimeType = (file.type || '').toLowerCase();
335
- var baseMimeType = mimeType.replace(/\/.*$/, '');
336
- return acceptedFilesArray.some(function (type) {
337
- var validType = type.trim().toLowerCase();
338
-
339
- if (validType.charAt(0) === '.') {
340
- return fileName.toLowerCase().endsWith(validType);
341
- } else if (validType.endsWith('/*')) {
342
- // This is something like a image/* mime type
343
- return baseMimeType === validType.replace(/\/.*$/, '');
344
- }
345
-
346
- return mimeType === validType;
347
- });
348
- }
349
-
350
- return true;
351
- };
352
-
353
- function ownKeys$1(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; }
354
-
355
- function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty$1(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
356
-
357
- function _defineProperty$1(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; }
358
-
359
- function _slicedToArray$1(arr, i) { return _arrayWithHoles$1(arr) || _iterableToArrayLimit$1(arr, i) || _unsupportedIterableToArray$1(arr, i) || _nonIterableRest$1(); }
360
-
361
- function _nonIterableRest$1() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
362
-
363
- function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(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$1(o, minLen); }
364
-
365
- function _arrayLikeToArray$1(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; }
366
-
367
- function _iterableToArrayLimit$1(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; }
368
-
369
- function _arrayWithHoles$1(arr) { if (Array.isArray(arr)) return arr; }
370
-
371
- var FILE_INVALID_TYPE = 'file-invalid-type';
372
- var FILE_TOO_LARGE = 'file-too-large';
373
- var FILE_TOO_SMALL = 'file-too-small';
374
- var TOO_MANY_FILES = 'too-many-files';
255
+ //#region src/index.ts
256
+ /**
257
+ * Check if the provided file should be accepted by an `<input type="file">`
258
+ * with the given `accept` attribute value.
259
+ *
260
+ * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#attr-accept
261
+ *
262
+ * Inspired by https://github.com/enyo/dropzone.
263
+ *
264
+ * @param file The file to check. When omitted or `null`, the file is accepted.
265
+ * @param acceptedFiles One or more MIME types and/or file extensions, either as
266
+ * a comma-delimited string or an array. When omitted or empty, any file is accepted.
267
+ * @returns `true` if the file matches (or when there is nothing to match against).
268
+ */
269
+ function accept(file, acceptedFiles) {
270
+ if (file && acceptedFiles) {
271
+ const acceptedFilesArray = Array.isArray(acceptedFiles) ? acceptedFiles : acceptedFiles.split(",");
272
+ if (acceptedFilesArray.length === 0) return true;
273
+ const fileName = file.name || "";
274
+ const mimeType = (file.type || "").toLowerCase();
275
+ const baseMimeType = mimeType.replace(/\/.*$/, "");
276
+ return acceptedFilesArray.some((type) => {
277
+ const validType = type.trim().toLowerCase();
278
+ if (validType.charAt(0) === ".") return fileName.toLowerCase().endsWith(validType);
279
+ else if (validType.endsWith("/*")) return baseMimeType === validType.replace(/\/.*$/, "");
280
+ return mimeType === validType;
281
+ });
282
+ }
283
+ return true;
284
+ }
375
285
 
376
- var getInvalidTypeRejectionErr = function getInvalidTypeRejectionErr(accept) {
377
- accept = Array.isArray(accept) && accept.length === 1 ? accept[0] : accept;
378
- var messageSuffix = Array.isArray(accept) ? "one of ".concat(accept.join(', ')) : accept;
379
- return {
380
- code: FILE_INVALID_TYPE,
381
- message: "File type must be ".concat(messageSuffix)
382
- };
383
- };
384
- var getTooLargeRejectionErr = function getTooLargeRejectionErr(maxSize) {
385
- return {
386
- code: FILE_TOO_LARGE,
387
- message: "File is larger than ".concat(maxSize, " ").concat(maxSize === 1 ? 'byte' : 'bytes')
388
- };
389
- };
390
- var getTooSmallRejectionErr = function getTooSmallRejectionErr(minSize) {
391
- return {
392
- code: FILE_TOO_SMALL,
393
- message: "File is smaller than ".concat(minSize, " ").concat(minSize === 1 ? 'byte' : 'bytes')
394
- };
286
+ //#region src/utils/index.ts
287
+ const accepts = typeof accept === "function" ? accept : accept.default;
288
+ const FILE_INVALID_TYPE = "file-invalid-type";
289
+ const FILE_TOO_LARGE = "file-too-large";
290
+ const FILE_TOO_SMALL = "file-too-small";
291
+ const TOO_MANY_FILES = "too-many-files";
292
+ function getInvalidTypeRejectionErr(accept = "") {
293
+ const acceptArr = accept.split(",");
294
+ const msg = acceptArr.length > 1 ? `one of ${acceptArr.join(", ")}` : acceptArr[0];
295
+ return {
296
+ code: FILE_INVALID_TYPE,
297
+ message: `File type must be ${msg}`
298
+ };
299
+ }
300
+ const FILE_SIZE_UNITS = [
301
+ "KB",
302
+ "MB",
303
+ "GB",
304
+ "TB",
305
+ "PB"
306
+ ];
307
+ /**
308
+ * Format a byte count into a human-readable string, e.g. `1111` -> `1.08 KB`.
309
+ * Values below 1 KB are kept in bytes to preserve the singular/plural wording.
310
+ */
311
+ function formatBytes(bytes) {
312
+ if (bytes < 1024) return `${bytes} ${bytes === 1 ? "byte" : "bytes"}`;
313
+ let size = bytes / 1024;
314
+ let unitIndex = 0;
315
+ while (size >= 1024 && unitIndex < FILE_SIZE_UNITS.length - 1) {
316
+ size /= 1024;
317
+ unitIndex++;
318
+ }
319
+ return `${Number(size.toFixed(2))} ${FILE_SIZE_UNITS[unitIndex]}`;
320
+ }
321
+ function getTooLargeRejectionErr(maxSize) {
322
+ return {
323
+ code: FILE_TOO_LARGE,
324
+ message: `File is larger than ${formatBytes(maxSize)}`
325
+ };
326
+ }
327
+ function getTooSmallRejectionErr(minSize) {
328
+ return {
329
+ code: FILE_TOO_SMALL,
330
+ message: `File is smaller than ${formatBytes(minSize)}`
331
+ };
332
+ }
333
+ const TOO_MANY_FILES_REJECTION = {
334
+ code: TOO_MANY_FILES,
335
+ message: "Too many files"
395
336
  };
396
- var TOO_MANY_FILES_REJECTION = {
397
- code: TOO_MANY_FILES,
398
- message: 'Too many files'
399
- }; // Firefox versions prior to 53 return a bogus MIME type for every file drag, so dragovers with
400
- // that MIME type will always be accepted
401
-
337
+ /**
338
+ * Check if the given file is a DataTransferItem with an empty type.
339
+ *
340
+ * During drag events, browsers may return DataTransferItem objects instead of File objects.
341
+ * Some browsers (e.g., Chrome) return an empty MIME type for certain file types (like .md files)
342
+ * on DataTransferItem during drag events, even though the type is correctly set during drop.
343
+ */
344
+ function isDataTransferItemWithEmptyType(file) {
345
+ return file.type === "" && typeof file.getAsFile === "function";
346
+ }
347
+ /**
348
+ * Check if file is accepted.
349
+ *
350
+ * Firefox versions prior to 53 return a bogus MIME type for every file drag,
351
+ * so dragovers with that MIME type will always be accepted.
352
+ *
353
+ * Chrome/other browsers may return an empty MIME type for files during drag events,
354
+ * so we accept those as well (we'll validate properly on drop).
355
+ */
402
356
  function fileAccepted(file, accept) {
403
- var isAcceptable = file.type === 'application/x-moz-file' || _default(file, accept);
404
- return [isAcceptable, isAcceptable ? null : getInvalidTypeRejectionErr(accept)];
357
+ const isAcceptable = file.type === "application/x-moz-file" || accepts(file, accept ?? "") || isDataTransferItemWithEmptyType(file);
358
+ return [isAcceptable, isAcceptable ? null : getInvalidTypeRejectionErr(accept)];
405
359
  }
406
360
  function fileMatchSize(file, minSize, maxSize) {
407
- if (isDefined(file.size)) {
408
- if (isDefined(minSize) && isDefined(maxSize)) {
409
- if (file.size > maxSize) return [false, getTooLargeRejectionErr(maxSize)];
410
- if (file.size < minSize) return [false, getTooSmallRejectionErr(minSize)];
411
- } else if (isDefined(minSize) && file.size < minSize) return [false, getTooSmallRejectionErr(minSize)];else if (isDefined(maxSize) && file.size > maxSize) return [false, getTooLargeRejectionErr(maxSize)];
412
- }
413
-
414
- return [true, null];
361
+ if (isDefined(file.size)) {
362
+ if (isDefined(minSize) && isDefined(maxSize)) {
363
+ if (file.size > maxSize) return [false, getTooLargeRejectionErr(maxSize)];
364
+ if (file.size < minSize) return [false, getTooSmallRejectionErr(minSize)];
365
+ } else if (isDefined(minSize) && file.size < minSize) return [false, getTooSmallRejectionErr(minSize)];
366
+ else if (isDefined(maxSize) && file.size > maxSize) return [false, getTooLargeRejectionErr(maxSize)];
367
+ }
368
+ return [true, null];
415
369
  }
416
-
417
370
  function isDefined(value) {
418
- return value !== undefined && value !== null;
371
+ return value !== void 0 && value !== null;
372
+ }
373
+ /**
374
+ * Check if a value is thenable (Promise-like), used to tell a synchronous validator result from an
375
+ * asynchronous one.
376
+ */
377
+ function isThenable(value) {
378
+ return value != null && typeof value.then === "function";
379
+ }
380
+ /**
381
+ * Classify a set of dragged files for the `isDragAccept`/`isDragReject`/`isDragUnknown` states.
382
+ *
383
+ * During `dragenter`/`dragover` the browser only exposes `DataTransferItem`s, which carry a MIME
384
+ * `type` but no file name, extension or size (see https://html.spec.whatwg.org/multipage/dnd.html#dndevents).
385
+ * So the drag-time check is deliberately optimistic about anything it can't see:
386
+ *
387
+ * - The custom `validator` is **never** run here. It is typed `(file: File) => ...` and users
388
+ * routinely read `file.name`/`file.size`, which are `undefined` on a `DataTransferItem` - running
389
+ * it would throw and abort the whole drag handler (leaving `isDragActive` stuck at `false`).
390
+ * See https://github.com/react-dropzone/react-dropzone/issues/1408
391
+ * - When a `validator` is configured we therefore can't promise the files are acceptable, so the
392
+ * verdict is `unknown` rather than a misleading `reject` (or a premature `accept`).
393
+ * See https://github.com/react-dropzone/react-dropzone/issues/1244
394
+ *
395
+ * The full check (including the `validator`) still runs on drop in {@link fileAccepted}/`setFiles`.
396
+ */
397
+ function evaluateDragFiles({ files, accept, minSize, maxSize, multiple, maxFiles = 0, validator, getErrorMessage }) {
398
+ const acceptedFiles = [];
399
+ const rejections = [];
400
+ const localizeError = (error, file) => getErrorMessage && typeof File !== "undefined" && file instanceof File ? {
401
+ ...error,
402
+ message: getErrorMessage(error, file)
403
+ } : error;
404
+ files.forEach((file) => {
405
+ const [accepted, acceptError] = fileAccepted(file, accept);
406
+ const [sizeMatch, sizeError] = fileMatchSize(file, minSize, maxSize);
407
+ if (accepted && sizeMatch) acceptedFiles.push(file);
408
+ else rejections.push({
409
+ file,
410
+ errors: [acceptError, sizeError].filter((error) => error != null).map((error) => localizeError(error, file))
411
+ });
412
+ });
413
+ const acceptedFilesLimit = multiple ? maxFiles >= 1 ? maxFiles : Number.POSITIVE_INFINITY : 1;
414
+ if (acceptedFiles.length > acceptedFilesLimit) acceptedFiles.slice(acceptedFilesLimit).forEach((file) => {
415
+ rejections.push({
416
+ file,
417
+ errors: [localizeError(TOO_MANY_FILES_REJECTION, file)]
418
+ });
419
+ });
420
+ if (rejections.length > 0) return {
421
+ verdict: "reject",
422
+ rejections
423
+ };
424
+ return {
425
+ verdict: validator ? "unknown" : "accept",
426
+ rejections
427
+ };
419
428
  }
420
-
421
- function allFilesAccepted(_ref) {
422
- var files = _ref.files,
423
- accept = _ref.accept,
424
- minSize = _ref.minSize,
425
- maxSize = _ref.maxSize,
426
- multiple = _ref.multiple,
427
- maxFiles = _ref.maxFiles;
428
-
429
- if (!multiple && files.length > 1 || multiple && maxFiles >= 1 && files.length > maxFiles) {
430
- return false;
431
- }
432
-
433
- return files.every(function (file) {
434
- var _fileAccepted = fileAccepted(file, accept),
435
- _fileAccepted2 = _slicedToArray$1(_fileAccepted, 1),
436
- accepted = _fileAccepted2[0];
437
-
438
- var _fileMatchSize = fileMatchSize(file, minSize, maxSize),
439
- _fileMatchSize2 = _slicedToArray$1(_fileMatchSize, 1),
440
- sizeMatch = _fileMatchSize2[0];
441
-
442
- return accepted && sizeMatch;
443
- });
444
- } // React's synthetic events has event.isPropagationStopped,
445
- // but to remain compatibility with other libs (Preact) fall back
446
- // to check event.cancelBubble
447
-
448
429
  function isPropagationStopped(event) {
449
- if (typeof event.isPropagationStopped === 'function') {
450
- return event.isPropagationStopped();
451
- } else if (typeof event.cancelBubble !== 'undefined') {
452
- return event.cancelBubble;
453
- }
454
-
455
- return false;
430
+ if (typeof event.isPropagationStopped === "function") return event.isPropagationStopped();
431
+ else if (typeof event.cancelBubble !== "undefined") return event.cancelBubble;
432
+ return false;
456
433
  }
457
434
  function isEvtWithFiles(event) {
458
- if (!event.dataTransfer) {
459
- return !!event.target && !!event.target.files;
460
- } // https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer/types
461
- // https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types#file
462
-
463
-
464
- return Array.prototype.some.call(event.dataTransfer.types, function (type) {
465
- return type === 'Files' || type === 'application/x-moz-file';
466
- });
435
+ const dataTransfer = event.dataTransfer ?? event.clipboardData;
436
+ if (!dataTransfer) return !!event.target && !!event.target.files;
437
+ return Array.prototype.some.call(dataTransfer.types, (type) => type === "Files" || type === "application/x-moz-file") || Array.prototype.some.call(dataTransfer.items ?? [], isKindFile);
438
+ }
439
+ function isKindFile(item) {
440
+ return typeof item === "object" && item !== null && item.kind === "file";
467
441
  }
468
-
469
442
  function onDocumentDragOver(event) {
470
- event.preventDefault();
443
+ event.preventDefault();
471
444
  }
472
-
473
445
  function isIe(userAgent) {
474
- return userAgent.indexOf('MSIE') !== -1 || userAgent.indexOf('Trident/') !== -1;
446
+ return userAgent.indexOf("MSIE") !== -1 || userAgent.indexOf("Trident/") !== -1;
475
447
  }
476
-
477
448
  function isEdge(userAgent) {
478
- return userAgent.indexOf('Edge/') !== -1;
449
+ return userAgent.indexOf("Edge/") !== -1;
479
450
  }
480
-
481
- function isIeOrEdge() {
482
- var userAgent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window.navigator.userAgent;
483
- return isIe(userAgent) || isEdge(userAgent);
451
+ function isIeOrEdge(userAgent = window.navigator.userAgent) {
452
+ return isIe(userAgent) || isEdge(userAgent);
484
453
  }
485
454
  /**
486
- * This is intended to be used to compose event handlers
487
- * They are executed in order until one of them calls `event.isPropagationStopped()`.
488
- * Note that the check is done on the first invoke too,
489
- * meaning that if propagation was stopped before invoking the fns,
490
- * no handlers will be executed.
491
- *
492
- * @param {Function} fns the event hanlder functions
493
- * @return {Function} the event handler to add to an element
494
- */
495
-
496
- function composeEventHandlers() {
497
- for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) {
498
- fns[_key] = arguments[_key];
499
- }
500
-
501
- return function (event) {
502
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
503
- args[_key2 - 1] = arguments[_key2];
504
- }
505
-
506
- return fns.some(function (fn) {
507
- if (!isPropagationStopped(event) && fn) {
508
- fn.apply(void 0, [event].concat(args));
509
- }
510
-
511
- return isPropagationStopped(event);
512
- });
513
- };
455
+ * This is intended to be used to compose event handlers.
456
+ * They are executed in order until one of them calls `event.isPropagationStopped()`.
457
+ * Note that the check is done on the first invoke too,
458
+ * meaning that if propagation was stopped before invoking the fns,
459
+ * no handlers will be executed.
460
+ */
461
+ function composeEventHandlers(...fns) {
462
+ return (event, ...args) => fns.some((fn) => {
463
+ if (!isPropagationStopped(event) && fn) fn(event, ...args);
464
+ return isPropagationStopped(event);
465
+ });
514
466
  }
515
467
  /**
516
- * canUseFileSystemAccessAPI checks if the [File System Access API](https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API)
517
- * is supported by the browser.
518
- * @returns {boolean}
519
- */
520
-
468
+ * canUseFileSystemAccessAPI checks if the File System Access API is supported by the browser.
469
+ */
521
470
  function canUseFileSystemAccessAPI() {
522
- return 'showOpenFilePicker' in window;
471
+ return "showOpenFilePicker" in window;
523
472
  }
524
473
  /**
525
- * filePickerOptionsTypes returns the {types} option for https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker
526
- * based on the accept attr (see https://github.com/react-dropzone/attr-accept)
527
- * E.g: converts ['image/*', 'text/*'] to {'image/*': [], 'text/*': []}
528
- * @param {string|string[]} accept
529
- */
530
-
531
- function filePickerOptionsTypes(accept) {
532
- accept = typeof accept === 'string' ? accept.split(',') : accept;
533
- return [{
534
- description: 'everything',
535
- // TODO: Need to handle filtering more elegantly than this!
536
- accept: Array.isArray(accept) // Accept just MIME types as per spec
537
- // NOTE: accept can be https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#unique_file_type_specifiers
538
- ? accept.filter(function (item) {
539
- return item === 'audio/*' || item === 'video/*' || item === 'image/*' || item === 'text/*' || /\w+\/[-+.\w]+/g.test(item);
540
- }).reduce(function (a, b) {
541
- return _objectSpread$1(_objectSpread$1({}, a), {}, _defineProperty$1({}, b, []));
542
- }, {}) : {}
543
- }];
474
+ * Coerce an `accept` extension value to an array. `window.showOpenFilePicker` allows a single
475
+ * extension string as well as an array, so we accept both and normalize to an array. Anything
476
+ * else (a malformed value) collapses to an empty list.
477
+ */
478
+ function toExtensions(ext) {
479
+ if (Array.isArray(ext)) return ext;
480
+ if (typeof ext === "string") return [ext];
481
+ return [];
544
482
  }
545
-
546
- var _excluded = ["children"],
547
- _excluded2 = ["open"],
548
- _excluded3 = ["refKey", "role", "onKeyDown", "onFocus", "onBlur", "onClick", "onDragEnter", "onDragOver", "onDragLeave", "onDrop"],
549
- _excluded4 = ["refKey", "onChange", "onClick"];
550
-
551
- function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
552
-
553
- 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."); }
554
-
555
- function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
556
-
557
- function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
558
-
559
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
560
-
561
- 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."); }
562
-
563
- 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); }
564
-
565
- 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; }
566
-
567
- 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; }
568
-
569
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
570
-
571
- 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; }
572
-
573
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), true).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; }
574
-
575
- 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; }
576
-
577
- 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; }
578
-
579
- 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; }
580
483
  /**
581
- * Convenience wrapper component for the `useDropzone` hook
582
- *
583
- * ```jsx
584
- * <Dropzone>
585
- * {({getRootProps, getInputProps}) => (
586
- * <div {...getRootProps()}>
587
- * <input {...getInputProps()} />
588
- * <p>Drag 'n' drop some files here, or click to select files</p>
589
- * </div>
590
- * )}
591
- * </Dropzone>
592
- * ```
593
- */
594
-
595
- var Dropzone = /*#__PURE__*/React.forwardRef(function (_ref, ref) {
596
- var children = _ref.children,
597
- params = _objectWithoutProperties(_ref, _excluded);
598
-
599
- var _useDropzone = useDropzone(params),
600
- open = _useDropzone.open,
601
- props = _objectWithoutProperties(_useDropzone, _excluded2);
602
-
603
- React.useImperativeHandle(ref, function () {
604
- return {
605
- open: open
606
- };
607
- }, [open]); // TODO: Figure out why react-styleguidist cannot create docs if we don't return a jsx element
608
-
609
- return /*#__PURE__*/React.createElement(React.Fragment, null, children(_objectSpread(_objectSpread({}, props), {}, {
610
- open: open
611
- })));
612
- });
613
- Dropzone.displayName = 'Dropzone'; // Add default props for react-docgen
614
-
615
- var defaultProps = {
616
- disabled: false,
617
- getFilesFromEvent: fromEvent,
618
- maxSize: Infinity,
619
- minSize: 0,
620
- multiple: true,
621
- maxFiles: 0,
622
- preventDropOnDocument: true,
623
- noClick: false,
624
- noKeyboard: false,
625
- noDrag: false,
626
- noDragEventsBubbling: false,
627
- validator: null,
628
- useFsAccessApi: false
629
- };
630
- Dropzone.defaultProps = defaultProps;
631
- Dropzone.propTypes = {
632
- /**
633
- * Render function that exposes the dropzone state and prop getter fns
634
- *
635
- * @param {object} params
636
- * @param {Function} params.getRootProps Returns the props you should apply to the root drop container you render
637
- * @param {Function} params.getInputProps Returns the props you should apply to hidden file input you render
638
- * @param {Function} params.open Open the native file selection dialog
639
- * @param {boolean} params.isFocused Dropzone area is in focus
640
- * @param {boolean} params.isFileDialogActive File dialog is opened
641
- * @param {boolean} params.isDragActive Active drag is in progress
642
- * @param {boolean} params.isDragAccept Dragged files are accepted
643
- * @param {boolean} params.isDragReject Some dragged files are rejected
644
- * @param {File[]} params.draggedFiles Files in active drag
645
- * @param {File[]} params.acceptedFiles Accepted files
646
- * @param {FileRejection[]} params.fileRejections Rejected files and why they were rejected
647
- */
648
- children: index.PropTypes.func,
649
-
650
- /**
651
- * Set accepted file types.
652
- * See https://github.com/okonet/attr-accept for more information.
653
- * Keep in mind that mime type determination is not reliable across platforms. CSV files,
654
- * for example, are reported as text/plain under macOS but as application/vnd.ms-excel under
655
- * Windows. In some cases there might not be a mime type set at all.
656
- * See: https://github.com/react-dropzone/react-dropzone/issues/276
657
- */
658
- accept: index.PropTypes.oneOfType([index.PropTypes.string, index.PropTypes.arrayOf(index.PropTypes.string)]),
659
-
660
- /**
661
- * Allow drag 'n' drop (or selection from the file dialog) of multiple files
662
- */
663
- multiple: index.PropTypes.bool,
664
-
665
- /**
666
- * If false, allow dropped items to take over the current browser window
667
- */
668
- preventDropOnDocument: index.PropTypes.bool,
669
-
670
- /**
671
- * If true, disables click to open the native file selection dialog
672
- */
673
- noClick: index.PropTypes.bool,
674
-
675
- /**
676
- * If true, disables SPACE/ENTER to open the native file selection dialog.
677
- * Note that it also stops tracking the focus state.
678
- */
679
- noKeyboard: index.PropTypes.bool,
680
-
681
- /**
682
- * If true, disables drag 'n' drop
683
- */
684
- noDrag: index.PropTypes.bool,
685
-
686
- /**
687
- * If true, stops drag event propagation to parents
688
- */
689
- noDragEventsBubbling: index.PropTypes.bool,
690
-
691
- /**
692
- * Minimum file size (in bytes)
693
- */
694
- minSize: index.PropTypes.number,
695
-
696
- /**
697
- * Maximum file size (in bytes)
698
- */
699
- maxSize: index.PropTypes.number,
700
-
701
- /**
702
- * Maximum accepted number of files
703
- * The default value is 0 which means there is no limitation to how many files are accepted.
704
- */
705
- maxFiles: index.PropTypes.number,
706
-
707
- /**
708
- * Enable/disable the dropzone
709
- */
710
- disabled: index.PropTypes.bool,
711
-
712
- /**
713
- * Use this to provide a custom file aggregator
714
- *
715
- * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
716
- */
717
- getFilesFromEvent: index.PropTypes.func,
718
-
719
- /**
720
- * Cb for when closing the file dialog with no selection
721
- */
722
- onFileDialogCancel: index.PropTypes.func,
723
-
724
- /**
725
- * Cb for when opening the file dialog
726
- */
727
- onFileDialogOpen: index.PropTypes.func,
728
-
729
- /**
730
- * Set to true to use the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API
731
- * to open the file picker instead of using an `<input type="file">` click event.
732
- */
733
- useFsAccessApi: index.PropTypes.bool,
734
-
735
- /**
736
- * Cb for when the `dragenter` event occurs.
737
- *
738
- * @param {DragEvent} event
739
- */
740
- onDragEnter: index.PropTypes.func,
741
-
742
- /**
743
- * Cb for when the `dragleave` event occurs
744
- *
745
- * @param {DragEvent} event
746
- */
747
- onDragLeave: index.PropTypes.func,
748
-
749
- /**
750
- * Cb for when the `dragover` event occurs
751
- *
752
- * @param {DragEvent} event
753
- */
754
- onDragOver: index.PropTypes.func,
755
-
756
- /**
757
- * Cb for when the `drop` event occurs.
758
- * Note that this callback is invoked after the `getFilesFromEvent` callback is done.
759
- *
760
- * Files are accepted or rejected based on the `accept`, `multiple`, `minSize` and `maxSize` props.
761
- * `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.
762
- * If `multiple` is set to false and additional files are dropped,
763
- * all files besides the first will be rejected.
764
- * Any file which does not have a size in the [`minSize`, `maxSize`] range, will be rejected as well.
765
- *
766
- * Note that the `onDrop` callback will always be invoked regardless if the dropped files were accepted or rejected.
767
- * If you'd like to react to a specific scenario, use the `onDropAccepted`/`onDropRejected` props.
768
- *
769
- * `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.
770
- * For example, with [SuperAgent](https://github.com/visionmedia/superagent) as a http/ajax library:
771
- *
772
- * ```js
773
- * function onDrop(acceptedFiles) {
774
- * const req = request.post('/upload')
775
- * acceptedFiles.forEach(file => {
776
- * req.attach(file.name, file)
777
- * })
778
- * req.end(callback)
779
- * }
780
- * ```
781
- *
782
- * @param {File[]} acceptedFiles
783
- * @param {FileRejection[]} fileRejections
784
- * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
785
- */
786
- onDrop: index.PropTypes.func,
787
-
788
- /**
789
- * Cb for when the `drop` event occurs.
790
- * Note that if no files are accepted, this callback is not invoked.
791
- *
792
- * @param {File[]} files
793
- * @param {(DragEvent|Event)} event
794
- */
795
- onDropAccepted: index.PropTypes.func,
796
-
797
- /**
798
- * Cb for when the `drop` event occurs.
799
- * Note that if no files are rejected, this callback is not invoked.
800
- *
801
- * @param {FileRejection[]} fileRejections
802
- * @param {(DragEvent|Event)} event
803
- */
804
- onDropRejected: index.PropTypes.func,
805
-
806
- /**
807
- * Custom validation function
808
- * @param {File} file
809
- * @returns {FileError|FileError[]}
810
- */
811
- validator: index.PropTypes.func
812
- };
484
+ * Normalize either `accept` form to the internal array of `{description, accept}` groups.
485
+ *
486
+ * - The object form (`{mime: ext}`) becomes a single group; its `description` (which the object
487
+ * form can't express) is derived from the extensions like any other group.
488
+ * - The array form is passed through; entries missing an `accept` map are dropped.
489
+ *
490
+ * In both cases a missing `description` is filled in later from the group's extensions (see
491
+ * {@link describeAccept}), so the picker always gets the non-empty description it requires
492
+ * (https://crbug.com/1264708). Returns `undefined` when no `accept` is provided.
493
+ */
494
+ function normalizeAcceptGroups(accept) {
495
+ if (!isDefined(accept)) return;
496
+ if (Array.isArray(accept)) return accept.filter((group) => isDefined(group) && isDefined(group.accept));
497
+ return [{ accept }];
498
+ }
813
499
  /**
814
- * A function that is invoked for the `dragenter`,
815
- * `dragover` and `dragleave` events.
816
- * It is not invoked if the items are not files (such as link, text, etc.).
817
- *
818
- * @callback dragCb
819
- * @param {DragEvent} event
820
- */
821
-
500
+ * Build a human-readable label for a picker group from its (validated) accept map, used when the
501
+ * caller doesn't supply a `description`. Prefer the file extensions, fall back to the MIME types,
502
+ * then to a generic label - `showOpenFilePicker` requires a non-empty description (crbug 1264708).
503
+ */
504
+ function describeAccept(accept) {
505
+ const extensions = [];
506
+ const mimeTypes = Object.keys(accept);
507
+ for (const ext of Object.values(accept)) for (const e of toExtensions(ext)) if (!extensions.includes(e)) extensions.push(e);
508
+ if (extensions.length > 0) return extensions.join(", ");
509
+ if (mimeTypes.length > 0) return mimeTypes.join(", ");
510
+ return "Files";
511
+ }
822
512
  /**
823
- * A function that is invoked for the `drop` or input change event.
824
- * It is not invoked if the items are not files (such as link, text, etc.).
825
- *
826
- * @callback dropCb
827
- * @param {File[]} acceptedFiles List of accepted files
828
- * @param {FileRejection[]} fileRejections List of rejected files and why they were rejected
829
- * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
830
- */
831
-
513
+ * Merge every `accept` group into a single MIME-type -> extensions map. Duplicate MIME keys union
514
+ * their extensions. This flattened map drives the native `<input accept>` attribute and the
515
+ * drag/drop validators, which have no concept of groups or descriptions.
516
+ */
517
+ function flattenAccept(accept) {
518
+ const groups = normalizeAcceptGroups(accept);
519
+ if (!isDefined(groups)) return;
520
+ const merged = {};
521
+ for (const group of groups) for (const [mimeType, ext] of Object.entries(group.accept)) {
522
+ const existing = merged[mimeType] ?? (merged[mimeType] = []);
523
+ for (const e of toExtensions(ext)) if (!existing.includes(e)) existing.push(e);
524
+ }
525
+ return merged;
526
+ }
832
527
  /**
833
- * A function that is invoked for the `drop` or input change event.
834
- * It is not invoked if the items are files (such as link, text, etc.).
835
- *
836
- * @callback dropAcceptedCb
837
- * @param {File[]} files List of accepted files that meet the given criteria
838
- * (`accept`, `multiple`, `minSize`, `maxSize`)
839
- * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
840
- */
841
-
528
+ * Convert the `{accept}` dropzone prop to the `{types}` option for showOpenFilePicker.
529
+ *
530
+ * Each group becomes one filter row in the picker. Invalid MIME types / extensions are dropped
531
+ * with a warning; a group left with no valid entries is omitted entirely (showOpenFilePicker
532
+ * rejects an empty `accept`). Returns `undefined` when nothing valid remains.
533
+ */
534
+ function pickerOptionsFromAccept(accept) {
535
+ const groups = normalizeAcceptGroups(accept);
536
+ if (!isDefined(groups)) return;
537
+ const options = groups.map((group) => {
538
+ const acceptForPicker = Object.entries(group.accept).filter(([mimeType, ext]) => {
539
+ let ok = true;
540
+ if (!isMIMEType(mimeType)) {
541
+ console.warn(`Skipped "${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.`);
542
+ ok = false;
543
+ }
544
+ if (!(Array.isArray(ext) || typeof ext === "string") || !toExtensions(ext).every(isExt)) {
545
+ console.warn(`Skipped "${mimeType}" because an invalid file extension was provided.`);
546
+ ok = false;
547
+ }
548
+ return ok;
549
+ }).reduce((agg, [mimeType, ext]) => {
550
+ agg[mimeType] = toExtensions(ext);
551
+ return agg;
552
+ }, {});
553
+ return {
554
+ description: isDefined(group.description) && group.description !== "" ? group.description : describeAccept(acceptForPicker),
555
+ accept: acceptForPicker
556
+ };
557
+ }).filter((option) => Object.keys(option.accept).length > 0);
558
+ return options.length > 0 ? options : void 0;
559
+ }
842
560
  /**
843
- * A function that is invoked for the `drop` or input change event.
844
- *
845
- * @callback dropRejectedCb
846
- * @param {File[]} files List of rejected files that do not meet the given criteria
847
- * (`accept`, `multiple`, `minSize`, `maxSize`)
848
- * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
849
- */
850
-
561
+ * Convert the `{accept}` dropzone prop to a comma-separated accept attribute string.
562
+ *
563
+ * When `omitWildcardMimeTypesWithExtensions` is set, a wildcard MIME type (e.g. `image/*`)
564
+ * that is paired with explicit extensions is dropped in favour of those extensions. The
565
+ * accept attribute is an OR list, so leaving `image/*` in would make both the native file
566
+ * picker and the drop-time validator accept ANY file of that type, ignoring the extension
567
+ * restriction. The drag-time `isDragAccept` check keeps the wildcard because file names
568
+ * (and therefore extensions) aren't readable during a drag.
569
+ *
570
+ * See https://github.com/react-dropzone/react-dropzone/issues/1220
571
+ */
572
+ function acceptPropAsAcceptAttr(accept, { omitWildcardMimeTypesWithExtensions = false } = {}) {
573
+ if (isDefined(accept)) return Object.entries(accept).reduce((a, [mimeType, extVal]) => {
574
+ const ext = toExtensions(extVal);
575
+ if (omitWildcardMimeTypesWithExtensions && isMIMETypeWildcard(mimeType) && ext.some(isExt)) a.push(...ext);
576
+ else a.push(mimeType, ...ext);
577
+ return a;
578
+ }, []).filter((v) => isMIMEType(v) || isExt(v)).join(",");
579
+ }
851
580
  /**
852
- * A function that is used aggregate files,
853
- * in a asynchronous fashion, from drag or input change events.
854
- *
855
- * @callback getFilesFromEvent
856
- * @param {(DragEvent|Event)} event A drag event or input change event (if files were selected via the file dialog)
857
- * @returns {(File[]|Promise<File[]>)}
858
- */
859
-
581
+ * Check if v is an exception caused by aborting a request (e.g window.showOpenFilePicker()).
582
+ */
583
+ function isAbort(v) {
584
+ return v instanceof DOMException && (v.name === "AbortError" || v.code === v.ABORT_ERR);
585
+ }
860
586
  /**
861
- * An object with the current dropzone state and some helper functions.
862
- *
863
- * @typedef {object} DropzoneState
864
- * @property {Function} getRootProps Returns the props you should apply to the root drop container you render
865
- * @property {Function} getInputProps Returns the props you should apply to hidden file input you render
866
- * @property {Function} open Open the native file selection dialog
867
- * @property {boolean} isFocused Dropzone area is in focus
868
- * @property {boolean} isFileDialogActive File dialog is opened
869
- * @property {boolean} isDragActive Active drag is in progress
870
- * @property {boolean} isDragAccept Dragged files are accepted
871
- * @property {boolean} isDragReject Some dragged files are rejected
872
- * @property {File[]} draggedFiles Files in active drag
873
- * @property {File[]} acceptedFiles Accepted files
874
- * @property {FileRejection[]} fileRejections Rejected files and why they were rejected
875
- */
876
-
877
- var initialState = {
878
- isFocused: false,
879
- isFileDialogActive: false,
880
- isDragActive: false,
881
- isDragAccept: false,
882
- isDragReject: false,
883
- draggedFiles: [],
884
- acceptedFiles: [],
885
- fileRejections: []
587
+ * Check if v is a security error.
588
+ */
589
+ function isSecurityError(v) {
590
+ return v instanceof DOMException && (v.name === "SecurityError" || v.code === v.SECURITY_ERR);
591
+ }
592
+ /**
593
+ * Check if v is a "not allowed" error.
594
+ *
595
+ * Some browsers/configurations block `window.showOpenFilePicker()` outright and reject with a
596
+ * `NotAllowedError` instead of showing the picker (e.g. Microsoft Edge for Business, or other
597
+ * restrictive enterprise/security policies). We treat this like a security error and fall back
598
+ * to the native `<input>`. See https://github.com/react-dropzone/react-dropzone/issues/1429
599
+ */
600
+ function isNotAllowedError(v) {
601
+ return v instanceof DOMException && v.name === "NotAllowedError";
602
+ }
603
+ /**
604
+ * Check if v is a MIME type string.
605
+ */
606
+ function isMIMEType(v) {
607
+ return v === "audio/*" || v === "video/*" || v === "image/*" || v === "text/*" || v === "application/*" || /\w+\/[-+.\w]+/g.test(v);
608
+ }
609
+ /**
610
+ * Check if v is a wildcard MIME type (e.g. `image/*`).
611
+ */
612
+ function isMIMETypeWildcard(v) {
613
+ return v.endsWith("/*");
614
+ }
615
+ /**
616
+ * Check if v is a file extension.
617
+ */
618
+ function isExt(v) {
619
+ return /^.*\.[\w]+$/.test(v);
620
+ }
621
+ //#endregion
622
+ //#region src/index.tsx
623
+ /**
624
+ * Convenience wrapper component for the `useDropzone` hook
625
+ *
626
+ * ```jsx
627
+ * <Dropzone>
628
+ * {({getRootProps, getInputProps}) => (
629
+ * <div {...getRootProps()}>
630
+ * <input {...getInputProps()} />
631
+ * <p>Drag 'n' drop some files here, or click to select files</p>
632
+ * </div>
633
+ * )}
634
+ * </Dropzone>
635
+ * ```
636
+ */
637
+ const Dropzone = React.forwardRef(({ children, ...params }, ref) => {
638
+ const { open, ...props } = useDropzone(params);
639
+ React.useImperativeHandle(ref, () => ({ open }), [open]);
640
+ return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: children?.({
641
+ ...props,
642
+ open
643
+ }) });
644
+ });
645
+ Dropzone.displayName = "Dropzone";
646
+ const initialState = {
647
+ isFocused: false,
648
+ isFileDialogActive: false,
649
+ isDragActive: false,
650
+ isDragAccept: false,
651
+ isDragReject: false,
652
+ isDragUnknown: false,
653
+ isDragGlobal: false,
654
+ isProcessing: false,
655
+ acceptedFiles: [],
656
+ fileRejections: [],
657
+ dragFileRejections: []
886
658
  };
887
659
  /**
888
- * A React hook that creates a drag 'n' drop area.
889
- *
890
- * ```jsx
891
- * function MyDropzone(props) {
892
- * const {getRootProps, getInputProps} = useDropzone({
893
- * onDrop: acceptedFiles => {
894
- * // do something with the File objects, e.g. upload to some server
895
- * }
896
- * });
897
- * return (
898
- * <div {...getRootProps()}>
899
- * <input {...getInputProps()} />
900
- * <p>Drag and drop some files here, or click to select files</p>
901
- * </div>
902
- * )
903
- * }
904
- * ```
905
- *
906
- * @function useDropzone
907
- *
908
- * @param {object} props
909
- * @param {string|string[]} [props.accept] Set accepted file types.
910
- * See https://github.com/okonet/attr-accept for more information.
911
- * Keep in mind that mime type determination is not reliable across platforms. CSV files,
912
- * for example, are reported as text/plain under macOS but as application/vnd.ms-excel under
913
- * Windows. In some cases there might not be a mime type set at all.
914
- * See: https://github.com/react-dropzone/react-dropzone/issues/276
915
- * @param {boolean} [props.multiple=true] Allow drag 'n' drop (or selection from the file dialog) of multiple files
916
- * @param {boolean} [props.preventDropOnDocument=true] If false, allow dropped items to take over the current browser window
917
- * @param {boolean} [props.noClick=false] If true, disables click to open the native file selection dialog
918
- * @param {boolean} [props.noKeyboard=false] If true, disables SPACE/ENTER to open the native file selection dialog.
919
- * Note that it also stops tracking the focus state.
920
- * @param {boolean} [props.noDrag=false] If true, disables drag 'n' drop
921
- * @param {boolean} [props.noDragEventsBubbling=false] If true, stops drag event propagation to parents
922
- * @param {number} [props.minSize=0] Minimum file size (in bytes)
923
- * @param {number} [props.maxSize=Infinity] Maximum file size (in bytes)
924
- * @param {boolean} [props.disabled=false] Enable/disable the dropzone
925
- * @param {getFilesFromEvent} [props.getFilesFromEvent] Use this to provide a custom file aggregator
926
- * @param {Function} [props.onFileDialogCancel] Cb for when closing the file dialog with no selection
927
- * @param {boolean} [props.useFsAccessApi] Set to true to use the https://developer.mozilla.org/en-US/docs/Web/API/File_System_Access_API
928
- * to open the file picker instead of using an `<input type="file">` click event.
929
- * @param {Function} [props.onFileDialogOpen] Cb for when opening the file dialog
930
- * @param {dragCb} [props.onDragEnter] Cb for when the `dragenter` event occurs.
931
- * @param {dragCb} [props.onDragLeave] Cb for when the `dragleave` event occurs
932
- * @param {dragCb} [props.onDragOver] Cb for when the `dragover` event occurs
933
- * @param {dropCb} [props.onDrop] Cb for when the `drop` event occurs.
934
- * Note that this callback is invoked after the `getFilesFromEvent` callback is done.
935
- *
936
- * Files are accepted or rejected based on the `accept`, `multiple`, `minSize` and `maxSize` props.
937
- * `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.
938
- * If `multiple` is set to false and additional files are dropped,
939
- * all files besides the first will be rejected.
940
- * Any file which does not have a size in the [`minSize`, `maxSize`] range, will be rejected as well.
941
- *
942
- * Note that the `onDrop` callback will always be invoked regardless if the dropped files were accepted or rejected.
943
- * If you'd like to react to a specific scenario, use the `onDropAccepted`/`onDropRejected` props.
944
- *
945
- * `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.
946
- * For example, with [SuperAgent](https://github.com/visionmedia/superagent) as a http/ajax library:
947
- *
948
- * ```js
949
- * function onDrop(acceptedFiles) {
950
- * const req = request.post('/upload')
951
- * acceptedFiles.forEach(file => {
952
- * req.attach(file.name, file)
953
- * })
954
- * req.end(callback)
955
- * }
956
- * ```
957
- * @param {dropAcceptedCb} [props.onDropAccepted]
958
- * @param {dropRejectedCb} [props.onDropRejected]
959
- *
960
- * @returns {DropzoneState}
961
- */
962
-
963
- function useDropzone() {
964
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
965
-
966
- var _defaultProps$options = _objectSpread(_objectSpread({}, defaultProps), options),
967
- accept = _defaultProps$options.accept,
968
- disabled = _defaultProps$options.disabled,
969
- getFilesFromEvent = _defaultProps$options.getFilesFromEvent,
970
- maxSize = _defaultProps$options.maxSize,
971
- minSize = _defaultProps$options.minSize,
972
- multiple = _defaultProps$options.multiple,
973
- maxFiles = _defaultProps$options.maxFiles,
974
- onDragEnter = _defaultProps$options.onDragEnter,
975
- onDragLeave = _defaultProps$options.onDragLeave,
976
- onDragOver = _defaultProps$options.onDragOver,
977
- onDrop = _defaultProps$options.onDrop,
978
- onDropAccepted = _defaultProps$options.onDropAccepted,
979
- onDropRejected = _defaultProps$options.onDropRejected,
980
- onFileDialogCancel = _defaultProps$options.onFileDialogCancel,
981
- onFileDialogOpen = _defaultProps$options.onFileDialogOpen,
982
- useFsAccessApi = _defaultProps$options.useFsAccessApi,
983
- preventDropOnDocument = _defaultProps$options.preventDropOnDocument,
984
- noClick = _defaultProps$options.noClick,
985
- noKeyboard = _defaultProps$options.noKeyboard,
986
- noDrag = _defaultProps$options.noDrag,
987
- noDragEventsBubbling = _defaultProps$options.noDragEventsBubbling,
988
- validator = _defaultProps$options.validator;
989
-
990
- var onFileDialogOpenCb = React.useMemo(function () {
991
- return typeof onFileDialogOpen === 'function' ? onFileDialogOpen : noop;
992
- }, [onFileDialogOpen]);
993
- var onFileDialogCancelCb = React.useMemo(function () {
994
- return typeof onFileDialogCancel === 'function' ? onFileDialogCancel : noop;
995
- }, [onFileDialogCancel]);
996
- var rootRef = React.useRef(null);
997
- var inputRef = React.useRef(null);
998
-
999
- var _useReducer = React.useReducer(reducer, initialState),
1000
- _useReducer2 = _slicedToArray(_useReducer, 2),
1001
- state = _useReducer2[0],
1002
- dispatch = _useReducer2[1];
1003
-
1004
- var isFocused = state.isFocused,
1005
- isFileDialogActive = state.isFileDialogActive,
1006
- draggedFiles = state.draggedFiles; // Update file dialog active state when the window is focused on
1007
-
1008
- var onWindowFocus = function onWindowFocus() {
1009
- // Execute the timeout only if the file dialog is opened in the browser
1010
- if (isFileDialogActive) {
1011
- setTimeout(function () {
1012
- if (inputRef.current) {
1013
- var files = inputRef.current.files;
1014
-
1015
- if (!files.length) {
1016
- dispatch({
1017
- type: 'closeDialog'
1018
- });
1019
- onFileDialogCancelCb();
1020
- }
1021
- }
1022
- }, 300);
1023
- }
1024
- };
1025
-
1026
- React.useEffect(function () {
1027
- if (useFsAccessApi && canUseFileSystemAccessAPI()) {
1028
- return function () {};
1029
- }
1030
-
1031
- window.addEventListener('focus', onWindowFocus, false);
1032
- return function () {
1033
- window.removeEventListener('focus', onWindowFocus, false);
1034
- };
1035
- }, [inputRef, isFileDialogActive, onFileDialogCancelCb, useFsAccessApi]);
1036
- var dragTargetsRef = React.useRef([]);
1037
-
1038
- var onDocumentDrop = function onDocumentDrop(event) {
1039
- if (rootRef.current && rootRef.current.contains(event.target)) {
1040
- // If we intercepted an event for our instance, let it propagate down to the instance's onDrop handler
1041
- return;
1042
- }
1043
-
1044
- event.preventDefault();
1045
- dragTargetsRef.current = [];
1046
- };
1047
-
1048
- React.useEffect(function () {
1049
- if (preventDropOnDocument) {
1050
- document.addEventListener('dragover', onDocumentDragOver, false);
1051
- document.addEventListener('drop', onDocumentDrop, false);
1052
- }
1053
-
1054
- return function () {
1055
- if (preventDropOnDocument) {
1056
- document.removeEventListener('dragover', onDocumentDragOver);
1057
- document.removeEventListener('drop', onDocumentDrop);
1058
- }
1059
- };
1060
- }, [rootRef, preventDropOnDocument]);
1061
- var onDragEnterCb = React.useCallback(function (event) {
1062
- event.preventDefault(); // Persist here because we need the event later after getFilesFromEvent() is done
1063
-
1064
- event.persist();
1065
- stopPropagation(event);
1066
- dragTargetsRef.current = [].concat(_toConsumableArray(dragTargetsRef.current), [event.target]);
1067
-
1068
- if (isEvtWithFiles(event)) {
1069
- Promise.resolve(getFilesFromEvent(event)).then(function (draggedFiles) {
1070
- if (isPropagationStopped(event) && !noDragEventsBubbling) {
1071
- return;
1072
- }
1073
-
1074
- dispatch({
1075
- draggedFiles: draggedFiles,
1076
- isDragActive: true,
1077
- type: 'setDraggedFiles'
1078
- });
1079
-
1080
- if (onDragEnter) {
1081
- onDragEnter(event);
1082
- }
1083
- });
1084
- }
1085
- }, [getFilesFromEvent, onDragEnter, noDragEventsBubbling]);
1086
- var onDragOverCb = React.useCallback(function (event) {
1087
- event.preventDefault();
1088
- event.persist();
1089
- stopPropagation(event);
1090
- var hasFiles = isEvtWithFiles(event);
1091
-
1092
- if (hasFiles && event.dataTransfer) {
1093
- try {
1094
- event.dataTransfer.dropEffect = 'copy';
1095
- } catch (_unused) {}
1096
- /* eslint-disable-line no-empty */
1097
-
1098
- }
1099
-
1100
- if (hasFiles && onDragOver) {
1101
- onDragOver(event);
1102
- }
1103
-
1104
- return false;
1105
- }, [onDragOver, noDragEventsBubbling]);
1106
- var onDragLeaveCb = React.useCallback(function (event) {
1107
- event.preventDefault();
1108
- event.persist();
1109
- stopPropagation(event); // Only deactivate once the dropzone and all children have been left
1110
-
1111
- var targets = dragTargetsRef.current.filter(function (target) {
1112
- return rootRef.current && rootRef.current.contains(target);
1113
- }); // Make sure to remove a target present multiple times only once
1114
- // (Firefox may fire dragenter/dragleave multiple times on the same element)
1115
-
1116
- var targetIdx = targets.indexOf(event.target);
1117
-
1118
- if (targetIdx !== -1) {
1119
- targets.splice(targetIdx, 1);
1120
- }
1121
-
1122
- dragTargetsRef.current = targets;
1123
-
1124
- if (targets.length > 0) {
1125
- return;
1126
- }
1127
-
1128
- dispatch({
1129
- isDragActive: false,
1130
- type: 'setDraggedFiles',
1131
- draggedFiles: []
1132
- });
1133
-
1134
- if (isEvtWithFiles(event) && onDragLeave) {
1135
- onDragLeave(event);
1136
- }
1137
- }, [rootRef, onDragLeave, noDragEventsBubbling]);
1138
- var setFiles = React.useCallback(function (files, event) {
1139
- var acceptedFiles = [];
1140
- var fileRejections = [];
1141
- files.forEach(function (file) {
1142
- var _fileAccepted = fileAccepted(file, accept),
1143
- _fileAccepted2 = _slicedToArray(_fileAccepted, 2),
1144
- accepted = _fileAccepted2[0],
1145
- acceptError = _fileAccepted2[1];
1146
-
1147
- var _fileMatchSize = fileMatchSize(file, minSize, maxSize),
1148
- _fileMatchSize2 = _slicedToArray(_fileMatchSize, 2),
1149
- sizeMatch = _fileMatchSize2[0],
1150
- sizeError = _fileMatchSize2[1];
1151
-
1152
- var customErrors = validator ? validator(file) : null;
1153
-
1154
- if (accepted && sizeMatch && !customErrors) {
1155
- acceptedFiles.push(file);
1156
- } else {
1157
- var errors = [acceptError, sizeError];
1158
-
1159
- if (customErrors) {
1160
- errors = errors.concat(customErrors);
1161
- }
1162
-
1163
- fileRejections.push({
1164
- file: file,
1165
- errors: errors.filter(function (e) {
1166
- return e;
1167
- })
1168
- });
1169
- }
1170
- });
1171
-
1172
- if (!multiple && acceptedFiles.length > 1 || multiple && maxFiles >= 1 && acceptedFiles.length > maxFiles) {
1173
- // Reject everything and empty accepted files
1174
- acceptedFiles.forEach(function (file) {
1175
- fileRejections.push({
1176
- file: file,
1177
- errors: [TOO_MANY_FILES_REJECTION]
1178
- });
1179
- });
1180
- acceptedFiles.splice(0);
1181
- }
1182
-
1183
- dispatch({
1184
- acceptedFiles: acceptedFiles,
1185
- fileRejections: fileRejections,
1186
- type: 'setFiles'
1187
- });
1188
-
1189
- if (onDrop) {
1190
- onDrop(acceptedFiles, fileRejections, event);
1191
- }
1192
-
1193
- if (fileRejections.length > 0 && onDropRejected) {
1194
- onDropRejected(fileRejections, event);
1195
- }
1196
-
1197
- if (acceptedFiles.length > 0 && onDropAccepted) {
1198
- onDropAccepted(acceptedFiles, event);
1199
- }
1200
- }, [dispatch, multiple, accept, minSize, maxSize, maxFiles, onDrop, onDropAccepted, onDropRejected, validator]);
1201
- var onDropCb = React.useCallback(function (event) {
1202
- event.preventDefault(); // Persist here because we need the event later after getFilesFromEvent() is done
1203
-
1204
- event.persist();
1205
- stopPropagation(event);
1206
- dragTargetsRef.current = [];
1207
-
1208
- if (isEvtWithFiles(event)) {
1209
- Promise.resolve(getFilesFromEvent(event)).then(function (files) {
1210
- if (isPropagationStopped(event) && !noDragEventsBubbling) {
1211
- return;
1212
- }
1213
-
1214
- setFiles(files, event);
1215
- });
1216
- }
1217
-
1218
- dispatch({
1219
- type: 'reset'
1220
- });
1221
- }, [getFilesFromEvent, setFiles, noDragEventsBubbling]); // Fn for opening the file dialog programmatically
1222
-
1223
- var openFileDialog = React.useCallback(function () {
1224
- if (useFsAccessApi && canUseFileSystemAccessAPI()) {
1225
- dispatch({
1226
- type: 'openDialog'
1227
- });
1228
- onFileDialogOpenCb(); // https://developer.mozilla.org/en-US/docs/Web/API/window/showOpenFilePicker
1229
-
1230
- var opts = {
1231
- multiple: multiple,
1232
- types: filePickerOptionsTypes(accept)
1233
- };
1234
- window.showOpenFilePicker(opts).then(function (handles) {
1235
- return getFilesFromEvent(handles);
1236
- }).then(function (files) {
1237
- return setFiles(files, null);
1238
- }).catch(function (e) {
1239
- return onFileDialogCancelCb(e);
1240
- }).finally(function () {
1241
- return dispatch({
1242
- type: 'closeDialog'
1243
- });
1244
- });
1245
- return;
1246
- }
1247
-
1248
- if (inputRef.current) {
1249
- dispatch({
1250
- type: 'openDialog'
1251
- });
1252
- onFileDialogOpenCb();
1253
- inputRef.current.value = null;
1254
- inputRef.current.click();
1255
- }
1256
- }, [dispatch, onFileDialogOpenCb, onFileDialogCancelCb, useFsAccessApi, setFiles, accept, multiple]); // Cb to open the file dialog when SPACE/ENTER occurs on the dropzone
1257
-
1258
- var onKeyDownCb = React.useCallback(function (event) {
1259
- // Ignore keyboard events bubbling up the DOM tree
1260
- if (!rootRef.current || !rootRef.current.isEqualNode(event.target)) {
1261
- return;
1262
- }
1263
-
1264
- if (event.keyCode === 32 || event.keyCode === 13) {
1265
- event.preventDefault();
1266
- openFileDialog();
1267
- }
1268
- }, [rootRef, inputRef, openFileDialog]); // Update focus state for the dropzone
1269
-
1270
- var onFocusCb = React.useCallback(function () {
1271
- dispatch({
1272
- type: 'focus'
1273
- });
1274
- }, []);
1275
- var onBlurCb = React.useCallback(function () {
1276
- dispatch({
1277
- type: 'blur'
1278
- });
1279
- }, []); // Cb to open the file dialog when click occurs on the dropzone
1280
-
1281
- var onClickCb = React.useCallback(function () {
1282
- if (noClick) {
1283
- return;
1284
- } // In IE11/Edge the file-browser dialog is blocking, therefore, use setTimeout()
1285
- // to ensure React can handle state changes
1286
- // See: https://github.com/react-dropzone/react-dropzone/issues/450
1287
-
1288
-
1289
- if (isIeOrEdge()) {
1290
- setTimeout(openFileDialog, 0);
1291
- } else {
1292
- openFileDialog();
1293
- }
1294
- }, [inputRef, noClick, openFileDialog]);
1295
-
1296
- var composeHandler = function composeHandler(fn) {
1297
- return disabled ? null : fn;
1298
- };
1299
-
1300
- var composeKeyboardHandler = function composeKeyboardHandler(fn) {
1301
- return noKeyboard ? null : composeHandler(fn);
1302
- };
1303
-
1304
- var composeDragHandler = function composeDragHandler(fn) {
1305
- return noDrag ? null : composeHandler(fn);
1306
- };
1307
-
1308
- var stopPropagation = function stopPropagation(event) {
1309
- if (noDragEventsBubbling) {
1310
- event.stopPropagation();
1311
- }
1312
- };
1313
-
1314
- var getRootProps = React.useMemo(function () {
1315
- return function () {
1316
- var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
1317
- _ref2$refKey = _ref2.refKey,
1318
- refKey = _ref2$refKey === void 0 ? 'ref' : _ref2$refKey,
1319
- role = _ref2.role,
1320
- onKeyDown = _ref2.onKeyDown,
1321
- onFocus = _ref2.onFocus,
1322
- onBlur = _ref2.onBlur,
1323
- onClick = _ref2.onClick,
1324
- onDragEnter = _ref2.onDragEnter,
1325
- onDragOver = _ref2.onDragOver,
1326
- onDragLeave = _ref2.onDragLeave,
1327
- onDrop = _ref2.onDrop,
1328
- rest = _objectWithoutProperties(_ref2, _excluded3);
1329
-
1330
- return _objectSpread(_objectSpread(_defineProperty({
1331
- onKeyDown: composeKeyboardHandler(composeEventHandlers(onKeyDown, onKeyDownCb)),
1332
- onFocus: composeKeyboardHandler(composeEventHandlers(onFocus, onFocusCb)),
1333
- onBlur: composeKeyboardHandler(composeEventHandlers(onBlur, onBlurCb)),
1334
- onClick: composeHandler(composeEventHandlers(onClick, onClickCb)),
1335
- onDragEnter: composeDragHandler(composeEventHandlers(onDragEnter, onDragEnterCb)),
1336
- onDragOver: composeDragHandler(composeEventHandlers(onDragOver, onDragOverCb)),
1337
- onDragLeave: composeDragHandler(composeEventHandlers(onDragLeave, onDragLeaveCb)),
1338
- onDrop: composeDragHandler(composeEventHandlers(onDrop, onDropCb)),
1339
- role: typeof role === 'string' && role !== '' ? role : 'button'
1340
- }, refKey, rootRef), !disabled && !noKeyboard ? {
1341
- tabIndex: 0
1342
- } : {}), rest);
1343
- };
1344
- }, [rootRef, onKeyDownCb, onFocusCb, onBlurCb, onClickCb, onDragEnterCb, onDragOverCb, onDragLeaveCb, onDropCb, noKeyboard, noDrag, disabled]);
1345
- var onInputElementClick = React.useCallback(function (event) {
1346
- event.stopPropagation();
1347
- }, []);
1348
- var getInputProps = React.useMemo(function () {
1349
- return function () {
1350
- var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
1351
- _ref3$refKey = _ref3.refKey,
1352
- refKey = _ref3$refKey === void 0 ? 'ref' : _ref3$refKey,
1353
- onChange = _ref3.onChange,
1354
- onClick = _ref3.onClick,
1355
- rest = _objectWithoutProperties(_ref3, _excluded4);
1356
-
1357
- var inputProps = _defineProperty({
1358
- accept: accept,
1359
- multiple: multiple,
1360
- type: 'file',
1361
- style: {
1362
- display: 'none'
1363
- },
1364
- onChange: composeHandler(composeEventHandlers(onChange, onDropCb)),
1365
- onClick: composeHandler(composeEventHandlers(onClick, onInputElementClick)),
1366
- autoComplete: 'off',
1367
- tabIndex: -1
1368
- }, refKey, inputRef);
1369
-
1370
- return _objectSpread(_objectSpread({}, inputProps), rest);
1371
- };
1372
- }, [inputRef, accept, multiple, onDropCb, disabled]);
1373
- var fileCount = draggedFiles.length;
1374
- var isDragAccept = fileCount > 0 && allFilesAccepted({
1375
- files: draggedFiles,
1376
- accept: accept,
1377
- minSize: minSize,
1378
- maxSize: maxSize,
1379
- multiple: multiple,
1380
- maxFiles: maxFiles
1381
- });
1382
- var isDragReject = fileCount > 0 && !isDragAccept;
1383
- return _objectSpread(_objectSpread({}, state), {}, {
1384
- isDragAccept: isDragAccept,
1385
- isDragReject: isDragReject,
1386
- isFocused: isFocused && !disabled,
1387
- getRootProps: getRootProps,
1388
- getInputProps: getInputProps,
1389
- rootRef: rootRef,
1390
- inputRef: inputRef,
1391
- open: composeHandler(openFileDialog)
1392
- });
660
+ * A React hook that creates a drag 'n' drop area.
661
+ *
662
+ * ```jsx
663
+ * function MyDropzone(props) {
664
+ * const {getRootProps, getInputProps} = useDropzone({
665
+ * onDrop: acceptedFiles => {
666
+ * // do something with the File objects, e.g. upload to some server
667
+ * }
668
+ * });
669
+ * return (
670
+ * <div {...getRootProps()}>
671
+ * <input {...getInputProps()} />
672
+ * <p>Drag and drop some files here, or click to select files</p>
673
+ * </div>
674
+ * )
675
+ * }
676
+ * ```
677
+ */
678
+ function useDropzone(props = {}) {
679
+ const { accept, disabled = false, getFilesFromEvent = fromEvent, maxSize = Number.POSITIVE_INFINITY, minSize = 0, multiple = true, maxFiles = 0, onDragEnter, onDragLeave, onDragOver, onDrop, onDropAccepted, onDropRejected, onFileDialogCancel, onFileDialogOpen, useFsAccessApi = false, autoFocus = false, preventDropOnDocument = true, noClick = false, noKeyboard = false, noDrag = false, noDragEventsBubbling = false, noPaste = false, onError, validator, getErrorMessage } = props;
680
+ const flatAccept = React.useMemo(() => flattenAccept(accept), [accept]);
681
+ const acceptAttr = React.useMemo(() => acceptPropAsAcceptAttr(flatAccept), [flatAccept]);
682
+ const inputAcceptAttr = React.useMemo(() => acceptPropAsAcceptAttr(flatAccept, { omitWildcardMimeTypesWithExtensions: true }), [flatAccept]);
683
+ const pickerTypes = React.useMemo(() => pickerOptionsFromAccept(accept), [accept]);
684
+ const onFileDialogOpenCb = React.useMemo(() => typeof onFileDialogOpen === "function" ? onFileDialogOpen : noop, [onFileDialogOpen]);
685
+ const onFileDialogCancelCb = React.useMemo(() => typeof onFileDialogCancel === "function" ? onFileDialogCancel : noop, [onFileDialogCancel]);
686
+ const rootRef = React.useRef(null);
687
+ const inputRef = React.useRef(null);
688
+ const [state, dispatch] = React.useReducer(reducer, initialState);
689
+ const { isFocused, isFileDialogActive } = state;
690
+ const isFileDialogActiveRef = React.useRef(isFileDialogActive);
691
+ isFileDialogActiveRef.current = isFileDialogActive;
692
+ const processingAbortRef = React.useRef(null);
693
+ const beginProcessing = React.useCallback(() => {
694
+ processingAbortRef.current?.abort();
695
+ const controller = new AbortController();
696
+ processingAbortRef.current = controller;
697
+ dispatch({
698
+ type: "setProcessing",
699
+ isProcessing: true
700
+ });
701
+ return controller.signal;
702
+ }, []);
703
+ const endProcessing = React.useCallback((signal) => {
704
+ if (!signal.aborted) dispatch({
705
+ type: "setProcessing",
706
+ isProcessing: false
707
+ });
708
+ }, []);
709
+ const fsAccessApiWorksRef = React.useRef(typeof window !== "undefined" && window.isSecureContext && useFsAccessApi && canUseFileSystemAccessAPI());
710
+ const onWindowFocus = () => {
711
+ if (!fsAccessApiWorksRef.current && isFileDialogActive) setTimeout(() => {
712
+ if (inputRef.current) {
713
+ const { files } = inputRef.current;
714
+ if (!files?.length) {
715
+ dispatch({ type: "closeDialog" });
716
+ onFileDialogCancelCb();
717
+ }
718
+ }
719
+ }, 300);
720
+ };
721
+ React.useEffect(() => {
722
+ window.addEventListener("focus", onWindowFocus, false);
723
+ return () => {
724
+ window.removeEventListener("focus", onWindowFocus, false);
725
+ };
726
+ }, [
727
+ inputRef,
728
+ isFileDialogActive,
729
+ onFileDialogCancelCb,
730
+ fsAccessApiWorksRef
731
+ ]);
732
+ const dragTargetsRef = React.useRef([]);
733
+ const globalDragTargetsRef = React.useRef([]);
734
+ const onDocumentDrop = (event) => {
735
+ if (rootRef.current && event.target && rootRef.current.contains(event.target) && event.defaultPrevented) return;
736
+ event.preventDefault();
737
+ dragTargetsRef.current = [];
738
+ };
739
+ React.useEffect(() => {
740
+ if (preventDropOnDocument) {
741
+ document.addEventListener("dragover", onDocumentDragOver, false);
742
+ document.addEventListener("drop", onDocumentDrop, false);
743
+ }
744
+ return () => {
745
+ if (preventDropOnDocument) {
746
+ document.removeEventListener("dragover", onDocumentDragOver);
747
+ document.removeEventListener("drop", onDocumentDrop);
748
+ }
749
+ };
750
+ }, [rootRef, preventDropOnDocument]);
751
+ React.useEffect(() => {
752
+ const onDocumentDragEnter = (event) => {
753
+ if (event.target) globalDragTargetsRef.current = [...globalDragTargetsRef.current, event.target];
754
+ if (isEvtWithFiles(event)) dispatch({
755
+ isDragGlobal: true,
756
+ type: "setDragGlobal"
757
+ });
758
+ };
759
+ const onDocumentDragLeave = (event) => {
760
+ globalDragTargetsRef.current = globalDragTargetsRef.current.filter((el) => el !== event.target && el !== null);
761
+ if (globalDragTargetsRef.current.length > 0) return;
762
+ dispatch({
763
+ isDragGlobal: false,
764
+ type: "setDragGlobal"
765
+ });
766
+ };
767
+ const onDocumentDragEnd = () => {
768
+ globalDragTargetsRef.current = [];
769
+ dispatch({
770
+ isDragGlobal: false,
771
+ type: "setDragGlobal"
772
+ });
773
+ };
774
+ const onDocumentDropGlobal = () => {
775
+ globalDragTargetsRef.current = [];
776
+ dispatch({
777
+ isDragGlobal: false,
778
+ type: "setDragGlobal"
779
+ });
780
+ };
781
+ document.addEventListener("dragenter", onDocumentDragEnter, false);
782
+ document.addEventListener("dragleave", onDocumentDragLeave, false);
783
+ document.addEventListener("dragend", onDocumentDragEnd, false);
784
+ document.addEventListener("drop", onDocumentDropGlobal, false);
785
+ return () => {
786
+ document.removeEventListener("dragenter", onDocumentDragEnter);
787
+ document.removeEventListener("dragleave", onDocumentDragLeave);
788
+ document.removeEventListener("dragend", onDocumentDragEnd);
789
+ document.removeEventListener("drop", onDocumentDropGlobal);
790
+ };
791
+ }, [rootRef]);
792
+ React.useEffect(() => {
793
+ if (!disabled && autoFocus && rootRef.current) rootRef.current.focus();
794
+ return () => {};
795
+ }, [
796
+ rootRef,
797
+ autoFocus,
798
+ disabled
799
+ ]);
800
+ const onErrCb = React.useCallback((e) => {
801
+ if (onError) onError(e);
802
+ else console.error(e);
803
+ }, [onError]);
804
+ const onDragEnterCb = React.useCallback((event) => {
805
+ event.preventDefault();
806
+ event.persist?.();
807
+ stopPropagation(event);
808
+ if (isFileDialogActiveRef.current) return;
809
+ dragTargetsRef.current = [...dragTargetsRef.current, event.target];
810
+ if (isEvtWithFiles(event)) Promise.resolve(getFilesFromEvent(event)).then((files) => {
811
+ if (isPropagationStopped(event) && !noDragEventsBubbling) return;
812
+ const evaluation = files.length > 0 ? evaluateDragFiles({
813
+ files,
814
+ accept: acceptAttr,
815
+ minSize,
816
+ maxSize,
817
+ multiple,
818
+ maxFiles,
819
+ validator,
820
+ getErrorMessage
821
+ }) : null;
822
+ dispatch({
823
+ isDragAccept: evaluation?.verdict === "accept",
824
+ isDragReject: evaluation?.verdict === "reject",
825
+ isDragUnknown: evaluation?.verdict === "unknown",
826
+ isDragActive: true,
827
+ dragFileRejections: evaluation?.rejections ?? [],
828
+ type: "setDraggedFiles"
829
+ });
830
+ if (onDragEnter) onDragEnter(event);
831
+ }).catch((e) => onErrCb(e));
832
+ }, [
833
+ getFilesFromEvent,
834
+ onDragEnter,
835
+ onErrCb,
836
+ noDragEventsBubbling,
837
+ acceptAttr,
838
+ minSize,
839
+ maxSize,
840
+ multiple,
841
+ maxFiles,
842
+ validator,
843
+ getErrorMessage
844
+ ]);
845
+ const onDragOverCb = React.useCallback((event) => {
846
+ event.preventDefault();
847
+ event.persist?.();
848
+ stopPropagation(event);
849
+ if (isFileDialogActiveRef.current) return false;
850
+ const hasFiles = isEvtWithFiles(event);
851
+ if (hasFiles && event.dataTransfer) try {
852
+ event.dataTransfer.dropEffect = "copy";
853
+ } catch {}
854
+ if (hasFiles && onDragOver) onDragOver(event);
855
+ return false;
856
+ }, [onDragOver, noDragEventsBubbling]);
857
+ const onDragLeaveCb = React.useCallback((event) => {
858
+ event.preventDefault();
859
+ event.persist?.();
860
+ stopPropagation(event);
861
+ const targets = dragTargetsRef.current.filter((target) => rootRef.current?.contains(target));
862
+ const targetIdx = targets.indexOf(event.target);
863
+ if (targetIdx !== -1) targets.splice(targetIdx, 1);
864
+ dragTargetsRef.current = targets;
865
+ if (targets.length > 0) return;
866
+ dispatch({
867
+ type: "setDraggedFiles",
868
+ isDragActive: false,
869
+ isDragAccept: false,
870
+ isDragReject: false,
871
+ isDragUnknown: false,
872
+ dragFileRejections: []
873
+ });
874
+ if (isEvtWithFiles(event) && onDragLeave) onDragLeave(event);
875
+ }, [
876
+ rootRef,
877
+ onDragLeave,
878
+ noDragEventsBubbling
879
+ ]);
880
+ const setFiles = React.useCallback(async (files, event, signal) => {
881
+ const localizeError = (error, file) => getErrorMessage ? {
882
+ ...error,
883
+ message: getErrorMessage(error, file)
884
+ } : error;
885
+ const commit = (results) => {
886
+ const acceptedFiles = [];
887
+ const fileRejections = [];
888
+ results.forEach(({ file, accepted, acceptError, sizeMatch, sizeError, customErrors }) => {
889
+ const valid = !customErrors || Array.isArray(customErrors) && customErrors.length === 0;
890
+ if (accepted && sizeMatch && valid) acceptedFiles.push(file);
891
+ else {
892
+ let errors = [acceptError, sizeError];
893
+ if (customErrors) errors = errors.concat(customErrors);
894
+ fileRejections.push({
895
+ file,
896
+ errors: errors.filter((e) => e != null).map((error) => localizeError(error, file))
897
+ });
898
+ }
899
+ });
900
+ const acceptedFilesLimit = multiple ? maxFiles >= 1 ? maxFiles : Number.POSITIVE_INFINITY : 1;
901
+ if (acceptedFiles.length > acceptedFilesLimit) acceptedFiles.splice(acceptedFilesLimit).forEach((file) => {
902
+ fileRejections.push({
903
+ file,
904
+ errors: [localizeError(TOO_MANY_FILES_REJECTION, file)]
905
+ });
906
+ });
907
+ dispatch({
908
+ acceptedFiles,
909
+ fileRejections,
910
+ type: "setFiles"
911
+ });
912
+ if (onDrop) onDrop(acceptedFiles, fileRejections, event);
913
+ if (fileRejections.length > 0 && onDropRejected) onDropRejected(fileRejections, event);
914
+ if (acceptedFiles.length > 0 && onDropAccepted) onDropAccepted(acceptedFiles, event);
915
+ };
916
+ const pending = files.map((file) => {
917
+ const [accepted, acceptError] = fileAccepted(file, inputAcceptAttr);
918
+ const [sizeMatch, sizeError] = fileMatchSize(file, minSize, maxSize);
919
+ return {
920
+ file,
921
+ accepted,
922
+ acceptError,
923
+ sizeMatch,
924
+ sizeError,
925
+ customErrors: validator ? validator(file) : null
926
+ };
927
+ });
928
+ if (!pending.some(({ customErrors }) => isThenable(customErrors))) {
929
+ commit(pending);
930
+ return;
931
+ }
932
+ let results;
933
+ try {
934
+ results = await Promise.all(pending.map(async ({ customErrors, ...rest }) => ({
935
+ ...rest,
936
+ customErrors: await customErrors
937
+ })));
938
+ } catch (e) {
939
+ if (!signal.aborted) {
940
+ endProcessing(signal);
941
+ onErrCb(e);
942
+ }
943
+ return;
944
+ }
945
+ if (signal.aborted) return;
946
+ commit(results);
947
+ }, [
948
+ dispatch,
949
+ multiple,
950
+ inputAcceptAttr,
951
+ minSize,
952
+ maxSize,
953
+ maxFiles,
954
+ onDrop,
955
+ onDropAccepted,
956
+ onDropRejected,
957
+ validator,
958
+ getErrorMessage,
959
+ onErrCb,
960
+ endProcessing
961
+ ]);
962
+ const onDropCb = React.useCallback((event) => {
963
+ event.preventDefault();
964
+ event.persist?.();
965
+ stopPropagation(event);
966
+ dragTargetsRef.current = [];
967
+ if (isFileDialogActiveRef.current && event.dataTransfer) return;
968
+ dispatch({ type: "reset" });
969
+ if (isEvtWithFiles(event)) {
970
+ const signal = beginProcessing();
971
+ Promise.resolve(getFilesFromEvent(event)).then((files) => {
972
+ if (signal.aborted) return;
973
+ if (isPropagationStopped(event) && !noDragEventsBubbling) {
974
+ endProcessing(signal);
975
+ return;
976
+ }
977
+ return setFiles(files, event, signal);
978
+ }).catch((e) => {
979
+ if (!signal.aborted) {
980
+ endProcessing(signal);
981
+ onErrCb(e);
982
+ }
983
+ });
984
+ }
985
+ }, [
986
+ getFilesFromEvent,
987
+ setFiles,
988
+ onErrCb,
989
+ noDragEventsBubbling,
990
+ beginProcessing,
991
+ endProcessing
992
+ ]);
993
+ const onPasteCb = React.useCallback((event) => {
994
+ if (!isEvtWithFiles(event)) return;
995
+ event.preventDefault();
996
+ event.persist?.();
997
+ stopPropagation(event);
998
+ const signal = beginProcessing();
999
+ Promise.resolve(getFilesFromEvent(event)).then((files) => {
1000
+ if (signal.aborted) return;
1001
+ if (isPropagationStopped(event) && !noDragEventsBubbling) {
1002
+ endProcessing(signal);
1003
+ return;
1004
+ }
1005
+ return setFiles(files, event, signal);
1006
+ }).catch((e) => {
1007
+ if (!signal.aborted) {
1008
+ endProcessing(signal);
1009
+ onErrCb(e);
1010
+ }
1011
+ });
1012
+ }, [
1013
+ getFilesFromEvent,
1014
+ setFiles,
1015
+ onErrCb,
1016
+ noDragEventsBubbling,
1017
+ beginProcessing,
1018
+ endProcessing
1019
+ ]);
1020
+ const openFileDialog = React.useCallback(() => {
1021
+ if (fsAccessApiWorksRef.current) {
1022
+ dispatch({ type: "openDialog" });
1023
+ onFileDialogOpenCb();
1024
+ const opts = {
1025
+ multiple,
1026
+ types: pickerTypes
1027
+ };
1028
+ let signal;
1029
+ window.showOpenFilePicker(opts).then((handles) => {
1030
+ signal = beginProcessing();
1031
+ return getFilesFromEvent(handles);
1032
+ }).then((files) => {
1033
+ dispatch({ type: "closeDialog" });
1034
+ if (signal.aborted) return;
1035
+ return setFiles(files, null, signal);
1036
+ }).catch((e) => {
1037
+ if (signal) endProcessing(signal);
1038
+ if (isAbort(e)) {
1039
+ onFileDialogCancelCb(e);
1040
+ dispatch({ type: "closeDialog" });
1041
+ } else if (isSecurityError(e) || isNotAllowedError(e)) {
1042
+ fsAccessApiWorksRef.current = false;
1043
+ if (inputRef.current) {
1044
+ inputRef.current.value = "";
1045
+ inputRef.current.click();
1046
+ } else onErrCb(/* @__PURE__ */ 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."));
1047
+ } else onErrCb(e);
1048
+ });
1049
+ return;
1050
+ }
1051
+ if (inputRef.current) {
1052
+ dispatch({ type: "openDialog" });
1053
+ onFileDialogOpenCb();
1054
+ inputRef.current.value = "";
1055
+ inputRef.current.click();
1056
+ }
1057
+ }, [
1058
+ dispatch,
1059
+ onFileDialogOpenCb,
1060
+ onFileDialogCancelCb,
1061
+ useFsAccessApi,
1062
+ setFiles,
1063
+ onErrCb,
1064
+ pickerTypes,
1065
+ multiple,
1066
+ beginProcessing,
1067
+ endProcessing
1068
+ ]);
1069
+ const onKeyDownCb = React.useCallback((event) => {
1070
+ if (!rootRef.current?.isEqualNode(event.target)) return;
1071
+ if (event.key === " " || event.key === "Enter" || event.keyCode === 32 || event.keyCode === 13) {
1072
+ event.preventDefault();
1073
+ openFileDialog();
1074
+ }
1075
+ }, [rootRef, openFileDialog]);
1076
+ const onFocusCb = React.useCallback(() => {
1077
+ dispatch({ type: "focus" });
1078
+ }, []);
1079
+ const onBlurCb = React.useCallback(() => {
1080
+ dispatch({ type: "blur" });
1081
+ }, []);
1082
+ const onClickCb = React.useCallback(() => {
1083
+ if (noClick) return;
1084
+ if (isIeOrEdge()) setTimeout(openFileDialog, 0);
1085
+ else openFileDialog();
1086
+ }, [noClick, openFileDialog]);
1087
+ const composeHandler = (fn) => {
1088
+ return disabled ? null : fn;
1089
+ };
1090
+ const composeKeyboardHandler = (fn) => {
1091
+ return noKeyboard ? null : composeHandler(fn);
1092
+ };
1093
+ const composeDragHandler = (fn) => {
1094
+ return noDrag ? null : composeHandler(fn);
1095
+ };
1096
+ const composePasteHandler = (fn) => {
1097
+ return noPaste ? null : composeHandler(fn);
1098
+ };
1099
+ const stopPropagation = (event) => {
1100
+ if (noDragEventsBubbling) event.stopPropagation();
1101
+ };
1102
+ const getRootProps = React.useMemo(() => ({ refKey = "ref", role, onKeyDown, onFocus, onBlur, onClick, onDragEnter, onDragOver, onDragLeave, onDrop, onPaste, ...rest } = {}) => ({
1103
+ onKeyDown: composeKeyboardHandler(composeEventHandlers(onKeyDown, onKeyDownCb)),
1104
+ onFocus: composeKeyboardHandler(composeEventHandlers(onFocus, onFocusCb)),
1105
+ onBlur: composeKeyboardHandler(composeEventHandlers(onBlur, onBlurCb)),
1106
+ onClick: composeHandler(composeEventHandlers(onClick, onClickCb)),
1107
+ onDragEnter: composeDragHandler(composeEventHandlers(onDragEnter, onDragEnterCb)),
1108
+ onDragOver: composeDragHandler(composeEventHandlers(onDragOver, onDragOverCb)),
1109
+ onDragLeave: composeDragHandler(composeEventHandlers(onDragLeave, onDragLeaveCb)),
1110
+ onDrop: composeDragHandler(composeEventHandlers(onDrop, onDropCb)),
1111
+ onPaste: composePasteHandler(composeEventHandlers(onPaste, onPasteCb)),
1112
+ role: typeof role === "string" && role !== "" ? role : "presentation",
1113
+ [refKey]: rootRef,
1114
+ ...!disabled && !noKeyboard ? { tabIndex: 0 } : {},
1115
+ ...disabled ? { "aria-disabled": true } : {},
1116
+ ...rest
1117
+ }), [
1118
+ rootRef,
1119
+ onKeyDownCb,
1120
+ onFocusCb,
1121
+ onBlurCb,
1122
+ onClickCb,
1123
+ onDragEnterCb,
1124
+ onDragOverCb,
1125
+ onDragLeaveCb,
1126
+ onDropCb,
1127
+ onPasteCb,
1128
+ noKeyboard,
1129
+ noDrag,
1130
+ noPaste,
1131
+ disabled
1132
+ ]);
1133
+ const onInputElementClick = React.useCallback((event) => {
1134
+ event.stopPropagation();
1135
+ }, []);
1136
+ const getInputProps = React.useMemo(() => ({ refKey = "ref", onChange, onClick, ...rest } = {}) => {
1137
+ return {
1138
+ accept: inputAcceptAttr,
1139
+ multiple,
1140
+ type: "file",
1141
+ "aria-label": "file upload",
1142
+ style: {
1143
+ border: 0,
1144
+ display: "block",
1145
+ height: 0,
1146
+ margin: 0,
1147
+ opacity: 0,
1148
+ overflow: "hidden",
1149
+ padding: 0,
1150
+ width: 0
1151
+ },
1152
+ onChange: composeHandler(composeEventHandlers(onChange, onDropCb)),
1153
+ onClick: composeHandler(composeEventHandlers(onClick, onInputElementClick)),
1154
+ tabIndex: -1,
1155
+ [refKey]: inputRef,
1156
+ ...rest
1157
+ };
1158
+ }, [
1159
+ inputRef,
1160
+ accept,
1161
+ multiple,
1162
+ onDropCb,
1163
+ disabled
1164
+ ]);
1165
+ return {
1166
+ ...state,
1167
+ isFocused: isFocused && !disabled,
1168
+ getRootProps,
1169
+ getInputProps,
1170
+ rootRef,
1171
+ inputRef,
1172
+ open: composeHandler(openFileDialog)
1173
+ };
1393
1174
  }
1394
-
1395
1175
  function reducer(state, action) {
1396
- /* istanbul ignore next */
1397
- switch (action.type) {
1398
- case 'focus':
1399
- return _objectSpread(_objectSpread({}, state), {}, {
1400
- isFocused: true
1401
- });
1402
-
1403
- case 'blur':
1404
- return _objectSpread(_objectSpread({}, state), {}, {
1405
- isFocused: false
1406
- });
1407
-
1408
- case 'openDialog':
1409
- return _objectSpread(_objectSpread({}, initialState), {}, {
1410
- isFileDialogActive: true
1411
- });
1412
-
1413
- case 'closeDialog':
1414
- return _objectSpread(_objectSpread({}, state), {}, {
1415
- isFileDialogActive: false
1416
- });
1417
-
1418
- case 'setDraggedFiles':
1419
- /* eslint no-case-declarations: 0 */
1420
- var isDragActive = action.isDragActive,
1421
- draggedFiles = action.draggedFiles;
1422
- return _objectSpread(_objectSpread({}, state), {}, {
1423
- draggedFiles: draggedFiles,
1424
- isDragActive: isDragActive
1425
- });
1426
-
1427
- case 'setFiles':
1428
- return _objectSpread(_objectSpread({}, state), {}, {
1429
- acceptedFiles: action.acceptedFiles,
1430
- fileRejections: action.fileRejections
1431
- });
1432
-
1433
- case 'reset':
1434
- return _objectSpread({}, initialState);
1435
-
1436
- default:
1437
- return state;
1438
- }
1176
+ switch (action.type) {
1177
+ case "focus": return {
1178
+ ...state,
1179
+ isFocused: true
1180
+ };
1181
+ case "blur": return {
1182
+ ...state,
1183
+ isFocused: false
1184
+ };
1185
+ case "openDialog": return {
1186
+ ...initialState,
1187
+ isFileDialogActive: true
1188
+ };
1189
+ case "closeDialog": return {
1190
+ ...state,
1191
+ isFileDialogActive: false
1192
+ };
1193
+ case "setDraggedFiles": return {
1194
+ ...state,
1195
+ isDragActive: action.isDragActive,
1196
+ isDragAccept: action.isDragAccept,
1197
+ isDragReject: action.isDragReject,
1198
+ isDragUnknown: action.isDragUnknown,
1199
+ dragFileRejections: action.dragFileRejections
1200
+ };
1201
+ case "setProcessing": return {
1202
+ ...state,
1203
+ isProcessing: action.isProcessing
1204
+ };
1205
+ case "setFiles": return {
1206
+ ...state,
1207
+ acceptedFiles: action.acceptedFiles,
1208
+ fileRejections: action.fileRejections,
1209
+ dragFileRejections: [],
1210
+ isProcessing: false,
1211
+ isDragReject: false,
1212
+ isDragUnknown: false
1213
+ };
1214
+ case "setDragGlobal": return {
1215
+ ...state,
1216
+ isDragGlobal: action.isDragGlobal
1217
+ };
1218
+ case "reset": return { ...initialState };
1219
+ default: return state;
1220
+ }
1439
1221
  }
1440
-
1441
1222
  function noop() {}
1442
1223
 
1443
1224
  var styles = {"dropZoneBase":"fSDkYM-382I-","dropZone":"yT6m1v71VK8-","active":"fCb0O1wAjR0-","error":"Cm5wIem0XQI-","validationErrors":"wyjYhAlF1qA-","dropzoneContent":"sAxF04DcAi4-"};
@@ -1534,38 +1315,46 @@ function InputFileValidationErrors({ validationErrors, }) {
1534
1315
  if (validationErrors.length === 0) {
1535
1316
  return null;
1536
1317
  }
1537
- return (React.createElement("div", { className: styles.validationErrors }, validationErrors.map(error => (React.createElement(InputValidation.InputValidation, { message: error.message, key: error.code })))));
1318
+ return (React.createElement("div", { className: styles.validationErrors }, validationErrors.map((error, index) => (React.createElement(InputValidation.InputValidation, { message: error.message, key: `${error.code}-${index}` })))));
1538
1319
  }
1539
1320
 
1321
+ const inputFileMessages = useAtlantisI18n.defineMessages({
1322
+ fileLimit: {
1323
+ en: {
1324
+ one: "Cannot exceed a maximum of {count} file.",
1325
+ other: "Cannot exceed a maximum of {count} files.",
1326
+ },
1327
+ es: {
1328
+ one: "No se puede superar el máximo de {count} archivo.",
1329
+ other: "No se puede superar el máximo de {count} archivos.",
1330
+ },
1331
+ },
1332
+ uploadFile: {
1333
+ en: "Upload file",
1334
+ es: "Subir archivo",
1335
+ },
1336
+ });
1337
+
1540
1338
  /* eslint-disable max-statements */
1541
1339
  function InputFile({ variation = "dropzone", size = "base", name, buttonLabel: providedButtonLabel, allowMultiple = false, allowedTypes = "all", description, hintText, maxFilesValidation, getUploadParams, onUploadStart, onUploadProgress, onUploadComplete, onUploadError, validator, children, }) {
1340
+ const { t, plural } = useAtlantisI18n.useAtlantisI18n(inputFileMessages);
1542
1341
  const maxFiles = (maxFilesValidation === null || maxFilesValidation === void 0 ? void 0 : maxFilesValidation.maxFiles) || 0;
1543
1342
  const numberOfCurrentFiles = (maxFilesValidation === null || maxFilesValidation === void 0 ? void 0 : maxFilesValidation.numberOfCurrentFiles) || 0;
1544
- const handleValidation = React.useCallback((file) => {
1545
- if (maxFiles &&
1546
- numberOfCurrentFiles &&
1547
- maxFiles - numberOfCurrentFiles <= 0) {
1548
- return {
1549
- code: "too-many-files",
1550
- message: `Cannot exceed a maximum of ${maxFiles} files.`,
1551
- };
1552
- }
1553
- return validator ? validator(file) : null;
1554
- }, [maxFiles, numberOfCurrentFiles, validator]);
1343
+ const [limitError, setLimitError] = React.useState();
1555
1344
  const options = {
1556
- multiple: allowMultiple,
1557
- maxFiles: maxFiles - numberOfCurrentFiles,
1558
- onDrop: React.useCallback(handleDrop, [uploadFile]),
1559
- validator: handleValidation,
1345
+ // InputFile applies count limits after per-file validation, including single-file drops.
1346
+ multiple: true,
1347
+ onDrop: handleDrop,
1348
+ validator,
1560
1349
  };
1561
1350
  if (allowedTypes === "images") {
1562
- options.accept = "image/*";
1351
+ options.accept = { "image/*": [] };
1563
1352
  }
1564
1353
  else if (allowedTypes === "basicImages") {
1565
- options.accept = convertToMimeTypes(BASIC_IMAGE_TYPES).join(",");
1354
+ options.accept = mimeTypesToAccept(convertToMimeTypes(BASIC_IMAGE_TYPES));
1566
1355
  }
1567
1356
  else if (Array.isArray(allowedTypes)) {
1568
- options.accept = convertToMimeTypes(allowedTypes).join(",");
1357
+ options.accept = mimeTypesToAccept(convertToMimeTypes(allowedTypes));
1569
1358
  }
1570
1359
  const { getRootProps, getInputProps, isDragActive, fileRejections } = useDropzone(options);
1571
1360
  const allowedTypesString = Array.isArray(allowedTypes)
@@ -1573,15 +1362,7 @@ function InputFile({ variation = "dropzone", size = "base", name, buttonLabel: p
1573
1362
  : allowedTypes;
1574
1363
  const validationErrors = fileRejections === null || fileRejections === void 0 ? void 0 : fileRejections.reduce((acc, { file, errors }) => {
1575
1364
  errors.forEach(error => {
1576
- if (error.code === "too-many-files") {
1577
- if (!acc.some(e => e.code === "too-many-files")) {
1578
- acc.push({
1579
- code: "too-many-files",
1580
- message: `Cannot exceed a maximum of ${maxFiles} files.`,
1581
- });
1582
- }
1583
- }
1584
- else if (error.code === "file-invalid-type") {
1365
+ if (error.code === "file-invalid-type") {
1585
1366
  let formatMessage;
1586
1367
  if (allowedTypes === "basicImages") {
1587
1368
  formatMessage = formatMimeTypes(BASIC_IMAGE_TYPES.map(mimeTypeToReadable));
@@ -1609,10 +1390,12 @@ function InputFile({ variation = "dropzone", size = "base", name, buttonLabel: p
1609
1390
  });
1610
1391
  return acc;
1611
1392
  }, []);
1393
+ if (limitError)
1394
+ validationErrors.push(limitError);
1612
1395
  const dropZone = classnames(styles.dropZoneBase, {
1613
1396
  [styles.dropZone]: variation === "dropzone",
1614
1397
  [styles.active]: isDragActive,
1615
- [styles.error]: (fileRejections === null || fileRejections === void 0 ? void 0 : fileRejections.length) > 0,
1398
+ [styles.error]: validationErrors.length > 0,
1616
1399
  });
1617
1400
  const fileType = allowedTypes === "images" || allowedTypes === "basicImages"
1618
1401
  ? "Image"
@@ -1634,11 +1417,27 @@ function InputFile({ variation = "dropzone", size = "base", name, buttonLabel: p
1634
1417
  React.createElement(InputFile.Description, null)))))),
1635
1418
  variation === "button" && React.createElement(InputFile.Button, { fullWidth: true })));
1636
1419
  return (React.createElement(React.Fragment, null,
1637
- React.createElement("div", Object.assign({}, getRootProps({ className: dropZone }), { tabIndex: variation === "button" ? -1 : 0 }),
1638
- React.createElement("input", Object.assign({}, getInputProps(), { "data-testid": "input-file-input", name: name })),
1420
+ React.createElement("div", Object.assign({}, getRootProps({ className: dropZone, role: "button" }), { tabIndex: variation === "button" ? -1 : 0 }),
1421
+ React.createElement("input", Object.assign({}, getInputProps({
1422
+ multiple: allowMultiple,
1423
+ "aria-label": providedButtonLabel || t("uploadFile"),
1424
+ }), { "data-testid": "input-file-input", name: name })),
1639
1425
  React.createElement(InputFileContentContext.Provider, { value: contentContext }, children || defaultContent)),
1640
1426
  React.createElement(InputFileValidationErrors, { validationErrors: validationErrors })));
1641
1427
  function handleDrop(acceptedFiles) {
1428
+ const remainingCapacity = maxFiles > 0 ? Math.max(0, maxFiles - numberOfCurrentFiles) : Infinity;
1429
+ const capacity = allowMultiple
1430
+ ? remainingCapacity
1431
+ : Math.min(1, remainingCapacity);
1432
+ if (acceptedFiles.length > capacity) {
1433
+ const maximum = allowMultiple || remainingCapacity === 0 ? maxFiles : 1;
1434
+ setLimitError({
1435
+ code: "too-many-files",
1436
+ message: plural("fileLimit", maximum),
1437
+ });
1438
+ return;
1439
+ }
1440
+ setLimitError(undefined);
1642
1441
  acceptedFiles.forEach(file => {
1643
1442
  uploadFile(file);
1644
1443
  });
@@ -1683,6 +1482,9 @@ function InputFile({ variation = "dropzone", size = "base", name, buttonLabel: p
1683
1482
  });
1684
1483
  }
1685
1484
  }
1485
+ function mimeTypesToAccept(mimeTypes) {
1486
+ return Object.fromEntries(mimeTypes.map(mimeType => [mimeType, []]));
1487
+ }
1686
1488
  function createAxiosConfig({ url, httpMethod = "POST", fields = {}, file, handleUploadProgress, }) {
1687
1489
  let data;
1688
1490
  let headers;