forked from RubaXa/jquery.fileapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.fileapi.min.js
2 lines (2 loc) · 15.5 KB
/
jquery.fileapi.min.js
1
2
/*! jquery.fileapi 0.3.2 - MIT | git://github.com/rubaxa/jquery.fileapi.git */
(function(e,t){"use strict";function i(e){var t;for(t in e)if(e.hasOwnProperty(t)&&!(e[t]instanceof Object||"overlay"===t))return!0;return!1}function s(e,t,i,s){if(i){var n=i-s,r=/max/.test(t);(r&&0>n||!r&&n>0)&&(e.errors||(e.errors={}),e.errors[t]=Math.abs(n))}}function n(e,t,i,n){if(e){var r=i.length-(e-t);r>0&&u(i.splice(0,r),function(e,t){s(e,"maxFiles",-1,t),n.push(e)})}}var r=e.noop,o=!e.fn.prop,l=o?"attr":"prop",a="data-fileapi",h="data-fileapi-id",p=[].slice,u=t.each,f=t.extend,c=function(e,t){var i=p.call(arguments,2);return t.bind?t.bind.apply(t,[e].concat(i)):function(){return t.apply(e,i.concat(p.call(arguments)))}},d=function(e){return"["+a+'="'+e+'"]'},m=function(e){return 0===e.indexOf("#")},g=function(t,i){if(this.$el=t=e(t).on("change.fileapi",'input[type="file"]',c(this,this._onSelect)),this.el=t[0],this._options={},this.options={url:0,data:{},accept:0,multiple:!1,paramName:0,dataType:"json",duplicate:!1,chunkSize:0,chunkUploadRetry:3,maxSize:0,maxFiles:0,imageSize:0,sortFn:0,filterFn:0,autoUpload:!1,clearOnSelect:void 0,clearOnComplete:void 0,lang:{B:"bytes",KB:"KB",MB:"MB",GB:"GB",TB:"TB"},sizeFormat:"0.00",imageTransform:0,imageAutoOrientation:!!FileAPI.support.exif,elements:{ctrl:{upload:d("ctrl.upload"),reset:d("ctrl.reset"),abort:d("ctrl.abort")},empty:{show:d("empty.show"),hide:d("empty.hide")},emptyQueue:{show:d("emptyQueue.show"),hide:d("emptyQueue.hide")},active:{show:d("active.show"),hide:d("active.hide")},size:d("size"),name:d("name"),progress:d("progress"),list:d("list"),file:{tpl:d("file.tpl"),progress:d("file.progress"),active:{show:d("file.active.show"),hide:d("file.active.hide")},preview:{el:0,get:0,width:0,height:0,processing:0},abort:d("file.abort"),remove:d("file.remove"),rotate:d("file.rotate")},dnd:{el:d("dnd"),hover:"dnd_hover",fallback:d("dnd.fallback")}},onDrop:r,onDropHover:r,onSelect:r,onUpload:r,onProgress:r,onComplete:r,onFilePrepare:r,onFileUpload:r,onFileProgress:r,onFileComplete:r,onFileRemove:null,onFileRemoveCompleted:null},e.extend(!0,this.options,i),i=this.options,this.option("elements.file.preview.rotate",i.imageAutoOrientation),!i.url){var s=this.$el.attr("action")||this.$el.find("form").attr("action");s?i.url=s:this._throw("url — is not defined")}this.$files=this.$elem("list"),this.itemTplFn=e.fn.fileapi.tpl(e("<div/>").append(this.$elem("file.tpl")).html()),u(i,function(e,t){this._setOption(t,e)},this),this.$el.on("reset.fileapi",c(this,this._onReset)).on("submit.fileapi",c(this,this._onSubmit)).on("upload.fileapi progress.fileapi complete.fileapi",c(this,this._onUploadEvent)).on("fileupload.fileapi fileprogress.fileapi filecomplete.fileapi",c(this,this._onFileUploadEvent)).on("click","["+a+"]",c(this,this._onActionClick));var n=i.elements.ctrl;n&&(this._listen("click",n.reset,c(this,this._onReset)),this._listen("click",n.upload,c(this,this._onSubmit)),this._listen("click",n.abort,c(this,this._onAbort)));var o=FileAPI.support.dnd;this.$elem("dnd.el",!0).toggle(o),this.$elem("dnd.fallback").toggle(!o),o&&this.$elem("dnd.el",!0).dnd(c(this,this._onDropHover),c(this,this._onDrop)),this.$progress=this.$elem("progress"),void 0===i.clearOnSelect&&(i.clearOnSelect=!i.multiple),this.clear()};g.prototype={constructor:g,_throw:function(e){throw"jquery.fileapi: "+e},_getFiles:function(e,i){var r=this.options,o=r.maxSize,l=r.maxFiles,a=r.filterFn,h=this.files.length,p=t.getFiles(e),f={all:p,files:[],other:[],duplicate:r.duplicate?[]:this._extractDuplicateFiles(p)},c=r.imageSize,d=this;c||a?t.filterFiles(p,function(e,t){return t&&c&&(s(e,"minWidth",c.minWidth,t.width),s(e,"minHeight",c.minHeight,t.height),s(e,"maxWidth",c.maxWidth,t.width),s(e,"maxHeight",c.maxHeight,t.height)),s(e,"maxSize",o,e.size),!e.errors&&(!a||a(e,t))},function(e,t){n(l,h,e,t),f.other=t,f.files=e,i.call(d,f)}):(u(p,function(e){s(e,"maxSize",o,e.size),f[e.errors?"other":"files"].push(e)}),n(l,h,f.files,f.other),i.call(d,f))},_extractDuplicateFiles:function(e){for(var t,i=[],s=e.length,n=this.files;s--;)for(t=n.length;t--;)if(this._fileCompare(e[s],n[t])){i.push(e.splice(s,1));break}return i},_fileCompare:function(e,t){return e.size==t.size&&e.name==t.name},_getFormatedSize:function(e){var i=this.options,s="B";return e>=t.TB?e/=t[s="TB"]:e>=t.GB?e/=t[s="GB"]:e>=t.MB?e/=t[s="MB"]:e>=t.KB&&(e/=t[s="KB"]),i.sizeFormat.replace(/^\d+([^\d]+)(\d*)/,function(t,n,r){return e=e.toFixed(r.length),(e+"").replace(".",n)+" "+i.lang[s]})},_onSelect:function(e){this.options.clearOnSelect&&(this.queue=[],this.files=[]),this._getFiles(e,c(this,function(t){t.all.length&&this.emit("select",t)!==!1&&this.add(t.files),FileAPI.reset(e.target)}))},_onActionClick:function(t){var i=t.currentTarget,s=e.attr(i,a),n=e(i).closest("["+h+"]",this.$el).attr(h),r=this._getFile(n),o=!0;"file.remove"==s?r&&this.emit("fileRemove"+(r.complete?"Completed":""),r)&&this.remove(n):/^file\.rotate/.test(s)?this.rotate(n,/ccw/.test(s)?"-=90":"+=90"):o=!1,o&&t.preventDefault()},_listen:function(t,i,s){i&&u(e.trim(i).split(","),function(i){i=e.trim(i),m(i)?e(i).on(t+".fileapi",s):this.$el.on(t+".fileapi",i,s)},this)},_onSubmit:function(e){e.preventDefault(),this.upload()},_onReset:function(e){e.preventDefault(),this.clear()},_onAbort:function(e){e.preventDefault(),this.abort()},_onDrop:function(e){this._getFiles(e,function(e){this.emit("drop",e)!==!1&&this.add(e.files)})},_onDropHover:function(t,i){if(this.emit("dropHover",{state:t,event:i})!==!1){var s=this.option("elements.dnd.hover");s&&e(i.currentTarget).toggleClass(s,t)}},_getFile:function(e){return t.filter(this.files,function(i){return t.uid(i)==e})[0]},_getUploadEvent:function(e){var t=this.xhr,i={xhr:t,file:t.currentFile,files:t.files,widget:this};return f(i,e)},_emitUploadEvent:function(e){var t=this._getUploadEvent();this.emit(e+"Upload",t)},_emitProgressEvent:function(e,t){var i=this._getUploadEvent(t);this.emit(e+"Progress",i)},_emitCompleteEvent:function(t,i,s,n){var r=this._getUploadEvent({error:i,status:s.status,statusText:s.statusText,result:s.responseText});if("file"==t&&(n.complete=!0),!i&&"json"==this.options.dataType)try{r.result=e.parseJSON(r.result)}catch(i){r.error=i}this.emit(t+"Complete",r)},_onUploadEvent:function(e,t){var i=this,s=i.$progress,n=e.type;if("progress"==n)s.stop().animate({width:100*(t.loaded/t.total)+"%"},300);else if("upload"==n)s.width(0);else{var r=function(){s.dequeue(),i[i.options.clearOnComplete?"clear":"dequeue"]()};this.xhr=null,this.active=!1,s.length?s.queue(r):r()}},_onFileUploadPrepare:function(s,n){var r=t.uid(s),o=this._rotate[r],l=this._crop[r],a=this._resize[r],h=this._getUploadEvent();if(o||l){var p=n.imageTransform=n.imageTransform||{};o=o||(this.options.imageAutoOrientation?"auto":void 0),e.isEmptyObject(p)||i(p)?(f(p,a),p.crop=l,p.rotate=o):u(p,function(e){f(e,a),e.crop=l,e.rotate=o})}h.file=s,h.options=n,this.emit("filePrepare",h)},_onFileUploadEvent:function(e,i){var s=this,n=e.type.substr(4),r=t.uid(i.file),o=this.$file(r),l=this._$fileprogress,a=this.options;if(this.__fileId!==r&&(this.__fileId=r,this._$fileprogress=l=this.$elem("file.progress",o)),"progress"==n)l.stop().animate({width:100*(i.loaded/i.total)+"%"},300);else if("upload"==n||"complete"==n){var h=function(){var e="file."+n,t=s.$elem("file.remove",o);"upload"==n?(t.hide(),l.width(0)):a.onRemoveCompleted&&t.show(),l.dequeue(),s.$elem(e+".show",o).show(),s.$elem(e+".hide",o).hide()};l.length?l.queue(h):h(),"complete"==n&&(this.uploaded.push(i.file),delete this._rotate[r])}},_redraw:function(i){var s=this.files,n=!!this.active,r=!s.length&&!n,o=!this.queue.length&&!n,a=[],p=0,f=this.$files,c=f.children().length,d=this.option("elements.file.preview");i&&this.$files.empty(),u(s,function(i,s){var n=t.uid(i);if(a.push(i.name),p+=i.size,f.length&&!this.$file(n).length){var r=this.itemTplFn({$idx:c+s,uid:n,name:i.name,type:i.type,size:i.size,sizeText:this._getFormatedSize(i.size)});f.append(e(r).attr(h,n)),d.el&&this._makeFilePreview(n,i,d)}},this),this.$elem("name").text(a.join(", ")),this.$elem("size").text(p?this._getFormatedSize(p):""),this.$elem("empty.show").toggle(r),this.$elem("empty.hide").toggle(!r),this.$elem("emptyQueue.show").toggle(o),this.$elem("emptyQueue.hide").toggle(!o),this.$elem("active.show").toggle(n),this.$elem("active.hide").toggle(!n),this.$(".js-fileapi-wrapper,:file")[n?"attr":"removeAttr"]("aria-disabled",n)[l]("disabled",n),this._disableElem("ctrl.upload",o||n),this._disableElem("ctrl.reset",o||n),this._disableElem("ctrl.abort",!n)},_disableElem:function(e,t){this.$elem(e)[t?"attr":"removeAttr"]("aria-disabled","disabled")[l]("disabled",t)},_makeFilePreview:function(e,i,s,n){var r=this,o=n?r.$(s.el):r.$file(e).find(s.el);if(!r._crop[e])if(/^image/.test(i.type)){var l=t.Image(i),a=function(){l.get(function(t,n){r._crop[e]||(t?(s.get&&s.get(o,i),r.emit("previewError",[t,i])):o.html(n))})};s.width&&l.preview(s.width,s.height),s.rotate&&l.rotate("auto"),s.processing?s.processing(i,l,a):a()}else s.get&&s.get(o,i)},emit:function(t,i){var s,n=this.options,r=e.Event(t.toLowerCase());return r.widget=this,t=e.camelCase("on-"+t),e.isFunction(n[t])&&(s=n[t].call(this.el,r,i)),this.$el.triggerHandler(r,i),s!==!1&&!r.isDefaultPrevented()},add:function(e,i){if(e=[].concat(e),e.length){var s=this.options,n=s.sortFn,r=s.elements.preview;n&&e.sort(n),r&&r.el&&u(e,function(e){this._makeFilePreview(t.uid(e),e,r,!0)},this),this.xhr&&this.xhr.append(e),this.queue=i?e:this.queue.concat(e),this.files=i?e:this.files.concat(e),this.active?(this.xhr.append(e),this._redraw(i)):(this._redraw(i),this.options.autoUpload&&this.upload())}},$:function(t,i){return"string"==typeof t&&(t=/^#/.test(t)?t:(i?e(i):this.$el).find(t)),e(t)},$elem:function(t,i,s){i&&i.jquery&&(s=i,i=!1);var n=this.option("elements."+t);return void 0===n&&i&&(n=this.option("elements."+t.substr(0,t.lastIndexOf(".")))),this.$("string"!=e.type(n)&&e.isEmptyObject(n)?[]:n,s)},$file:function(e){return this.$("["+h+'="'+e+'"]')},option:function(t,i){if(void 0!==i&&e.isPlainObject(i))return u(i,function(e,i){this.option(t+"."+i,e)},this),this;var s,n,r=this.options,o=r[t],l=0;if(-1!=t.indexOf("."))for(o=r,t=t.split("."),s=t.length;s>l;l++){if(n=t[l],void 0!==i&&1===s-l){o[n]=i;break}o[n]||(o[n]={}),o=o[n]}else void 0!==i&&(r[t]=i);return void 0!==i&&(this._setOption(t,i,this._options[t]),this._options[t]=i),void 0!==i?i:o},_setOption:function(e,t){switch(e){case"accept":case"multiple":case"paramName":"paramName"==e&&(e="name"),t&&this.$(":file")[l](e,t)}},serialize:function(){var t,i={};return this.$el.find(":input").each(function(s,n){(s=n.name)&&!n.disabled&&(n.checked||/select|textarea|input/i.test(n.nodeName)&&!/checkbox|radio|file/i.test(n.type))&&(t=e(n).val(),void 0!==i[s]?(i[s].push||(i[s]=[i[s]]),i[s].push(t)):i[s]=t)}),i},upload:function(){if(!this.active){this.active=!0;var e=this.$el,i=this.options,s={},n={url:i.url,data:f({},this.serialize(),i.data),headers:i.headers,files:s,chunkSize:0|i.chunkSize,chunkUploadRetry:0|i.chunkUploadRetry,prepare:c(this,this._onFileUploadPrepare),imageTransform:i.imageTransform};s[e.find(":file").attr("name")||"files[]"]=this.queue,u(["Upload","Progress","Complete"],function(e){var t=e.toLowerCase();n[t]=c(this,this["_emit"+e+"Event"],""),n["file"+t]=c(this,this["_emit"+e+"Event"],"file")},this),this.xhr=t.upload(n),this._redraw()}},abort:function(e){this.active&&this.xhr&&this.xhr.abort(e)},crop:function(i,s){var n=t.uid(i),r=this.options,o=r.multiple?this.option("elements.file.preview"):r.elements.preview,l=(r.multiple?this.$file(n):this.$el).find(o&&o.el);l.length&&t.getInfo(i,c(this,function(n,a){if(n)this.emit("previewError",[n,i]);else{l.find("div>div").length||l.html(e("<div><div></div></div>").css(o).css("overflow","hidden")),this.__cropFile!==i&&(this.__cropFile=i,t.Image(i).rotate(r.imageAutoOrientation?"auto":0).get(function(t,i){l.find(">div>div").html(e(i).width("100%").height("100%"))},"exactFit"));var h=o.width,p=o.height,u=h,f=p,c=h/s.rw,d=p/s.rh;o.keepAspectRatio&&(c>1&&d>1?(c=d=1,f=s.h,u=s.w):d>c?(d=c,f=h*s.rh/s.rw):(c=d,u=p*s.rw/s.rh)),l.find(">div>div").css({width:Math.round(c*a[s.flip?"height":"width"]),height:Math.round(d*a[s.flip?"width":"height"]),marginLeft:-Math.round(c*s.rx),marginTop:-Math.round(d*s.ry)}),o.keepAspectRatio&&l.find(">div").css({width:Math.round(u),height:Math.round(f),marginLeft:h>u?Math.round((h-u)/2):0,marginTop:p>f?Math.round((p-f)/2):0})}})),this._crop[n]=s},resize:function(e,i,s,n){this._resize[t.uid(e)]={type:n,width:i,height:s}},rotate:function(e,i){var s="object"==typeof e?t.uid(e):e,n=this.options,r=n.multiple?this.option("elements.file.preview"):n.elements.preview,o=(n.multiple?this.$file(s):this.$el).find(r&&r.el),l=this._rotate;/([+-])=/.test(i)?i=l[s]=(l[s]||0)+("+"==RegExp.$1?1:-1)*i.substr(2):l[s]=i,o.css({"-webkit-transform":"rotate("+i+"deg)","-moz-transform":"rotate("+i+"deg)",transform:"rotate("+i+"deg)"})},remove:function(e){var i="object"==typeof e?t.uid(e):e;this.$file(i).remove(),this.queue=t.filter(this.queue,function(e){return t.uid(e)!=i}),this.files=t.filter(this.files,function(e){return t.uid(e)!=i}),this._redraw()},clear:function(){this._crop={},this._resize={},this._rotate={},this.queue=[],this.files=[],this.uploaded=[],this.$files.empty(),this._redraw()},dequeue:function(){this.queue=[],this._redraw()},widget:function(){return this},toString:function(){return"[jQuery.FileAPI object]"},destroy:function(){this.$el.off(".fileapi").removeData("fileapi"),u(this.options.elements.ctrl,function(t){m(t)&&e(t).off("click.fileapi")})}},e.fn.fileapi=function(t,i){var s=this.data("fileapi");if(s){if("widget"===t)return s;if("string"==typeof t){var n,r=s[t];return e.isFunction(r)?n=r.apply(s,p.call(arguments,1)):void 0===r&&(n=s.option(t,i)),void 0===n?this:n}}else(null==t||"object"==typeof t)&&this.data("fileapi",new g(this,t));return this},e.fn.fileapi.version="0.3.2",e.fn.fileapi.tpl=function(e){var t=0,i="__b+='";return e.replace(/(?:<|<)%([-=])?([\s\S]+?)%(?:>|>)|$/g,function(s,n,r,o){return i+=e.slice(t,o).replace(/[\r\n"']/g,function(e){return"\\"+e}),r&&(i+=n?"'+\n((__x=("+r+"))==null?'':"+("-"==n?"__esc(__x)":"__x")+")\n+'":"';\n"+r+"\n__b+='"),t=o+s.length,s}),Function("ctx","var __x,__b='',__esc=function(val){return typeof val=='string'?val.replace(/</g,'<').replace(/\"/g,'"'):val;};with(ctx||{}){\n"+i+"';\n}return __b;")},e.fn.webcam=function(i){var s=this,n=s,o=e(s),l="fileapi-camera",a=o.data(l);return a===!0?(t.log("[webcam.warn] not ready."),n=null):"widget"===i?n=a:"destroy"===i?(a.stop(),o.empty()):a?n=a[i]():a===!1?(t.log("[webcam.error] вoes not work."),n=null):(o.data(l,!0),i=f({success:r,error:r},i),FileAPI.Camera.publish(o,i,function(e,t){o.data(l,e?!1:t),i[e?"error":"success"].call(s,e||t)})),n},e.fn.cropper=function(i){var s=this,n=i.file;if("string"==typeof i)s.first().Jcrop.apply(s,arguments);else{var r=i.minSize||[0,0],o=i.aspectRatio||r[0]/r[1];e.isArray(i.minSize)&&void 0===i.aspectRatio&&o>0&&(i.aspectRatio=o),t.getInfo(n,function(l,a){var h=t.Image(n),p=i.maxSize;p&&h.resize(Math.max(p[0],r[0]),Math.max(p[1],r[1]),"max"),h.rotate("auto").get(function(t,n){var r=i.selection,l=Math.min(n.width,n.height),h=l,p=l/o,f=FileAPI.Image.exifOrientation[a.exif&&a.exif.Orientation]||0;if(r){(/%/.test(r)||r>0&&1>r)&&(r=parseFloat(r,10)/(r>0?1:100),h*=r,p*=r);var c=(n.width-h)/2,d=(n.height-p)/2;i.setSelect=[0|c,0|d,0|c+h,0|d+p]}u(["onSelect","onChange"],function(e,t){(t=i[e])&&(i[e]=function(e){var i=f%180,s=a.width,r=a.height,o=e.x/n.width,l=e.y/n.height,h=e.w/n.width,p=e.h/n.height,u=s*(i?l:o),c=r*(i?1-(e.x+e.w)/n.width:l),d=s*(i?p:h),m=r*(i?h:p);t({x:u,y:c,w:d,h:m,rx:o*(i?r:s),ry:l*(i?s:r),rw:h*(i?r:s),rh:p*(i?s:r),lx:e.x,ly:e.y,lw:e.w,lh:e.h,deg:f,flip:i})})});var m=e("<div/>").css("lineHeight",0).append(e(n).css("margin",0));s.html(m),m.Jcrop(i).trigger("resize")})})}return s}})(jQuery,FileAPI);