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
14 KiB

!function(j,O,w){"use strict";O=void 0!==O&&O.Math==Math?O:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();j.api=j.fn.api=function(q){var R,e=j.isFunction(this)?j(O):j(this),x=e.selector||"",S=(new Date).getTime(),A=[],k=q,T="string"==typeof k,P=[].slice.call(arguments,1);return e.each(function(){var s,i,r,e,a,u=j.isPlainObject(q)?j.extend(!0,{},j.fn.api.settings,q):j.extend({},j.fn.api.settings),t=u.namespace,n=u.metadata,o=u.selector,c=u.error,d=u.className,l="."+t,g="module-"+t,f=j(this),p=f.closest(o.form),m=u.stateContext?j(u.stateContext):f,b=this,v=m[0],h=f.data(g),y={initialize:function(){T||y.bind.events(),y.instantiate()},instantiate:function(){y.verbose("Storing instance of module",y),h=y,f.data(g,h)},destroy:function(){y.verbose("Destroying previous module for",b),f.removeData(g).off(l)},bind:{events:function(){var e=y.get.event();e?(y.verbose("Attaching API events to element",e),f.on(e+l,y.event.trigger)):"now"==u.on&&(y.debug("Querying API endpoint immediately"),y.query())}},decode:{json:function(e){if(e!==w&&"string"==typeof e)try{e=JSON.parse(e)}catch(e){}return e}},read:{cachedResponse:function(e){var t;if(O.Storage!==w)return t=sessionStorage.getItem(e),y.debug("Using cached response",e,t),t=y.decode.json(t);y.error(c.noStorage)}},write:{cachedResponse:function(e,t){t&&""===t?y.debug("Response empty, not caching",t):O.Storage!==w?(j.isPlainObject(t)&&(t=JSON.stringify(t)),sessionStorage.setItem(e,t),y.verbose("Storing cached response for url",e,t)):y.error(c.noStorage)}},query:function(){if(y.is.disabled())y.debug("Element is disabled API request aborted");else{if(y.is.loading()){if(!u.interruptRequests)return void y.debug("Cancelling request, previous request is still pending");y.debug("Interrupting previous request"),y.abort()}if(u.defaultData&&j.extend(!0,u.urlData,y.get.defaultData()),u.serializeForm&&(u.data=y.add.formData(u.data)),!1===(i=y.get.settings()))return y.cancelled=!0,void y.error(c.beforeSend);if(y.cancelled=!1,(r=y.get.templatedURL())||y.is.mocked()){if((r=y.add.urlData(r))||y.is.mocked()){if(i.url=u.base+r,s=j.extend(!0,{},u,{type:u.method||u.type,data:e,url:u.base+r,beforeSend:u.beforeXHR,success:function(){},failure:function(){},complete:function(){}}),y.debug("Querying URL",s.url),y.verbose("Using AJAX settings",s),"local"===u.cache&&y.read.cachedResponse(r))return y.debug("Response returned from local cache"),y.request=y.create.request(),void y.request.resolveWith(v,[y.read.cachedResponse(r)]);u.throttle?u.throttleFirstRequest||y.timer?(y.debug("Throttling request",u.throttle),clearTimeout(y.timer),y.timer=setTimeout(function(){y.timer&&delete y.timer,y.debug("Sending throttled request",e,s.method),y.send.request()},u.throttle)):(y.debug("Sending request",e,s.method),y.send.request(),y.timer=setTimeout(function(){},u.throttle)):(y.debug("Sending request",e,s.method),y.send.request())}}else y.error(c.missingURL)}},should:{removeError:function(){return!0===u.hideError||"auto"===u.hideError&&!y.is.form()}},is:{disabled:function(){return 0<f.filter(o.disabled).length},expectingJSON:function(){return"json"===u.dataType||"jsonp"===u.dataType},form:function(){return f.is("form")||m.is("form")},mocked:function(){return u.mockResponse||u.mockResponseAsync||u.response||u.responseAsync},input:function(){return f.is("input")},loading:function(){return!!y.request&&"pending"==y.request.state()},abortedRequest:function(e){return e&&e.readyState!==w&&0===e.readyState?(y.verbose("XHR request determined to be aborted"),!0):(y.verbose("XHR request was not aborted"),!1)},validResponse:function(e){return y.is.expectingJSON()&&j.isFunction(u.successTest)?(y.debug("Checking JSON returned success",u.successTest,e),u.successTest(e)?(y.debug("Response passed success test",e),!0):(y.debug("Response failed success test",e),!1)):(y.verbose("Response is not JSON, skipping validation",u.successTest,e),!0)}},was:{cancelled:function(){return y.cancelled||!1},succesful:function(){return y.request&&"resolved"==y.request.state()},failure:function(){return y.request&&"rejected"==y.request.state()},complete:function(){return y.request&&("resolved"==y.request.state()||"rejected"==y.request.state())}},add:{urlData:function(o,s){var e,t;return o&&(e=o.match(u.regExp.required),t=o.match(u.regExp.optional),s=s||u.urlData,e&&(y.debug("Looking for required URL variables",e),j.each(e,function(e,t){var r=-1!==t.indexOf("$")?t.substr(2,t.length-3):t.substr(1,t.length-2),n=j.isPlainObject(s)&&s[r]!==w?s[r]:f.data(r)!==w?f.data(r):m.data(r)!==w?m.data(r):s[r];if(n===w)return y.error(c.requiredParameter,r,o),o=!1;y.verbose("Found required variable",r,n),n=u.encodeParameters?y.get.urlEncodedValue(n):n,o=o.replace(t,n)})),t&&(y.debug("Looking for optional URL variables",e),j.each(t,function(e,t){var r=-1!==t.indexOf("$")?t.substr(3,t.length-4):t.substr(2,t.length-3),n=j.isPlainObject(s)&&s[r]!==w?s[r]:f.data(r)!==w?f.data(r):m.data(r)!==w?m.data(r):s[r];o=n!==w?(y.verbose("Optional variable Found",r,n),o.replace(t,n)):(y.verbose("Optional variable not found",r),-1!==o.indexOf("/"+t)?o.replace("/"+t,""):o.replace(t,""))}))),o},formData:function(e){var t=j.fn.serializeObject!==w,r=t?p.serializeObject():p.serialize();return e=e||u.data,e=j.isPlainObject(e)?t?(y.debug("Extending existing data with form data",e,r),j.extend(!0,{},e,r)):(y.error(c.missingSerialize),y.debug("Cant extend data. Replacing data with form data",e,r),r):(y.debug("Adding form data",r),r)}},send:{request:function(){y.set.loading(),y.request=y.create.request(),y.is.mocked()?y.mockedXHR=y.create.mockedXHR():y.xhr=y.create.xhr(),u.onRequest.call(v,y.request,y.xhr)}},event:{trigger:function(e){y.query(),"submit"!=e.type&&"click"!=e.type||e.preventDefault()},xhr:{always:function(){},done:function(e,t,r){var n=this,o=(new Date).getTime()-a,s=u.loadingDuration-o,i=!!j.isFunction(u.onResponse)&&(y.is.expectingJSON()?u.onResponse.call(n,j.extend(!0,{},e)):u.onResponse.call(n,e)),s=0<s?s:0;i&&(y.debug("Modified API response in onResponse callback",u.onResponse,i,e),e=i),0<s&&y.debug("Response completed early delaying state change by",s),setTimeout(function(){y.is.validResponse(e)?y.request.resolveWith(n,[e,r]):y.request.rejectWith(n,[r,"invalid"])},s)},fail:function(e,t,r){var n=this,o=(new Date).getTime()-a,s=u.loadingDuration-o;0<(s=0<s?s:0)&&y.debug("Response completed early delaying state change by",s),setTimeout(function(){y.is.abortedRequest(e)?y.request.rejectWith(n,[e,"aborted",r]):y.request.rejectWith(n,[e,"error",t,r])},s)}},request:{done:function(e,t){y.debug("Successful API Response",e),"local"===u.cache&&r&&(y.write.cachedResponse(r,e),y.debug("Saving server response locally",y.cache)),u.onSuccess.call(v,e,f,t)},complete:function(e,t){var r,n;y.was.succesful()?(n=e,r=t):(r=e,n=y.get.responseFromXHR(r)),y.remove.loading(),u.onComplete.call(v,n,f,r)},fail:function(e,t,r){var n=y.get.responseFromXHR(e),o=y.get.errorFromRequest(n,t,r);if("aborted"==t)return y.debug("XHR Aborted (Most likely caused by page navigation or CORS Policy)",t,r),u.onAbort.call(v,t,f,e),!0;"invalid"==t?y.debug("JSON did not pass success test. A server-side error has most likely occurred",n):"error"==t&&e!==w&&(y.debug("XHR produced a server error",t,r),200!=e.status&&r!==w&&""!==r&&y.error(c.statusMessage+r,s.url),u.onError.call(v,o,f,e)),u.errorDuration&&"aborted"!==t&&(y.debug("Adding error state"),y.set.error(),y.should.removeError()&&setTimeout(y.remove.error,u.errorDuration)),y.debug("API Request failed",o,e),u.onFailure.call(v,n,f,e)}}},create:{request:function(){return j.Deferred().always(y.event.request.complete).done(y.event.request.done).fail(y.event.request.fail)},mockedXHR:function(){var e,t,r=u.mockResponse||u.response,n=u.mockResponseAsync||u.responseAsync,o=j.Deferred().always(y.event.xhr.complete).done(y.event.xhr.done).fail(y.event.xhr.fail);return r?(t=j.isFunction(r)?(y.debug("Using specified synchronous callback",r),r.call(v,i)):(y.debug("Using settings specified response",r),r),o.resolveWith(v,[t,!1,{responseText:t}])):j.isFunction(n)&&(e=function(e){y.debug("Async callback returned response",e),e?o.resolveWith(v,[e,!1,{responseText:e}]):o.rejectWith(v,[{responseText:e},!1,!1])},y.debug("Using specified async response callback",n),n.call(v,i,e)),o},xhr:function(){var e=j.ajax(s).always(y.event.xhr.always).done(y.event.xhr.done).fail(y.event.xhr.fail);return y.verbose("Created server request",e,s),e}},set:{error:function(){y.verbose("Adding error state to element",m),m.addClass(d.error)},loading:function(){y.verbose("Adding loading state to element",m),m.addClass(d.loading),a=(new Date).getTime()}},remove:{error:function(){y.verbose("Removing error state from element",m),m.removeClass(d.error)},loading:function(){y.verbose("Removing loading state from element",m),m.removeClass(d.loading)}},get:{responseFromXHR:function(e){return!!j.isPlainObject(e)&&(y.is.expectingJSON()?y.decode.json(e.responseText):e.responseText)},errorFromRequest:function(e,t,r){return j.isPlainObject(e)&&e.error!==w?e.error:u.error[t]!==w?u.error[t]:r},request:function(){return y.request||!1},xhr:function(){return y.xhr||!1},settings:function(){var e=u.beforeSend.call(v,u);return e&&(e.success!==w&&(y.debug("Legacy success callback detected",e),y.error(c.legacyParameters,e.success),e.onSuccess=e.success),e.failure!==w&&(y.debug("Legacy failure callback detected",e),y.error(c.legacyParameters,e.failure),e.onFailure=e.failure),e.complete!==w&&(y.debug("Legacy complete callback detected",e),y.error(c.legacyParameters,e.complete),e.onComplete=e.complete)),e===w&&y.error(c.noReturnedValue),!1===e?e:e!==w?j.extend(!0,{},e):j.extend(!0,{},u)},urlEncodedValue:function(e){var t=O.decodeURIComponent(e),r=O.encodeURIComponent(e);return t!==e?(y.debug("URL value is already encoded, avoiding double encoding",e),e):(y.verbose("Encoding value using encodeURIComponent",e,r),r)},defaultData:function(){var e={};return j.isWindow(b)||(y.is.input()?e.value=f.val():y.is.form()||(e.text=f.text())),e},event:function(){return j.isWindow(b)||"now"==u.on?(y.debug("API called without element, no events attached"),!1):"auto"==u.on?f.is("input")?b.oninput!==w?"input":b.onpropertychange!==w?"propertychange":"keyup":f.is("form")?"submit":"click":u.on},templatedURL:function(e){if(e=e||f.data(n.action)||u.action||!1,r=f.data(n.url)||u.url||!1)return y.debug("Using specified url",r),r;if(e){if(y.debug("Looking up url for action",e,u.api),u.api[e]===w&&!y.is.mocked())return void y.error(c.missingAction,u.action,u.api);r=u.api[e]}else y.is.form()&&(r=f.attr("action")||m.attr("action")||!1,y.debug("No url or action specified, defaulting to form action",r));return r}},abort:function(){var e=y.get.xhr();e&&"resolved"!==e.state()&&(y.debug("Cancelling API request"),e.abort())},reset:function(){y.remove.error(),y.remove.loading()},setting:function(e,t){if(y.debug("Changing setting",e,t),j.isPlainObject(e))j.extend(!0,u,e);else{if(t===w)return u[e];j.isPlainObject(u[e])?j.extend(!0,u[e],t):u[e]=t}},internal:function(e,t){if(j.isPlainObject(e))j.extend(!0,y,e);else{if(t===w)return y[e];y[e]=t}},debug:function(){!u.silent&&u.debug&&(u.performance?y.performance.log(arguments):(y.debug=Function.prototype.bind.call(console.info,console,u.name+":"),y.debug.apply(console,arguments)))},verbose:function(){!u.silent&&u.verbose&&u.debug&&(u.performance?y.performance.log(arguments):(y.verbose=Function.prototype.bind.call(console.info,console,u.name+":"),y.verbose.apply(console,arguments)))},error:function(){u.silent||(y.error=Function.prototype.bind.call(console.error,console,u.name+":"),y.error.apply(console,arguments))},performance:{log:function(e){var t,r;u.performance&&(r=(t=(new Date).getTime())-(S||t),S=t,A.push({Name:e[0],Arguments:[].slice.call(e,1)||"","Execution Time":r})),clearTimeout(y.performance.timer),y.performance.timer=setTimeout(y.performance.display,500)},display:function(){var e=u.name+":",r=0;S=!1,clearTimeout(y.performance.timer),j.each(A,function(e,t){r+=t["Execution Time"]}),e+=" "+r+"ms",x&&(e+=" '"+x+"'"),(console.group!==w||console.table!==w)&&0<A.length&&(console.groupCollapsed(e),console.table?console.table(A):j.each(A,function(e,t){console.log(t.Name+": "+t["Execution Time"]+"ms")}),console.groupEnd()),A=[]}},invoke:function(n,e,t){var o,s,r,i=h;return e=e||P,t=b||t,"string"==typeof n&&i!==w&&(n=n.split(/[\. ]/),o=n.length-1,j.each(n,function(e,t){var r=e!=o?t+n[e+1].charAt(0).toUpperCase()+n[e+1].slice(1):n;if(j.isPlainObject(i[r])&&e!=o)i=i[r];else{if(i[r]!==w)return s=i[r],!1;if(!j.isPlainObject(i[t])||e==o)return i[t]!==w?s=i[t]:y.error(c.method,n),!1;i=i[t]}})),j.isFunction(s)?r=s.apply(t,e):s!==w&&(r=s),j.isArray(R)?R.push(r):R!==w?R=[R,r]:r!==w&&(R=r),s}};T?(h===w&&y.initialize(),y.invoke(k)):(h!==w&&h.invoke("destroy"),y.initialize())}),R!==w?R:this},j.api.settings={name:"API",namespace:"api",debug:!1,verbose:!1,performance:!0,api:{},cache:!0,interruptRequests:!0,on:"auto",stateContext:!1,loadingDuration:0,hideError:"auto",errorDuration:2e3,encodeParameters:!0,action:!1,url:!1,base:"",urlData:{},defaultData:!0,serializeForm:!1,throttle:0,throttleFirstRequest:!0,method:"get",data:{},dataType:"json",mockResponse:!1,mockResponseAsync:!1,response:!1,responseAsync:!1,beforeSend:function(e){return e},beforeXHR:function(e){},onRequest:function(e,t){},onResponse:!1,onSuccess:function(e,t){},onComplete:function(e,t){},onFailure:function(e,t){},onError:function(e,t){},onAbort:function(e,t){},successTest:!1,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",method:"The method you called is not defined",missingAction:"API action used but no url was defined",missingSerialize:"jquery-serialize-object is required to add form data to an existing data object",missingURL:"No URL specified for api event",noReturnedValue:"The beforeSend callback must return a settings object, beforeSend ignored.",noStorage:"Caching responses locally requires session storage",parseError:"There was an error parsing your request",requiredParameter:"Missing a required URL parameter: ",statusMessage:"Server gave an error: ",timeout:"Your request timed out"},regExp:{required:/\{\$*[A-z0-9]+\}/g,optional:/\{\/\$*[A-z0-9]+\}/g},className:{loading:"loading",error:"error"},selector:{disabled:".disabled",form:"form"},metadata:{action:"action",url:"url"}}}(jQuery,window,void document);