vue-transmit
Advanced tools
Comparing version 9.0.0-alpha.1 to 9.0.0-alpha.2
@@ -5,2 +5,12 @@ # Change Log | ||
<a name="9.0.0-alpha.2"></a> | ||
# [9.0.0-alpha.2](https://github.com/alexsasharegan/vue-transmit/compare/v8.0.0...v9.0.0-alpha.2) (2018-02-09) | ||
### Features | ||
* abstract upload transport into adapter ([#27](https://github.com/alexsasharegan/vue-transmit/issues/27)) ([6cf71cf](https://github.com/alexsasharegan/vue-transmit/commit/6cf71cf)) | ||
<a name="9.0.0-alpha.1"></a> | ||
@@ -7,0 +17,0 @@ # [9.0.0-alpha.1](https://github.com/alexsasharegan/vue-transmit/compare/v9.0.0-alpha.0...v9.0.0-alpha.1) (2018-02-09) |
@@ -1,2 +0,1256 @@ | ||
import Vue from"vue";var UploadStatuses,VTransmitEvents,idCounter=0;function uniqueId(e){return e+ ++idCounter}function round(e,t,i){void 0===t&&(t=2),void 0===i&&(i="round");var s=Math.pow(10,t);return Math[i](e*s)/s}function fromBytesToKbit(e){return e/125}function fromBytesToMbit(e){return e/125e3}function toKbps(e,t){return fromBytesToKbit(e)/t}function toMbps(e,t){return fromBytesToMbit(e)/t}function objFactory(){return{}}function noop(){}function scaleH(e,t){return t/e}function scaleW(e,t){return t*e}function resizeImg(e,t){var i,s,a=e.width/e.height,n=t.width/t.height,r={sx:0,sy:0,sWidth:e.width,sHeight:e.height,dx:0,dy:0,dWidth:t.width,dHeight:t.height};return n>a?(i=e.width,s=scaleH(n,e.width)):(i=scaleW(n,e.height),s=e.height),i<e.width&&(r.sx=(e.width-i)/2,r.sWidth=i),s<e.height&&(r.sy=(e.height-s)/2,r.sHeight=s),r}function webkitIsFile(e){return e.isFile}function webkitIsDir(e){return e.isDirectory}!function(e){e.None="",e.Added="added",e.Queued="queued",e.Accepted="queued",e.Uploading="uploading",e.Canceled="canceled",e.Error="error",e.Timeout="timeout",e.Success="success"}(UploadStatuses||(UploadStatuses={})),function(e){e.Initialize="initialize",e.AddedFile="added-file",e.AddedFiles="added-files",e.RemovedFile="removed-file",e.AcceptedFile="accepted-file",e.RejectedFile="rejected-file",e.AcceptComplete="accept-complete",e.Thumbnail="thumbnail",e.Processing="processing",e.ProcessingMultiple="processing-multiple",e.Canceled="canceled",e.CanceledMultiple="canceled-multiple",e.Sending="sending",e.SendingMultiple="sending-multiple",e.Timeout="timeout",e.TimeoutMultiple="timeout-multiple",e.UploadProgress="upload-progress",e.TotalUploadProgress="total-upload-progress",e.Success="success",e.SuccessMultiple="success-multiple",e.QueueComplete="queue-complete",e.Complete="complete",e.CompleteMultiple="complete-multiple",e.Error="error",e.ErrorMultiple="error-multiple",e.MaxFilesReached="max-files-reached",e.MaxFilesExceeded="max-files-exceeded",e.Reset="reset",e.DragOver="drag-over",e.DragEnter="drag-enter",e.DragLeave="drag-leave",e.DragEnd="drag-end",e.Drop="drop",e.Paste="paste"}(VTransmitEvents||(VTransmitEvents={}));var VTransmitFile=function(){function e(t){this._dataUrl="",this.id=e.idFactory(),this.status=UploadStatuses.None,this.accepted=!1,this.processing=!1,this.width=0,this.height=0,this.errorMessage="",this.adapterData={},this.upload={bytesSent:0,progress:0,total:0,speed:{kbps:0,mbps:0},start:0,end:0,time:0},this.nativeFile=t,this.lastModified=t.lastModified,this.lastModifiedDate=t.lastModifiedDate,this.name=t.name,this.size=t.size,this.type=t.type,this.webkitRelativePath=t.webkitRelativePath,this.upload.total=t.size}return e.prototype.handleProgress=function(e){this.startProgress();var t=e.total||this.upload.total;this.upload.progress=Math.min(100,100*e.loaded/t),this.upload.bytesSent=e.loaded,this.upload.total=t,this.upload.time=(Date.now()-this.upload.start)/1e3,this.upload.speed.kbps=round(toKbps(this.upload.bytesSent,this.upload.time)),this.upload.speed.mbps=round(toMbps(this.upload.bytesSent,this.upload.time)),100===this.upload.progress&&this.endProgress()},e.prototype.startProgress=function(){return this.upload.start||(this.upload.start=Date.now()),this},e.prototype.endProgress=function(){return this.upload.end||(this.upload.end=Date.now(),this.upload.time=(Date.now()-this.upload.start)/1e3),this},Object.defineProperty(e.prototype,"dataUrl",{get:function(){return this._dataUrl||""},set:function(e){Object.defineProperty(this,"_dataUrl",{value:e,enumerable:!1,configurable:!0,writable:!0})},enumerable:!0,configurable:!0}),e.idFactory=function(){return uniqueId("v-transmit-file-")},e}(),VTransmitUploadContext=function(){function e(e){this.vtransmit=e,this.Statuses=UploadStatuses,this.Events=VTransmitEvents,this.props=e.$props}return e.prototype.emit=function(e){for(var t,i=[],s=1;s<arguments.length;s++)i[s-1]=arguments[s];(t=this.vtransmit).$emit.apply(t,[e].concat(i))},Object.defineProperty(e.prototype,"acceptedFiles",{get:function(){return this.vtransmit.acceptedFiles},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rejectedFiles",{get:function(){return this.vtransmit.rejectedFiles},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"addedFiles",{get:function(){return this.vtransmit.addedFiles},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"queuedFiles",{get:function(){return this.vtransmit.queuedFiles},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"uploadingFiles",{get:function(){return this.vtransmit.uploadingFiles},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"activeFiles",{get:function(){return this.vtransmit.activeFiles},enumerable:!0,configurable:!0}),e}(),GroupID=0,XHRUploadAdapter=function(){function e(e,t){this.context=e,this.url="",this.method="post",this.withCredentials=!1,this.timeout=0,this.paramName="file",this.params=Object.create(null),this.headers={Accept:"application/json","Cache-Control":"no-cache","X-Requested-With":"XMLHttpRequest"},this.responseType="",this.errUploadError=function(e){return"Error during upload: "+e.statusText+" ["+e.status+"]"},this.errUploadTimeout=function(e){return"Error during upload: the server timed out."},this.renameFile=function(e){return e},this.uploadGroups=Object.create(null),Object.assign(this,t)}return e.prototype.uploadFiles=function(e){var t=this;return new Promise(function(i,s){if(!t.url)throw new Error("[Vue-Transmit] Missing upload URL.");var a=new XMLHttpRequest,n=t.handleUploadProgress(e),r=GroupID++;t.uploadGroups[r]={id:r,xhr:a,files:e};for(var o=0,l=e;o<l.length;o++){var u=l[o];u.adapterData.groupID=r,u.startProgress()}a.open(t.method,t.url,!0),a.timeout=t.timeout,a.withCredentials=Boolean(t.withCredentials),a.responseType=t.responseType,a.addEventListener("error",function(){t.rmGroup(r),s({event:VTransmitEvents.Error,message:t.errUploadError(a),xhr:a})}),a.upload.addEventListener("progress",n),a.addEventListener("timeout",function(){t.rmGroup(r),s({event:VTransmitEvents.Timeout,message:t.errUploadTimeout(a),xhr:a})}),a.addEventListener("load",function(o){if(e[0].status!==UploadStatuses.Canceled&&a.readyState===XMLHttpRequest.DONE){t.rmGroup(r);var l={};if(t.responseParseFunc)l=t.responseParseFunc(a);else if(Object.assign(l,a.response),!a.responseType){var u=a.getResponseHeader("content-type");if(u&&u.indexOf("application/json")>-1)try{l=JSON.parse(a.responseText)}catch(e){return s({message:"Invalid JSON response from server.",event:VTransmitEvents.Error,error:e})}}return n(),a.status<200||a.status>=300?s({event:VTransmitEvents.Error,message:"The server responded with code "+a.status+" ("+a.statusText+").",xhr:a}):i(l)}});var d=Object.assign(Object.create(null),t.headers);for(var p in d)d[p]&&a.setRequestHeader(p,d[p]);var c,h=new FormData;for(var m in t.params)h.append(m,t.params[m]);for(var f=0,g=e;f<g.length;f++){var v=g[f];t.context.emit(VTransmitEvents.Sending,v,a,h)}t.context.props.uploadMultiple&&t.context.emit(VTransmitEvents.SendingMultiple,e,a,h);for(var F=0;F<e.length;F++)(c=e[F].nativeFile)&&h.append(t.getParamName(F),c,t.renameFile(e[F].name||""));a.send(h)})},e.prototype.handleUploadProgress=function(e){var t=this.context.vtransmit;return function(i){if(!i){for(var s=!0,a=0,n=e;a<n.length;a++){100===(l=n[a]).upload.progress&&l.upload.bytesSent===l.upload.total||(s=!1),l.upload.progress=100,l.upload.bytesSent=l.upload.total,l.endProgress()}if(s)return}for(var r=0,o=e;r<o.length;r++){var l=o[r];i&&l.handleProgress(i),t.$emit(VTransmitEvents.UploadProgress,l,l.upload.progress,l.upload.bytesSent)}}},e.prototype.getParamName=function(e){return this.paramName+(this.context.props.uploadMultiple?"["+e+"]":"")},e.prototype.cancelUpload=function(e){var t=this.uploadGroups[e.adapterData.groupID];return t?(t.xhr.abort(),this.rmGroup(e.adapterData.groupID),t.files.slice()):[]},e.prototype.rmGroup=function(e){delete this.uploadGroups[e]},e}(),VueTransmit=Vue.extend({render:function(){var e=this,t=e.$createElement,i=e._self._c||t;return i(e.tag,{tag:"component"},[i("div",e._g(e._b({staticClass:"v-transmit__upload-area",class:[e.isDraggingClass,e.uploadAreaClasses],attrs:{draggable:"true"},on:{click:e.handleClickUploaderAction,dragstart:e.handleDragStart,dragend:e.handleDragEnd,dragenter:function(t){t.preventDefault(),t.stopPropagation(),e.handleDragEnter(t)},dragover:function(t){t.preventDefault(),t.stopPropagation(),e.handleDragOver(t)},dragleave:e.handleDragLeave,drop:function(t){t.preventDefault(),t.stopPropagation(),e.handleDrop(t)}}},"div",e.uploadAreaAttrs,!1),e.uploadAreaListeners),[e._t("default")],2),e._v(" "),e._t("files",null,null,e.fileSlotBindings),e._v(" "),i("form",{ref:"uploadForm",style:e.formStyles},[i("input",{ref:"hiddenFileInput",class:[e.maxFilesReachedClass],attrs:{type:"file",multiple:e.multiple,accept:e.filesToAccept,capture:e.capture},on:{change:e.onFileInputChange}})])],2)},staticRenderFns:[],name:"VueTransmit",props:{tag:{type:String,default:"div"},uploadAreaClasses:{type:[Array,Object,String],default:null},uploadAreaAttrs:{type:Object,default:objFactory},uploadAreaListeners:{type:Object,default:objFactory},dragClass:{type:String,default:null},maxConcurrentUploads:{type:Number,default:2},uploadMultiple:{type:Boolean,default:!1},maxFileSize:{type:Number,default:256},fileSizeBaseInBinary:{type:Boolean,default:!1},createImageThumbnails:{type:Boolean,default:!0},maxThumbnailFileSize:{type:Number,default:10},thumbnailWidth:{type:Number,default:120},thumbnailHeight:{type:Number,default:120},maxFiles:{type:Number,default:null},clickable:{type:Boolean,default:!0},ignoreHiddenFiles:{type:Boolean,default:!0},acceptedFileTypes:{type:Array,default:function(){return[]}},autoProcessQueue:{type:Boolean,default:!0},autoQueue:{type:Boolean,default:!0},capture:{type:String,default:null},errMaxFileSizeExceeded:{type:Function,default:function(e,t,i){return"The file is too big ("+e+i+"). Max file size: "+t+i+"."}},errInvalidFileType:{type:Function,default:function(e,t,i){return"You can't upload files of this type: "+e}},errMaxFilesExceeded:{type:Function,default:function(e){return"You can not upload any more files ("+e+" max)."}},accept:{type:Function,default:function(e,t){t()}},resize:{type:Function,default:resizeImg},adapterOptions:{type:Object,default:objFactory},uploadAdapter:{type:Function,default:XHRUploadAdapter}},mounted:function(){var e=this;this.$on(VTransmitEvents.UploadProgress,this.updateTotalUploadProgress),this.$on(VTransmitEvents.RemovedFile,this.updateTotalUploadProgress),this.$on(VTransmitEvents.Canceled,function(t){return e.$emit(VTransmitEvents.Complete,t)}),this.$on(VTransmitEvents.Complete,function(t){0===e.addedFiles.length&&0===e.uploadingFiles.length&&0===e.queuedFiles.length&&Promise.resolve().then(function(){return e.$emit(VTransmitEvents.QueueComplete,t)})}),this.$emit(VTransmitEvents.Initialize,this)},data:function(){return{dragging:!1,processingThumbnail:!1,thumbnailQueue:[],files:[],defaultHeaders:{Accept:"application/json","Cache-Control":"no-cache","X-Requested-With":"XMLHttpRequest"},formStyles:{visibility:"hidden !important",position:"absolute !important",top:"0 !important",left:"0 !important",height:"0px !important",width:"0px !important"}}},computed:{inputEl:function(){var e=this.$refs.hiddenFileInput;return e instanceof HTMLInputElement?e:null},formEl:function(){var e=this.$refs.uploadForm;return e instanceof HTMLFormElement?e:null},fileSizeBase:function(){return this.fileSizeBaseInBinary?1024:1e3},maxFileSizeBytes:function(){return this.maxFileSize*this.fileSizeBase*this.fileSizeBase},filesToAccept:function(){return this.acceptedFileTypes.join(",")},multiple:function(){return null===this.maxFiles||this.maxFiles>1},acceptedFiles:function(){return this.files.filter(function(e){return e.accepted})},rejectedFiles:function(){return this.files.filter(function(e){return!e.accepted})},addedFiles:function(){return this.getFilesWithStatus(UploadStatuses.Added)},queuedFiles:function(){return this.getFilesWithStatus(UploadStatuses.Queued)},uploadingFiles:function(){return this.getFilesWithStatus(UploadStatuses.Uploading)},activeFiles:function(){return this.getFilesWithStatus(UploadStatuses.Uploading,UploadStatuses.Queued)},maxFilesReached:function(){return null!=this.maxFiles&&this.acceptedFiles.length>=this.maxFiles},maxFilesReachedClass:function(){return this.maxFilesReached?"v-transmit__max-files--reached":null},isDraggingClass:function(){return(e={"v-transmit__upload-area--is-dragging":this.dragging})[this.dragClass]=this.dragging,e;var e},isUploading:function(){return this.uploadingFiles.length>0},fileSlotBindings:function(){return{files:this.files,acceptedFiles:this.acceptedFiles,rejectedFiles:this.rejectedFiles,addedFiles:this.addedFiles,queuedFiles:this.queuedFiles,uploadingFiles:this.uploadingFiles,activeFiles:this.activeFiles,isUploading:this.isUploading}},transport:function(){var e=this.uploadAdapter;try{return new e(new VTransmitUploadContext(this),this.adapterOptions)}catch(e){throw console.error(e),e}}},watch:{acceptedFiles:function(e){null!=this.maxFiles&&e.length>=this.maxFiles&&this.$emit(VTransmitEvents.MaxFilesReached,this.files)}},methods:{getFilesWithStatus:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this.files.filter(function(t){return e.indexOf(t.status)>-1})},onFileInputChange:function(){var e=this.inputEl,t=this.formEl;if(null==e||null==t)throw TypeError();e.files&&(this.$emit(VTransmitEvents.AddedFiles,Array.from(e.files).map(this.addFile)),t.reset())},addFile:function(e){var t=this,i=new VTransmitFile(e);return i.status=UploadStatuses.Added,this.files.push(i),this.$emit(VTransmitEvents.AddedFile,i),this.enqueueThumbnail(i),this.acceptFile(i,function(e){if(e)return i.accepted=!1,t.errorProcessing([i],e),t.$emit(VTransmitEvents.RejectedFile,i),void t.$emit(VTransmitEvents.AcceptComplete,i);i.accepted=!0,t.$emit(VTransmitEvents.AcceptedFile,i),t.$emit(VTransmitEvents.AcceptComplete,i),t.autoQueue&&t.enqueueFile(i)}),i},acceptFile:function(e,t){if(e.size>this.maxFileSizeBytes){var i=this.fileSizeBase*this.fileSizeBase,s=e.size/i,a="MB";return this.fileSizeBaseInBinary&&(a="MiB"),t(this.errMaxFileSizeExceeded(s,this.maxFileSize,a))}return this.isValidFileType(e,this.acceptedFileTypes)?null!=this.maxFiles&&this.acceptedFiles.length>=this.maxFiles?(this.$emit(VTransmitEvents.MaxFilesExceeded,e),t(this.errMaxFilesExceeded(this.maxFiles))):void this.accept(e,t):t(this.errInvalidFileType(e.type,this.acceptedFileTypes,e))},removeFile:function(e){e.status===UploadStatuses.Uploading&&this.cancelUpload(e);var t=this.files.findIndex(function(t){return t.id===e.id});t>-1&&(this.$emit(VTransmitEvents.RemovedFile,this.files.splice(t,1)[0]),0===this.files.length&&this.$emit(VTransmitEvents.Reset))},removeAllFiles:function(e){var t;void 0===e&&(e=!1);for(var i=0,s=this.files;i<s.length;i++)((t=s[i]).status!==UploadStatuses.Uploading||e)&&this.removeFile(t)},triggerBrowseFiles:function(){this.inputEl&&this.inputEl.click()},handleClickUploaderAction:function(){this.clickable&&this.triggerBrowseFiles()},enqueueFile:function(e){if(e.status!==UploadStatuses.Added||!0!==e.accepted)throw new Error("This file can't be queued because it has already been processed or was rejected.");e.status=UploadStatuses.Queued,this.autoProcessQueue&&setTimeout(this.processQueue,0)},enqueueThumbnail:function(e){!this.createImageThumbnails||!e.type.match(/image.*/)||e.size>1024*this.maxThumbnailFileSize*1024||(this.thumbnailQueue.push(e),setTimeout(this.processThumbnailQueue,0))},processThumbnailQueue:function(){var e,t=this;this.processingThumbnail||0===this.thumbnailQueue.length||(this.processingThumbnail=!0,(e=this.thumbnailQueue.shift())&&this.createThumbnail(e,function(){t.processingThumbnail=!1,t.processThumbnailQueue()}))},createThumbnail:function(e,t){var i=this;void 0===t&&(t=noop);var s=new FileReader;s.addEventListener("load",function(){"image/svg+xml"===e.type&&(e.dataUrl=s.result,i.$emit(VTransmitEvents.Thumbnail,e,s.result),t()),i.createThumbnailFromUrl(e,s.result,t)},!1),s.readAsDataURL(e.nativeFile)},createThumbnailFromUrl:function(e,t,i){var s=this,a=document.createElement("img");a.addEventListener("load",function(){var t;e.width=a.width,e.height=a.height;var n=s.resize(e,{width:s.thumbnailWidth,height:s.thumbnailHeight}),r=document.createElement("canvas");if(t=r.getContext("2d")){r.width=n.dWidth,r.height=n.dHeight,t.drawImage(a,n.sx,n.sy,n.sWidth,n.sHeight,n.dx,n.dy,n.dWidth,n.dHeight);var o=r.toDataURL("image/png");return e.dataUrl=o,s.$emit(VTransmitEvents.Thumbnail,e,o),i?i():void 0}},!1),i&&a.addEventListener("error",i,!1),a.src=t},processQueue:function(){var e=this.uploadingFiles.length;if(!(e>=this.maxConcurrentUploads||0===this.queuedFiles.length)){var t=this.queuedFiles.slice();if(this.uploadMultiple)return this.processFiles(t.slice(0,this.maxConcurrentUploads-e));for(var i,s=e;s<this.maxConcurrentUploads;s++)(i=t.shift())&&this.processFile(i)}},processFile:function(e){this.processFiles([e])},processFiles:function(e){for(var t,i=0,s=e;i<s.length;i++)(t=s[i]).processing=!0,t.status=UploadStatuses.Uploading,this.$emit(VTransmitEvents.Processing,t);return this.uploadMultiple&&this.$emit(VTransmitEvents.ProcessingMultiple,e),this.uploadFiles(e)},cancelUpload:function(e){if(e.status!==UploadStatuses.Added&&e.status!==UploadStatuses.Queued||(e.status=UploadStatuses.Canceled,this.$emit(VTransmitEvents.Canceled,e),this.uploadMultiple&&this.$emit(VTransmitEvents.CanceledMultiple,[e])),e.status===UploadStatuses.Uploading){for(var t=this.transport.cancelUpload(e),i=void 0,s=0,a=t;s<a.length;s++)(i=a[s]).status=UploadStatuses.Canceled,this.$emit(VTransmitEvents.Canceled,i);this.uploadMultiple&&this.$emit(VTransmitEvents.CanceledMultiple,t)}this.autoProcessQueue&&this.processQueue()},uploadFile:function(e){this.uploadFiles([e])},uploadFiles:function(e){var t=this;this.transport.uploadFiles(e).then(function(i){return t.uploadFinished(e,i)}).catch(function(i){switch(i.event){case VTransmitEvents.Timeout:t.handleTimeout(e,i.message);break;case VTransmitEvents.Error:default:t.errorProcessing(e,i.message)}})},handleTimeout:function(e,t){for(var i,s=[],a=2;a<arguments.length;a++)s[a-2]=arguments[a];for(var n=0,r=e;n<r.length;n++)(i=r[n]).status=UploadStatuses.Timeout,i.endProgress(),this.$emit.apply(this,[VTransmitEvents.Timeout,i,t].concat(s));this.$emit.apply(this,[VTransmitEvents.TimeoutMultiple,e,t].concat(s)),this.autoProcessQueue&&this.processQueue()},updateTotalUploadProgress:function(){var e=this.activeFiles.reduce(function(e,t){return e.totalBytesSent+=t.upload.bytesSent,e.totalBytes+=t.upload.total,e},{totalBytesSent:0,totalBytes:0,totalProgress:100});this.activeFiles.length&&(e.totalProgress=100*e.totalBytesSent/e.totalBytes),this.$emit(VTransmitEvents.TotalUploadProgress,e)},uploadFinished:function(e,t){for(var i=[],s=2;s<arguments.length;s++)i[s-2]=arguments[s];for(var a=0,n=e;a<n.length;a++){var r=n[a];r.status=UploadStatuses.Success,r.endProgress(),this.$emit.apply(this,[VTransmitEvents.Success,r,t].concat(i)),this.$emit(VTransmitEvents.Complete,r)}this.uploadMultiple&&(this.$emit.apply(this,[VTransmitEvents.SuccessMultiple,e,t].concat(i)),this.$emit(VTransmitEvents.CompleteMultiple,e)),this.autoProcessQueue&&this.processQueue()},errorProcessing:function(e,t,i){for(var s=0,a=e;s<a.length;s++){var n=a[s];n.status=UploadStatuses.Error,n.endProgress(),this.$emit(VTransmitEvents.Error,n,t,i),this.$emit(VTransmitEvents.Complete,n)}if(this.uploadMultiple&&(this.$emit(VTransmitEvents.ErrorMultiple,e,t,i),this.$emit(VTransmitEvents.CompleteMultiple,e)),this.autoProcessQueue)return this.processQueue()},isValidFileType:function(e,t){if(!t.length)return!0;for(var i=e.type,s=i.replace(/\/.*$/,""),a=0;a<t.length;a++){var n=t[a];if("."===n.charAt(0)){if(-1!==e.name.toLowerCase().indexOf(n.toLowerCase(),e.name.length-n.length))return!0}else if(/\/\*$/.test(n)){if(s===n.replace(/\/.*$/,""))return!0}else if(i===n)return!0}return!1},handleDragStart:function(e){this.$emit("drag-start",e)},handleDragOver:function(e){var t;this.dragging=!0;try{t=e.dataTransfer.effectAllowed}catch(e){}e.dataTransfer.dropEffect="move"===t||"linkMove"===t?"move":"copy",this.$emit(VTransmitEvents.DragOver,e)},handleDragEnter:function(e){this.dragging=!0,this.$emit(VTransmitEvents.DragEnter,e)},handleDragLeave:function(e){this.dragging=!1,this.$emit(VTransmitEvents.DragLeave,e)},handleDragEnd:function(e){this.dragging=!1,this.$emit(VTransmitEvents.DragEnd,e)},handleDrop:function(e){var t,i;(this.dragging=!1,e.dataTransfer)&&(this.$emit(VTransmitEvents.Drop,e),this.$emit(VTransmitEvents.AddedFiles,t=Array.from(e.dataTransfer.files)),e.dataTransfer.items&&(i=Array.from(e.dataTransfer.items))&&i.length&&(i[0].getAsFile||i[0].webkitGetAsEntry)?this.addFilesFromItems(i):this.handleFiles(t))},paste:function(e){if(e&&e.clipboardData&&e.clipboardData.items){this.$emit(VTransmitEvents.Paste,e);var t=Array.from(e.clipboardData.items);t.length&&this.addFilesFromItems(t)}},handleFiles:function(e){return e.map(this.addFile)},addFilesFromItems:function(e){for(var t,i=0,s=e;i<s.length;i++){var a=s[i];if(a.getAsFile&&"file"==a.kind){var n=a.getAsFile();n&&this.addFile(n)}else if(a.webkitGetAsEntry){if(null==(t=a.webkitGetAsEntry()))continue;if(webkitIsFile(t)){t.file(this.addFile,console.error);continue}if(webkitIsDir(t)){this.addFilesFromDirectory(t,t.name);continue}}}},addFilesFromDirectory:function(e,t){var i=this;e.createReader().readEntries(function(e){for(var s=0,a=e;s<a.length;s++){var n=a[s];null!=n&&(webkitIsDir(n)?i.addFilesFromDirectory(n,t+"/"+n.name):webkitIsFile(n)&&n.file(function(e){i.ignoreHiddenFiles&&/^\./.test(e.name)||(e.fullPath=t+"/"+e.name,i.addFile(e))},console.error))}},console.error)}}}),Plugin={install:function(e){e.component("VueTransmit",VueTransmit)},name:"vue-transmit"};export default Plugin; | ||
import Vue from 'vue'; | ||
var idCounter = 0; | ||
function uniqueId(prefix) { | ||
return prefix + ++idCounter; | ||
} | ||
function round(number, decimals, roundStyle) { | ||
if (decimals === void 0) { decimals = 2; } | ||
if (roundStyle === void 0) { roundStyle = "round"; } | ||
var roundingFactor = Math.pow(10, decimals); | ||
return Math[roundStyle](number * roundingFactor) / roundingFactor; | ||
} | ||
function fromBytesToKbit(bytes) { | ||
return bytes / 125; | ||
} | ||
function fromBytesToMbit(bytes) { | ||
return bytes / 125000; | ||
} | ||
function toKbps(bytes, seconds) { | ||
return fromBytesToKbit(bytes) / seconds; | ||
} | ||
function toMbps(bytes, seconds) { | ||
return fromBytesToMbit(bytes) / seconds; | ||
} | ||
function objFactory() { | ||
return {}; | ||
} | ||
function noop() { } | ||
function scaleH(ratio, width) { | ||
return width / ratio; | ||
} | ||
function scaleW(ratio, height) { | ||
return height * ratio; | ||
} | ||
var UploadStatuses; | ||
(function (UploadStatuses) { | ||
UploadStatuses["None"] = ""; | ||
UploadStatuses["Added"] = "added"; | ||
UploadStatuses["Queued"] = "queued"; | ||
UploadStatuses["Accepted"] = "queued"; | ||
UploadStatuses["Uploading"] = "uploading"; | ||
UploadStatuses["Canceled"] = "canceled"; | ||
UploadStatuses["Error"] = "error"; | ||
UploadStatuses["Timeout"] = "timeout"; | ||
UploadStatuses["Success"] = "success"; | ||
})(UploadStatuses || (UploadStatuses = {})); | ||
var VTransmitEvents; | ||
(function (VTransmitEvents) { | ||
VTransmitEvents["Initialize"] = "initialize"; | ||
VTransmitEvents["AddedFile"] = "added-file"; | ||
VTransmitEvents["AddedFiles"] = "added-files"; | ||
VTransmitEvents["RemovedFile"] = "removed-file"; | ||
VTransmitEvents["AcceptedFile"] = "accepted-file"; | ||
VTransmitEvents["RejectedFile"] = "rejected-file"; | ||
VTransmitEvents["AcceptComplete"] = "accept-complete"; | ||
VTransmitEvents["Thumbnail"] = "thumbnail"; | ||
VTransmitEvents["Processing"] = "processing"; | ||
VTransmitEvents["ProcessingMultiple"] = "processing-multiple"; | ||
VTransmitEvents["Canceled"] = "canceled"; | ||
VTransmitEvents["CanceledMultiple"] = "canceled-multiple"; | ||
VTransmitEvents["Sending"] = "sending"; | ||
VTransmitEvents["SendingMultiple"] = "sending-multiple"; | ||
VTransmitEvents["Timeout"] = "timeout"; | ||
VTransmitEvents["TimeoutMultiple"] = "timeout-multiple"; | ||
VTransmitEvents["UploadProgress"] = "upload-progress"; | ||
VTransmitEvents["TotalUploadProgress"] = "total-upload-progress"; | ||
VTransmitEvents["Success"] = "success"; | ||
VTransmitEvents["SuccessMultiple"] = "success-multiple"; | ||
VTransmitEvents["QueueComplete"] = "queue-complete"; | ||
VTransmitEvents["Complete"] = "complete"; | ||
VTransmitEvents["CompleteMultiple"] = "complete-multiple"; | ||
VTransmitEvents["Error"] = "error"; | ||
VTransmitEvents["ErrorMultiple"] = "error-multiple"; | ||
VTransmitEvents["MaxFilesReached"] = "max-files-reached"; | ||
VTransmitEvents["MaxFilesExceeded"] = "max-files-exceeded"; | ||
VTransmitEvents["Reset"] = "reset"; | ||
VTransmitEvents["DragOver"] = "drag-over"; | ||
VTransmitEvents["DragEnter"] = "drag-enter"; | ||
VTransmitEvents["DragLeave"] = "drag-leave"; | ||
VTransmitEvents["DragEnd"] = "drag-end"; | ||
VTransmitEvents["Drop"] = "drop"; | ||
VTransmitEvents["Paste"] = "paste"; | ||
})(VTransmitEvents || (VTransmitEvents = {})); | ||
function resizeImg(file, dims) { | ||
// 's' variables are for source | ||
// 'd' variables are for destination | ||
var sRatio = file.width / file.height; | ||
var dRatio = dims.width / dims.height; | ||
var coords = { | ||
sx: 0, | ||
sy: 0, | ||
sWidth: file.width, | ||
sHeight: file.height, | ||
dx: 0, | ||
dy: 0, | ||
dWidth: dims.width, | ||
dHeight: dims.height, | ||
}; | ||
var w, h; | ||
if (dRatio > sRatio) { | ||
w = file.width; | ||
h = scaleH(dRatio, file.width); | ||
} | ||
else { | ||
w = scaleW(dRatio, file.height); | ||
h = file.height; | ||
} | ||
if (w < file.width) { | ||
coords.sx = (file.width - w) / 2; | ||
coords.sWidth = w; | ||
} | ||
if (h < file.height) { | ||
coords.sy = (file.height - h) / 2; | ||
coords.sHeight = h; | ||
} | ||
return coords; | ||
} | ||
function webkitIsFile(entry) { | ||
return entry.isFile; | ||
} | ||
function webkitIsDir(entry) { | ||
return entry.isDirectory; | ||
} | ||
var VTransmitFile = /** @class */ (function () { | ||
function VTransmitFile(file) { | ||
this._dataUrl = ""; | ||
this.id = VTransmitFile.idFactory(); | ||
this.status = UploadStatuses.None; | ||
this.accepted = false; // Passed all validation. | ||
this.processing = false; | ||
this.width = 0; | ||
this.height = 0; | ||
this.errorMessage = ""; | ||
this.adapterData = {}; | ||
this.upload = { | ||
bytesSent: 0, | ||
progress: 0, | ||
total: 0, | ||
speed: { | ||
kbps: 0, | ||
mbps: 0, | ||
}, | ||
start: 0, | ||
end: 0, | ||
time: 0, | ||
}; | ||
this.nativeFile = file; | ||
this.lastModified = file.lastModified; | ||
this.lastModifiedDate = file.lastModifiedDate; | ||
this.name = file.name; | ||
this.size = file.size; | ||
this.type = file.type; | ||
this.webkitRelativePath = file.webkitRelativePath; | ||
this.upload.total = file.size; | ||
} | ||
VTransmitFile.prototype.handleProgress = function (e) { | ||
this.startProgress(); | ||
var total = e.total || this.upload.total; | ||
this.upload.progress = Math.min(100, 100 * e.loaded / total); | ||
this.upload.bytesSent = e.loaded; | ||
this.upload.total = total; | ||
this.upload.time = (Date.now() - this.upload.start) / 1000; | ||
// Recalculate the upload speed in bytes/sec | ||
this.upload.speed.kbps = round(toKbps(this.upload.bytesSent, this.upload.time)); | ||
this.upload.speed.mbps = round(toMbps(this.upload.bytesSent, this.upload.time)); | ||
if (this.upload.progress === 100) { | ||
this.endProgress(); | ||
} | ||
}; | ||
VTransmitFile.prototype.startProgress = function () { | ||
// Avoid starting twice | ||
if (!this.upload.start) { | ||
this.upload.start = Date.now(); | ||
} | ||
return this; | ||
}; | ||
VTransmitFile.prototype.endProgress = function () { | ||
// Avoid ending twice | ||
if (!this.upload.end) { | ||
this.upload.end = Date.now(); | ||
this.upload.time = (Date.now() - this.upload.start) / 1000; | ||
} | ||
return this; | ||
}; | ||
Object.defineProperty(VTransmitFile.prototype, "dataUrl", { | ||
get: function () { | ||
return this._dataUrl || ""; | ||
}, | ||
set: function (value) { | ||
// Use non-enumerable data url to avoid copying around large datasets | ||
Object.defineProperty(this, "_dataUrl", { | ||
value: value, | ||
enumerable: false, | ||
configurable: true, | ||
writable: true, | ||
}); | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
VTransmitFile.idFactory = function () { | ||
return uniqueId("v-transmit-file-"); | ||
}; | ||
return VTransmitFile; | ||
}()); | ||
var VTransmitUploadContext = /** @class */ (function () { | ||
function VTransmitUploadContext(vtransmit) { | ||
this.vtransmit = vtransmit; | ||
this.Statuses = UploadStatuses; | ||
this.Events = VTransmitEvents; | ||
this.props = vtransmit.$props; | ||
} | ||
VTransmitUploadContext.prototype.emit = function (event) { | ||
var args = []; | ||
for (var _i = 1; _i < arguments.length; _i++) { | ||
args[_i - 1] = arguments[_i]; | ||
} | ||
(_a = this.vtransmit).$emit.apply(_a, [event].concat(args)); | ||
var _a; | ||
}; | ||
Object.defineProperty(VTransmitUploadContext.prototype, "acceptedFiles", { | ||
get: function () { | ||
return this.vtransmit.acceptedFiles; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(VTransmitUploadContext.prototype, "rejectedFiles", { | ||
get: function () { | ||
return this.vtransmit.rejectedFiles; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(VTransmitUploadContext.prototype, "addedFiles", { | ||
get: function () { | ||
return this.vtransmit.addedFiles; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(VTransmitUploadContext.prototype, "queuedFiles", { | ||
get: function () { | ||
return this.vtransmit.queuedFiles; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(VTransmitUploadContext.prototype, "uploadingFiles", { | ||
get: function () { | ||
return this.vtransmit.uploadingFiles; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(VTransmitUploadContext.prototype, "activeFiles", { | ||
get: function () { | ||
return this.vtransmit.activeFiles; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
return VTransmitUploadContext; | ||
}()); | ||
var GroupID = 0; | ||
var XHRUploadAdapter = /** @class */ (function () { | ||
function XHRUploadAdapter(context, options) { | ||
this.context = context; | ||
this.url = ""; | ||
this.method = "post"; | ||
this.withCredentials = false; | ||
this.timeout = 0; | ||
this.paramName = "file"; | ||
this.params = Object.create(null); | ||
this.headers = { | ||
Accept: "application/json", | ||
"Cache-Control": "no-cache", | ||
"X-Requested-With": "XMLHttpRequest", | ||
}; | ||
this.responseType = ""; | ||
this.errUploadError = function (xhr) { | ||
return "Error during upload: " + xhr.statusText + " [" + xhr.status + "]"; | ||
}; | ||
this.errUploadTimeout = function (_xhr) { | ||
return "Error during upload: the server timed out."; | ||
}; | ||
this.renameFile = function (name) { return name; }; | ||
this.uploadGroups = Object.create(null); | ||
Object.assign(this, options); | ||
} | ||
XHRUploadAdapter.prototype.uploadFiles = function (files) { | ||
var _this = this; | ||
return new Promise(function (resolve, reject) { | ||
if (!_this.url) { | ||
throw new Error("[Vue-Transmit] Missing upload URL."); | ||
} | ||
var xhr = new XMLHttpRequest(); | ||
var updateProgress = _this.handleUploadProgress(files); | ||
var id = GroupID++; | ||
_this.uploadGroups[id] = { id: id, xhr: xhr, files: files }; | ||
for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { | ||
var file_1 = files_1[_i]; | ||
file_1.adapterData.groupID = id; | ||
file_1.startProgress(); | ||
} | ||
xhr.open(_this.method, _this.url, true); | ||
// Setting the timeout after open because of IE11 issue: https://gitlab.com/meno/dropzone/issues/8 | ||
xhr.timeout = _this.timeout; | ||
xhr.withCredentials = Boolean(_this.withCredentials); | ||
xhr.responseType = _this.responseType; | ||
xhr.addEventListener("error", function () { | ||
_this.rmGroup(id); | ||
reject({ | ||
event: VTransmitEvents.Error, | ||
message: _this.errUploadError(xhr), | ||
xhr: xhr, | ||
}); | ||
}); | ||
xhr.upload.addEventListener("progress", updateProgress); | ||
xhr.addEventListener("timeout", function () { | ||
_this.rmGroup(id); | ||
reject({ | ||
event: VTransmitEvents.Timeout, | ||
message: _this.errUploadTimeout(xhr), | ||
xhr: xhr, | ||
}); | ||
}); | ||
xhr.addEventListener("load", function (_) { | ||
if (files[0].status === UploadStatuses.Canceled || | ||
xhr.readyState !== XMLHttpRequest.DONE) { | ||
return; | ||
} | ||
// The XHR is complete, so remove the group | ||
_this.rmGroup(id); | ||
var response = {}; | ||
if (_this.responseParseFunc) { | ||
response = _this.responseParseFunc(xhr); | ||
} | ||
else { | ||
Object.assign(response, xhr.response); | ||
if (!xhr.responseType) { | ||
var contentType = xhr.getResponseHeader("content-type"); | ||
if (contentType && contentType.indexOf("application/json") > -1) { | ||
try { | ||
response = JSON.parse(xhr.responseText); | ||
} | ||
catch (err) { | ||
return reject({ | ||
message: "Invalid JSON response from server.", | ||
event: VTransmitEvents.Error, | ||
error: err, | ||
}); | ||
} | ||
} | ||
} | ||
} | ||
// Called at load (when complete) will enable all the progress done logic. | ||
updateProgress(); | ||
if (xhr.status < 200 || xhr.status >= 300) { | ||
return reject({ | ||
event: VTransmitEvents.Error, | ||
message: "The server responded with code " + xhr.status + " (" + xhr.statusText + ").", | ||
xhr: xhr, | ||
}); | ||
} | ||
return resolve(response); | ||
}); | ||
// Use null proto obj for the following 'for in' loop without hasOwnProperty check | ||
var headers = Object.assign(Object.create(null), _this.headers); | ||
for (var headerName in headers) { | ||
if (headers[headerName]) { | ||
xhr.setRequestHeader(headerName, headers[headerName]); | ||
} | ||
} | ||
var formData = new FormData(); | ||
for (var key in _this.params) { | ||
formData.append(key, _this.params[key]); | ||
} | ||
for (var _a = 0, files_2 = files; _a < files_2.length; _a++) { | ||
var file_2 = files_2[_a]; | ||
_this.context.emit(VTransmitEvents.Sending, file_2, xhr, formData); | ||
} | ||
if (_this.context.props.uploadMultiple) { | ||
_this.context.emit(VTransmitEvents.SendingMultiple, files, xhr, formData); | ||
} | ||
var file; | ||
for (var i = 0; i < files.length; i++) { | ||
file = files[i].nativeFile; | ||
if (!file) { | ||
continue; | ||
} | ||
formData.append(_this.getParamName(i), file, _this.renameFile(files[i].name || "")); | ||
} | ||
xhr.send(formData); | ||
}); | ||
}; | ||
XHRUploadAdapter.prototype.handleUploadProgress = function (files) { | ||
var vm = this.context.vtransmit; | ||
return function onProgressFn(e) { | ||
if (!e) { | ||
var allFilesFinished = true; | ||
for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { | ||
var file = files_3[_i]; | ||
if (file.upload.progress !== 100 || | ||
file.upload.bytesSent !== file.upload.total) { | ||
allFilesFinished = false; | ||
} | ||
file.upload.progress = 100; | ||
file.upload.bytesSent = file.upload.total; | ||
file.endProgress(); | ||
} | ||
if (allFilesFinished) { | ||
return; | ||
} | ||
} | ||
for (var _a = 0, files_4 = files; _a < files_4.length; _a++) { | ||
var file = files_4[_a]; | ||
if (e) { | ||
file.handleProgress(e); | ||
} | ||
vm.$emit(VTransmitEvents.UploadProgress, file, file.upload.progress, file.upload.bytesSent); | ||
} | ||
}; | ||
}; | ||
XHRUploadAdapter.prototype.getParamName = function (index) { | ||
return (this.paramName + (this.context.props.uploadMultiple ? "[" + index + "]" : "")); | ||
}; | ||
XHRUploadAdapter.prototype.cancelUpload = function (file) { | ||
var group = this.uploadGroups[file.adapterData.groupID]; | ||
if (!group) { | ||
return []; | ||
} | ||
group.xhr.abort(); | ||
this.rmGroup(file.adapterData.groupID); | ||
return group.files.slice(); | ||
}; | ||
XHRUploadAdapter.prototype.rmGroup = function (id) { | ||
delete this.uploadGroups[id]; | ||
}; | ||
return XHRUploadAdapter; | ||
}()); | ||
// @ts-ignore | ||
var VueTransmit = Vue.extend({render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c(_vm.tag,{tag:"component"},[_c('div',_vm._g(_vm._b({staticClass:"v-transmit__upload-area",class:[_vm.isDraggingClass, _vm.uploadAreaClasses],attrs:{"draggable":"true"},on:{"click":_vm.handleClickUploaderAction,"dragstart":_vm.handleDragStart,"dragend":_vm.handleDragEnd,"dragenter":function($event){$event.preventDefault();$event.stopPropagation();_vm.handleDragEnter($event);},"dragover":function($event){$event.preventDefault();$event.stopPropagation();_vm.handleDragOver($event);},"dragleave":_vm.handleDragLeave,"drop":function($event){$event.preventDefault();$event.stopPropagation();_vm.handleDrop($event);}}},'div',_vm.uploadAreaAttrs,false),_vm.uploadAreaListeners),[_vm._t("default")],2),_vm._v(" "),_vm._t("files",null,null,_vm.fileSlotBindings),_vm._v(" "),_c('form',{ref:"uploadForm",style:(_vm.formStyles)},[_c('input',{ref:"hiddenFileInput",class:[_vm.maxFilesReachedClass],attrs:{"type":"file","multiple":_vm.multiple,"accept":_vm.filesToAccept,"capture":_vm.capture},on:{"change":_vm.onFileInputChange}})])],2)},staticRenderFns: [], | ||
name: "VueTransmit", | ||
props: { | ||
tag: { | ||
type: String, | ||
"default": "div" | ||
}, | ||
uploadAreaClasses: { | ||
type: [Array, Object, String], | ||
"default": null | ||
}, | ||
uploadAreaAttrs: { | ||
type: Object, | ||
"default": objFactory | ||
}, | ||
uploadAreaListeners: { | ||
type: Object, | ||
"default": objFactory | ||
}, | ||
dragClass: { | ||
type: String, | ||
"default": null | ||
}, | ||
/** | ||
* Sets the maximum number of uploads that can be running at a given time. | ||
*/ | ||
maxConcurrentUploads: { | ||
type: Number, | ||
"default": 2 | ||
}, | ||
/** | ||
* Whether to send multiple files in one request. | ||
*/ | ||
uploadMultiple: { | ||
type: Boolean, | ||
"default": false | ||
}, | ||
/** | ||
* Size in MB by default, or MiB if fileSizeBaseInBinary === true | ||
*/ | ||
maxFileSize: { | ||
type: Number, | ||
"default": 256 | ||
}, | ||
/** | ||
* The base that is used to calculate the file size. | ||
* 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. | ||
*/ | ||
fileSizeBaseInBinary: { | ||
type: Boolean, | ||
"default": false | ||
}, | ||
createImageThumbnails: { | ||
type: Boolean, | ||
"default": true | ||
}, | ||
// in MB. When the filename exceeds this limit, the thumbnail will not be generated. | ||
maxThumbnailFileSize: { | ||
type: Number, | ||
"default": 10 | ||
}, | ||
thumbnailWidth: { | ||
type: Number, | ||
"default": 120 | ||
}, | ||
thumbnailHeight: { | ||
type: Number, | ||
"default": 120 | ||
}, | ||
/** | ||
* Can be used to limit the maximum number of files that will be handled | ||
* by this Dropzone | ||
*/ | ||
maxFiles: { | ||
type: Number, | ||
"default": null | ||
}, | ||
/** | ||
* If true, the dropzone will present a file selector when clicked. | ||
*/ | ||
clickable: { | ||
type: Boolean, | ||
"default": true | ||
}, | ||
/** | ||
* Whether dot files in directories should be ignored. | ||
*/ | ||
ignoreHiddenFiles: { | ||
type: Boolean, | ||
"default": true | ||
}, | ||
/** | ||
* You can set accepted mime types here. | ||
* | ||
* The default implementation of the `accept()` function will check this | ||
* property, and if the Dropzone is clickable this will be used as | ||
* `accept` attribute. | ||
* | ||
* This is a comma separated list of mime types or extensions. E.g.: | ||
* - audio/*,video/*,image/png,.pdf | ||
* | ||
* See https://developer.mozilla.org/en-US/docs/HTML/Element/input#attr-accept | ||
* for a reference. | ||
*/ | ||
acceptedFileTypes: { | ||
type: Array, | ||
"default": function () { | ||
return []; | ||
} | ||
}, | ||
/** | ||
* 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() | ||
*/ | ||
autoProcessQueue: { | ||
type: Boolean, | ||
"default": true | ||
}, | ||
/** | ||
* If false, files added to the dropzone will not be queued by default. | ||
* You'll have to call `enqueueFile(file)` manually. | ||
*/ | ||
autoQueue: { | ||
type: Boolean, | ||
"default": true | ||
}, | ||
/** | ||
* 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: { | ||
type: String, | ||
"default": null | ||
}, | ||
// If the file size is too big. | ||
errMaxFileSizeExceeded: { | ||
type: Function, | ||
"default": function (fileSize, maxFileSize, units) { | ||
return "The file is too big (" + fileSize + units + "). Max file size: " + maxFileSize + units + "."; | ||
} | ||
}, | ||
errInvalidFileType: { | ||
type: Function, | ||
"default": function (type, _acceptedTypes, _file) { | ||
return "You can't upload files of this type: " + type; | ||
} | ||
}, | ||
errMaxFilesExceeded: { | ||
type: Function, | ||
"default": function (maxFiles) { | ||
return "You can not upload any more files (" + maxFiles + " max)."; | ||
} | ||
}, | ||
/** | ||
* 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). | ||
*/ | ||
accept: { | ||
type: Function, | ||
"default": function (_file, done) { | ||
done(); | ||
} | ||
}, | ||
resize: { | ||
type: Function, | ||
"default": resizeImg | ||
}, | ||
adapterOptions: { | ||
type: Object, | ||
"default": objFactory | ||
}, | ||
uploadAdapter: { | ||
type: Function, | ||
"default": XHRUploadAdapter | ||
} | ||
}, | ||
mounted: function () { | ||
var _this = this; | ||
this.$on(VTransmitEvents.UploadProgress, this.updateTotalUploadProgress); | ||
this.$on(VTransmitEvents.RemovedFile, this.updateTotalUploadProgress); | ||
this.$on(VTransmitEvents.Canceled, function (file) { | ||
return _this.$emit(VTransmitEvents.Complete, file); | ||
}); | ||
this.$on(VTransmitEvents.Complete, function (file) { | ||
if (_this.addedFiles.length === 0 && | ||
_this.uploadingFiles.length === 0 && | ||
_this.queuedFiles.length === 0) { | ||
Promise.resolve().then(function () { return _this.$emit(VTransmitEvents.QueueComplete, file); }); | ||
} | ||
}); | ||
this.$emit(VTransmitEvents.Initialize, this); | ||
}, | ||
data: function () { | ||
return { | ||
dragging: false, | ||
// Used to keep the createThumbnail calls processing async one-at-a-time | ||
processingThumbnail: false, | ||
thumbnailQueue: [], | ||
files: [], | ||
defaultHeaders: { | ||
Accept: "application/json", | ||
"Cache-Control": "no-cache", | ||
"X-Requested-With": "XMLHttpRequest" | ||
}, | ||
formStyles: { | ||
visibility: "hidden !important", | ||
position: "absolute !important", | ||
top: "0 !important", | ||
left: "0 !important", | ||
height: "0px !important", | ||
width: "0px !important" | ||
} | ||
}; | ||
}, | ||
computed: { | ||
inputEl: function () { | ||
var el = this.$refs.hiddenFileInput; | ||
if (!(el instanceof HTMLInputElement)) { | ||
return null; | ||
} | ||
return el; | ||
}, | ||
formEl: function () { | ||
var el = this.$refs.uploadForm; | ||
if (!(el instanceof HTMLFormElement)) { | ||
return null; | ||
} | ||
return el; | ||
}, | ||
fileSizeBase: function () { | ||
if (this.fileSizeBaseInBinary) { | ||
return 1024; | ||
} | ||
return 1000; | ||
}, | ||
maxFileSizeBytes: function () { | ||
return this.maxFileSize * this.fileSizeBase * this.fileSizeBase; | ||
}, | ||
filesToAccept: function () { | ||
return this.acceptedFileTypes.join(","); | ||
}, | ||
multiple: function () { | ||
return this.maxFiles === null || this.maxFiles > 1; | ||
}, | ||
acceptedFiles: function () { | ||
return this.files.filter(function (f) { return f.accepted; }); | ||
}, | ||
rejectedFiles: function () { | ||
return this.files.filter(function (f) { return !f.accepted; }); | ||
}, | ||
addedFiles: function () { | ||
return this.getFilesWithStatus(UploadStatuses.Added); | ||
}, | ||
queuedFiles: function () { | ||
return this.getFilesWithStatus(UploadStatuses.Queued); | ||
}, | ||
uploadingFiles: function () { | ||
return this.getFilesWithStatus(UploadStatuses.Uploading); | ||
}, | ||
activeFiles: function () { | ||
return this.getFilesWithStatus(UploadStatuses.Uploading, UploadStatuses.Queued); | ||
}, | ||
maxFilesReached: function () { | ||
return (this.maxFiles != null && this.acceptedFiles.length >= this.maxFiles); | ||
}, | ||
maxFilesReachedClass: function () { | ||
return this.maxFilesReached ? "v-transmit__max-files--reached" : null; | ||
}, | ||
isDraggingClass: function () { | ||
return _a = { | ||
"v-transmit__upload-area--is-dragging": this.dragging | ||
}, _a[this.dragClass] = this.dragging, _a; | ||
var _a; | ||
}, | ||
isUploading: function () { | ||
return this.uploadingFiles.length > 0; | ||
}, | ||
fileSlotBindings: function () { | ||
return { | ||
files: this.files, | ||
acceptedFiles: this.acceptedFiles, | ||
rejectedFiles: this.rejectedFiles, | ||
addedFiles: this.addedFiles, | ||
queuedFiles: this.queuedFiles, | ||
uploadingFiles: this.uploadingFiles, | ||
activeFiles: this.activeFiles, | ||
isUploading: this.isUploading | ||
}; | ||
}, | ||
transport: function () { | ||
var Adapter = this.uploadAdapter; | ||
try { | ||
return new Adapter(new VTransmitUploadContext(this), this.adapterOptions); | ||
} | ||
catch (err) { | ||
console.error(err); | ||
throw err; | ||
} | ||
} | ||
}, | ||
watch: { | ||
acceptedFiles: function (acceptedFiles) { | ||
if (this.maxFiles == null) { | ||
return; | ||
} | ||
if (acceptedFiles.length >= this.maxFiles) { | ||
this.$emit(VTransmitEvents.MaxFilesReached, this.files); | ||
} | ||
} | ||
}, | ||
methods: { | ||
getFilesWithStatus: function () { | ||
var statuses = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
statuses[_i] = arguments[_i]; | ||
} | ||
return this.files.filter(function (f) { return statuses.indexOf(f.status) > -1; }); | ||
}, | ||
onFileInputChange: function () { | ||
var _a = this, inputEl = _a.inputEl, formEl = _a.formEl; | ||
if (inputEl == null || formEl == null) { | ||
// This is unreachable code, | ||
// but we need to let TS know it. | ||
throw TypeError(); | ||
} | ||
// Can be null | ||
if (!inputEl.files) { | ||
return; | ||
} | ||
this.$emit(VTransmitEvents.AddedFiles, Array.from(inputEl.files).map(this.addFile)); | ||
// Reset input element's files | ||
// https://github.com/alexsasharegan/vue-transmit/issues/25 | ||
formEl.reset(); | ||
}, | ||
addFile: function (file) { | ||
var _this = this; | ||
var vtFile = new VTransmitFile(file); | ||
vtFile.status = UploadStatuses.Added; | ||
this.files.push(vtFile); | ||
this.$emit(VTransmitEvents.AddedFile, vtFile); | ||
this.enqueueThumbnail(vtFile); | ||
this.acceptFile(vtFile, function (error) { | ||
if (error) { | ||
vtFile.accepted = false; | ||
_this.errorProcessing([vtFile], error); | ||
_this.$emit(VTransmitEvents.RejectedFile, vtFile); | ||
_this.$emit(VTransmitEvents.AcceptComplete, vtFile); | ||
return; | ||
} | ||
vtFile.accepted = true; | ||
_this.$emit(VTransmitEvents.AcceptedFile, vtFile); | ||
_this.$emit(VTransmitEvents.AcceptComplete, vtFile); | ||
if (_this.autoQueue) { | ||
_this.enqueueFile(vtFile); | ||
} | ||
}); | ||
return vtFile; | ||
}, | ||
acceptFile: function (file, done) { | ||
// File size check | ||
if (file.size > this.maxFileSizeBytes) { | ||
// size is in bytes, base is kilo multiplier, so base * base == mega | ||
var mega = this.fileSizeBase * this.fileSizeBase; | ||
var fileSize = file.size / mega; | ||
var units = "MB"; | ||
if (this.fileSizeBaseInBinary) { | ||
units = "MiB"; | ||
} | ||
return done(this.errMaxFileSizeExceeded(fileSize, this.maxFileSize, units)); | ||
} | ||
// File type check | ||
if (!this.isValidFileType(file, this.acceptedFileTypes)) { | ||
return done(this.errInvalidFileType(file.type, this.acceptedFileTypes, file)); | ||
} | ||
// Upload limit check | ||
if (this.maxFiles != null && this.acceptedFiles.length >= this.maxFiles) { | ||
this.$emit(VTransmitEvents.MaxFilesExceeded, file); | ||
return done(this.errMaxFilesExceeded(this.maxFiles)); | ||
} | ||
// Happy path 😀 | ||
this.accept(file, done); | ||
}, | ||
removeFile: function (file) { | ||
if (file.status === UploadStatuses.Uploading) { | ||
this.cancelUpload(file); | ||
} | ||
var idxToRm = this.files.findIndex(function (f) { return f.id === file.id; }); | ||
if (idxToRm > -1) { | ||
this.$emit(VTransmitEvents.RemovedFile, this.files.splice(idxToRm, 1)[0]); | ||
if (this.files.length === 0) { | ||
this.$emit(VTransmitEvents.Reset); | ||
} | ||
} | ||
}, | ||
removeAllFiles: function (cancelInProgressUploads) { | ||
if (cancelInProgressUploads === void 0) { cancelInProgressUploads = false; } | ||
var f; | ||
for (var _i = 0, _a = this.files; _i < _a.length; _i++) { | ||
f = _a[_i]; | ||
if (f.status !== UploadStatuses.Uploading || cancelInProgressUploads) { | ||
this.removeFile(f); | ||
} | ||
} | ||
}, | ||
triggerBrowseFiles: function () { | ||
if (this.inputEl) { | ||
this.inputEl.click(); | ||
} | ||
}, | ||
handleClickUploaderAction: function () { | ||
if (this.clickable) { | ||
this.triggerBrowseFiles(); | ||
} | ||
}, | ||
enqueueFile: function (file) { | ||
if (file.status !== UploadStatuses.Added || file.accepted !== true) { | ||
throw new Error("This file can't be queued because it has already been processed or was rejected."); | ||
} | ||
file.status = UploadStatuses.Queued; | ||
if (this.autoProcessQueue) { | ||
Promise.resolve().then(this.processQueue); | ||
} | ||
}, | ||
enqueueThumbnail: function (file) { | ||
if (!this.createImageThumbnails || | ||
!file.type.match(/image.*/) || | ||
file.size > this.maxThumbnailFileSize * 1024 * 1024) { | ||
return; | ||
} | ||
this.thumbnailQueue.push(file); | ||
Promise.resolve().then(this.processThumbnailQueue); | ||
}, | ||
processThumbnailQueue: function () { | ||
var _this = this; | ||
var file; | ||
// Employ a chain of self-calling, self-queuing createThumbnail calls | ||
// so execution can stay as non-blocking as possible. | ||
if (this.processingThumbnail || this.thumbnailQueue.length === 0) { | ||
return; | ||
} | ||
this.processingThumbnail = true; | ||
if ((file = this.thumbnailQueue.shift())) { | ||
this.createThumbnail(file, function () { | ||
_this.processingThumbnail = false; | ||
_this.processThumbnailQueue(); | ||
}); | ||
} | ||
}, | ||
createThumbnail: function (file, callback) { | ||
var _this = this; | ||
if (callback === void 0) { callback = noop; } | ||
var reader = new FileReader(); | ||
reader.addEventListener("load", function () { | ||
if (file.type === "image/svg+xml") { | ||
file.dataUrl = reader.result; | ||
_this.$emit(VTransmitEvents.Thumbnail, file, reader.result); | ||
callback(); | ||
} | ||
_this.createThumbnailFromUrl(file, reader.result, callback); | ||
}, false); | ||
// FileReader requires a native File|Blob object | ||
reader.readAsDataURL(file.nativeFile); | ||
}, | ||
createThumbnailFromUrl: function (file, imageUrl, callback) { | ||
var _this = this; | ||
var imgEl = document.createElement("img"); | ||
imgEl.addEventListener("load", function () { | ||
var ctx; | ||
file.width = imgEl.width; | ||
file.height = imgEl.height; | ||
var resizeInfo = _this.resize(file, { | ||
width: _this.thumbnailWidth, | ||
height: _this.thumbnailHeight | ||
}); | ||
var canvas = document.createElement("canvas"); | ||
// Can be null | ||
if (!(ctx = canvas.getContext("2d"))) { | ||
return; | ||
} | ||
canvas.width = resizeInfo.dWidth; | ||
canvas.height = resizeInfo.dHeight; | ||
ctx.drawImage(imgEl, resizeInfo.sx, resizeInfo.sy, resizeInfo.sWidth, resizeInfo.sHeight, resizeInfo.dx, resizeInfo.dy, resizeInfo.dWidth, resizeInfo.dHeight); | ||
var thumbnail = canvas.toDataURL("image/png"); | ||
file.dataUrl = thumbnail; | ||
_this.$emit(VTransmitEvents.Thumbnail, file, thumbnail); | ||
if (callback) { | ||
return callback(); | ||
} | ||
}, false); | ||
if (callback) { | ||
imgEl.addEventListener("error", callback, false); | ||
} | ||
imgEl.src = imageUrl; | ||
}, | ||
processQueue: function () { | ||
var processingLength = this.uploadingFiles.length; | ||
if (processingLength >= this.maxConcurrentUploads || | ||
this.queuedFiles.length === 0) { | ||
return; | ||
} | ||
var queuedFiles = this.queuedFiles.slice(); | ||
if (this.uploadMultiple) { | ||
return this.processFiles(queuedFiles.slice(0, this.maxConcurrentUploads - processingLength)); | ||
} | ||
var i = processingLength; | ||
var file; | ||
for (; i < this.maxConcurrentUploads; i++) { | ||
if ((file = queuedFiles.shift())) { | ||
this.processFile(file); | ||
} | ||
} | ||
}, | ||
processFile: function (file) { | ||
this.processFiles([file]); | ||
}, | ||
processFiles: function (files) { | ||
var file; | ||
for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { | ||
file = files_1[_i]; | ||
file.processing = true; | ||
file.status = UploadStatuses.Uploading; | ||
this.$emit(VTransmitEvents.Processing, file); | ||
} | ||
if (this.uploadMultiple) { | ||
this.$emit(VTransmitEvents.ProcessingMultiple, files); | ||
} | ||
return this.uploadFiles(files); | ||
}, | ||
cancelUpload: function (file) { | ||
// Cancel a file before uploading | ||
if (file.status === UploadStatuses.Added || | ||
file.status === UploadStatuses.Queued) { | ||
file.status = UploadStatuses.Canceled; | ||
this.$emit(VTransmitEvents.Canceled, file); | ||
if (this.uploadMultiple) { | ||
this.$emit(VTransmitEvents.CanceledMultiple, [file]); | ||
} | ||
} | ||
// Cancel an in-progress upload | ||
if (file.status === UploadStatuses.Uploading) { | ||
var canceledFiles = this.transport.cancelUpload(file); | ||
var f = void 0; | ||
for (var _i = 0, canceledFiles_1 = canceledFiles; _i < canceledFiles_1.length; _i++) { | ||
f = canceledFiles_1[_i]; | ||
f.status = UploadStatuses.Canceled; | ||
this.$emit(VTransmitEvents.Canceled, f); | ||
} | ||
if (this.uploadMultiple) { | ||
this.$emit(VTransmitEvents.CanceledMultiple, canceledFiles); | ||
} | ||
} | ||
if (this.autoProcessQueue) { | ||
this.processQueue(); | ||
} | ||
}, | ||
uploadFile: function (file) { | ||
this.uploadFiles([file]); | ||
}, | ||
uploadFiles: function (files) { | ||
var _this = this; | ||
this.transport | ||
.uploadFiles(files) | ||
.then(function (response) { return _this.uploadFinished(files, response); })["catch"](function (err) { | ||
switch (err.event) { | ||
case VTransmitEvents.Timeout: | ||
_this.handleTimeout(files, err.message); | ||
break; | ||
case VTransmitEvents.Error: | ||
default: | ||
_this.errorProcessing(files, err.message); | ||
break; | ||
} | ||
}); | ||
}, | ||
handleTimeout: function (files, message) { | ||
var args = []; | ||
for (var _i = 2; _i < arguments.length; _i++) { | ||
args[_i - 2] = arguments[_i]; | ||
} | ||
var f; | ||
for (var _a = 0, files_2 = files; _a < files_2.length; _a++) { | ||
f = files_2[_a]; | ||
f.status = UploadStatuses.Timeout; | ||
f.endProgress(); | ||
this.$emit.apply(this, [VTransmitEvents.Timeout, f, message].concat(args)); | ||
} | ||
this.$emit.apply(this, [VTransmitEvents.TimeoutMultiple, files, message].concat(args)); | ||
if (this.autoProcessQueue) { | ||
this.processQueue(); | ||
} | ||
}, | ||
updateTotalUploadProgress: function () { | ||
var progress = this.activeFiles.reduce(function (memo, file) { | ||
memo.totalBytesSent += file.upload.bytesSent; | ||
memo.totalBytes += file.upload.total; | ||
return memo; | ||
}, { totalBytesSent: 0, totalBytes: 0, totalProgress: 100 }); | ||
if (this.activeFiles.length) { | ||
progress.totalProgress = | ||
100 * progress.totalBytesSent / progress.totalBytes; | ||
} | ||
this.$emit(VTransmitEvents.TotalUploadProgress, progress); | ||
}, | ||
uploadFinished: function (files, response) { | ||
var args = []; | ||
for (var _i = 2; _i < arguments.length; _i++) { | ||
args[_i - 2] = arguments[_i]; | ||
} | ||
for (var _a = 0, files_3 = files; _a < files_3.length; _a++) { | ||
var file = files_3[_a]; | ||
file.status = UploadStatuses.Success; | ||
file.endProgress(); | ||
this.$emit.apply(this, [VTransmitEvents.Success, file, response].concat(args)); | ||
this.$emit(VTransmitEvents.Complete, file); | ||
} | ||
if (this.uploadMultiple) { | ||
this.$emit.apply(this, [VTransmitEvents.SuccessMultiple, files, response].concat(args)); | ||
this.$emit(VTransmitEvents.CompleteMultiple, files); | ||
} | ||
if (this.autoProcessQueue) { | ||
this.processQueue(); | ||
} | ||
}, | ||
errorProcessing: function (files, message, xhr) { | ||
for (var _i = 0, files_4 = files; _i < files_4.length; _i++) { | ||
var file = files_4[_i]; | ||
file.status = UploadStatuses.Error; | ||
file.endProgress(); | ||
this.$emit(VTransmitEvents.Error, file, message, xhr); | ||
this.$emit(VTransmitEvents.Complete, file); | ||
} | ||
if (this.uploadMultiple) { | ||
this.$emit(VTransmitEvents.ErrorMultiple, files, message, xhr); | ||
this.$emit(VTransmitEvents.CompleteMultiple, files); | ||
} | ||
if (this.autoProcessQueue) { | ||
return this.processQueue(); | ||
} | ||
}, | ||
isValidFileType: function (file, acceptedFileTypes) { | ||
if (!acceptedFileTypes.length) { | ||
return true; | ||
} | ||
var mimeType = file.type; | ||
var baseMimeType = mimeType.replace(/\/.*$/, ""); | ||
// Return true on the first condition match, | ||
// otherwise exhaust all conditions and return false. | ||
for (var i = 0; i < acceptedFileTypes.length; i++) { | ||
var validType = acceptedFileTypes[i]; | ||
if (validType.charAt(0) === ".") { | ||
// Handle extension validation | ||
// Ensure extension exists at the end of the filename. | ||
if (file.name | ||
.toLowerCase() | ||
.indexOf(validType.toLowerCase(), file.name.length - validType.length) !== -1) { | ||
return true; | ||
} | ||
} | ||
else if (/\/\*$/.test(validType)) { | ||
// Handle globbed mimetype validation ("image/*") | ||
if (baseMimeType === validType.replace(/\/.*$/, "")) { | ||
return true; | ||
} | ||
} | ||
else { | ||
if (mimeType === validType) { | ||
return true; | ||
} | ||
} | ||
} | ||
return false; | ||
}, | ||
handleDragStart: function (e) { | ||
this.$emit("drag-start", e); | ||
}, | ||
handleDragOver: function (e) { | ||
this.dragging = true; | ||
var effect; | ||
try { | ||
// Handle browser bug | ||
effect = e.dataTransfer.effectAllowed; | ||
} | ||
catch (error) { } | ||
e.dataTransfer.dropEffect = | ||
effect === "move" || effect === "linkMove" ? "move" : "copy"; | ||
this.$emit(VTransmitEvents.DragOver, e); | ||
}, | ||
handleDragEnter: function (e) { | ||
this.dragging = true; | ||
this.$emit(VTransmitEvents.DragEnter, e); | ||
}, | ||
handleDragLeave: function (e) { | ||
this.dragging = false; | ||
this.$emit(VTransmitEvents.DragLeave, e); | ||
}, | ||
handleDragEnd: function (e) { | ||
this.dragging = false; | ||
this.$emit(VTransmitEvents.DragEnd, e); | ||
}, | ||
handleDrop: function (e) { | ||
this.dragging = false; | ||
if (!e.dataTransfer) { | ||
return; | ||
} | ||
var files; | ||
var items; | ||
this.$emit(VTransmitEvents.Drop, e); | ||
this.$emit(VTransmitEvents.AddedFiles, (files = Array.from(e.dataTransfer.files))); | ||
if (!e.dataTransfer.items) { | ||
this.handleFiles(files); | ||
return; | ||
} | ||
items = Array.from(e.dataTransfer.items); | ||
if (!items || | ||
!items.length || | ||
!(items[0].getAsFile || items[0].webkitGetAsEntry)) { | ||
this.handleFiles(files); | ||
return; | ||
} | ||
this.addFilesFromItems(items); | ||
}, | ||
paste: function (e) { | ||
if (!e || !e.clipboardData || !e.clipboardData.items) { | ||
return; | ||
} | ||
this.$emit(VTransmitEvents.Paste, e); | ||
var items = Array.from(e.clipboardData.items); | ||
if (items.length) { | ||
this.addFilesFromItems(items); | ||
} | ||
}, | ||
handleFiles: function (files) { | ||
return files.map(this.addFile); | ||
}, | ||
addFilesFromItems: function (items) { | ||
var entry; | ||
for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { | ||
var item = items_1[_i]; | ||
// Newer API on standards track | ||
if (item.getAsFile && item.kind == "file") { | ||
var file = item.getAsFile(); | ||
if (file) { | ||
this.addFile(file); | ||
} | ||
continue; | ||
} | ||
// Vendor prefixed experimental API | ||
if (item.webkitGetAsEntry) { | ||
entry = item.webkitGetAsEntry(); | ||
if (entry == null) { | ||
continue; | ||
} | ||
if (webkitIsFile(entry)) { | ||
entry.file(this.addFile, console.error); | ||
continue; | ||
} | ||
if (webkitIsDir(entry)) { | ||
this.addFilesFromDirectory(entry, entry.name); | ||
continue; | ||
} | ||
} | ||
} | ||
}, | ||
addFilesFromDirectory: function (directory, path) { | ||
var _this = this; | ||
directory.createReader().readEntries((function (entries) { | ||
for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { | ||
var entry = entries_1[_i]; | ||
if (entry == null) { | ||
continue; | ||
} | ||
if (webkitIsDir(entry)) { | ||
_this.addFilesFromDirectory(entry, path + "/" + entry.name); | ||
continue; | ||
} | ||
if (webkitIsFile(entry)) { | ||
entry.file((function (file) { | ||
if (_this.ignoreHiddenFiles && /^\./.test(file.name)) { | ||
return; | ||
} | ||
file.fullPath = path + "/" + file.name; | ||
_this.addFile(file); | ||
}), console.error); | ||
} | ||
} | ||
}), console.error); | ||
} | ||
} | ||
}); | ||
var Plugin = { | ||
install: function (Vue$$1) { | ||
Vue$$1.component("VueTransmit", VueTransmit); | ||
}, | ||
name: "vue-transmit", | ||
}; | ||
export default Plugin; | ||
//# sourceMappingURL=vue-transmit.esm.js.map |
@@ -1,2 +0,1264 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("vue")):"function"==typeof define&&define.amd?define(["vue"],t):e.VueTransmit=t(e.Vue)}(this,function(e){"use strict";e=e&&e.hasOwnProperty("default")?e.default:e;var t,i,s=0;function r(e,t,i){void 0===t&&(t=2),void 0===i&&(i="round");var s=Math.pow(10,t);return Math[i](e*s)/s}function a(){return{}}function n(){}function l(e){return e.isFile}function o(e){return e.isDirectory}!function(e){e.None="",e.Added="added",e.Queued="queued",e.Accepted="queued",e.Uploading="uploading",e.Canceled="canceled",e.Error="error",e.Timeout="timeout",e.Success="success"}(t||(t={})),function(e){e.Initialize="initialize",e.AddedFile="added-file",e.AddedFiles="added-files",e.RemovedFile="removed-file",e.AcceptedFile="accepted-file",e.RejectedFile="rejected-file",e.AcceptComplete="accept-complete",e.Thumbnail="thumbnail",e.Processing="processing",e.ProcessingMultiple="processing-multiple",e.Canceled="canceled",e.CanceledMultiple="canceled-multiple",e.Sending="sending",e.SendingMultiple="sending-multiple",e.Timeout="timeout",e.TimeoutMultiple="timeout-multiple",e.UploadProgress="upload-progress",e.TotalUploadProgress="total-upload-progress",e.Success="success",e.SuccessMultiple="success-multiple",e.QueueComplete="queue-complete",e.Complete="complete",e.CompleteMultiple="complete-multiple",e.Error="error",e.ErrorMultiple="error-multiple",e.MaxFilesReached="max-files-reached",e.MaxFilesExceeded="max-files-exceeded",e.Reset="reset",e.DragOver="drag-over",e.DragEnter="drag-enter",e.DragLeave="drag-leave",e.DragEnd="drag-end",e.Drop="drop",e.Paste="paste"}(i||(i={}));var u=function(){function e(i){this._dataUrl="",this.id=e.idFactory(),this.status=t.None,this.accepted=!1,this.processing=!1,this.width=0,this.height=0,this.errorMessage="",this.adapterData={},this.upload={bytesSent:0,progress:0,total:0,speed:{kbps:0,mbps:0},start:0,end:0,time:0},this.nativeFile=i,this.lastModified=i.lastModified,this.lastModifiedDate=i.lastModifiedDate,this.name=i.name,this.size=i.size,this.type=i.type,this.webkitRelativePath=i.webkitRelativePath,this.upload.total=i.size}return e.prototype.handleProgress=function(e){this.startProgress();var t,i,s=e.total||this.upload.total;this.upload.progress=Math.min(100,100*e.loaded/s),this.upload.bytesSent=e.loaded,this.upload.total=s,this.upload.time=(Date.now()-this.upload.start)/1e3,this.upload.speed.kbps=r((t=this.upload.bytesSent,i=this.upload.time,function(e){return e/125}(t)/i)),this.upload.speed.mbps=r(function(e,t){return function(e){return e/125e3}(e)/t}(this.upload.bytesSent,this.upload.time)),100===this.upload.progress&&this.endProgress()},e.prototype.startProgress=function(){return this.upload.start||(this.upload.start=Date.now()),this},e.prototype.endProgress=function(){return this.upload.end||(this.upload.end=Date.now(),this.upload.time=(Date.now()-this.upload.start)/1e3),this},Object.defineProperty(e.prototype,"dataUrl",{get:function(){return this._dataUrl||""},set:function(e){Object.defineProperty(this,"_dataUrl",{value:e,enumerable:!1,configurable:!0,writable:!0})},enumerable:!0,configurable:!0}),e.idFactory=function(){return"v-transmit-file-"+ ++s},e}(),d=function(){function e(e){this.vtransmit=e,this.Statuses=t,this.Events=i,this.props=e.$props}return e.prototype.emit=function(e){for(var t,i=[],s=1;s<arguments.length;s++)i[s-1]=arguments[s];(t=this.vtransmit).$emit.apply(t,[e].concat(i))},Object.defineProperty(e.prototype,"acceptedFiles",{get:function(){return this.vtransmit.acceptedFiles},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"rejectedFiles",{get:function(){return this.vtransmit.rejectedFiles},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"addedFiles",{get:function(){return this.vtransmit.addedFiles},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"queuedFiles",{get:function(){return this.vtransmit.queuedFiles},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"uploadingFiles",{get:function(){return this.vtransmit.uploadingFiles},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"activeFiles",{get:function(){return this.vtransmit.activeFiles},enumerable:!0,configurable:!0}),e}(),p=0,c=function(){function e(e,t){this.context=e,this.url="",this.method="post",this.withCredentials=!1,this.timeout=0,this.paramName="file",this.params=Object.create(null),this.headers={Accept:"application/json","Cache-Control":"no-cache","X-Requested-With":"XMLHttpRequest"},this.responseType="",this.errUploadError=function(e){return"Error during upload: "+e.statusText+" ["+e.status+"]"},this.errUploadTimeout=function(e){return"Error during upload: the server timed out."},this.renameFile=function(e){return e},this.uploadGroups=Object.create(null),Object.assign(this,t)}return e.prototype.uploadFiles=function(e){var s=this;return new Promise(function(r,a){if(!s.url)throw new Error("[Vue-Transmit] Missing upload URL.");var n=new XMLHttpRequest,l=s.handleUploadProgress(e),o=p++;s.uploadGroups[o]={id:o,xhr:n,files:e};for(var u=0,d=e;u<d.length;u++){var c=d[u];c.adapterData.groupID=o,c.startProgress()}n.open(s.method,s.url,!0),n.timeout=s.timeout,n.withCredentials=Boolean(s.withCredentials),n.responseType=s.responseType,n.addEventListener("error",function(){s.rmGroup(o),a({event:i.Error,message:s.errUploadError(n),xhr:n})}),n.upload.addEventListener("progress",l),n.addEventListener("timeout",function(){s.rmGroup(o),a({event:i.Timeout,message:s.errUploadTimeout(n),xhr:n})}),n.addEventListener("load",function(u){if(e[0].status!==t.Canceled&&n.readyState===XMLHttpRequest.DONE){s.rmGroup(o);var d={};if(s.responseParseFunc)d=s.responseParseFunc(n);else if(Object.assign(d,n.response),!n.responseType){var p=n.getResponseHeader("content-type");if(p&&p.indexOf("application/json")>-1)try{d=JSON.parse(n.responseText)}catch(e){return a({message:"Invalid JSON response from server.",event:i.Error,error:e})}}return l(),n.status<200||n.status>=300?a({event:i.Error,message:"The server responded with code "+n.status+" ("+n.statusText+").",xhr:n}):r(d)}});var h=Object.assign(Object.create(null),s.headers);for(var f in h)h[f]&&n.setRequestHeader(f,h[f]);var m,g=new FormData;for(var F in s.params)g.append(F,s.params[F]);for(var v=0,y=e;v<y.length;v++){var b=y[v];s.context.emit(i.Sending,b,n,g)}s.context.props.uploadMultiple&&s.context.emit(i.SendingMultiple,e,n,g);for(var x=0;x<e.length;x++)(m=e[x].nativeFile)&&g.append(s.getParamName(x),m,s.renameFile(e[x].name||""));n.send(g)})},e.prototype.handleUploadProgress=function(e){var t=this.context.vtransmit;return function(s){if(!s){for(var r=!0,a=0,n=e;a<n.length;a++){100===(u=n[a]).upload.progress&&u.upload.bytesSent===u.upload.total||(r=!1),u.upload.progress=100,u.upload.bytesSent=u.upload.total,u.endProgress()}if(r)return}for(var l=0,o=e;l<o.length;l++){var u=o[l];s&&u.handleProgress(s),t.$emit(i.UploadProgress,u,u.upload.progress,u.upload.bytesSent)}}},e.prototype.getParamName=function(e){return this.paramName+(this.context.props.uploadMultiple?"["+e+"]":"")},e.prototype.cancelUpload=function(e){var t=this.uploadGroups[e.adapterData.groupID];return t?(t.xhr.abort(),this.rmGroup(e.adapterData.groupID),t.files.slice()):[]},e.prototype.rmGroup=function(e){delete this.uploadGroups[e]},e}(),h=e.extend({render:function(){var e=this,t=e.$createElement,i=e._self._c||t;return i(e.tag,{tag:"component"},[i("div",e._g(e._b({staticClass:"v-transmit__upload-area",class:[e.isDraggingClass,e.uploadAreaClasses],attrs:{draggable:"true"},on:{click:e.handleClickUploaderAction,dragstart:e.handleDragStart,dragend:e.handleDragEnd,dragenter:function(t){t.preventDefault(),t.stopPropagation(),e.handleDragEnter(t)},dragover:function(t){t.preventDefault(),t.stopPropagation(),e.handleDragOver(t)},dragleave:e.handleDragLeave,drop:function(t){t.preventDefault(),t.stopPropagation(),e.handleDrop(t)}}},"div",e.uploadAreaAttrs,!1),e.uploadAreaListeners),[e._t("default")],2),e._v(" "),e._t("files",null,null,e.fileSlotBindings),e._v(" "),i("form",{ref:"uploadForm",style:e.formStyles},[i("input",{ref:"hiddenFileInput",class:[e.maxFilesReachedClass],attrs:{type:"file",multiple:e.multiple,accept:e.filesToAccept,capture:e.capture},on:{change:e.onFileInputChange}})])],2)},staticRenderFns:[],name:"VueTransmit",props:{tag:{type:String,default:"div"},uploadAreaClasses:{type:[Array,Object,String],default:null},uploadAreaAttrs:{type:Object,default:a},uploadAreaListeners:{type:Object,default:a},dragClass:{type:String,default:null},maxConcurrentUploads:{type:Number,default:2},uploadMultiple:{type:Boolean,default:!1},maxFileSize:{type:Number,default:256},fileSizeBaseInBinary:{type:Boolean,default:!1},createImageThumbnails:{type:Boolean,default:!0},maxThumbnailFileSize:{type:Number,default:10},thumbnailWidth:{type:Number,default:120},thumbnailHeight:{type:Number,default:120},maxFiles:{type:Number,default:null},clickable:{type:Boolean,default:!0},ignoreHiddenFiles:{type:Boolean,default:!0},acceptedFileTypes:{type:Array,default:function(){return[]}},autoProcessQueue:{type:Boolean,default:!0},autoQueue:{type:Boolean,default:!0},capture:{type:String,default:null},errMaxFileSizeExceeded:{type:Function,default:function(e,t,i){return"The file is too big ("+e+i+"). Max file size: "+t+i+"."}},errInvalidFileType:{type:Function,default:function(e,t,i){return"You can't upload files of this type: "+e}},errMaxFilesExceeded:{type:Function,default:function(e){return"You can not upload any more files ("+e+" max)."}},accept:{type:Function,default:function(e,t){t()}},resize:{type:Function,default:function(e,t){var i,s,r,a=e.width/e.height,n=t.width/t.height,l={sx:0,sy:0,sWidth:e.width,sHeight:e.height,dx:0,dy:0,dWidth:t.width,dHeight:t.height};return n>a?(i=e.width,r=n,s=e.width/r):(i=function(e,t){return t*e}(n,e.height),s=e.height),i<e.width&&(l.sx=(e.width-i)/2,l.sWidth=i),s<e.height&&(l.sy=(e.height-s)/2,l.sHeight=s),l}},adapterOptions:{type:Object,default:a},uploadAdapter:{type:Function,default:c}},mounted:function(){var e=this;this.$on(i.UploadProgress,this.updateTotalUploadProgress),this.$on(i.RemovedFile,this.updateTotalUploadProgress),this.$on(i.Canceled,function(t){return e.$emit(i.Complete,t)}),this.$on(i.Complete,function(t){0===e.addedFiles.length&&0===e.uploadingFiles.length&&0===e.queuedFiles.length&&Promise.resolve().then(function(){return e.$emit(i.QueueComplete,t)})}),this.$emit(i.Initialize,this)},data:function(){return{dragging:!1,processingThumbnail:!1,thumbnailQueue:[],files:[],defaultHeaders:{Accept:"application/json","Cache-Control":"no-cache","X-Requested-With":"XMLHttpRequest"},formStyles:{visibility:"hidden !important",position:"absolute !important",top:"0 !important",left:"0 !important",height:"0px !important",width:"0px !important"}}},computed:{inputEl:function(){var e=this.$refs.hiddenFileInput;return e instanceof HTMLInputElement?e:null},formEl:function(){var e=this.$refs.uploadForm;return e instanceof HTMLFormElement?e:null},fileSizeBase:function(){return this.fileSizeBaseInBinary?1024:1e3},maxFileSizeBytes:function(){return this.maxFileSize*this.fileSizeBase*this.fileSizeBase},filesToAccept:function(){return this.acceptedFileTypes.join(",")},multiple:function(){return null===this.maxFiles||this.maxFiles>1},acceptedFiles:function(){return this.files.filter(function(e){return e.accepted})},rejectedFiles:function(){return this.files.filter(function(e){return!e.accepted})},addedFiles:function(){return this.getFilesWithStatus(t.Added)},queuedFiles:function(){return this.getFilesWithStatus(t.Queued)},uploadingFiles:function(){return this.getFilesWithStatus(t.Uploading)},activeFiles:function(){return this.getFilesWithStatus(t.Uploading,t.Queued)},maxFilesReached:function(){return null!=this.maxFiles&&this.acceptedFiles.length>=this.maxFiles},maxFilesReachedClass:function(){return this.maxFilesReached?"v-transmit__max-files--reached":null},isDraggingClass:function(){return(e={"v-transmit__upload-area--is-dragging":this.dragging})[this.dragClass]=this.dragging,e;var e},isUploading:function(){return this.uploadingFiles.length>0},fileSlotBindings:function(){return{files:this.files,acceptedFiles:this.acceptedFiles,rejectedFiles:this.rejectedFiles,addedFiles:this.addedFiles,queuedFiles:this.queuedFiles,uploadingFiles:this.uploadingFiles,activeFiles:this.activeFiles,isUploading:this.isUploading}},transport:function(){var e=this.uploadAdapter;try{return new e(new d(this),this.adapterOptions)}catch(e){throw console.error(e),e}}},watch:{acceptedFiles:function(e){null!=this.maxFiles&&e.length>=this.maxFiles&&this.$emit(i.MaxFilesReached,this.files)}},methods:{getFilesWithStatus:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this.files.filter(function(t){return e.indexOf(t.status)>-1})},onFileInputChange:function(){var e=this.inputEl,t=this.formEl;if(null==e||null==t)throw TypeError();e.files&&(this.$emit(i.AddedFiles,Array.from(e.files).map(this.addFile)),t.reset())},addFile:function(e){var s=this,r=new u(e);return r.status=t.Added,this.files.push(r),this.$emit(i.AddedFile,r),this.enqueueThumbnail(r),this.acceptFile(r,function(e){if(e)return r.accepted=!1,s.errorProcessing([r],e),s.$emit(i.RejectedFile,r),void s.$emit(i.AcceptComplete,r);r.accepted=!0,s.$emit(i.AcceptedFile,r),s.$emit(i.AcceptComplete,r),s.autoQueue&&s.enqueueFile(r)}),r},acceptFile:function(e,t){if(e.size>this.maxFileSizeBytes){var s=this.fileSizeBase*this.fileSizeBase,r=e.size/s,a="MB";return this.fileSizeBaseInBinary&&(a="MiB"),t(this.errMaxFileSizeExceeded(r,this.maxFileSize,a))}return this.isValidFileType(e,this.acceptedFileTypes)?null!=this.maxFiles&&this.acceptedFiles.length>=this.maxFiles?(this.$emit(i.MaxFilesExceeded,e),t(this.errMaxFilesExceeded(this.maxFiles))):void this.accept(e,t):t(this.errInvalidFileType(e.type,this.acceptedFileTypes,e))},removeFile:function(e){e.status===t.Uploading&&this.cancelUpload(e);var s=this.files.findIndex(function(t){return t.id===e.id});s>-1&&(this.$emit(i.RemovedFile,this.files.splice(s,1)[0]),0===this.files.length&&this.$emit(i.Reset))},removeAllFiles:function(e){var i;void 0===e&&(e=!1);for(var s=0,r=this.files;s<r.length;s++)((i=r[s]).status!==t.Uploading||e)&&this.removeFile(i)},triggerBrowseFiles:function(){this.inputEl&&this.inputEl.click()},handleClickUploaderAction:function(){this.clickable&&this.triggerBrowseFiles()},enqueueFile:function(e){if(e.status!==t.Added||!0!==e.accepted)throw new Error("This file can't be queued because it has already been processed or was rejected.");e.status=t.Queued,this.autoProcessQueue&&setTimeout(this.processQueue,0)},enqueueThumbnail:function(e){!this.createImageThumbnails||!e.type.match(/image.*/)||e.size>1024*this.maxThumbnailFileSize*1024||(this.thumbnailQueue.push(e),setTimeout(this.processThumbnailQueue,0))},processThumbnailQueue:function(){var e,t=this;this.processingThumbnail||0===this.thumbnailQueue.length||(this.processingThumbnail=!0,(e=this.thumbnailQueue.shift())&&this.createThumbnail(e,function(){t.processingThumbnail=!1,t.processThumbnailQueue()}))},createThumbnail:function(e,t){var s=this;void 0===t&&(t=n);var r=new FileReader;r.addEventListener("load",function(){"image/svg+xml"===e.type&&(e.dataUrl=r.result,s.$emit(i.Thumbnail,e,r.result),t()),s.createThumbnailFromUrl(e,r.result,t)},!1),r.readAsDataURL(e.nativeFile)},createThumbnailFromUrl:function(e,t,s){var r=this,a=document.createElement("img");a.addEventListener("load",function(){var t;e.width=a.width,e.height=a.height;var n=r.resize(e,{width:r.thumbnailWidth,height:r.thumbnailHeight}),l=document.createElement("canvas");if(t=l.getContext("2d")){l.width=n.dWidth,l.height=n.dHeight,t.drawImage(a,n.sx,n.sy,n.sWidth,n.sHeight,n.dx,n.dy,n.dWidth,n.dHeight);var o=l.toDataURL("image/png");return e.dataUrl=o,r.$emit(i.Thumbnail,e,o),s?s():void 0}},!1),s&&a.addEventListener("error",s,!1),a.src=t},processQueue:function(){var e=this.uploadingFiles.length;if(!(e>=this.maxConcurrentUploads||0===this.queuedFiles.length)){var t=this.queuedFiles.slice();if(this.uploadMultiple)return this.processFiles(t.slice(0,this.maxConcurrentUploads-e));for(var i,s=e;s<this.maxConcurrentUploads;s++)(i=t.shift())&&this.processFile(i)}},processFile:function(e){this.processFiles([e])},processFiles:function(e){for(var s,r=0,a=e;r<a.length;r++)(s=a[r]).processing=!0,s.status=t.Uploading,this.$emit(i.Processing,s);return this.uploadMultiple&&this.$emit(i.ProcessingMultiple,e),this.uploadFiles(e)},cancelUpload:function(e){if(e.status!==t.Added&&e.status!==t.Queued||(e.status=t.Canceled,this.$emit(i.Canceled,e),this.uploadMultiple&&this.$emit(i.CanceledMultiple,[e])),e.status===t.Uploading){for(var s=this.transport.cancelUpload(e),r=void 0,a=0,n=s;a<n.length;a++)(r=n[a]).status=t.Canceled,this.$emit(i.Canceled,r);this.uploadMultiple&&this.$emit(i.CanceledMultiple,s)}this.autoProcessQueue&&this.processQueue()},uploadFile:function(e){this.uploadFiles([e])},uploadFiles:function(e){var t=this;this.transport.uploadFiles(e).then(function(i){return t.uploadFinished(e,i)}).catch(function(s){switch(s.event){case i.Timeout:t.handleTimeout(e,s.message);break;case i.Error:default:t.errorProcessing(e,s.message)}})},handleTimeout:function(e,s){for(var r,a=[],n=2;n<arguments.length;n++)a[n-2]=arguments[n];for(var l=0,o=e;l<o.length;l++)(r=o[l]).status=t.Timeout,r.endProgress(),this.$emit.apply(this,[i.Timeout,r,s].concat(a));this.$emit.apply(this,[i.TimeoutMultiple,e,s].concat(a)),this.autoProcessQueue&&this.processQueue()},updateTotalUploadProgress:function(){var e=this.activeFiles.reduce(function(e,t){return e.totalBytesSent+=t.upload.bytesSent,e.totalBytes+=t.upload.total,e},{totalBytesSent:0,totalBytes:0,totalProgress:100});this.activeFiles.length&&(e.totalProgress=100*e.totalBytesSent/e.totalBytes),this.$emit(i.TotalUploadProgress,e)},uploadFinished:function(e,s){for(var r=[],a=2;a<arguments.length;a++)r[a-2]=arguments[a];for(var n=0,l=e;n<l.length;n++){var o=l[n];o.status=t.Success,o.endProgress(),this.$emit.apply(this,[i.Success,o,s].concat(r)),this.$emit(i.Complete,o)}this.uploadMultiple&&(this.$emit.apply(this,[i.SuccessMultiple,e,s].concat(r)),this.$emit(i.CompleteMultiple,e)),this.autoProcessQueue&&this.processQueue()},errorProcessing:function(e,s,r){for(var a=0,n=e;a<n.length;a++){var l=n[a];l.status=t.Error,l.endProgress(),this.$emit(i.Error,l,s,r),this.$emit(i.Complete,l)}if(this.uploadMultiple&&(this.$emit(i.ErrorMultiple,e,s,r),this.$emit(i.CompleteMultiple,e)),this.autoProcessQueue)return this.processQueue()},isValidFileType:function(e,t){if(!t.length)return!0;for(var i=e.type,s=i.replace(/\/.*$/,""),r=0;r<t.length;r++){var a=t[r];if("."===a.charAt(0)){if(-1!==e.name.toLowerCase().indexOf(a.toLowerCase(),e.name.length-a.length))return!0}else if(/\/\*$/.test(a)){if(s===a.replace(/\/.*$/,""))return!0}else if(i===a)return!0}return!1},handleDragStart:function(e){this.$emit("drag-start",e)},handleDragOver:function(e){var t;this.dragging=!0;try{t=e.dataTransfer.effectAllowed}catch(e){}e.dataTransfer.dropEffect="move"===t||"linkMove"===t?"move":"copy",this.$emit(i.DragOver,e)},handleDragEnter:function(e){this.dragging=!0,this.$emit(i.DragEnter,e)},handleDragLeave:function(e){this.dragging=!1,this.$emit(i.DragLeave,e)},handleDragEnd:function(e){this.dragging=!1,this.$emit(i.DragEnd,e)},handleDrop:function(e){var t,s;(this.dragging=!1,e.dataTransfer)&&(this.$emit(i.Drop,e),this.$emit(i.AddedFiles,t=Array.from(e.dataTransfer.files)),e.dataTransfer.items&&(s=Array.from(e.dataTransfer.items))&&s.length&&(s[0].getAsFile||s[0].webkitGetAsEntry)?this.addFilesFromItems(s):this.handleFiles(t))},paste:function(e){if(e&&e.clipboardData&&e.clipboardData.items){this.$emit(i.Paste,e);var t=Array.from(e.clipboardData.items);t.length&&this.addFilesFromItems(t)}},handleFiles:function(e){return e.map(this.addFile)},addFilesFromItems:function(e){for(var t,i=0,s=e;i<s.length;i++){var r=s[i];if(r.getAsFile&&"file"==r.kind){var a=r.getAsFile();a&&this.addFile(a)}else if(r.webkitGetAsEntry){if(null==(t=r.webkitGetAsEntry()))continue;if(l(t)){t.file(this.addFile,console.error);continue}if(o(t)){this.addFilesFromDirectory(t,t.name);continue}}}},addFilesFromDirectory:function(e,t){var i=this;e.createReader().readEntries(function(e){for(var s=0,r=e;s<r.length;s++){var a=r[s];null!=a&&(o(a)?i.addFilesFromDirectory(a,t+"/"+a.name):l(a)&&a.file(function(e){i.ignoreHiddenFiles&&/^\./.test(e.name)||(e.fullPath=t+"/"+e.name,i.addFile(e))},console.error))}},console.error)}}});return{install:function(e){e.component("VueTransmit",h)},name:"vue-transmit"}}); | ||
(function (global, factory) { | ||
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('vue')) : | ||
typeof define === 'function' && define.amd ? define(['vue'], factory) : | ||
(global.VueTransmit = factory(global.Vue)); | ||
}(this, (function (Vue) { 'use strict'; | ||
Vue = Vue && Vue.hasOwnProperty('default') ? Vue['default'] : Vue; | ||
var idCounter = 0; | ||
function uniqueId(prefix) { | ||
return prefix + ++idCounter; | ||
} | ||
function round(number, decimals, roundStyle) { | ||
if (decimals === void 0) { decimals = 2; } | ||
if (roundStyle === void 0) { roundStyle = "round"; } | ||
var roundingFactor = Math.pow(10, decimals); | ||
return Math[roundStyle](number * roundingFactor) / roundingFactor; | ||
} | ||
function fromBytesToKbit(bytes) { | ||
return bytes / 125; | ||
} | ||
function fromBytesToMbit(bytes) { | ||
return bytes / 125000; | ||
} | ||
function toKbps(bytes, seconds) { | ||
return fromBytesToKbit(bytes) / seconds; | ||
} | ||
function toMbps(bytes, seconds) { | ||
return fromBytesToMbit(bytes) / seconds; | ||
} | ||
function objFactory() { | ||
return {}; | ||
} | ||
function noop() { } | ||
function scaleH(ratio, width) { | ||
return width / ratio; | ||
} | ||
function scaleW(ratio, height) { | ||
return height * ratio; | ||
} | ||
var UploadStatuses; | ||
(function (UploadStatuses) { | ||
UploadStatuses["None"] = ""; | ||
UploadStatuses["Added"] = "added"; | ||
UploadStatuses["Queued"] = "queued"; | ||
UploadStatuses["Accepted"] = "queued"; | ||
UploadStatuses["Uploading"] = "uploading"; | ||
UploadStatuses["Canceled"] = "canceled"; | ||
UploadStatuses["Error"] = "error"; | ||
UploadStatuses["Timeout"] = "timeout"; | ||
UploadStatuses["Success"] = "success"; | ||
})(UploadStatuses || (UploadStatuses = {})); | ||
var VTransmitEvents; | ||
(function (VTransmitEvents) { | ||
VTransmitEvents["Initialize"] = "initialize"; | ||
VTransmitEvents["AddedFile"] = "added-file"; | ||
VTransmitEvents["AddedFiles"] = "added-files"; | ||
VTransmitEvents["RemovedFile"] = "removed-file"; | ||
VTransmitEvents["AcceptedFile"] = "accepted-file"; | ||
VTransmitEvents["RejectedFile"] = "rejected-file"; | ||
VTransmitEvents["AcceptComplete"] = "accept-complete"; | ||
VTransmitEvents["Thumbnail"] = "thumbnail"; | ||
VTransmitEvents["Processing"] = "processing"; | ||
VTransmitEvents["ProcessingMultiple"] = "processing-multiple"; | ||
VTransmitEvents["Canceled"] = "canceled"; | ||
VTransmitEvents["CanceledMultiple"] = "canceled-multiple"; | ||
VTransmitEvents["Sending"] = "sending"; | ||
VTransmitEvents["SendingMultiple"] = "sending-multiple"; | ||
VTransmitEvents["Timeout"] = "timeout"; | ||
VTransmitEvents["TimeoutMultiple"] = "timeout-multiple"; | ||
VTransmitEvents["UploadProgress"] = "upload-progress"; | ||
VTransmitEvents["TotalUploadProgress"] = "total-upload-progress"; | ||
VTransmitEvents["Success"] = "success"; | ||
VTransmitEvents["SuccessMultiple"] = "success-multiple"; | ||
VTransmitEvents["QueueComplete"] = "queue-complete"; | ||
VTransmitEvents["Complete"] = "complete"; | ||
VTransmitEvents["CompleteMultiple"] = "complete-multiple"; | ||
VTransmitEvents["Error"] = "error"; | ||
VTransmitEvents["ErrorMultiple"] = "error-multiple"; | ||
VTransmitEvents["MaxFilesReached"] = "max-files-reached"; | ||
VTransmitEvents["MaxFilesExceeded"] = "max-files-exceeded"; | ||
VTransmitEvents["Reset"] = "reset"; | ||
VTransmitEvents["DragOver"] = "drag-over"; | ||
VTransmitEvents["DragEnter"] = "drag-enter"; | ||
VTransmitEvents["DragLeave"] = "drag-leave"; | ||
VTransmitEvents["DragEnd"] = "drag-end"; | ||
VTransmitEvents["Drop"] = "drop"; | ||
VTransmitEvents["Paste"] = "paste"; | ||
})(VTransmitEvents || (VTransmitEvents = {})); | ||
function resizeImg(file, dims) { | ||
// 's' variables are for source | ||
// 'd' variables are for destination | ||
var sRatio = file.width / file.height; | ||
var dRatio = dims.width / dims.height; | ||
var coords = { | ||
sx: 0, | ||
sy: 0, | ||
sWidth: file.width, | ||
sHeight: file.height, | ||
dx: 0, | ||
dy: 0, | ||
dWidth: dims.width, | ||
dHeight: dims.height, | ||
}; | ||
var w, h; | ||
if (dRatio > sRatio) { | ||
w = file.width; | ||
h = scaleH(dRatio, file.width); | ||
} | ||
else { | ||
w = scaleW(dRatio, file.height); | ||
h = file.height; | ||
} | ||
if (w < file.width) { | ||
coords.sx = (file.width - w) / 2; | ||
coords.sWidth = w; | ||
} | ||
if (h < file.height) { | ||
coords.sy = (file.height - h) / 2; | ||
coords.sHeight = h; | ||
} | ||
return coords; | ||
} | ||
function webkitIsFile(entry) { | ||
return entry.isFile; | ||
} | ||
function webkitIsDir(entry) { | ||
return entry.isDirectory; | ||
} | ||
var VTransmitFile = /** @class */ (function () { | ||
function VTransmitFile(file) { | ||
this._dataUrl = ""; | ||
this.id = VTransmitFile.idFactory(); | ||
this.status = UploadStatuses.None; | ||
this.accepted = false; // Passed all validation. | ||
this.processing = false; | ||
this.width = 0; | ||
this.height = 0; | ||
this.errorMessage = ""; | ||
this.adapterData = {}; | ||
this.upload = { | ||
bytesSent: 0, | ||
progress: 0, | ||
total: 0, | ||
speed: { | ||
kbps: 0, | ||
mbps: 0, | ||
}, | ||
start: 0, | ||
end: 0, | ||
time: 0, | ||
}; | ||
this.nativeFile = file; | ||
this.lastModified = file.lastModified; | ||
this.lastModifiedDate = file.lastModifiedDate; | ||
this.name = file.name; | ||
this.size = file.size; | ||
this.type = file.type; | ||
this.webkitRelativePath = file.webkitRelativePath; | ||
this.upload.total = file.size; | ||
} | ||
VTransmitFile.prototype.handleProgress = function (e) { | ||
this.startProgress(); | ||
var total = e.total || this.upload.total; | ||
this.upload.progress = Math.min(100, 100 * e.loaded / total); | ||
this.upload.bytesSent = e.loaded; | ||
this.upload.total = total; | ||
this.upload.time = (Date.now() - this.upload.start) / 1000; | ||
// Recalculate the upload speed in bytes/sec | ||
this.upload.speed.kbps = round(toKbps(this.upload.bytesSent, this.upload.time)); | ||
this.upload.speed.mbps = round(toMbps(this.upload.bytesSent, this.upload.time)); | ||
if (this.upload.progress === 100) { | ||
this.endProgress(); | ||
} | ||
}; | ||
VTransmitFile.prototype.startProgress = function () { | ||
// Avoid starting twice | ||
if (!this.upload.start) { | ||
this.upload.start = Date.now(); | ||
} | ||
return this; | ||
}; | ||
VTransmitFile.prototype.endProgress = function () { | ||
// Avoid ending twice | ||
if (!this.upload.end) { | ||
this.upload.end = Date.now(); | ||
this.upload.time = (Date.now() - this.upload.start) / 1000; | ||
} | ||
return this; | ||
}; | ||
Object.defineProperty(VTransmitFile.prototype, "dataUrl", { | ||
get: function () { | ||
return this._dataUrl || ""; | ||
}, | ||
set: function (value) { | ||
// Use non-enumerable data url to avoid copying around large datasets | ||
Object.defineProperty(this, "_dataUrl", { | ||
value: value, | ||
enumerable: false, | ||
configurable: true, | ||
writable: true, | ||
}); | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
VTransmitFile.idFactory = function () { | ||
return uniqueId("v-transmit-file-"); | ||
}; | ||
return VTransmitFile; | ||
}()); | ||
var VTransmitUploadContext = /** @class */ (function () { | ||
function VTransmitUploadContext(vtransmit) { | ||
this.vtransmit = vtransmit; | ||
this.Statuses = UploadStatuses; | ||
this.Events = VTransmitEvents; | ||
this.props = vtransmit.$props; | ||
} | ||
VTransmitUploadContext.prototype.emit = function (event) { | ||
var args = []; | ||
for (var _i = 1; _i < arguments.length; _i++) { | ||
args[_i - 1] = arguments[_i]; | ||
} | ||
(_a = this.vtransmit).$emit.apply(_a, [event].concat(args)); | ||
var _a; | ||
}; | ||
Object.defineProperty(VTransmitUploadContext.prototype, "acceptedFiles", { | ||
get: function () { | ||
return this.vtransmit.acceptedFiles; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(VTransmitUploadContext.prototype, "rejectedFiles", { | ||
get: function () { | ||
return this.vtransmit.rejectedFiles; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(VTransmitUploadContext.prototype, "addedFiles", { | ||
get: function () { | ||
return this.vtransmit.addedFiles; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(VTransmitUploadContext.prototype, "queuedFiles", { | ||
get: function () { | ||
return this.vtransmit.queuedFiles; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(VTransmitUploadContext.prototype, "uploadingFiles", { | ||
get: function () { | ||
return this.vtransmit.uploadingFiles; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(VTransmitUploadContext.prototype, "activeFiles", { | ||
get: function () { | ||
return this.vtransmit.activeFiles; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
return VTransmitUploadContext; | ||
}()); | ||
var GroupID = 0; | ||
var XHRUploadAdapter = /** @class */ (function () { | ||
function XHRUploadAdapter(context, options) { | ||
this.context = context; | ||
this.url = ""; | ||
this.method = "post"; | ||
this.withCredentials = false; | ||
this.timeout = 0; | ||
this.paramName = "file"; | ||
this.params = Object.create(null); | ||
this.headers = { | ||
Accept: "application/json", | ||
"Cache-Control": "no-cache", | ||
"X-Requested-With": "XMLHttpRequest", | ||
}; | ||
this.responseType = ""; | ||
this.errUploadError = function (xhr) { | ||
return "Error during upload: " + xhr.statusText + " [" + xhr.status + "]"; | ||
}; | ||
this.errUploadTimeout = function (_xhr) { | ||
return "Error during upload: the server timed out."; | ||
}; | ||
this.renameFile = function (name) { return name; }; | ||
this.uploadGroups = Object.create(null); | ||
Object.assign(this, options); | ||
} | ||
XHRUploadAdapter.prototype.uploadFiles = function (files) { | ||
var _this = this; | ||
return new Promise(function (resolve, reject) { | ||
if (!_this.url) { | ||
throw new Error("[Vue-Transmit] Missing upload URL."); | ||
} | ||
var xhr = new XMLHttpRequest(); | ||
var updateProgress = _this.handleUploadProgress(files); | ||
var id = GroupID++; | ||
_this.uploadGroups[id] = { id: id, xhr: xhr, files: files }; | ||
for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { | ||
var file_1 = files_1[_i]; | ||
file_1.adapterData.groupID = id; | ||
file_1.startProgress(); | ||
} | ||
xhr.open(_this.method, _this.url, true); | ||
// Setting the timeout after open because of IE11 issue: https://gitlab.com/meno/dropzone/issues/8 | ||
xhr.timeout = _this.timeout; | ||
xhr.withCredentials = Boolean(_this.withCredentials); | ||
xhr.responseType = _this.responseType; | ||
xhr.addEventListener("error", function () { | ||
_this.rmGroup(id); | ||
reject({ | ||
event: VTransmitEvents.Error, | ||
message: _this.errUploadError(xhr), | ||
xhr: xhr, | ||
}); | ||
}); | ||
xhr.upload.addEventListener("progress", updateProgress); | ||
xhr.addEventListener("timeout", function () { | ||
_this.rmGroup(id); | ||
reject({ | ||
event: VTransmitEvents.Timeout, | ||
message: _this.errUploadTimeout(xhr), | ||
xhr: xhr, | ||
}); | ||
}); | ||
xhr.addEventListener("load", function (_) { | ||
if (files[0].status === UploadStatuses.Canceled || | ||
xhr.readyState !== XMLHttpRequest.DONE) { | ||
return; | ||
} | ||
// The XHR is complete, so remove the group | ||
_this.rmGroup(id); | ||
var response = {}; | ||
if (_this.responseParseFunc) { | ||
response = _this.responseParseFunc(xhr); | ||
} | ||
else { | ||
Object.assign(response, xhr.response); | ||
if (!xhr.responseType) { | ||
var contentType = xhr.getResponseHeader("content-type"); | ||
if (contentType && contentType.indexOf("application/json") > -1) { | ||
try { | ||
response = JSON.parse(xhr.responseText); | ||
} | ||
catch (err) { | ||
return reject({ | ||
message: "Invalid JSON response from server.", | ||
event: VTransmitEvents.Error, | ||
error: err, | ||
}); | ||
} | ||
} | ||
} | ||
} | ||
// Called at load (when complete) will enable all the progress done logic. | ||
updateProgress(); | ||
if (xhr.status < 200 || xhr.status >= 300) { | ||
return reject({ | ||
event: VTransmitEvents.Error, | ||
message: "The server responded with code " + xhr.status + " (" + xhr.statusText + ").", | ||
xhr: xhr, | ||
}); | ||
} | ||
return resolve(response); | ||
}); | ||
// Use null proto obj for the following 'for in' loop without hasOwnProperty check | ||
var headers = Object.assign(Object.create(null), _this.headers); | ||
for (var headerName in headers) { | ||
if (headers[headerName]) { | ||
xhr.setRequestHeader(headerName, headers[headerName]); | ||
} | ||
} | ||
var formData = new FormData(); | ||
for (var key in _this.params) { | ||
formData.append(key, _this.params[key]); | ||
} | ||
for (var _a = 0, files_2 = files; _a < files_2.length; _a++) { | ||
var file_2 = files_2[_a]; | ||
_this.context.emit(VTransmitEvents.Sending, file_2, xhr, formData); | ||
} | ||
if (_this.context.props.uploadMultiple) { | ||
_this.context.emit(VTransmitEvents.SendingMultiple, files, xhr, formData); | ||
} | ||
var file; | ||
for (var i = 0; i < files.length; i++) { | ||
file = files[i].nativeFile; | ||
if (!file) { | ||
continue; | ||
} | ||
formData.append(_this.getParamName(i), file, _this.renameFile(files[i].name || "")); | ||
} | ||
xhr.send(formData); | ||
}); | ||
}; | ||
XHRUploadAdapter.prototype.handleUploadProgress = function (files) { | ||
var vm = this.context.vtransmit; | ||
return function onProgressFn(e) { | ||
if (!e) { | ||
var allFilesFinished = true; | ||
for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { | ||
var file = files_3[_i]; | ||
if (file.upload.progress !== 100 || | ||
file.upload.bytesSent !== file.upload.total) { | ||
allFilesFinished = false; | ||
} | ||
file.upload.progress = 100; | ||
file.upload.bytesSent = file.upload.total; | ||
file.endProgress(); | ||
} | ||
if (allFilesFinished) { | ||
return; | ||
} | ||
} | ||
for (var _a = 0, files_4 = files; _a < files_4.length; _a++) { | ||
var file = files_4[_a]; | ||
if (e) { | ||
file.handleProgress(e); | ||
} | ||
vm.$emit(VTransmitEvents.UploadProgress, file, file.upload.progress, file.upload.bytesSent); | ||
} | ||
}; | ||
}; | ||
XHRUploadAdapter.prototype.getParamName = function (index) { | ||
return (this.paramName + (this.context.props.uploadMultiple ? "[" + index + "]" : "")); | ||
}; | ||
XHRUploadAdapter.prototype.cancelUpload = function (file) { | ||
var group = this.uploadGroups[file.adapterData.groupID]; | ||
if (!group) { | ||
return []; | ||
} | ||
group.xhr.abort(); | ||
this.rmGroup(file.adapterData.groupID); | ||
return group.files.slice(); | ||
}; | ||
XHRUploadAdapter.prototype.rmGroup = function (id) { | ||
delete this.uploadGroups[id]; | ||
}; | ||
return XHRUploadAdapter; | ||
}()); | ||
// @ts-ignore | ||
var VueTransmit = Vue.extend({render: function(){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c(_vm.tag,{tag:"component"},[_c('div',_vm._g(_vm._b({staticClass:"v-transmit__upload-area",class:[_vm.isDraggingClass, _vm.uploadAreaClasses],attrs:{"draggable":"true"},on:{"click":_vm.handleClickUploaderAction,"dragstart":_vm.handleDragStart,"dragend":_vm.handleDragEnd,"dragenter":function($event){$event.preventDefault();$event.stopPropagation();_vm.handleDragEnter($event);},"dragover":function($event){$event.preventDefault();$event.stopPropagation();_vm.handleDragOver($event);},"dragleave":_vm.handleDragLeave,"drop":function($event){$event.preventDefault();$event.stopPropagation();_vm.handleDrop($event);}}},'div',_vm.uploadAreaAttrs,false),_vm.uploadAreaListeners),[_vm._t("default")],2),_vm._v(" "),_vm._t("files",null,null,_vm.fileSlotBindings),_vm._v(" "),_c('form',{ref:"uploadForm",style:(_vm.formStyles)},[_c('input',{ref:"hiddenFileInput",class:[_vm.maxFilesReachedClass],attrs:{"type":"file","multiple":_vm.multiple,"accept":_vm.filesToAccept,"capture":_vm.capture},on:{"change":_vm.onFileInputChange}})])],2)},staticRenderFns: [], | ||
name: "VueTransmit", | ||
props: { | ||
tag: { | ||
type: String, | ||
"default": "div" | ||
}, | ||
uploadAreaClasses: { | ||
type: [Array, Object, String], | ||
"default": null | ||
}, | ||
uploadAreaAttrs: { | ||
type: Object, | ||
"default": objFactory | ||
}, | ||
uploadAreaListeners: { | ||
type: Object, | ||
"default": objFactory | ||
}, | ||
dragClass: { | ||
type: String, | ||
"default": null | ||
}, | ||
/** | ||
* Sets the maximum number of uploads that can be running at a given time. | ||
*/ | ||
maxConcurrentUploads: { | ||
type: Number, | ||
"default": 2 | ||
}, | ||
/** | ||
* Whether to send multiple files in one request. | ||
*/ | ||
uploadMultiple: { | ||
type: Boolean, | ||
"default": false | ||
}, | ||
/** | ||
* Size in MB by default, or MiB if fileSizeBaseInBinary === true | ||
*/ | ||
maxFileSize: { | ||
type: Number, | ||
"default": 256 | ||
}, | ||
/** | ||
* The base that is used to calculate the file size. | ||
* 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. | ||
*/ | ||
fileSizeBaseInBinary: { | ||
type: Boolean, | ||
"default": false | ||
}, | ||
createImageThumbnails: { | ||
type: Boolean, | ||
"default": true | ||
}, | ||
// in MB. When the filename exceeds this limit, the thumbnail will not be generated. | ||
maxThumbnailFileSize: { | ||
type: Number, | ||
"default": 10 | ||
}, | ||
thumbnailWidth: { | ||
type: Number, | ||
"default": 120 | ||
}, | ||
thumbnailHeight: { | ||
type: Number, | ||
"default": 120 | ||
}, | ||
/** | ||
* Can be used to limit the maximum number of files that will be handled | ||
* by this Dropzone | ||
*/ | ||
maxFiles: { | ||
type: Number, | ||
"default": null | ||
}, | ||
/** | ||
* If true, the dropzone will present a file selector when clicked. | ||
*/ | ||
clickable: { | ||
type: Boolean, | ||
"default": true | ||
}, | ||
/** | ||
* Whether dot files in directories should be ignored. | ||
*/ | ||
ignoreHiddenFiles: { | ||
type: Boolean, | ||
"default": true | ||
}, | ||
/** | ||
* You can set accepted mime types here. | ||
* | ||
* The default implementation of the `accept()` function will check this | ||
* property, and if the Dropzone is clickable this will be used as | ||
* `accept` attribute. | ||
* | ||
* This is a comma separated list of mime types or extensions. E.g.: | ||
* - audio/*,video/*,image/png,.pdf | ||
* | ||
* See https://developer.mozilla.org/en-US/docs/HTML/Element/input#attr-accept | ||
* for a reference. | ||
*/ | ||
acceptedFileTypes: { | ||
type: Array, | ||
"default": function () { | ||
return []; | ||
} | ||
}, | ||
/** | ||
* 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() | ||
*/ | ||
autoProcessQueue: { | ||
type: Boolean, | ||
"default": true | ||
}, | ||
/** | ||
* If false, files added to the dropzone will not be queued by default. | ||
* You'll have to call `enqueueFile(file)` manually. | ||
*/ | ||
autoQueue: { | ||
type: Boolean, | ||
"default": true | ||
}, | ||
/** | ||
* 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: { | ||
type: String, | ||
"default": null | ||
}, | ||
// If the file size is too big. | ||
errMaxFileSizeExceeded: { | ||
type: Function, | ||
"default": function (fileSize, maxFileSize, units) { | ||
return "The file is too big (" + fileSize + units + "). Max file size: " + maxFileSize + units + "."; | ||
} | ||
}, | ||
errInvalidFileType: { | ||
type: Function, | ||
"default": function (type, _acceptedTypes, _file) { | ||
return "You can't upload files of this type: " + type; | ||
} | ||
}, | ||
errMaxFilesExceeded: { | ||
type: Function, | ||
"default": function (maxFiles) { | ||
return "You can not upload any more files (" + maxFiles + " max)."; | ||
} | ||
}, | ||
/** | ||
* 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). | ||
*/ | ||
accept: { | ||
type: Function, | ||
"default": function (_file, done) { | ||
done(); | ||
} | ||
}, | ||
resize: { | ||
type: Function, | ||
"default": resizeImg | ||
}, | ||
adapterOptions: { | ||
type: Object, | ||
"default": objFactory | ||
}, | ||
uploadAdapter: { | ||
type: Function, | ||
"default": XHRUploadAdapter | ||
} | ||
}, | ||
mounted: function () { | ||
var _this = this; | ||
this.$on(VTransmitEvents.UploadProgress, this.updateTotalUploadProgress); | ||
this.$on(VTransmitEvents.RemovedFile, this.updateTotalUploadProgress); | ||
this.$on(VTransmitEvents.Canceled, function (file) { | ||
return _this.$emit(VTransmitEvents.Complete, file); | ||
}); | ||
this.$on(VTransmitEvents.Complete, function (file) { | ||
if (_this.addedFiles.length === 0 && | ||
_this.uploadingFiles.length === 0 && | ||
_this.queuedFiles.length === 0) { | ||
Promise.resolve().then(function () { return _this.$emit(VTransmitEvents.QueueComplete, file); }); | ||
} | ||
}); | ||
this.$emit(VTransmitEvents.Initialize, this); | ||
}, | ||
data: function () { | ||
return { | ||
dragging: false, | ||
// Used to keep the createThumbnail calls processing async one-at-a-time | ||
processingThumbnail: false, | ||
thumbnailQueue: [], | ||
files: [], | ||
defaultHeaders: { | ||
Accept: "application/json", | ||
"Cache-Control": "no-cache", | ||
"X-Requested-With": "XMLHttpRequest" | ||
}, | ||
formStyles: { | ||
visibility: "hidden !important", | ||
position: "absolute !important", | ||
top: "0 !important", | ||
left: "0 !important", | ||
height: "0px !important", | ||
width: "0px !important" | ||
} | ||
}; | ||
}, | ||
computed: { | ||
inputEl: function () { | ||
var el = this.$refs.hiddenFileInput; | ||
if (!(el instanceof HTMLInputElement)) { | ||
return null; | ||
} | ||
return el; | ||
}, | ||
formEl: function () { | ||
var el = this.$refs.uploadForm; | ||
if (!(el instanceof HTMLFormElement)) { | ||
return null; | ||
} | ||
return el; | ||
}, | ||
fileSizeBase: function () { | ||
if (this.fileSizeBaseInBinary) { | ||
return 1024; | ||
} | ||
return 1000; | ||
}, | ||
maxFileSizeBytes: function () { | ||
return this.maxFileSize * this.fileSizeBase * this.fileSizeBase; | ||
}, | ||
filesToAccept: function () { | ||
return this.acceptedFileTypes.join(","); | ||
}, | ||
multiple: function () { | ||
return this.maxFiles === null || this.maxFiles > 1; | ||
}, | ||
acceptedFiles: function () { | ||
return this.files.filter(function (f) { return f.accepted; }); | ||
}, | ||
rejectedFiles: function () { | ||
return this.files.filter(function (f) { return !f.accepted; }); | ||
}, | ||
addedFiles: function () { | ||
return this.getFilesWithStatus(UploadStatuses.Added); | ||
}, | ||
queuedFiles: function () { | ||
return this.getFilesWithStatus(UploadStatuses.Queued); | ||
}, | ||
uploadingFiles: function () { | ||
return this.getFilesWithStatus(UploadStatuses.Uploading); | ||
}, | ||
activeFiles: function () { | ||
return this.getFilesWithStatus(UploadStatuses.Uploading, UploadStatuses.Queued); | ||
}, | ||
maxFilesReached: function () { | ||
return (this.maxFiles != null && this.acceptedFiles.length >= this.maxFiles); | ||
}, | ||
maxFilesReachedClass: function () { | ||
return this.maxFilesReached ? "v-transmit__max-files--reached" : null; | ||
}, | ||
isDraggingClass: function () { | ||
return _a = { | ||
"v-transmit__upload-area--is-dragging": this.dragging | ||
}, _a[this.dragClass] = this.dragging, _a; | ||
var _a; | ||
}, | ||
isUploading: function () { | ||
return this.uploadingFiles.length > 0; | ||
}, | ||
fileSlotBindings: function () { | ||
return { | ||
files: this.files, | ||
acceptedFiles: this.acceptedFiles, | ||
rejectedFiles: this.rejectedFiles, | ||
addedFiles: this.addedFiles, | ||
queuedFiles: this.queuedFiles, | ||
uploadingFiles: this.uploadingFiles, | ||
activeFiles: this.activeFiles, | ||
isUploading: this.isUploading | ||
}; | ||
}, | ||
transport: function () { | ||
var Adapter = this.uploadAdapter; | ||
try { | ||
return new Adapter(new VTransmitUploadContext(this), this.adapterOptions); | ||
} | ||
catch (err) { | ||
console.error(err); | ||
throw err; | ||
} | ||
} | ||
}, | ||
watch: { | ||
acceptedFiles: function (acceptedFiles) { | ||
if (this.maxFiles == null) { | ||
return; | ||
} | ||
if (acceptedFiles.length >= this.maxFiles) { | ||
this.$emit(VTransmitEvents.MaxFilesReached, this.files); | ||
} | ||
} | ||
}, | ||
methods: { | ||
getFilesWithStatus: function () { | ||
var statuses = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
statuses[_i] = arguments[_i]; | ||
} | ||
return this.files.filter(function (f) { return statuses.indexOf(f.status) > -1; }); | ||
}, | ||
onFileInputChange: function () { | ||
var _a = this, inputEl = _a.inputEl, formEl = _a.formEl; | ||
if (inputEl == null || formEl == null) { | ||
// This is unreachable code, | ||
// but we need to let TS know it. | ||
throw TypeError(); | ||
} | ||
// Can be null | ||
if (!inputEl.files) { | ||
return; | ||
} | ||
this.$emit(VTransmitEvents.AddedFiles, Array.from(inputEl.files).map(this.addFile)); | ||
// Reset input element's files | ||
// https://github.com/alexsasharegan/vue-transmit/issues/25 | ||
formEl.reset(); | ||
}, | ||
addFile: function (file) { | ||
var _this = this; | ||
var vtFile = new VTransmitFile(file); | ||
vtFile.status = UploadStatuses.Added; | ||
this.files.push(vtFile); | ||
this.$emit(VTransmitEvents.AddedFile, vtFile); | ||
this.enqueueThumbnail(vtFile); | ||
this.acceptFile(vtFile, function (error) { | ||
if (error) { | ||
vtFile.accepted = false; | ||
_this.errorProcessing([vtFile], error); | ||
_this.$emit(VTransmitEvents.RejectedFile, vtFile); | ||
_this.$emit(VTransmitEvents.AcceptComplete, vtFile); | ||
return; | ||
} | ||
vtFile.accepted = true; | ||
_this.$emit(VTransmitEvents.AcceptedFile, vtFile); | ||
_this.$emit(VTransmitEvents.AcceptComplete, vtFile); | ||
if (_this.autoQueue) { | ||
_this.enqueueFile(vtFile); | ||
} | ||
}); | ||
return vtFile; | ||
}, | ||
acceptFile: function (file, done) { | ||
// File size check | ||
if (file.size > this.maxFileSizeBytes) { | ||
// size is in bytes, base is kilo multiplier, so base * base == mega | ||
var mega = this.fileSizeBase * this.fileSizeBase; | ||
var fileSize = file.size / mega; | ||
var units = "MB"; | ||
if (this.fileSizeBaseInBinary) { | ||
units = "MiB"; | ||
} | ||
return done(this.errMaxFileSizeExceeded(fileSize, this.maxFileSize, units)); | ||
} | ||
// File type check | ||
if (!this.isValidFileType(file, this.acceptedFileTypes)) { | ||
return done(this.errInvalidFileType(file.type, this.acceptedFileTypes, file)); | ||
} | ||
// Upload limit check | ||
if (this.maxFiles != null && this.acceptedFiles.length >= this.maxFiles) { | ||
this.$emit(VTransmitEvents.MaxFilesExceeded, file); | ||
return done(this.errMaxFilesExceeded(this.maxFiles)); | ||
} | ||
// Happy path 😀 | ||
this.accept(file, done); | ||
}, | ||
removeFile: function (file) { | ||
if (file.status === UploadStatuses.Uploading) { | ||
this.cancelUpload(file); | ||
} | ||
var idxToRm = this.files.findIndex(function (f) { return f.id === file.id; }); | ||
if (idxToRm > -1) { | ||
this.$emit(VTransmitEvents.RemovedFile, this.files.splice(idxToRm, 1)[0]); | ||
if (this.files.length === 0) { | ||
this.$emit(VTransmitEvents.Reset); | ||
} | ||
} | ||
}, | ||
removeAllFiles: function (cancelInProgressUploads) { | ||
if (cancelInProgressUploads === void 0) { cancelInProgressUploads = false; } | ||
var f; | ||
for (var _i = 0, _a = this.files; _i < _a.length; _i++) { | ||
f = _a[_i]; | ||
if (f.status !== UploadStatuses.Uploading || cancelInProgressUploads) { | ||
this.removeFile(f); | ||
} | ||
} | ||
}, | ||
triggerBrowseFiles: function () { | ||
if (this.inputEl) { | ||
this.inputEl.click(); | ||
} | ||
}, | ||
handleClickUploaderAction: function () { | ||
if (this.clickable) { | ||
this.triggerBrowseFiles(); | ||
} | ||
}, | ||
enqueueFile: function (file) { | ||
if (file.status !== UploadStatuses.Added || file.accepted !== true) { | ||
throw new Error("This file can't be queued because it has already been processed or was rejected."); | ||
} | ||
file.status = UploadStatuses.Queued; | ||
if (this.autoProcessQueue) { | ||
Promise.resolve().then(this.processQueue); | ||
} | ||
}, | ||
enqueueThumbnail: function (file) { | ||
if (!this.createImageThumbnails || | ||
!file.type.match(/image.*/) || | ||
file.size > this.maxThumbnailFileSize * 1024 * 1024) { | ||
return; | ||
} | ||
this.thumbnailQueue.push(file); | ||
Promise.resolve().then(this.processThumbnailQueue); | ||
}, | ||
processThumbnailQueue: function () { | ||
var _this = this; | ||
var file; | ||
// Employ a chain of self-calling, self-queuing createThumbnail calls | ||
// so execution can stay as non-blocking as possible. | ||
if (this.processingThumbnail || this.thumbnailQueue.length === 0) { | ||
return; | ||
} | ||
this.processingThumbnail = true; | ||
if ((file = this.thumbnailQueue.shift())) { | ||
this.createThumbnail(file, function () { | ||
_this.processingThumbnail = false; | ||
_this.processThumbnailQueue(); | ||
}); | ||
} | ||
}, | ||
createThumbnail: function (file, callback) { | ||
var _this = this; | ||
if (callback === void 0) { callback = noop; } | ||
var reader = new FileReader(); | ||
reader.addEventListener("load", function () { | ||
if (file.type === "image/svg+xml") { | ||
file.dataUrl = reader.result; | ||
_this.$emit(VTransmitEvents.Thumbnail, file, reader.result); | ||
callback(); | ||
} | ||
_this.createThumbnailFromUrl(file, reader.result, callback); | ||
}, false); | ||
// FileReader requires a native File|Blob object | ||
reader.readAsDataURL(file.nativeFile); | ||
}, | ||
createThumbnailFromUrl: function (file, imageUrl, callback) { | ||
var _this = this; | ||
var imgEl = document.createElement("img"); | ||
imgEl.addEventListener("load", function () { | ||
var ctx; | ||
file.width = imgEl.width; | ||
file.height = imgEl.height; | ||
var resizeInfo = _this.resize(file, { | ||
width: _this.thumbnailWidth, | ||
height: _this.thumbnailHeight | ||
}); | ||
var canvas = document.createElement("canvas"); | ||
// Can be null | ||
if (!(ctx = canvas.getContext("2d"))) { | ||
return; | ||
} | ||
canvas.width = resizeInfo.dWidth; | ||
canvas.height = resizeInfo.dHeight; | ||
ctx.drawImage(imgEl, resizeInfo.sx, resizeInfo.sy, resizeInfo.sWidth, resizeInfo.sHeight, resizeInfo.dx, resizeInfo.dy, resizeInfo.dWidth, resizeInfo.dHeight); | ||
var thumbnail = canvas.toDataURL("image/png"); | ||
file.dataUrl = thumbnail; | ||
_this.$emit(VTransmitEvents.Thumbnail, file, thumbnail); | ||
if (callback) { | ||
return callback(); | ||
} | ||
}, false); | ||
if (callback) { | ||
imgEl.addEventListener("error", callback, false); | ||
} | ||
imgEl.src = imageUrl; | ||
}, | ||
processQueue: function () { | ||
var processingLength = this.uploadingFiles.length; | ||
if (processingLength >= this.maxConcurrentUploads || | ||
this.queuedFiles.length === 0) { | ||
return; | ||
} | ||
var queuedFiles = this.queuedFiles.slice(); | ||
if (this.uploadMultiple) { | ||
return this.processFiles(queuedFiles.slice(0, this.maxConcurrentUploads - processingLength)); | ||
} | ||
var i = processingLength; | ||
var file; | ||
for (; i < this.maxConcurrentUploads; i++) { | ||
if ((file = queuedFiles.shift())) { | ||
this.processFile(file); | ||
} | ||
} | ||
}, | ||
processFile: function (file) { | ||
this.processFiles([file]); | ||
}, | ||
processFiles: function (files) { | ||
var file; | ||
for (var _i = 0, files_1 = files; _i < files_1.length; _i++) { | ||
file = files_1[_i]; | ||
file.processing = true; | ||
file.status = UploadStatuses.Uploading; | ||
this.$emit(VTransmitEvents.Processing, file); | ||
} | ||
if (this.uploadMultiple) { | ||
this.$emit(VTransmitEvents.ProcessingMultiple, files); | ||
} | ||
return this.uploadFiles(files); | ||
}, | ||
cancelUpload: function (file) { | ||
// Cancel a file before uploading | ||
if (file.status === UploadStatuses.Added || | ||
file.status === UploadStatuses.Queued) { | ||
file.status = UploadStatuses.Canceled; | ||
this.$emit(VTransmitEvents.Canceled, file); | ||
if (this.uploadMultiple) { | ||
this.$emit(VTransmitEvents.CanceledMultiple, [file]); | ||
} | ||
} | ||
// Cancel an in-progress upload | ||
if (file.status === UploadStatuses.Uploading) { | ||
var canceledFiles = this.transport.cancelUpload(file); | ||
var f = void 0; | ||
for (var _i = 0, canceledFiles_1 = canceledFiles; _i < canceledFiles_1.length; _i++) { | ||
f = canceledFiles_1[_i]; | ||
f.status = UploadStatuses.Canceled; | ||
this.$emit(VTransmitEvents.Canceled, f); | ||
} | ||
if (this.uploadMultiple) { | ||
this.$emit(VTransmitEvents.CanceledMultiple, canceledFiles); | ||
} | ||
} | ||
if (this.autoProcessQueue) { | ||
this.processQueue(); | ||
} | ||
}, | ||
uploadFile: function (file) { | ||
this.uploadFiles([file]); | ||
}, | ||
uploadFiles: function (files) { | ||
var _this = this; | ||
this.transport | ||
.uploadFiles(files) | ||
.then(function (response) { return _this.uploadFinished(files, response); })["catch"](function (err) { | ||
switch (err.event) { | ||
case VTransmitEvents.Timeout: | ||
_this.handleTimeout(files, err.message); | ||
break; | ||
case VTransmitEvents.Error: | ||
default: | ||
_this.errorProcessing(files, err.message); | ||
break; | ||
} | ||
}); | ||
}, | ||
handleTimeout: function (files, message) { | ||
var args = []; | ||
for (var _i = 2; _i < arguments.length; _i++) { | ||
args[_i - 2] = arguments[_i]; | ||
} | ||
var f; | ||
for (var _a = 0, files_2 = files; _a < files_2.length; _a++) { | ||
f = files_2[_a]; | ||
f.status = UploadStatuses.Timeout; | ||
f.endProgress(); | ||
this.$emit.apply(this, [VTransmitEvents.Timeout, f, message].concat(args)); | ||
} | ||
this.$emit.apply(this, [VTransmitEvents.TimeoutMultiple, files, message].concat(args)); | ||
if (this.autoProcessQueue) { | ||
this.processQueue(); | ||
} | ||
}, | ||
updateTotalUploadProgress: function () { | ||
var progress = this.activeFiles.reduce(function (memo, file) { | ||
memo.totalBytesSent += file.upload.bytesSent; | ||
memo.totalBytes += file.upload.total; | ||
return memo; | ||
}, { totalBytesSent: 0, totalBytes: 0, totalProgress: 100 }); | ||
if (this.activeFiles.length) { | ||
progress.totalProgress = | ||
100 * progress.totalBytesSent / progress.totalBytes; | ||
} | ||
this.$emit(VTransmitEvents.TotalUploadProgress, progress); | ||
}, | ||
uploadFinished: function (files, response) { | ||
var args = []; | ||
for (var _i = 2; _i < arguments.length; _i++) { | ||
args[_i - 2] = arguments[_i]; | ||
} | ||
for (var _a = 0, files_3 = files; _a < files_3.length; _a++) { | ||
var file = files_3[_a]; | ||
file.status = UploadStatuses.Success; | ||
file.endProgress(); | ||
this.$emit.apply(this, [VTransmitEvents.Success, file, response].concat(args)); | ||
this.$emit(VTransmitEvents.Complete, file); | ||
} | ||
if (this.uploadMultiple) { | ||
this.$emit.apply(this, [VTransmitEvents.SuccessMultiple, files, response].concat(args)); | ||
this.$emit(VTransmitEvents.CompleteMultiple, files); | ||
} | ||
if (this.autoProcessQueue) { | ||
this.processQueue(); | ||
} | ||
}, | ||
errorProcessing: function (files, message, xhr) { | ||
for (var _i = 0, files_4 = files; _i < files_4.length; _i++) { | ||
var file = files_4[_i]; | ||
file.status = UploadStatuses.Error; | ||
file.endProgress(); | ||
this.$emit(VTransmitEvents.Error, file, message, xhr); | ||
this.$emit(VTransmitEvents.Complete, file); | ||
} | ||
if (this.uploadMultiple) { | ||
this.$emit(VTransmitEvents.ErrorMultiple, files, message, xhr); | ||
this.$emit(VTransmitEvents.CompleteMultiple, files); | ||
} | ||
if (this.autoProcessQueue) { | ||
return this.processQueue(); | ||
} | ||
}, | ||
isValidFileType: function (file, acceptedFileTypes) { | ||
if (!acceptedFileTypes.length) { | ||
return true; | ||
} | ||
var mimeType = file.type; | ||
var baseMimeType = mimeType.replace(/\/.*$/, ""); | ||
// Return true on the first condition match, | ||
// otherwise exhaust all conditions and return false. | ||
for (var i = 0; i < acceptedFileTypes.length; i++) { | ||
var validType = acceptedFileTypes[i]; | ||
if (validType.charAt(0) === ".") { | ||
// Handle extension validation | ||
// Ensure extension exists at the end of the filename. | ||
if (file.name | ||
.toLowerCase() | ||
.indexOf(validType.toLowerCase(), file.name.length - validType.length) !== -1) { | ||
return true; | ||
} | ||
} | ||
else if (/\/\*$/.test(validType)) { | ||
// Handle globbed mimetype validation ("image/*") | ||
if (baseMimeType === validType.replace(/\/.*$/, "")) { | ||
return true; | ||
} | ||
} | ||
else { | ||
if (mimeType === validType) { | ||
return true; | ||
} | ||
} | ||
} | ||
return false; | ||
}, | ||
handleDragStart: function (e) { | ||
this.$emit("drag-start", e); | ||
}, | ||
handleDragOver: function (e) { | ||
this.dragging = true; | ||
var effect; | ||
try { | ||
// Handle browser bug | ||
effect = e.dataTransfer.effectAllowed; | ||
} | ||
catch (error) { } | ||
e.dataTransfer.dropEffect = | ||
effect === "move" || effect === "linkMove" ? "move" : "copy"; | ||
this.$emit(VTransmitEvents.DragOver, e); | ||
}, | ||
handleDragEnter: function (e) { | ||
this.dragging = true; | ||
this.$emit(VTransmitEvents.DragEnter, e); | ||
}, | ||
handleDragLeave: function (e) { | ||
this.dragging = false; | ||
this.$emit(VTransmitEvents.DragLeave, e); | ||
}, | ||
handleDragEnd: function (e) { | ||
this.dragging = false; | ||
this.$emit(VTransmitEvents.DragEnd, e); | ||
}, | ||
handleDrop: function (e) { | ||
this.dragging = false; | ||
if (!e.dataTransfer) { | ||
return; | ||
} | ||
var files; | ||
var items; | ||
this.$emit(VTransmitEvents.Drop, e); | ||
this.$emit(VTransmitEvents.AddedFiles, (files = Array.from(e.dataTransfer.files))); | ||
if (!e.dataTransfer.items) { | ||
this.handleFiles(files); | ||
return; | ||
} | ||
items = Array.from(e.dataTransfer.items); | ||
if (!items || | ||
!items.length || | ||
!(items[0].getAsFile || items[0].webkitGetAsEntry)) { | ||
this.handleFiles(files); | ||
return; | ||
} | ||
this.addFilesFromItems(items); | ||
}, | ||
paste: function (e) { | ||
if (!e || !e.clipboardData || !e.clipboardData.items) { | ||
return; | ||
} | ||
this.$emit(VTransmitEvents.Paste, e); | ||
var items = Array.from(e.clipboardData.items); | ||
if (items.length) { | ||
this.addFilesFromItems(items); | ||
} | ||
}, | ||
handleFiles: function (files) { | ||
return files.map(this.addFile); | ||
}, | ||
addFilesFromItems: function (items) { | ||
var entry; | ||
for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { | ||
var item = items_1[_i]; | ||
// Newer API on standards track | ||
if (item.getAsFile && item.kind == "file") { | ||
var file = item.getAsFile(); | ||
if (file) { | ||
this.addFile(file); | ||
} | ||
continue; | ||
} | ||
// Vendor prefixed experimental API | ||
if (item.webkitGetAsEntry) { | ||
entry = item.webkitGetAsEntry(); | ||
if (entry == null) { | ||
continue; | ||
} | ||
if (webkitIsFile(entry)) { | ||
entry.file(this.addFile, console.error); | ||
continue; | ||
} | ||
if (webkitIsDir(entry)) { | ||
this.addFilesFromDirectory(entry, entry.name); | ||
continue; | ||
} | ||
} | ||
} | ||
}, | ||
addFilesFromDirectory: function (directory, path) { | ||
var _this = this; | ||
directory.createReader().readEntries((function (entries) { | ||
for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { | ||
var entry = entries_1[_i]; | ||
if (entry == null) { | ||
continue; | ||
} | ||
if (webkitIsDir(entry)) { | ||
_this.addFilesFromDirectory(entry, path + "/" + entry.name); | ||
continue; | ||
} | ||
if (webkitIsFile(entry)) { | ||
entry.file((function (file) { | ||
if (_this.ignoreHiddenFiles && /^\./.test(file.name)) { | ||
return; | ||
} | ||
file.fullPath = path + "/" + file.name; | ||
_this.addFile(file); | ||
}), console.error); | ||
} | ||
} | ||
}), console.error); | ||
} | ||
} | ||
}); | ||
var Plugin = { | ||
install: function (Vue$$1) { | ||
Vue$$1.component("VueTransmit", VueTransmit); | ||
}, | ||
name: "vue-transmit", | ||
}; | ||
return Plugin; | ||
}))); | ||
//# sourceMappingURL=vue-transmit.js.map |
{ | ||
"name": "vue-transmit", | ||
"version": "9.0.0-alpha.1", | ||
"version": "9.0.0-alpha.2", | ||
"description": "Vue.js drag & drop uploader based on Dropzone.js", | ||
"module": "dist/vue-transmit.esm.min.js", | ||
"main": "dist/vue-transmit.common.min.js", | ||
"module": "dist/vue-transmit.esm.js", | ||
"main": "dist/vue-transmit.js", | ||
"types": "dist/index.d.ts", | ||
@@ -22,3 +22,3 @@ "keywords": [ | ||
"prebuild": "npm run clean", | ||
"build": "cross-env NODE_ENV=production rollup -c ./rollup.config.js", | ||
"build": "cross-env NODE_ENV=production rollup -c ./rollup.config.js && rollup -c ./rollup.config.min.js", | ||
"prepublishOnly": "npm run build", | ||
@@ -52,5 +52,3 @@ "test:site": "php -S localhost:3030 -t ./test/", | ||
}, | ||
"dependencies": { | ||
"lodash-es": "^4.17.5" | ||
}, | ||
"dependencies": {}, | ||
"devDependencies": { | ||
@@ -57,0 +55,0 @@ "@types/jest": "^22.1.1", |
@@ -32,9 +32,14 @@ # Vue-Transmit | ||
In order to comply with Vue.js reactivity, an object's properties must be | ||
defined up front and be configurable. A special File class has been written | ||
(`VTransmitFile`) to register file objects from uploads reactively, since the | ||
native File object's properties are read-only. This class also adds useful | ||
information not present in the native File object (dimensions, upload stats, | ||
etc.). | ||
Vue-Transmit also has a modular upload transport. The default transport | ||
implementation uses `XMLHttpRequest` to upload client-side files using | ||
multi-part form data, but this could be swapped for a custom implementation for | ||
something like Firebase. | ||
In order to integrate with Vue.js reactivity, an object's properties must be | ||
defined initially, be enumerable, and be configurable. A special File class has | ||
been written (`VTransmitFile`) to register native browser file objects from | ||
uploads reactively, since the native object properties are read-only. This class | ||
also adds useful information not present in the native File object (dimensions, | ||
upload stats, etc.). | ||
* HTML 5 file uploads | ||
@@ -44,2 +49,3 @@ * Emits upload lifecycle events (accepted, sending, progress, success, etc.) | ||
* Support for concurrent uploads | ||
* Modular upload transport layer | ||
* Completely written in Vue.js—no wrapper components | ||
@@ -49,5 +55,7 @@ * Scoped slots allow for fully customizable styling | ||
_\* Note: this library uses some built-ins (`Array.from`) that require a | ||
polyfill. All other ESNext language features (arrow fns, for of, etc.) are | ||
transpiled with babel._ | ||
_\* Note: this library uses some built-ins (`Array.from`, `Promise`) that | ||
require | ||
[a polyfill](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from#Polyfill). | ||
All other ESNext language features (arrow fns, for of, etc.) are transpiled with | ||
TypeScript._ | ||
@@ -58,3 +66,3 @@ ![upload-example](./docs/vue-transmit-10fps.gif) | ||
```shell | ||
```sh | ||
npm install vue-transmit | ||
@@ -66,4 +74,5 @@ ``` | ||
The default build for ESM loaders like webpack is indicated in the `module` | ||
fields of the package. For most setups, importing the lib would like the | ||
following: | ||
field of the package, while non-esm will resolve from the `main` field. By | ||
default, the unminified versions are specified. For most setups, importing the | ||
lib would like either of the following: | ||
@@ -82,6 +91,8 @@ ```js | ||
| Target | Path | Minified | | ||
| ------ | --------------------------------------- | -------- | | ||
| ESM | `vue-transmit/dist/vue-transmit.esm.js` | true | | ||
| AMD | `vue-transmit/dist/vue-transmit.js` | true | | ||
| Target | Path | Minified | | ||
| ------ | ------------------------------------------- | -------- | | ||
| ESM | `vue-transmit/dist/vue-transmit.esm.js` | false | | ||
| ESM | `vue-transmit/dist/vue-transmit.esm.min.js` | true | | ||
| UMD | `vue-transmit/dist/vue-transmit.js` | false | | ||
| UMD | `vue-transmit/dist/vue-transmit.min.js` | true | | ||
@@ -254,3 +265,3 @@ ## Props: <code><vue-transmit></code> | ||
<!-- Scoped slot --> | ||
<template slot="files" scope="props"> | ||
<template slot="files" slot-scope="props"> | ||
<div v-for="(file, i) in props.files" :key="file.id" :class="{'mt-5': i === 0}"> | ||
@@ -283,4 +294,6 @@ <div class="media"> | ||
acceptedFileTypes: ['image/*'], | ||
url: './upload.php', | ||
clickable: false | ||
clickable: false, | ||
adapterOptions: { | ||
url: './upload.php', | ||
}, | ||
} | ||
@@ -287,0 +300,0 @@ }, |
const path = require("path"); | ||
const typescript = require("rollup-plugin-typescript2"); | ||
const vue = require("rollup-plugin-vue"); | ||
const uglify = require("rollup-plugin-uglify"); | ||
const { minify } = require("uglify-js"); | ||
// const uglify = require("rollup-plugin-uglify"); | ||
// const { minify } = require("uglify-js"); | ||
@@ -20,3 +20,3 @@ const isProduction = process.env.NODE_ENV === `production`; | ||
}), | ||
uglify(), | ||
// uglify(), | ||
], | ||
@@ -23,0 +23,0 @@ output: [ |
{ | ||
"compileOnSave": false, | ||
"compilerOptions": { | ||
"outDir": "lib", | ||
"declarationDir": "lib", | ||
"outDir": "dist", | ||
"declarationDir": "dist", | ||
"allowSyntheticDefaultImports": true, | ||
"lib": ["dom", "esnext"], | ||
"jsx": "preserve", | ||
"target": "es5", | ||
@@ -21,3 +20,3 @@ "module": "es2015", | ||
"removeComments": false, | ||
"preserveConstEnums": true, | ||
"preserveConstEnums": false, | ||
"sourceMap": true, | ||
@@ -24,0 +23,0 @@ "skipLibCheck": true, |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
7258364
0
48
3864
341
3
1
- Removedlodash-es@^4.17.5
- Removedlodash-es@4.17.21(transitive)