dropzone
Version:
Handles drag and drop of files for you.
1,077 lines (1,065 loc) • 100 kB
JavaScript
import $ewBKy$justextend from "just-extend";
function $parcel$interopDefault(a) {
return a && a.__esModule ? a.default : a;
}
class $4040acfd8584338d$export$2e2bcd8739ae039 {
// Add an event listener for given event
on(event, fn) {
this._callbacks = this._callbacks || {
};
// Create namespace for this event
if (!this._callbacks[event]) this._callbacks[event] = [];
this._callbacks[event].push(fn);
return this;
}
emit(event, ...args) {
this._callbacks = this._callbacks || {
};
let callbacks = this._callbacks[event];
if (callbacks) for (let callback of callbacks)callback.apply(this, args);
// trigger a corresponding DOM event
if (this.element) this.element.dispatchEvent(this.makeEvent("dropzone:" + event, {
args: args
}));
return this;
}
makeEvent(eventName, detail) {
let params = {
bubbles: true,
cancelable: true,
detail: detail
};
if (typeof window.CustomEvent === "function") return new CustomEvent(eventName, params);
else {
// IE 11 support
// https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent
var evt = document.createEvent("CustomEvent");
evt.initCustomEvent(eventName, params.bubbles, params.cancelable, params.detail);
return evt;
}
}
// Remove event listener for given event. If fn is not provided, all event
// listeners for that event will be removed. If neither is provided, all
// event listeners will be removed.
off(event, fn) {
if (!this._callbacks || arguments.length === 0) {
this._callbacks = {
};
return this;
}
// specific event
let callbacks = this._callbacks[event];
if (!callbacks) return this;
// remove all handlers
if (arguments.length === 1) {
delete this._callbacks[event];
return this;
}
// remove specific handler
for(let i = 0; i < callbacks.length; i++){
let callback = callbacks[i];
if (callback === fn) {
callbacks.splice(i, 1);
break;
}
}
return this;
}
}
var $fd6031f88dce2e32$exports = {};
$fd6031f88dce2e32$exports = "<div class=\"dz-preview dz-file-preview\">\n <div class=\"dz-image\"><img data-dz-thumbnail=\"\"></div>\n <div class=\"dz-details\">\n <div class=\"dz-size\"><span data-dz-size=\"\"></span></div>\n <div class=\"dz-filename\"><span data-dz-name=\"\"></span></div>\n </div>\n <div class=\"dz-progress\">\n <span class=\"dz-upload\" data-dz-uploadprogress=\"\"></span>\n </div>\n <div class=\"dz-error-message\"><span data-dz-errormessage=\"\"></span></div>\n <div class=\"dz-success-mark\">\n <svg width=\"54\" height=\"54\" viewBox=\"0 0 54 54\" fill=\"white\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M10.2071 29.7929L14.2929 25.7071C14.6834 25.3166 15.3166 25.3166 15.7071 25.7071L21.2929 31.2929C21.6834 31.6834 22.3166 31.6834 22.7071 31.2929L38.2929 15.7071C38.6834 15.3166 39.3166 15.3166 39.7071 15.7071L43.7929 19.7929C44.1834 20.1834 44.1834 20.8166 43.7929 21.2071L22.7071 42.2929C22.3166 42.6834 21.6834 42.6834 21.2929 42.2929L10.2071 31.2071C9.81658 30.8166 9.81658 30.1834 10.2071 29.7929Z\"></path>\n </svg>\n </div>\n <div class=\"dz-error-mark\">\n <svg width=\"54\" height=\"54\" viewBox=\"0 0 54 54\" fill=\"white\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M26.2929 20.2929L19.2071 13.2071C18.8166 12.8166 18.1834 12.8166 17.7929 13.2071L13.2071 17.7929C12.8166 18.1834 12.8166 18.8166 13.2071 19.2071L20.2929 26.2929C20.6834 26.6834 20.6834 27.3166 20.2929 27.7071L13.2071 34.7929C12.8166 35.1834 12.8166 35.8166 13.2071 36.2071L17.7929 40.7929C18.1834 41.1834 18.8166 41.1834 19.2071 40.7929L26.2929 33.7071C26.6834 33.3166 27.3166 33.3166 27.7071 33.7071L34.7929 40.7929C35.1834 41.1834 35.8166 41.1834 36.2071 40.7929L40.7929 36.2071C41.1834 35.8166 41.1834 35.1834 40.7929 34.7929L33.7071 27.7071C33.3166 27.3166 33.3166 26.6834 33.7071 26.2929L40.7929 19.2071C41.1834 18.8166 41.1834 18.1834 40.7929 17.7929L36.2071 13.2071C35.8166 12.8166 35.1834 12.8166 34.7929 13.2071L27.7071 20.2929C27.3166 20.6834 26.6834 20.6834 26.2929 20.2929Z\"></path>\n </svg>\n </div>\n</div>\n";
let $4ca367182776f80b$var$defaultOptions = {
/**
* Has to be specified on elements other than form (or when the form doesn't
* have an `action` attribute).
*
* You can also provide a function that will be called with `files` and
* `dataBlocks` and must return the url as string.
*/ url: null,
/**
* Can be changed to `"put"` if necessary. You can also provide a function
* that will be called with `files` and must return the method (since `v3.12.0`).
*/ method: "post",
/**
* Will be set on the XHRequest.
*/ withCredentials: false,
/**
* The timeout for the XHR requests in milliseconds (since `v4.4.0`).
* If set to null or 0, no timeout is going to be set.
*/ timeout: null,
/**
* How many file uploads to process in parallel (See the
* Enqueuing file uploads documentation section for more info)
*/ parallelUploads: 2,
/**
* Whether to send multiple files in one request. If
* this it set to true, then the fallback file input element will
* have the `multiple` attribute as well. This option will
* also trigger additional events (like `processingmultiple`). See the events
* documentation section for more information.
*/ uploadMultiple: false,
/**
* Whether you want files to be uploaded in chunks to your server. This can't be
* used in combination with `uploadMultiple`.
*
* See [chunksUploaded](#config-chunksUploaded) for the callback to finalise an upload.
*/ chunking: false,
/**
* If `chunking` is enabled, this defines whether **every** file should be chunked,
* even if the file size is below chunkSize. This means, that the additional chunk
* form data will be submitted and the `chunksUploaded` callback will be invoked.
*/ forceChunking: false,
/**
* If `chunking` is `true`, then this defines the chunk size in bytes.
*/ chunkSize: 2097152,
/**
* If `true`, the individual chunks of a file are being uploaded simultaneously.
*/ parallelChunkUploads: false,
/**
* Whether a chunk should be retried if it fails.
*/ retryChunks: false,
/**
* If `retryChunks` is true, how many times should it be retried.
*/ retryChunksLimit: 3,
/**
* The maximum filesize (in MiB) that is allowed to be uploaded.
*/ maxFilesize: 256,
/**
* The name of the file param that gets transferred.
* **NOTE**: If you have the option `uploadMultiple` set to `true`, then
* Dropzone will append `[]` to the name.
*/ paramName: "file",
/**
* Whether thumbnails for images should be generated
*/ createImageThumbnails: true,
/**
* In MB. When the filename exceeds this limit, the thumbnail will not be generated.
*/ maxThumbnailFilesize: 10,
/**
* If `null`, the ratio of the image will be used to calculate it.
*/ thumbnailWidth: 120,
/**
* The same as `thumbnailWidth`. If both are null, images will not be resized.
*/ thumbnailHeight: 120,
/**
* How the images should be scaled down in case both, `thumbnailWidth` and `thumbnailHeight` are provided.
* Can be either `contain` or `crop`.
*/ thumbnailMethod: "crop",
/**
* If set, images will be resized to these dimensions before being **uploaded**.
* If only one, `resizeWidth` **or** `resizeHeight` is provided, the original aspect
* ratio of the file will be preserved.
*
* The `options.transformFile` function uses these options, so if the `transformFile` function
* is overridden, these options don't do anything.
*/ resizeWidth: null,
/**
* See `resizeWidth`.
*/ resizeHeight: null,
/**
* The mime type of the resized image (before it gets uploaded to the server).
* If `null` the original mime type will be used. To force jpeg, for example, use `image/jpeg`.
* See `resizeWidth` for more information.
*/ resizeMimeType: null,
/**
* The quality of the resized images. See `resizeWidth`.
*/ resizeQuality: 0.8,
/**
* How the images should be scaled down in case both, `resizeWidth` and `resizeHeight` are provided.
* Can be either `contain` or `crop`.
*/ resizeMethod: "contain",
/**
* The base that is used to calculate the **displayed** filesize. You can
* change this to 1024 if you would rather display kibibytes, mebibytes,
* etc... 1024 is technically incorrect, because `1024 bytes` are `1 kibibyte`
* not `1 kilobyte`. You can change this to `1024` if you don't care about
* validity.
*/ filesizeBase: 1000,
/**
* If not `null` defines how many files this Dropzone handles. If it exceeds,
* the event `maxfilesexceeded` will be called. The dropzone element gets the
* class `dz-max-files-reached` accordingly so you can provide visual
* feedback.
*/ maxFiles: null,
/**
* An optional object to send additional headers to the server. Eg:
* `{ "My-Awesome-Header": "header value" }`
*/ headers: null,
/**
* Should the default headers be set or not?
* Accept: application/json <- for requesting json response
* Cache-Control: no-cache <- Request shouldnt be cached
* X-Requested-With: XMLHttpRequest <- We sent the request via XMLHttpRequest
*/ defaultHeaders: true,
/**
* If `true`, the dropzone element itself will be clickable, if `false`
* nothing will be clickable.
*
* You can also pass an HTML element, a CSS selector (for multiple elements)
* or an array of those. In that case, all of those elements will trigger an
* upload when clicked.
*/ clickable: true,
/**
* Whether hidden files in directories should be ignored.
*/ ignoreHiddenFiles: true,
/**
* The default implementation of `accept` checks the file's mime type or
* extension against this list. This is a comma separated list of mime
* types or file extensions.
*
* Eg.: `image/*,application/pdf,.psd`
*
* If the Dropzone is `clickable` this option will also be used as
* [`accept`](https://developer.mozilla.org/en-US/docs/HTML/Element/input#attr-accept)
* parameter on the hidden file input as well.
*/ acceptedFiles: null,
/**
* **Deprecated!**
* Use acceptedFiles instead.
*/ acceptedMimeTypes: null,
/**
* If false, files will be added to the queue but the queue will not be
* processed automatically.
* This can be useful if you need some additional user input before sending
* files (or if you want want all files sent at once).
* If you're ready to send the file simply call `myDropzone.processQueue()`.
*
* See the [enqueuing file uploads](#enqueuing-file-uploads) documentation
* section for more information.
*/ autoProcessQueue: true,
/**
* If false, files added to the dropzone will not be queued by default.
* You'll have to call `enqueueFile(file)` manually.
*/ autoQueue: true,
/**
* If `true`, this will add a link to every file preview to remove or cancel (if
* already uploading) the file. The `dictCancelUpload`, `dictCancelUploadConfirmation`
* and `dictRemoveFile` options are used for the wording.
*/ addRemoveLinks: false,
/**
* Defines where to display the file previews – if `null` the
* Dropzone element itself is used. Can be a plain `HTMLElement` or a CSS
* selector. The element should have the `dropzone-previews` class so
* the previews are displayed properly.
*/ previewsContainer: null,
/**
* Set this to `true` if you don't want previews to be shown.
*/ disablePreviews: false,
/**
* This is the element the hidden input field (which is used when clicking on the
* dropzone to trigger file selection) will be appended to. This might
* be important in case you use frameworks to switch the content of your page.
*
* Can be a selector string, or an element directly.
*/ hiddenInputContainer: "body",
/**
* If null, no capture type will be specified
* If camera, mobile devices will skip the file selection and choose camera
* If microphone, mobile devices will skip the file selection and choose the microphone
* If camcorder, mobile devices will skip the file selection and choose the camera in video mode
* On apple devices multiple must be set to false. AcceptedFiles may need to
* be set to an appropriate mime type (e.g. "image/*", "audio/*", or "video/*").
*/ capture: null,
/**
* **Deprecated**. Use `renameFile` instead.
*/ renameFilename: null,
/**
* A function that is invoked before the file is uploaded to the server and renames the file.
* This function gets the `File` as argument and can use the `file.name`. The actual name of the
* file that gets used during the upload can be accessed through `file.upload.filename`.
*/ renameFile: null,
/**
* If `true` the fallback will be forced. This is very useful to test your server
* implementations first and make sure that everything works as
* expected without dropzone if you experience problems, and to test
* how your fallbacks will look.
*/ forceFallback: false,
/**
* The text used before any files are dropped.
*/ dictDefaultMessage: "Drop files here to upload",
/**
* The text that replaces the default message text it the browser is not supported.
*/ dictFallbackMessage: "Your browser does not support drag'n'drop file uploads.",
/**
* The text that will be added before the fallback form.
* If you provide a fallback element yourself, or if this option is `null` this will
* be ignored.
*/ dictFallbackText: "Please use the fallback form below to upload your files like in the olden days.",
/**
* If the filesize is too big.
* `{{filesize}}` and `{{maxFilesize}}` will be replaced with the respective configuration values.
*/ dictFileTooBig: "File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.",
/**
* If the file doesn't match the file type.
*/ dictInvalidFileType: "You can't upload files of this type.",
/**
* If the server response was invalid.
* `{{statusCode}}` will be replaced with the servers status code.
*/ dictResponseError: "Server responded with {{statusCode}} code.",
/**
* If `addRemoveLinks` is true, the text to be used for the cancel upload link.
*/ dictCancelUpload: "Cancel upload",
/**
* The text that is displayed if an upload was manually canceled
*/ dictUploadCanceled: "Upload canceled.",
/**
* If `addRemoveLinks` is true, the text to be used for confirmation when cancelling upload.
*/ dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?",
/**
* If `addRemoveLinks` is true, the text to be used to remove a file.
*/ dictRemoveFile: "Remove file",
/**
* If this is not null, then the user will be prompted before removing a file.
*/ dictRemoveFileConfirmation: null,
/**
* Displayed if `maxFiles` is st and exceeded.
* The string `{{maxFiles}}` will be replaced by the configuration value.
*/ dictMaxFilesExceeded: "You can not upload any more files.",
/**
* Allows you to translate the different units. Starting with `tb` for terabytes and going down to
* `b` for bytes.
*/ dictFileSizeUnits: {
tb: "TB",
gb: "GB",
mb: "MB",
kb: "KB",
b: "b"
},
/**
* Called when dropzone initialized
* You can add event listeners here
*/ init () {
},
/**
* Can be an **object** of additional parameters to transfer to the server, **or** a `Function`
* that gets invoked with the `files`, `xhr` and, if it's a chunked upload, `chunk` arguments. In case
* of a function, this needs to return a map.
*
* The default implementation does nothing for normal uploads, but adds relevant information for
* chunked uploads.
*
* This is the same as adding hidden input fields in the form element.
*/ params (files, xhr, chunk) {
if (chunk) return {
dzuuid: chunk.file.upload.uuid,
dzchunkindex: chunk.index,
dztotalfilesize: chunk.file.size,
dzchunksize: this.options.chunkSize,
dztotalchunkcount: chunk.file.upload.totalChunkCount,
dzchunkbyteoffset: chunk.index * this.options.chunkSize
};
},
/**
* A function that gets a [file](https://developer.mozilla.org/en-US/docs/DOM/File)
* and a `done` function as parameters.
*
* If the done function is invoked without arguments, the file is "accepted" and will
* be processed. If you pass an error message, the file is rejected, and the error
* message will be displayed.
* This function will not be called if the file is too big or doesn't match the mime types.
*/ accept (file, done) {
return done();
},
/**
* The callback that will be invoked when all chunks have been uploaded for a file.
* It gets the file for which the chunks have been uploaded as the first parameter,
* and the `done` function as second. `done()` needs to be invoked when everything
* needed to finish the upload process is done.
*/ chunksUploaded: function(file, done) {
done();
},
/**
* Sends the file as binary blob in body instead of form data.
* If this is set, the `params` option will be ignored.
* It's an error to set this to `true` along with `uploadMultiple` since
* multiple files cannot be in a single binary body.
*/ binaryBody: false,
/**
* Gets called when the browser is not supported.
* The default implementation shows the fallback input field and adds
* a text.
*/ fallback () {
// This code should pass in IE7... :(
let messageElement;
this.element.className = `${this.element.className} dz-browser-not-supported`;
for (let child of this.element.getElementsByTagName("div"))if (/(^| )dz-message($| )/.test(child.className)) {
messageElement = child;
child.className = "dz-message"; // Removes the 'dz-default' class
break;
}
if (!messageElement) {
messageElement = $3ed269f2f0fb224b$export$2e2bcd8739ae039.createElement('<div class="dz-message"><span></span></div>');
this.element.appendChild(messageElement);
}
let span = messageElement.getElementsByTagName("span")[0];
if (span) {
if (span.textContent != null) span.textContent = this.options.dictFallbackMessage;
else if (span.innerText != null) span.innerText = this.options.dictFallbackMessage;
}
return this.element.appendChild(this.getFallbackForm());
},
/**
* Gets called to calculate the thumbnail dimensions.
*
* It gets `file`, `width` and `height` (both may be `null`) as parameters and must return an object containing:
*
* - `srcWidth` & `srcHeight` (required)
* - `trgWidth` & `trgHeight` (required)
* - `srcX` & `srcY` (optional, default `0`)
* - `trgX` & `trgY` (optional, default `0`)
*
* Those values are going to be used by `ctx.drawImage()`.
*/ resize (file, width, height, resizeMethod) {
let info = {
srcX: 0,
srcY: 0,
srcWidth: file.width,
srcHeight: file.height
};
let srcRatio = file.width / file.height;
// Automatically calculate dimensions if not specified
if (width == null && height == null) {
width = info.srcWidth;
height = info.srcHeight;
} else if (width == null) width = height * srcRatio;
else if (height == null) height = width / srcRatio;
// Make sure images aren't upscaled
width = Math.min(width, info.srcWidth);
height = Math.min(height, info.srcHeight);
let trgRatio = width / height;
if (info.srcWidth > width || info.srcHeight > height) {
// Image is bigger and needs rescaling
if (resizeMethod === "crop") {
if (srcRatio > trgRatio) {
info.srcHeight = file.height;
info.srcWidth = info.srcHeight * trgRatio;
} else {
info.srcWidth = file.width;
info.srcHeight = info.srcWidth / trgRatio;
}
} else if (resizeMethod === "contain") {
// Method 'contain'
if (srcRatio > trgRatio) height = width / srcRatio;
else width = height * srcRatio;
} else throw new Error(`Unknown resizeMethod '${resizeMethod}'`);
}
info.srcX = (file.width - info.srcWidth) / 2;
info.srcY = (file.height - info.srcHeight) / 2;
info.trgWidth = width;
info.trgHeight = height;
return info;
},
/**
* Can be used to transform the file (for example, resize an image if necessary).
*
* The default implementation uses `resizeWidth` and `resizeHeight` (if provided) and resizes
* images according to those dimensions.
*
* Gets the `file` as the first parameter, and a `done()` function as the second, that needs
* to be invoked with the file when the transformation is done.
*/ transformFile (file, done) {
if ((this.options.resizeWidth || this.options.resizeHeight) && file.type.match(/image.*/)) return this.resizeImage(file, this.options.resizeWidth, this.options.resizeHeight, this.options.resizeMethod, done);
else return done(file);
},
/**
* A string that contains the template used for each dropped
* file. Change it to fulfill your needs but make sure to properly
* provide all elements.
*
* If you want to use an actual HTML element instead of providing a String
* as a config option, you could create a div with the id `tpl`,
* put the template inside it and provide the element like this:
*
* document
* .querySelector('#tpl')
* .innerHTML
*
*/ previewTemplate: (/*@__PURE__*/$parcel$interopDefault($fd6031f88dce2e32$exports)),
/*
Those functions register themselves to the events on init and handle all
the user interface specific stuff. Overwriting them won't break the upload
but can break the way it's displayed.
You can overwrite them if you don't like the default behavior. If you just
want to add an additional event handler, register it on the dropzone object
and don't overwrite those options.
*/ // Those are self explanatory and simply concern the DragnDrop.
drop (e) {
return this.element.classList.remove("dz-drag-hover");
},
dragstart (e) {
},
dragend (e) {
return this.element.classList.remove("dz-drag-hover");
},
dragenter (e) {
return this.element.classList.add("dz-drag-hover");
},
dragover (e) {
return this.element.classList.add("dz-drag-hover");
},
dragleave (e) {
return this.element.classList.remove("dz-drag-hover");
},
paste (e) {
},
// Called whenever there are no files left in the dropzone anymore, and the
// dropzone should be displayed as if in the initial state.
reset () {
return this.element.classList.remove("dz-started");
},
// Called when a file is added to the queue
// Receives `file`
addedfile (file) {
if (this.element === this.previewsContainer) this.element.classList.add("dz-started");
if (this.previewsContainer && !this.options.disablePreviews) {
file.previewElement = $3ed269f2f0fb224b$export$2e2bcd8739ae039.createElement(this.options.previewTemplate.trim());
file.previewTemplate = file.previewElement; // Backwards compatibility
this.previewsContainer.appendChild(file.previewElement);
for (var node of file.previewElement.querySelectorAll("[data-dz-name]"))node.textContent = file.name;
for (node of file.previewElement.querySelectorAll("[data-dz-size]"))node.innerHTML = this.filesize(file.size);
if (this.options.addRemoveLinks) {
file._removeLink = $3ed269f2f0fb224b$export$2e2bcd8739ae039.createElement(`<a class="dz-remove" href="javascript:undefined;" data-dz-remove>${this.options.dictRemoveFile}</a>`);
file.previewElement.appendChild(file._removeLink);
}
let removeFileEvent = (e)=>{
e.preventDefault();
e.stopPropagation();
if (file.status === $3ed269f2f0fb224b$export$2e2bcd8739ae039.UPLOADING) return $3ed269f2f0fb224b$export$2e2bcd8739ae039.confirm(this.options.dictCancelUploadConfirmation, ()=>this.removeFile(file)
);
else {
if (this.options.dictRemoveFileConfirmation) return $3ed269f2f0fb224b$export$2e2bcd8739ae039.confirm(this.options.dictRemoveFileConfirmation, ()=>this.removeFile(file)
);
else return this.removeFile(file);
}
};
for (let removeLink of file.previewElement.querySelectorAll("[data-dz-remove]"))removeLink.addEventListener("click", removeFileEvent);
}
},
// Called whenever a file is removed.
removedfile (file) {
if (file.previewElement != null && file.previewElement.parentNode != null) file.previewElement.parentNode.removeChild(file.previewElement);
return this._updateMaxFilesReachedClass();
},
// Called when a thumbnail has been generated
// Receives `file` and `dataUrl`
thumbnail (file, dataUrl) {
if (file.previewElement) {
file.previewElement.classList.remove("dz-file-preview");
for (let thumbnailElement of file.previewElement.querySelectorAll("[data-dz-thumbnail]")){
thumbnailElement.alt = file.name;
thumbnailElement.src = dataUrl;
}
return setTimeout(()=>file.previewElement.classList.add("dz-image-preview")
, 1);
}
},
// Called whenever an error occurs
// Receives `file` and `message`
error (file, message) {
if (file.previewElement) {
file.previewElement.classList.add("dz-error");
if (typeof message !== "string" && message.error) message = message.error;
for (let node of file.previewElement.querySelectorAll("[data-dz-errormessage]"))node.textContent = message;
}
},
errormultiple () {
},
// Called when a file gets processed. Since there is a cue, not all added
// files are processed immediately.
// Receives `file`
processing (file) {
if (file.previewElement) {
file.previewElement.classList.add("dz-processing");
if (file._removeLink) return file._removeLink.innerHTML = this.options.dictCancelUpload;
}
},
processingmultiple () {
},
// Called whenever the upload progress gets updated.
// Receives `file`, `progress` (percentage 0-100) and `bytesSent`.
// To get the total number of bytes of the file, use `file.size`
uploadprogress (file, progress, bytesSent) {
if (file.previewElement) for (let node of file.previewElement.querySelectorAll("[data-dz-uploadprogress]"))node.nodeName === "PROGRESS" ? node.value = progress : node.style.width = `${progress}%`;
},
// Called whenever the total upload progress gets updated.
// Called with totalUploadProgress (0-100), totalBytes and totalBytesSent
totaluploadprogress () {
},
// Called just before the file is sent. Gets the `xhr` object as second
// parameter, so you can modify it (for example to add a CSRF token) and a
// `formData` object to add additional information.
sending () {
},
sendingmultiple () {
},
// When the complete upload is finished and successful
// Receives `file`
success (file) {
if (file.previewElement) return file.previewElement.classList.add("dz-success");
},
successmultiple () {
},
// When the upload is canceled.
canceled (file) {
return this.emit("error", file, this.options.dictUploadCanceled);
},
canceledmultiple () {
},
// When the upload is finished, either with success or an error.
// Receives `file`
complete (file) {
if (file._removeLink) file._removeLink.innerHTML = this.options.dictRemoveFile;
if (file.previewElement) return file.previewElement.classList.add("dz-complete");
},
completemultiple () {
},
maxfilesexceeded () {
},
maxfilesreached () {
},
queuecomplete () {
},
addedfiles () {
}
};
var $4ca367182776f80b$export$2e2bcd8739ae039 = $4ca367182776f80b$var$defaultOptions;
class $3ed269f2f0fb224b$export$2e2bcd8739ae039 extends $4040acfd8584338d$export$2e2bcd8739ae039 {
static initClass() {
// Exposing the emitter class, mainly for tests
this.prototype.Emitter = $4040acfd8584338d$export$2e2bcd8739ae039;
/*
This is a list of all available events you can register on a dropzone object.
You can register an event handler like this:
dropzone.on("dragEnter", function() { });
*/ this.prototype.events = [
"drop",
"dragstart",
"dragend",
"dragenter",
"dragover",
"dragleave",
"addedfile",
"addedfiles",
"removedfile",
"thumbnail",
"error",
"errormultiple",
"processing",
"processingmultiple",
"uploadprogress",
"totaluploadprogress",
"sending",
"sendingmultiple",
"success",
"successmultiple",
"canceled",
"canceledmultiple",
"complete",
"completemultiple",
"reset",
"maxfilesexceeded",
"maxfilesreached",
"queuecomplete",
];
this.prototype._thumbnailQueue = [];
this.prototype._processingThumbnail = false;
}
// Returns all files that have been accepted
getAcceptedFiles() {
return this.files.filter((file)=>file.accepted
).map((file)=>file
);
}
// Returns all files that have been rejected
// Not sure when that's going to be useful, but added for completeness.
getRejectedFiles() {
return this.files.filter((file)=>!file.accepted
).map((file)=>file
);
}
getFilesWithStatus(status) {
return this.files.filter((file)=>file.status === status
).map((file)=>file
);
}
// Returns all files that are in the queue
getQueuedFiles() {
return this.getFilesWithStatus($3ed269f2f0fb224b$export$2e2bcd8739ae039.QUEUED);
}
getUploadingFiles() {
return this.getFilesWithStatus($3ed269f2f0fb224b$export$2e2bcd8739ae039.UPLOADING);
}
getAddedFiles() {
return this.getFilesWithStatus($3ed269f2f0fb224b$export$2e2bcd8739ae039.ADDED);
}
// Files that are either queued or uploading
getActiveFiles() {
return this.files.filter((file)=>file.status === $3ed269f2f0fb224b$export$2e2bcd8739ae039.UPLOADING || file.status === $3ed269f2f0fb224b$export$2e2bcd8739ae039.QUEUED
).map((file)=>file
);
}
// The function that gets called when Dropzone is initialized. You
// can (and should) setup event listeners inside this function.
init() {
// In case it isn't set already
if (this.element.tagName === "form") this.element.setAttribute("enctype", "multipart/form-data");
if (this.element.classList.contains("dropzone") && !this.element.querySelector(".dz-message")) this.element.appendChild($3ed269f2f0fb224b$export$2e2bcd8739ae039.createElement(`<div class="dz-default dz-message"><button class="dz-button" type="button">${this.options.dictDefaultMessage}</button></div>`));
if (this.clickableElements.length) {
let setupHiddenFileInput = ()=>{
if (this.hiddenFileInput) this.hiddenFileInput.parentNode.removeChild(this.hiddenFileInput);
this.hiddenFileInput = document.createElement("input");
this.hiddenFileInput.setAttribute("type", "file");
if (this.options.maxFiles === null || this.options.maxFiles > 1) this.hiddenFileInput.setAttribute("multiple", "multiple");
this.hiddenFileInput.className = "dz-hidden-input";
if (this.options.acceptedFiles !== null) this.hiddenFileInput.setAttribute("accept", this.options.acceptedFiles);
if (this.options.capture !== null) this.hiddenFileInput.setAttribute("capture", this.options.capture);
// Making sure that no one can "tab" into this field.
this.hiddenFileInput.setAttribute("tabindex", "-1");
// Not setting `display="none"` because some browsers don't accept clicks
// on elements that aren't displayed.
this.hiddenFileInput.style.visibility = "hidden";
this.hiddenFileInput.style.position = "absolute";
this.hiddenFileInput.style.top = "0";
this.hiddenFileInput.style.left = "0";
this.hiddenFileInput.style.height = "0";
this.hiddenFileInput.style.width = "0";
$3ed269f2f0fb224b$export$2e2bcd8739ae039.getElement(this.options.hiddenInputContainer, "hiddenInputContainer").appendChild(this.hiddenFileInput);
this.hiddenFileInput.addEventListener("change", ()=>{
let { files: files } = this.hiddenFileInput;
if (files.length) for (let file of files)this.addFile(file);
this.emit("addedfiles", files);
setupHiddenFileInput();
});
};
setupHiddenFileInput();
}
this.URL = window.URL !== null ? window.URL : window.webkitURL;
// Setup all event listeners on the Dropzone object itself.
// They're not in @setupEventListeners() because they shouldn't be removed
// again when the dropzone gets disabled.
for (let eventName of this.events)this.on(eventName, this.options[eventName]);
this.on("uploadprogress", ()=>this.updateTotalUploadProgress()
);
this.on("removedfile", ()=>this.updateTotalUploadProgress()
);
this.on("canceled", (file)=>this.emit("complete", file)
);
// Emit a `queuecomplete` event if all files finished uploading.
this.on("complete", (file)=>{
if (this.getAddedFiles().length === 0 && this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) // This needs to be deferred so that `queuecomplete` really triggers after `complete`
return setTimeout(()=>this.emit("queuecomplete")
, 0);
});
const containsFiles = function(e) {
if (e.dataTransfer.types) // Because e.dataTransfer.types is an Object in
// IE, we need to iterate like this instead of
// using e.dataTransfer.types.some()
for(var i = 0; i < e.dataTransfer.types.length; i++){
if (e.dataTransfer.types[i] === "Files") return true;
}
return false;
};
let noPropagation = function(e) {
// If there are no files, we don't want to stop
// propagation so we don't interfere with other
// drag and drop behaviour.
if (!containsFiles(e)) return;
e.stopPropagation();
if (e.preventDefault) return e.preventDefault();
else return e.returnValue = false;
};
// Create the listeners
this.listeners = [
{
element: this.element,
events: {
dragstart: (e)=>{
return this.emit("dragstart", e);
},
dragenter: (e)=>{
noPropagation(e);
return this.emit("dragenter", e);
},
dragover: (e)=>{
// Makes it possible to drag files from chrome's download bar
// http://stackoverflow.com/questions/19526430/drag-and-drop-file-uploads-from-chrome-downloads-bar
// Try is required to prevent bug in Internet Explorer 11 (SCRIPT65535 exception)
let efct;
try {
efct = e.dataTransfer.effectAllowed;
} catch (error) {
}
e.dataTransfer.dropEffect = "move" === efct || "linkMove" === efct ? "move" : "copy";
noPropagation(e);
return this.emit("dragover", e);
},
dragleave: (e)=>{
return this.emit("dragleave", e);
},
drop: (e)=>{
noPropagation(e);
return this.drop(e);
},
dragend: (e)=>{
return this.emit("dragend", e);
}
}
},
];
this.clickableElements.forEach((clickableElement)=>{
return this.listeners.push({
element: clickableElement,
events: {
click: (evt)=>{
// Only the actual dropzone or the message element should trigger file selection
if (clickableElement !== this.element || evt.target === this.element || $3ed269f2f0fb224b$export$2e2bcd8739ae039.elementInside(evt.target, this.element.querySelector(".dz-message"))) this.hiddenFileInput.click(); // Forward the click
return true;
}
}
});
});
this.enable();
return this.options.init.call(this);
}
// Not fully tested yet
destroy() {
this.disable();
this.removeAllFiles(true);
if (this.hiddenFileInput != null ? this.hiddenFileInput.parentNode : undefined) {
this.hiddenFileInput.parentNode.removeChild(this.hiddenFileInput);
this.hiddenFileInput = null;
}
delete this.element.dropzone;
return $3ed269f2f0fb224b$export$2e2bcd8739ae039.instances.splice($3ed269f2f0fb224b$export$2e2bcd8739ae039.instances.indexOf(this), 1);
}
updateTotalUploadProgress() {
let totalUploadProgress;
let totalBytesSent = 0;
let totalBytes = 0;
let activeFiles = this.getActiveFiles();
if (activeFiles.length) {
for (let file of this.getActiveFiles()){
totalBytesSent += file.upload.bytesSent;
totalBytes += file.upload.total;
}
totalUploadProgress = 100 * totalBytesSent / totalBytes;
} else totalUploadProgress = 100;
return this.emit("totaluploadprogress", totalUploadProgress, totalBytes, totalBytesSent);
}
// @options.paramName can be a function taking one parameter rather than a string.
// A parameter name for a file is obtained simply by calling this with an index number.
_getParamName(n) {
if (typeof this.options.paramName === "function") return this.options.paramName(n);
else return `${this.options.paramName}${this.options.uploadMultiple ? `[${n}]` : ""}`;
}
// If @options.renameFile is a function,
// the function will be used to rename the file.name before appending it to the formData
_renameFile(file) {
if (typeof this.options.renameFile !== "function") return file.name;
return this.options.renameFile(file);
}
// Returns a form that can be used as fallback if the browser does not support DragnDrop
//
// If the dropzone is already a form, only the input field and button are returned. Otherwise a complete form element is provided.
// This code has to pass in IE7 :(
getFallbackForm() {
let existingFallback, form;
if (existingFallback = this.getExistingFallback()) return existingFallback;
let fieldsString = '<div class="dz-fallback">';
if (this.options.dictFallbackText) fieldsString += `<p>${this.options.dictFallbackText}</p>`;
fieldsString += `<input type="file" name="${this._getParamName(0)}" ${this.options.uploadMultiple ? 'multiple="multiple"' : undefined} /><input type="submit" value="Upload!"></div>`;
let fields = $3ed269f2f0fb224b$export$2e2bcd8739ae039.createElement(fieldsString);
if (this.element.tagName !== "FORM") {
form = $3ed269f2f0fb224b$export$2e2bcd8739ae039.createElement(`<form action="${this.options.url}" enctype="multipart/form-data" method="${this.options.method}"></form>`);
form.appendChild(fields);
} else {
// Make sure that the enctype and method attributes are set properly
this.element.setAttribute("enctype", "multipart/form-data");
this.element.setAttribute("method", this.options.method);
}
return form != null ? form : fields;
}
// Returns the fallback elements if they exist already
//
// This code has to pass in IE7 :(
getExistingFallback() {
let getFallback = function(elements) {
for (let el of elements){
if (/(^| )fallback($| )/.test(el.className)) return el;
}
};
for (let tagName of [
"div",
"form"
]){
var fallback;
if (fallback = getFallback(this.element.getElementsByTagName(tagName))) return fallback;
}
}
// Activates all listeners stored in @listeners
setupEventListeners() {
return this.listeners.map((elementListeners)=>(()=>{
let result = [];
for(let event in elementListeners.events){
let listener = elementListeners.events[event];
result.push(elementListeners.element.addEventListener(event, listener, false));
}
return result;
})()
);
}
// Deactivates all listeners stored in @listeners
removeEventListeners() {
return this.listeners.map((elementListeners)=>(()=>{
let result = [];
for(let event in elementListeners.events){
let listener = elementListeners.events[event];
result.push(elementListeners.element.removeEventListener(event, listener, false));
}
return result;
})()
);
}
// Removes all event listeners and cancels all files in the queue or being processed.
disable() {
this.clickableElements.forEach((element)=>element.classList.remove("dz-clickable")
);
this.removeEventListeners();
this.disabled = true;
return this.files.map((file)=>this.cancelUpload(file)
);
}
enable() {
delete this.disabled;
this.clickableElements.forEach((element)=>element.classList.add("dz-clickable")
);
return this.setupEventListeners();
}
// Returns a nicely formatted filesize
filesize(size) {
let selectedSize = 0;
let selectedUnit = "b";
if (size > 0) {
let units = [
"tb",
"gb",
"mb",
"kb",
"b"
];
for(let i = 0; i < units.length; i++){
let unit = units[i];
let cutoff = Math.pow(this.options.filesizeBase, 4 - i) / 10;
if (size >= cutoff) {
selectedSize = size / Math.pow(this.options.filesizeBase, 4 - i);
selectedUnit = unit;
break;
}
}
selectedSize = Math.round(10 * selectedSize) / 10; // Cutting of digits
}
return `<strong>${selectedSize}</strong> ${this.options.dictFileSizeUnits[selectedUnit]}`;
}
// Adds or removes the `dz-max-files-reached` class from the form.
_updateMaxFilesReachedClass() {
if (this.options.maxFiles != null && this.getAcceptedFiles().length >= this.options.maxFiles) {
if (this.getAcceptedFiles().length === this.options.maxFiles) this.emit("maxfilesreached", this.files);
return this.element.classList.add("dz-max-files-reached");
} else return this.element.classList.remove("dz-max-files-reached");
}
drop(e) {
if (!e.dataTransfer) return;
this.emit("drop", e);
// Convert the FileList to an Array
// This is necessary for IE11
let files = [];
for(let i = 0; i < e.dataTransfer.files.length; i++)files[i] = e.dataTransfer.files[i];
// Even if it's a folder, files.length will contain the folders.
if (files.length) {
let { items: items } = e.dataTransfer;
if (items && items.length && items[0].webkitGetAsEntry != null) // The browser supports dropping of folders, so handle items instead of files
this._addFilesFromItems(items);
else this.handleFiles(files);
}
this.emit("addedfiles", files);
}
paste(e) {
if ($3ed269f2f0fb224b$var$__guard__(e != null ? e.clipboardData : undefined, (x)=>x.items
) == null) return;
this.emit("paste", e);
let { items: items } = e.clipboardData;
if (items.length) return this._addFilesFromItems(items);
}
handleFiles(files) {
for (let file of files)this.addFile(file);
}
// When a folder is dropped (or files are pasted), items must be handled
// instead of files.
_addFilesFromItems(items) {
return (()=>{
let result = [];
for (let item of items){
var entry;
if (item.webkitGetAsEntry != null && (entry = item.webkitGetAsEntry())) {
if (entry.isFile) result.push(this.addFile(item.getAsFile()));
else if (entry.isDirectory) // Append all files from that directory to files
result.push(this._addFilesFromDirectory(entry, entry.name));
else result.push(undefined);
} else if (item.getAsFile != null) {
if (item.kind == null || item.kind === "file") result.push(this.addFile(item.getAsFile()));
else result.push(undefined);
} else result.push(undefined);
}
return result;
})();
}
// Goes through the directory, and adds each file it finds recursively
_addFilesFromDirectory(directory, path) {
let dirReader = directory.createReader();
let errorHandler = (error)=>$3ed269f2f0fb224b$var$__guardMethod__(console, "log", (o)=>o.log(error)
)
;
var readEntries = ()=>{
return dirReader.readEntries((entries)=>{
if (entries.length > 0) {
for (let entry of entries){
if (entry.isFile) entry.file((file)=>{
if (this.options.ignoreHiddenFiles && file.name.substring(0, 1) === ".") return;
file.fullPath = `${path}/${file.name}`;
return this.addFile(file);
});
else if (entry.isDirectory) this._addFilesFromDirectory(entry, `${path}/${entry.name}`);
}
// Recursively call readEntries() again, since browser only handle
// the first 100 entries.
// See: https://developer.mozilla.org/en-US/docs/Web/API/DirectoryReader#readEntries
readEntries();
}
return null;
}, errorHandler);
};
return readEntries();
}
// If `done()` is called without argument the file is accepted
// If you call it with an error message, the file is rejected
// (This allows for asynchronous validation)
//
// This function checks the filesize, and if the file.type passes the
// `acceptedFiles` check.
accept(file, done) {
if (this.options.maxFilesize && file.size > this.options.maxFilesize * 1048576) done(this.options.dictFileTooBig.replace("{{filesize}}", Math.round(file.size / 1024 / 10.24) / 100).replace("{{maxFilesize}}", this.options.maxFilesize));
else if (!$3ed269f2f0fb224b$export$2e2bcd8739ae039.isValidFile(file, this.options.acceptedFiles)) done(this.options.dictInvalidFileType);
else if (this.options.maxFiles != null && this.getAcceptedFiles().length >= this.options.maxFiles) {
done(this.options.dictMaxFilesExceeded.replace("{{maxFiles}}", this.options.maxFiles));
this.emit("maxfilesexceeded", file);
} else this.options.accept.call(this, file, done);
}
addFile(file) {
file.upload = {
uuid: $3ed269f2f0fb224b$export$2e2bcd8739ae039.uuidv4(),
progress: 0,
// Setting the total upload size to file.size for the beginning
// It's actual different than the size to be transmitted.
total: file.size,
bytesSent: 0,
filename: this.