@progress/kendo-ui
Version:
This package is part of the [Kendo UI for jQuery](http://www.telerik.com/kendo-ui) suite.
1,312 lines (1,071 loc) • 92.1 kB
JavaScript
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(1349);
/***/ }),
/***/ 3:
/***/ (function(module, exports) {
module.exports = function() { throw new Error("define cannot be used indirect"); };
/***/ }),
/***/ 1003:
/***/ (function(module, exports) {
module.exports = require("jquery");
/***/ }),
/***/ 1004:
/***/ (function(module, exports) {
module.exports = require("./kendo.core");
/***/ }),
/***/ 1349:
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(jQuery) {(function(f, define){
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [ __webpack_require__(1004) ], __WEBPACK_AMD_DEFINE_FACTORY__ = (f), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
})(function(){
var __meta__ = { // jshint ignore:line
id: "upload",
name: "Upload",
category: "web",
description: "The Upload widget uses progressive enhancement to deliver the best possible uploading experience to users.",
depends: [ "core" ]
};
(function($, undefined) {
var kendo = window.kendo,
Widget = kendo.ui.Widget,
antiForgeryTokens = kendo.antiForgeryTokens,
logToConsole = kendo.logToConsole,
rFileExtension = /\.([^\.]+)$/,
NS = ".kendoUpload",
SELECT = "select",
UPLOAD = "upload",
SUCCESS = "success",
ERROR = "error",
COMPLETE = "complete",
CANCEL = "cancel",
CLEAR = "clear",
PAUSE = "pause",
RESUME = "resume",
PROGRESS = "progress",
REMOVE = "remove",
VALIDATIONERRORS = "validationErrors",
INVALIDMAXFILESIZE = "invalidMaxFileSize",
INVALIDMINFILESIZE = "invalidMinFileSize",
INVALIDFILEEXTENSION = "invalidFileExtension",
PROGRESSHIDEDELAY = 1000,
PROGRESSHIDEDURATION = 2000;
var headerStatusIcon = {
loading: "k-i-loading",
warning: "k-i-warning",
success: "k-i-check"
};
var Upload = Widget.extend({
init: function(element, options) {
var that = this;
Widget.fn.init.call(that, element, options);
that.name = element.name;
that.multiple = that.options.multiple;
that.directory = that.options.directory;
that.localization = that.options.localization;
var activeInput = that.element;
that.wrapper = activeInput.closest(".k-upload");
if (that.wrapper.length === 0) {
that.wrapper = that._wrapInput(activeInput);
}
that._activeInput(activeInput);
that.toggle(that.options.enabled);
var ns = that._ns = NS + "-" + kendo.guid();
activeInput.closest("form")
.on("submit" + ns, $.proxy(that._onParentFormSubmit, that))
.on("reset" + ns, $.proxy(that._onParentFormReset, that));
if (that.options.async.saveUrl) {
that._module = that._supportsFormData() ?
new formDataUploadModule(that) :
new iframeUploadModule(that);
that._async = true;
var initialFiles = that.options.files;
if (initialFiles.length > 0) {
that._renderInitialFiles(initialFiles);
}
} else {
that._module = new syncUploadModule(that);
}
if (that._supportsDrop()) {
if(that.options.dropZone !== "") {
that._setupCustomDropZone();
} else {
that._setupDropZone();
}
}
that.wrapper
.on("click", ".k-upload-action", $.proxy(that._onFileAction, that))
.on("click", ".k-clear-selected", $.proxy(that._onClearSelected, that))
.on("click", ".k-upload-selected", $.proxy(that._onUploadSelected, that));
if(that.element.val()) {
that._onInputChange({ target: that.element });
}
},
events: [
SELECT,
UPLOAD,
SUCCESS,
ERROR,
COMPLETE,
CANCEL,
CLEAR,
PROGRESS,
REMOVE,
PAUSE,
RESUME
],
options: {
name: "Upload",
enabled: true,
multiple: true,
directory: false,
showFileList: true,
template: "",
files: [],
async: {
autoRetryAfter: 0,
bufferChunkSize: 10000000,
maxAutoRetries: 1,
removeVerb: "POST",
autoUpload: true,
withCredentials: true,
accept: "*/*; q=0.5, application/json",
useArrayBuffer: false
},
localization: {
"select": "Select files...",
"cancel": "Cancel",
"retry": "Retry",
"remove": "Remove",
"pause": "Pause",
"resume": "Resume",
"clearSelectedFiles": "Clear",
"uploadSelectedFiles": "Upload",
"dropFilesHere": "Drop files here to upload",
"invalidFiles": "Invalid file(s). Please check file upload requirements.",
"statusUploading": "uploading",
"statusUploaded": "uploaded",
"statusWarning": "warning",
"statusFailed": "failed",
"headerStatusUploading": "Uploading...",
"headerStatusPaused": "Paused",
"headerStatusUploaded": "Done",
"invalidMaxFileSize": "File size too large.",
"invalidMinFileSize": "File size too small.",
"invalidFileExtension": "File type not allowed."
},
validation: {
allowedExtensions: [],
maxFileSize: 0,
minFileSize: 0
},
dropZone: ""
},
setOptions: function(options) {
var that = this,
activeInput = that.element;
Widget.fn.setOptions.call(that, options);
that.multiple = that.options.multiple;
that.directory = that.options.directory;
activeInput.attr("multiple", that._supportsMultiple() ? that.multiple : false);
if(that.directory){
activeInput.attr("webkitdirectory", that.directory);
activeInput.attr("directory", that.directory);
}
that.toggle(that.options.enabled);
},
enable: function(enable) {
enable = typeof (enable) === "undefined" ? true : enable;
this.toggle(enable);
},
disable: function() {
this.toggle(false);
},
toggle: function(enable) {
enable = typeof (enable) === "undefined" ? enable : !enable;
this.wrapper.toggleClass("k-state-disabled", enable);
this.element.prop("disabled", enable);
},
focus: function() {
this.element.focus();
},
destroy: function() {
var that = this;
var customDropZone = $(that.options.dropZone);
$(document)
.add($(".k-dropzone", that.wrapper))
.add(that.wrapper.closest("form"))
.off(that._ns);
if(customDropZone.length > 0) {
customDropZone.off(that._ns);
}
$(that.element).off(NS);
Widget.fn.destroy.call(that);
},
pause: function(fileEntry){
this._module.onPause({ target: $(fileEntry, this.wrapper) });
var pauseIcon = fileEntry.find(".k-i-pause-sm");
pauseIcon.removeClass("k-i-pause-sm").addClass("k-i-play-sm").attr("title", this.localization.resume);
$(pauseIcon).parent().attr("aria-label", this.localization.resume);
},
resume: function(fileEntry){
this._module.onResume({ target: $(fileEntry, this.wrapper) });
var playIcon = fileEntry.find(".k-i-play-sm");
playIcon.removeClass("k-i-play-sm").addClass("k-i-pause-sm").attr("title", this.localization.pause);
$(playIcon).parent().attr("aria-label", this.localization.pause);
},
upload: function() {
var that = this;
that._module.onSaveSelected();
},
getFiles: function() {
var that = this;
var filesData;
var allFiles = [];
var listItems = that.wrapper.find(".k-file");
for(var i = 0; i < listItems.length; i++) {
filesData = $(listItems[i]).data("fileNames");
if(filesData) {
for(var j = 0; j < filesData.length; j++) {
allFiles.push(filesData[j]);
}
}
}
return allFiles;
},
clearAllFiles: function() {
var that = this;
var files = that.wrapper.find(".k-file");
files.each(function(index, file) {
that._removeFileByDomElement(file, false);
});
},
removeAllFiles: function() {
var that = this;
var files = that.wrapper.find(".k-file");
files.each(function(index, file) {
that._removeFileByDomElement(file, true);
});
},
removeFileByUid: function(uid) {
this._removeFileByUid(uid, true);
},
clearFileByUid: function(uid) {
this._removeFileByUid(uid, false);
},
_removeFileByUid: function(uid, shouldSendRemoveRequest) {
var that = this;
var fileEntry;
if(typeof uid !== 'string') { return; }
fileEntry = $('.k-file[' + kendo.attr('uid') + '="' + uid + '"]', that.wrapper);
if(fileEntry.length > 0) {
that._removeFileByDomElement(fileEntry, shouldSendRemoveRequest);
}
},
clearFile: function(callback) {
this._removeFile(callback, false);
},
removeFile: function(callback) {
this._removeFile(callback, true);
},
_removeFile: function(callback, shouldSendRemoveRequest) {
var that = this;
var files = that.wrapper.find(".k-file");
var fileData;
if(typeof callback === "function") {
files.each(function(index, file){
fileData = $(file).data("fileNames");
if(callback(fileData)) {
that._removeFileByDomElement(file, shouldSendRemoveRequest);
}
});
}
},
_removeFileByDomElement: function(fileEntry, shouldSendRemoveRequest) {
var that = this;
var fileData = {
target: $(fileEntry, that.wrapper)
};
var allFiles;
if(that.options.async.saveUrl) {
if($(fileEntry).hasClass("k-file-progress")) {
that._module.onCancel(fileData);
} else {
that._module.onRemove(fileData, {}, shouldSendRemoveRequest);
}
allFiles = $(".k-file", that.wrapper);
if(allFiles.length === 0) {
that._hideHeaderUploadstatus();
} else {
that._updateHeaderUploadStatus();
}
} else {
that._module.onRemove(fileData, {}, shouldSendRemoveRequest);
}
},
_addInput: function(sourceInput) {
//check if source input is a DOM element. Required for some unit tests
if (!sourceInput[0].nodeType) {
return;
}
var that = this,
input = sourceInput.clone().val("");
input
.insertAfter(that.element)
.data("kendo" + that.options.prefix + that.options.name, that);
$(that.element)
.hide()
.attr("tabindex", "-1")
.removeAttr("id")
.off(NS);
that._activeInput(input);
that.element.focus();
},
_activeInput: function(input) {
var that = this,
wrapper = that.wrapper;
that.element = input;
if(that.directory){
input.attr("webkitdirectory", that.directory);
input.attr("directory", that.directory);
}
input
.attr("multiple", that._supportsMultiple() ? that.multiple : false)
.attr("autocomplete", "off")
.on("click" + NS, function(e) {
if (wrapper.hasClass("k-state-disabled")) {
e.preventDefault();
}
})
.on("focus" + NS, function() {
$(this).parent().addClass("k-state-focused");
})
.on("blur" + NS, function() {
$(this).parent().removeClass("k-state-focused");
})
.on("change" + NS, $.proxy(that._onInputChange, that))
.on("keydown" + NS, $.proxy(that._onInputKeyDown, that));
},
_onInputKeyDown: function(e) {
var that = this;
var firstButton = that.wrapper.find(".k-upload-action:visible:first");
if (e.keyCode === kendo.keys.TAB && firstButton.length > 0 && !e.shiftKey) {
e.preventDefault();
firstButton.focus();
}
},
_onInputChange: function(e) {
var that = this;
var input = $(e.target);
var files = assignGuidToFiles(that._inputFiles(input), that._isAsyncNonBatch());
validateFiles(files, that.options.validation);
var prevented = that.trigger(SELECT, { files: files });
if (prevented) {
that._addInput(input);
input.remove();
} else {
that._module.onSelect({target : input}, files);
}
},
_readDirectory: function(item){
var deferred = new $.Deferred();
var dirReader = item.createReader();
var allFolderFiles = [];
var readEntries = function () {
dirReader.readEntries(function(entries) {
if (!entries.length) {
deferred.resolve(allFolderFiles);
} else {
allFolderFiles = allFolderFiles.concat(entries);
readEntries();
}
}, deferred.reject);
};
readEntries();
return deferred.promise();
},
_readFile: function(item){
var that = this;
var fullpath = item.fullPath;
item.file(function(file){
file.relativePath = fullpath.slice(1);
that.droppedFolderFiles.push(file);
that.droppedFolderCounter --;
if(that.droppedFolderCounter === 0){
setTimeout(function(){
if(that.droppedFolderCounter === 0){
if(that.droppedFolderFiles.length){
that._proceedDroppedItems(that.droppedFolderFiles);
that.droppedFolderFiles = [];
}
}
},0);
}
}, function(){
logToConsole("File error.");
});
},
_traverseFileTree: function (item, skipCounter) {
var that = this;
if(!skipCounter){
that.droppedFolderCounter--;
}
this._readDirectory(item).then(function(items){
that.droppedFolderCounter += items.length;
for (var i = 0; i < items.length; i++) {
if(items[i].isFile){
that._readFile(items[i]);
} else if (items[i].isDirectory){
that._traverseFileTree(items[i]);
}
}
});
},
_onDrop: function (e) {
var dt = e.originalEvent.dataTransfer;
var that = this;
var droppedFiles = dt.files;
var length;
stopEvent(e);
if(that.options.directoryDrop && dt.items){
length = dt.items.length;
that.droppedFolderCounter = 0;
that.droppedFolderFiles = [];
for (var i = 0; i < length; i++) {
if(dt.items[i].webkitGetAsEntry){
var entry = dt.items[i].webkitGetAsEntry();
if(entry.isDirectory){
that._traverseFileTree(entry, true);
}else if (entry.isFile){
that.droppedFolderFiles.push(dt.files[i]);
}
}else{
that._proceedDroppedItems(droppedFiles);
}
}
}else{
that._proceedDroppedItems(droppedFiles);
}
},
_proceedDroppedItems: function(droppedFiles){
var that = this;
var files = assignGuidToFiles(getAllFileInfo(droppedFiles), that._isAsyncNonBatch());
if (droppedFiles.length > 0 && !that.wrapper.hasClass("k-state-disabled")) {
if (!that.multiple && files.length > 1) {
files.splice(1, files.length - 1);
}
validateFiles(files, that.options.validation);
var prevented = that.trigger(SELECT, { files: files });
if (!prevented) {
that._module.onSelect({target : $(".k-dropzone", that.wrapper) }, files);
}
}
},
_filesContainValidationErrors: function(files) {
var hasErrors = false;
$(files).each(function(index, file){
if(file[VALIDATIONERRORS] && file[VALIDATIONERRORS].length > 0) {
hasErrors = true;
return false;
}
});
return hasErrors;
},
_isAsyncNonBatch: function () {
return (this._async && !this.options.async.batch) || false;
},
_renderInitialFiles: function(files) {
var that = this;
var idx = 0;
files = assignGuidToFiles(files, true);
for (idx = 0; idx < files.length; idx++) {
var currentFile = files[idx];
var fileEntry = that._enqueueFile(currentFile.name, { fileNames: [ currentFile ] });
fileEntry.addClass("k-file-success").data("files", [ files[idx] ]);
if (that._supportsRemove()){
that._fileAction(fileEntry, REMOVE);
}
}
},
_prepareTemplateData: function(name, data) {
var filesData = data.fileNames,
templateData = {},
totalSize = 0,
idx = 0;
for (idx = 0; idx < filesData.length; idx++) {
totalSize += filesData[idx].size;
}
templateData.name = name;
templateData.size = totalSize;
templateData.files = data.fileNames;
return templateData;
},
_prepareDefaultSingleFileEntryTemplate: function(data) {
var that = this;
var file = data.fileNames[0];
var fileSize = getTotalFilesSizeMessage(data.fileNames);
var errors = file[VALIDATIONERRORS];
var template = "";
if(errors && errors.length > 0) {
template += "<li class='k-file k-file-invalid'><span class='k-progress'></span>" +
"<span class='k-file-invalid-extension-wrapper'>" +
"<span class='k-file-invalid-icon'>!</span>" +
"<span class='k-file-state'></span>" +
"</span>" +
"<span class='k-file-name-size-wrapper'>" +
"<span class='k-file-name k-file-name-invalid' title='" + file.name + "'>" + file.name + "</span>" +
"<span class='k-file-validation-message'>" + that.localization[errors[0]] + "</span>" +
"</span>";
} else {
template += "<li class='k-file'><span class='k-progress'></span>" +
"<span class='k-file-extension-wrapper'>" +
"<span class='k-file-extension'>" + file.extension.substring(1) + "</span>" +
"<span class='k-file-state'></span>" +
"</span>" +
"<span class='k-file-name-size-wrapper'><span class='k-file-name' title='" + file.name + "'>" + file.name + "</span>" +
"<span class='k-file-size'>" + fileSize + "</span></span>";
}
template += "<strong class='k-upload-status'></strong>";
return $(template);
},
_prepareDefaultMultipleFileEntriesTemplate: function(data) {
var that = this;
var files = data.fileNames;
var filesHaveValidationErrors = that._filesContainValidationErrors(files);
var totalFileSize = getTotalFilesSizeMessage(files);
var template = "";
var i, currentFile;
if(filesHaveValidationErrors) {
template += "<li class='k-file k-file-invalid'><span class='k-progress'></span>" +
"<span class='k-multiple-files-invalid-extension-wrapper'>" +
"<span class='k-file-invalid-icon'>!</span>";
} else {
template += "<li class='k-file'><span class='k-progress'></span>" +
"<span class='k-multiple-files-extension-wrapper'>";
}
template += "<span class='k-file-state'></span></span>";
files.sort(function(a, b){
if(a[VALIDATIONERRORS]) { return -1; }
if (b[VALIDATIONERRORS]) { return 1; }
return 0;
});
template += "<span class='k-file-name-size-wrapper'>";
for(i = 0; i < files.length; i++) {
currentFile = files[i];
if(currentFile[VALIDATIONERRORS] && currentFile[VALIDATIONERRORS].length > 0) {
template += "<span class='k-file-name k-file-name-invalid' title='" + currentFile.name + "'>" + currentFile.name + "</span>";
} else {
template += "<span class='k-file-name' title='" + currentFile.name + "'>" + currentFile.name + "</span>";
}
}
if(filesHaveValidationErrors) {
template += "<span class='k-file-validation-message'>" + that.localization.invalidFiles +"</span>";
} else {
template += "<span class='k-file-information'>Total: " + files.length + " files, " + totalFileSize + "</span>";
}
template += "</span><strong class='k-upload-status'></strong>";
return $(template);
},
_enqueueFile: function(name, data) {
var that = this;
var existingFileEntries;
var fileEntry;
var fileUid = data.fileNames[0].uid;
var fileList = $(".k-upload-files", that.wrapper);
var options = that.options;
var template = options.template;
var templateData;
var removeEventArgs;
if (fileList.length === 0) {
fileList = $("<ul class='k-upload-files k-reset'></ul>").appendTo(that.wrapper);
if (!that.options.showFileList) {
fileList.hide();
}
that.wrapper.removeClass("k-upload-empty");
}
existingFileEntries = $(".k-file", fileList);
if (!template) {
if(data.fileNames.length === 1) {
fileEntry = that._prepareDefaultSingleFileEntryTemplate(data);
} else {
fileEntry = that._prepareDefaultMultipleFileEntriesTemplate(data);
}
} else {
templateData = that._prepareTemplateData(name, data);
template = kendo.template(template);
fileEntry = $("<li class='k-file'>" + template(templateData) + "</li>");
fileEntry.find(".k-upload-action").addClass("k-button");
that.angular("compile", function(){
return {
elements: fileEntry,
data: [ templateData ]
};
});
}
fileEntry
.attr(kendo.attr("uid"), fileUid)
.appendTo(fileList)
.data(data);
if (!that._async) {
$(".k-progress", fileEntry).width('100%');
}
if (!that.multiple && existingFileEntries.length > 0) {
removeEventArgs = {
files: existingFileEntries.data("fileNames"),
headers: {}
};
if (!that.trigger(REMOVE, removeEventArgs)) {
that._module.onRemove({target : $(existingFileEntries, that.wrapper)}, removeEventArgs);
}
}
return fileEntry;
},
_removeFileEntry: function(fileEntry) {
var that = this;
var fileList = fileEntry.closest(".k-upload-files");
var allFiles, allCompletedFiles, allInvalidFiles;
fileEntry.remove();
allFiles = $(".k-file", fileList);
allCompletedFiles = $(".k-file-success, .k-file-error", fileList);
allInvalidFiles = $(".k-file-invalid", fileList);
if (allCompletedFiles.length === allFiles.length || allInvalidFiles.length === allFiles.length) {
this._hideUploadButton();
}
if (allFiles.length === 0) {
fileList.remove();
that.wrapper.addClass("k-upload-empty");
that._hideHeaderUploadstatus();
} else {
that._updateHeaderUploadStatus();
}
},
_fileAction: function(fileElement, actionKey, skipClear) {
var classDictionary = { remove: "k-i-x", cancel: "k-i-cancel", retry: "k-i-retry", pause: "k-i-pause-sm"};
var iconsClassDictionary = {remove: "k-i-close", cancel: "k-i-close", retry: "k-i-reload-sm", pause: "k-i-pause-sm"};
var firstActionButton;
if (!classDictionary.hasOwnProperty(actionKey)) {
return;
}
if(!skipClear){
this._clearFileAction(fileElement);
}
if (!this.options.template) {
if(!skipClear){
fileElement.find(".k-upload-status .k-upload-action").remove();
}
fileElement.find(".k-upload-status").append(
this._renderAction(classDictionary[actionKey], this.localization[actionKey], iconsClassDictionary[actionKey])
);
} else {
firstActionButton = fileElement.find(".k-upload-action").first();
if(!firstActionButton.find(".k-icon").length){
firstActionButton
.addClass("k-button")
.append("<span class='k-icon " + iconsClassDictionary[actionKey] + " " + classDictionary[actionKey] +
"' title='" + this.localization[actionKey] + "'" +
"aria-label='" + this.localization[actionKey] + "'></span>")
.show();
}else if (firstActionButton.next(".k-upload-action").length){
firstActionButton.next(".k-upload-action")
.addClass("k-button")
.append("<span class='k-icon " + iconsClassDictionary[actionKey] + " " + classDictionary[actionKey] +
"' title='" + this.localization[actionKey] + "'" +
"aria-label='" + this.localization[actionKey] + "'></span>")
.show();
}
}
},
_fileState: function(fileEntry, stateKey) {
var localization = this.localization,
states = {
uploading: {
text : localization.statusUploading
},
uploaded: {
text : localization.statusUploaded
},
failed: {
text : localization.statusFailed
}
},
currentState = states[stateKey];
if (currentState) {
$("span.k-file-state", fileEntry).text(currentState.text);
}
},
_renderAction: function (actionClass, actionText, iconClass) {
if (actionClass !== "") {
return $(
"<button type='button' class='k-button k-upload-action' aria-label='" + actionText + "'>" +
"<span class='k-icon "+ iconClass + " " + actionClass + "' title='" + actionText + "'></span>" +
"</button>"
).on("focus", function() { $(this).addClass("k-state-focused"); })
.on("blur", function() { $(this).removeClass("k-state-focused"); });
}
else {
return $(
"<button type='button' class='k-button'>" +
actionText +
"</button>"
);
}
},
_clearFileAction: function(fileElement) {
$(".k-upload-action", fileElement).empty().hide();
},
_onFileAction: function(e) {
var that = this;
if (!that.wrapper.hasClass("k-state-disabled")) {
var button = $(e.target).closest(".k-upload-action");
var icon = button.find(".k-icon");
var fileEntry = button.closest(".k-file");
var files = fileEntry.data("fileNames");
var hasValidationErrors = that._filesContainValidationErrors(files);
var eventArgs = {
files: files,
headers: {}
};
that._retryClicked = false;
if (icon.hasClass("k-i-x")) {
if (!that.trigger(REMOVE, eventArgs)) {
that._module.onRemove({target : $(fileEntry, that.wrapper)}, eventArgs, !hasValidationErrors);
}
} else if (icon.hasClass("k-i-cancel")) {
that.trigger(CANCEL, eventArgs);
that._module.onCancel({ target: $(fileEntry, that.wrapper) });
that._checkAllComplete();
that._updateHeaderUploadStatus();
} else if (icon.hasClass("k-i-pause-sm")) {
that.trigger(PAUSE, eventArgs);
that.pause(fileEntry);
that._updateHeaderUploadStatus();
} else if (icon.hasClass("k-i-play-sm")) {
that.trigger(RESUME, eventArgs);
that.resume(fileEntry);
}else if (icon.hasClass("k-i-retry")) {
$(".k-i-warning", fileEntry).remove();
$(".k-progress", fileEntry).finish().show();
that._module.onRetry({ target: $(fileEntry, that.wrapper) });
that._retryClicked = true;
}
}
return false;
},
_onUploadSelected: function() {
var that = this;
var wrapper = that.wrapper;
if (!wrapper.hasClass("k-state-disabled")) {
this._module.onSaveSelected();
}
return false;
},
_onClearSelected: function() {
var that = this;
var wrapper = that.wrapper;
var clearEventArgs = { };
if(!wrapper.hasClass("k-state-disabled") && !that.trigger(CLEAR, clearEventArgs)) {
that.clearAllFiles();
}
return false;
},
_onFileProgress: function(e, percentComplete) {
var progressPct;
var warningPct;
if (percentComplete > 100) {
percentComplete = 100;
}
if (!this.options.template) {
progressPct = $(".k-upload-pct", e.target);
warningPct = $(".k-i-warning", e.target);
if(warningPct.length){
warningPct.removeClass("k-i-warning").removeClass("k-icon").addClass("k-upload-pct");
}else if (progressPct.length === 0) {
$(".k-upload-status", e.target).prepend("<span class='k-upload-pct'></span>");
}
if(percentComplete !== 100){
$(".k-upload-pct", e.target).text(percentComplete + "%");
}else{
$(".k-upload-pct", e.target).remove();
}
$(".k-progress", e.target).width(percentComplete + "%");
} else {
$(".k-progress", e.target).width(percentComplete + "%");
}
this.trigger(PROGRESS, {
files: getFileEntry(e).data("fileNames"),
percentComplete: percentComplete
});
},
_onUploadSuccess: function(e, response, xhr) {
var that = this;
var fileEntry = getFileEntry(e);
var prevented = that.trigger(SUCCESS, {
files: fileEntry.data("fileNames"),
response: response,
operation: "upload",
XMLHttpRequest: xhr
});
if(prevented) {
that._setUploadErrorState(fileEntry);
} else {
that._fileState(fileEntry, "uploaded");
fileEntry.removeClass('k-file-progress').addClass('k-file-success');
that._updateHeaderUploadStatus();
if (that._supportsRemove()) {
that._fileAction(fileEntry, REMOVE);
} else {
that._clearFileAction(fileEntry);
}
}
that._hideUploadProgress(fileEntry);
that._checkAllComplete();
},
_onUploadError: function(e, xhr) {
var that = this;
var module = that._module;
var fileEntry = getFileEntry(e);
var fileUid = fileEntry.data("uid");
that._setUploadErrorState(fileEntry);
that.trigger(ERROR, {
operation: "upload",
files: fileEntry.data("fileNames"),
XMLHttpRequest: xhr
});
logToConsole("Server response: " + xhr.responseText);
if(!that.options.async.chunkSize){
that._hideUploadProgress(fileEntry);
}else{
if(module._decreasePosition){
module._decreasePosition(fileUid);
}
}
that._checkAllComplete();
if(this.options.async.autoRetryAfter){
this._autoRetryAfter(fileEntry);
}
},
_autoRetryAfter: function(fileEntry){
var that = this;
var retries = this._module.retries;
if(!retries){
return;
}
if(!retries[fileEntry.data("uid")]){
retries[fileEntry.data("uid")] = 1;
}
if(retries[fileEntry.data("uid")] <= this.options.async.maxAutoRetries){
retries[fileEntry.data("uid")]++;
setTimeout(function(){
that._module.performUpload(fileEntry);
},this.options.async.autoRetryAfter);
}
},
_setUploadErrorState: function(fileEntry) {
var that = this;
var uploadPercentage;
that._fileState(fileEntry, "failed");
fileEntry.removeClass('k-file-progress').addClass('k-file-error');
that._updateUploadProgress(fileEntry);
uploadPercentage = $('.k-upload-pct', fileEntry);
if (uploadPercentage.length > 0) {
if(!uploadPercentage.parent().find(".k-i-warning").length){
uploadPercentage.removeClass('k-upload-pct').addClass('k-icon k-i-warning');
}
uploadPercentage.empty();
} else {
$('.k-upload-status', fileEntry).prepend("<span class='k-icon k-i-warning'></span>");
}
this._updateHeaderUploadStatus();
this._fileAction(fileEntry, "retry");
this._fileAction(fileEntry, REMOVE, true);
if (that._retryClicked) {
fileEntry.find(".k-i-retry").parent().focus();
}
},
_updateUploadProgress: function(fileEntry){
var that = this;
if(!that.options.async.chunkSize){
$('.k-progress', fileEntry).width("100%");
}else{
var fileUid = fileEntry.data("uid");
if(that._module.metaData){
var fileMetaData = that._module.metaData[fileUid];
if(fileMetaData){
var percentComplete = fileMetaData.totalChunks ? Math.round(((fileMetaData.chunkIndex)/fileMetaData.totalChunks)*100):100;
that._onFileProgress({ target : $(fileEntry, that.wrapper) }, percentComplete);
}
}
}
},
_hideUploadProgress: function(fileEntry) {
$(".k-progress", fileEntry)
.delay(PROGRESSHIDEDELAY)
.fadeOut(PROGRESSHIDEDURATION, function() {
$(this).css("width", "0%");
});
},
_showUploadButton: function() {
var that = this;
var uploadButton = $(".k-upload-selected", that.wrapper);
var clearButton = $(".k-clear-selected", that.wrapper);
if (uploadButton.length === 0) {
uploadButton = that._renderAction("", this.localization.uploadSelectedFiles)
.addClass("k-upload-selected");
clearButton = that._renderAction("", this.localization.clearSelectedFiles)
.addClass("k-clear-selected");
}
this.wrapper.append(clearButton, uploadButton);
},
_hideUploadButton: function() {
$(".k-upload-selected, .k-clear-selected", this.wrapper).remove();
},
_showHeaderUploadStatus: function(isUploading) {
var that = this;
var localization = that.localization;
var dropZone = $(".k-dropzone", that.wrapper);
var headerUploadStatus = $('.k-upload-status-total', that.wrapper);
if (headerUploadStatus.length !== 0) {
headerUploadStatus.remove();
}
headerUploadStatus = '<strong class="k-upload-status k-upload-status-total"><span class="k-icon"></span></strong>';
if(isUploading) {
headerUploadStatus = $(headerUploadStatus).append(localization.headerStatusUploading);
headerUploadStatus.find(".k-icon").addClass(headerStatusIcon.loading);
} else {
headerUploadStatus = $(headerUploadStatus).append(localization.headerStatusUploaded);
headerUploadStatus.find(".k-icon").addClass(headerStatusIcon.warning);
}
if (dropZone.length > 0) {
dropZone.append(headerUploadStatus);
} else {
$('.k-upload-button', that.wrapper).after(headerUploadStatus);
}
},
_updateHeaderUploadStatus: function() {
var that = this;
var headerUploadStatus = $('.k-upload-status-total', this.wrapper);
var currentlyUploading = $('.k-file', that.wrapper).not('.k-file-success, .k-file-error, .k-file-invalid');
var currentlyInvalid = $('.k-file-invalid', that.wrapper);
var currentlyFailed = $('.k-file-error', that.wrapper);
var currentlyPaused = $('.k-file', that.wrapper).find(".k-i-play-sm");
var failedUploads, headerUploadStatusIcon;
if(currentlyPaused.length &&
(currentlyPaused.length === currentlyUploading.length || !that.options.async.concurrent)){
headerUploadStatusIcon = $('.k-icon', headerUploadStatus)
.removeClass()
.addClass("k-icon")
.addClass("k-i-pause-sm");
headerUploadStatus.html(headerUploadStatusIcon)
.append(that.localization.headerStatusPaused);
}else if (currentlyUploading.length === 0 || currentlyInvalid.length > 0 || currentlyFailed.length > 0) {
failedUploads = $('.k-file.k-file-error, .k-file.k-file-invalid', that.wrapper);
headerUploadStatus = $('.k-upload-status-total', that.wrapper);
headerUploadStatusIcon = $('.k-icon', headerUploadStatus).removeClass().addClass("k-icon")
.addClass(failedUploads.length !== 0 ? headerStatusIcon.warning : headerStatusIcon.success);
headerUploadStatus.html(headerUploadStatusIcon)
.append(that.localization.headerStatusUploaded);
}
},
_hideHeaderUploadstatus: function() {
$('.k-upload-status-total', this.wrapper).remove();
},
_onParentFormSubmit: function() {
var upload = this,
element = upload.element;
if(typeof this._module.onAbort !== 'undefined'){
this._module.onAbort();
}
if (!element.value) {
var input = $(element);
// Prevent submitting an empty input
input.attr("disabled", "disabled");
window.setTimeout(function() {
// Restore the input so the Upload remains functional
// in case the user cancels the form submit
input.removeAttr("disabled");
}, 0);
}
},
_onParentFormReset: function() {
$(".k-upload-files", this.wrapper).remove();
},
_supportsFormData: function() {
return typeof(FormData) != "undefined";
},
_supportsMultiple: function() {
var windows = this._userAgent().indexOf("Windows") > -1;
return !kendo.support.browser.opera &&
!(kendo.support.browser.safari && windows);
},
_supportsDrop: function() {
var userAgent = this._userAgent().toLowerCase();
var isChrome = /chrome/.test(userAgent);
var isSafari = !isChrome && /safari/.test(userAgent);
var isWindowsSafari = isSafari && /windows/.test(userAgent);
return !isWindowsSafari && this._supportsFormData() && (this.options.async.saveUrl);
},
_userAgent: function() {
return navigator.userAgent;
},
_setupDropZone: function() {
var that = this;
$(".k-upload-button", that.wrapper).wrap("<div class='k-dropzone'></div>");
var ns = that._ns;
var dropZone = $(".k-dropzone", that.wrapper)
.append($("<em>" + that.localization.dropFilesHere + "</em>"))
.on("dragenter" + ns, stopEvent)
.on("dragover" + ns, function(e) { e.preventDefault(); })
.on("drop" + ns, $.proxy(that._onDrop, that));
bindDragEventWrappers(dropZone, ns,
function() {
if (!dropZone.closest('.k-upload').hasClass("k-state-disabled")) {
dropZone.addClass("k-dropzone-hovered");
}
},
function() { dropZone.removeClass("k-dropzone-hovered"); });
that._bindDocumentDragEventWrappers(dropZone);
},
_setupCustomDropZone: function() {
var that = this;
var dropZone = $(that.options.dropZone);
$(".k-upload-button", that.wrapper)
.wrap("<div class='k-dropzone'></div>")
.after($("<em>" + that.localization.dropFilesHere + "</em>"));
var ns = that._ns;
dropZone.on("dragenter" + ns, stopEvent)
.on("dragover" + ns, function(e) { e.preventDefault(); })
.on("drop" + ns, $.proxy(that._onDrop, that));
bindDragEventWrappers(dropZone, ns,