You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

1 lines
9.4 KiB

!function(a,b,c,d){a.api=a.fn.api=function(c){var e,f=a(a.isFunction(this)?b:this),g=f.selector||"",h=(new Date).getTime(),i=[],j=arguments[0],k="string"==typeof j,l=[].slice.call(arguments,1);return f.each(function(){var b,f,m,n,o,p=a.extend(!0,{},a.fn.api.settings,c),q=p.namespace,r=(p.metadata,p.selector),s=p.error,t=p.className,u="."+q,v="module-"+q,w=a(this),x=w.closest(r.form),y=p.stateContext?a(p.stateContext):w,z=this,A=w.data(v);o={initialize:function(){var a=o.get.event();k||(a?(o.debug("Attaching API events to element",a),w.on(a+u,o.event.trigger)):o.query()),o.instantiate()},instantiate:function(){o.verbose("Storing instance of module",o),A=o,w.data(v,A)},destroy:function(){o.verbose("Destroying previous module for",z),w.removeData(v).off(u)},query:function(){if(o.is.disabled())return void o.debug("Element is disabled API request aborted");if(o.is.loading()&&!p.allowMultiple)return void o.debug("Request cancelled previous request is still pending");if(p.defaultData&&a.extend(!0,p.urlData,o.get.defaultData()),(p.serializeForm!==!1||w.is("form"))&&("json"==p.serializeForm?a.extend(!0,p.data,o.get.formData()):p.data=o.get.formData()),f=o.get.settings(),f===!1)return void o.error(s.beforeSend);if(p.url?(o.debug("Using specified url",m),m=o.add.urlData(p.url)):(m=o.add.urlData(o.get.templateURL()),o.debug("API url resolved to",m)),!m){if(!w.is("form"))return void o.error(s.missingURL);o.debug("No url or action specified, defaulting to form action"),m=w.attr("action")}o.set.loading(),b=a.extend(!0,{},p,{type:p.method||p.type,data:n,url:m,beforeSend:p.beforeXHR,success:function(){},failure:function(){},complete:function(){}}),o.verbose("Creating AJAX request with settings",b),o.request=o.create.request(),o.xhr=o.create.xhr()},is:{disabled:function(){return w.filter(p.filter).size()>0},loading:function(){return o.request&&"pending"==o.request.state()}},was:{succesful:function(){return o.request&&"resolved"==o.request.state()},failure:function(){return o.request&&"rejected"==o.request.state()},complete:function(){return o.request&&("resolved"==o.request.state()||"rejected"==o.request.state())}},add:{urlData:function(b,c){var e,f;return b&&(e=b.match(p.regExp.required),f=b.match(p.regExp.optional),c=c||p.urlData,e&&(o.debug("Looking for required URL variables",e),a.each(e,function(e,f){var g=-1!==f.indexOf("$")?f.substr(2,f.length-3):f.substr(1,f.length-2),h=a.isPlainObject(c)&&c[g]!==d?c[g]:w.data(g)!==d?w.data(g):y.data(g)!==d?y.data(g):c[g];return h===d?(o.error(s.requiredParameter,g,b),b=!1,!1):(o.verbose("Found required variable",g,h),void(b=b.replace(f,h)))})),f&&(o.debug("Looking for optional URL variables",e),a.each(f,function(e,f){var g=-1!==f.indexOf("$")?f.substr(3,f.length-4):f.substr(2,f.length-3),h=a.isPlainObject(c)&&c[g]!==d?c[g]:w.data(g)!==d?w.data(g):y.data(g)!==d?y.data(g):c[g];h!==d?(o.verbose("Optional variable Found",g,h),b=b.replace(f,h)):(o.verbose("Optional variable not found",g),b=-1!==b.indexOf("/"+f)?b.replace("/"+f,""):b.replace(f,""))}))),b}},event:{trigger:function(a){o.query(),("submit"==a.type||"click"==a.type)&&a.preventDefault()},xhr:{always:function(){},done:function(a){var b=this,c=(new Date).getTime()-h,d=p.loadingDuration-c;d=d>0?d:0,setTimeout(function(){o.request.resolveWith(b,[a])},d)},fail:function(a,b,c){var d=this,e=(new Date).getTime()-h,f=p.loadingDuration-e;f=f>0?f:0,setTimeout(function(){"abort"!==b?o.request.rejectWith(d,[a,b,c]):o.reset()},f)}},request:{complete:function(b){o.remove.loading(),a.proxy(p.onComplete,y)(b,w)},done:function(b){o.debug("API request received",b),"json"==p.dataType&&a.isFunction(p.successTest)?(o.debug("Checking JSON",p.successTest,b),p.onSuccess(b)?a.proxy(p.onSuccess,y)(b,w):(o.debug("JSON test specified by user and response failed",b),a.proxy(p.onFailure,y)(b,w))):a.proxy(p.onSuccess,y)(b,w)},error:function(b,c,e){var f,g=p.error[c]!==d?p.error[c]:e;if(b!==d)if(b.readyState!==d&&4==b.readyState){if(200!=b.status&&e!==d&&""!==e)o.error(s.statusMessage+e);else if("error"==c&&"json"==p.dataType)try{f=a.parseJSON(b.responseText),f&&f.error!==d&&(g=f.error)}catch(h){o.error(s.JSONParse)}o.remove.loading(),o.set.error(),p.errorDuration&&setTimeout(o.remove.error,p.errorDuration),o.debug("API Request error:",g),a.proxy(p.onFailure,y)(g,w)}else a.proxy(p.onAbort,y)(g,w),o.debug("Request Aborted (Most likely caused by page change or CORS Policy)",c,e)}}},create:{request:function(){return a.Deferred().always(o.event.request.complete).done(o.event.request.done).fail(o.event.request.error)},xhr:function(){a.ajax(b).always(o.event.xhr.always).done(o.event.xhr.done).fail(o.event.xhr.fail)}},set:{error:function(){o.verbose("Adding error state to element",y),y.addClass(t.error)},loading:function(){o.verbose("Adding loading state to element",y),y.addClass(t.loading)}},remove:{error:function(){o.verbose("Removing error state from element",y),y.removeClass(t.error)},loading:function(){o.verbose("Removing loading state from element",y),y.removeClass(t.loading)}},get:{request:function(){return o.request||!1},xhr:function(){return o.xhr||!1},settings:function(){var b;return b=a.proxy(p.beforeSend,w)(p),b.success!==d&&(o.debug("Legacy success callback detected",b),o.error(s.legacyParameters),b.onSuccess=b.success),b.failure!==d&&(o.debug("Legacy failure callback detected",b),o.error(s.legacyParameters),b.onFailure=b.failure),b.complete!==d&&(o.debug("Legacy complete callback detected",b),o.error(s.legacyParameters),b.onComplete=b.complete),b},defaultData:function(){var b={};return a.isWindow(z)||(w.is("input")?b.value=w.val():w.is("form")||(b.text=w.text())),b},event:function(){return a.isWindow(z)||"now"==p.on?(o.debug("API called without element, no events attached"),!1):"auto"==p.on?w.is("input")?z.oninput!==d?"input":z.onpropertychange!==d?"propertychange":"keyup":w.is("form")?"submit":"click":p.on},formData:function(){var b;if("json"==p.serializeForm){if(a(this).toJSON===d)return void o.error(s.missingSerialize);b=x.toJSON()}else b=x.serialize();return o.debug("Retrieving form data",b),b},templateURL:function(a){var b;return a=a||w.data(p.metadata.action)||p.action||!1,a&&(o.debug("Looking up url for action",a),p.api[a]!==d?(b=p.api[a],o.debug("Found template url",b)):o.error(s.missingAction,p.action)),b}},reset:function(){o.remove.error(),o.remove.loading()},setting:function(b,c){if(a.isPlainObject(b))a.extend(!0,p,b);else{if(c===d)return p[b];p[b]=c}},internal:function(b,c){if(a.isPlainObject(b))a.extend(!0,o,b);else{if(c===d)return o[b];o[b]=c}},debug:function(){p.debug&&(p.performance?o.performance.log(arguments):(o.debug=Function.prototype.bind.call(console.info,console,p.name+":"),o.debug.apply(console,arguments)))},verbose:function(){p.verbose&&p.debug&&(p.performance?o.performance.log(arguments):(o.verbose=Function.prototype.bind.call(console.info,console,p.name+":"),o.verbose.apply(console,arguments)))},error:function(){o.error=Function.prototype.bind.call(console.error,console,p.name+":"),o.error.apply(console,arguments)},performance:{log:function(a){var b,c,d;p.performance&&(b=(new Date).getTime(),d=h||b,c=b-d,h=b,i.push({Element:z,Name:a[0],Arguments:[].slice.call(a,1)||"","Execution Time":c})),clearTimeout(o.performance.timer),o.performance.timer=setTimeout(o.performance.display,100)},display:function(){var b=p.name+":",c=0;h=(new Date).getTime(),clearTimeout(o.performance.timer),a.each(i,function(a,b){c+=b["Execution Time"]}),b+=" "+c+"ms",g&&(b+=" '"+g+"'"),(console.group!==d||console.table!==d)&&i.length>0&&(console.groupCollapsed(b),console.table?console.table(i):a.each(i,function(a,b){console.log(b.Name+": "+b["Execution Time"]+"ms")}),console.groupEnd()),i=[]}},invoke:function(b,c,f){var g,h,i;return c=c||l,f=z||f,"string"==typeof b&&A!==d&&(b=b.split(/[\. ]/),g=b.length-1,a.each(b,function(c,e){var f=c!=g?e+b[c+1].charAt(0).toUpperCase()+b[c+1].slice(1):b;if(a.isPlainObject(A[e])&&c!=g)A=A[e];else{if(!a.isPlainObject(A[f])||c==g)return A[e]!==d?(h=A[e],!1):A[f]!==d?(h=A[f],!1):(o.error(s.method,b),!1);A=A[f]}})),a.isFunction(h)?i=h.apply(f,c):h!==d&&(i=h),a.isArray(e)?e.push(i):e!==d?e=[e,i]:i!==d&&(e=i),h}},k?(A===d&&o.initialize(),o.invoke(j)):(A!==d&&o.destroy(),o.initialize())}),e!==d?e:this},a.api.settings={name:"API",namespace:"api",debug:!0,verbose:!0,performance:!0,on:"auto",filter:".disabled, .loading",context:!1,stateContext:!1,action:!1,regExp:{required:/\{\$*[A-z0-9]+\}/g,optional:/\{\/\$*[A-z0-9]+\}/g},url:!1,urlData:!1,serializeForm:!1,defaultData:!0,throttle:100,allowMultiple:!1,loadingDuration:0,errorDuration:2e3,method:"get",data:{},dataType:"json",cache:!0,beforeSend:function(a){return a},beforeXHR:function(){},onSuccess:function(){},onComplete:function(){},onFailure:function(){},onAbort:function(){},successText:function(){return!0},error:{beforeSend:"The before send function has aborted the request",error:"There was an error with your request",exitConditions:"API Request Aborted. Exit conditions met",JSONParse:"JSON could not be parsed during error handling",legacyParameters:"You are using legacy API success callback names",missingAction:"API action used but no url was defined",missingSerialize:"Serializing a Form requires toJSON to be included",missingURL:"No URL specified for api event",parseError:"There was an error parsing your request",requiredParameter:"Missing a required URL parameter: ",statusMessage:"Server gave an error: ",timeout:"Your request timed out"},className:{loading:"loading",error:"error"},selector:{form:"form"},metadata:{action:"action",request:"request",xhr:"xhr"}},a.api.settings.api={}}(jQuery,window,document);