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.
 
 
 

11 lines
12 KiB

/*!
* # Semantic UI 2.0.0 - API
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
!function(e,t,r,n){"use strict";e.api=e.fn.api=function(r){var o,s=e(e.isFunction(this)?t:this),i=s.selector||"",a=(new Date).getTime(),u=[],c=arguments[0],l="string"==typeof c,d=[].slice.call(arguments,1);return s.each(function(){var s,g,f,m,p,b,v=e.isPlainObject(r)?e.extend(!0,{},e.fn.api.settings,r):e.extend({},e.fn.api.settings),h=v.namespace,y=v.metadata,q=v.selector,R=v.error,k=v.className,x="."+h,S="module-"+h,A=e(this),T=A.closest(q.form),D=v.stateContext?e(v.stateContext):A,P=this,j=D[0],w=A.data(S);b={initialize:function(){l||b.bind.events(),b.instantiate()},instantiate:function(){b.verbose("Storing instance of module",b),w=b,A.data(S,w)},destroy:function(){b.verbose("Destroying previous module for",P),A.removeData(S).off(x)},bind:{events:function(){var e=b.get.event();e?(b.debug("Attaching API events to element",e),A.on(e+x,b.event.trigger)):"now"==v.on&&(b.debug("Querying API now",e),b.query())}},read:{cachedResponse:function(e){var r;if(t.Storage===n)return void b.error(R.noStorage);if(r=sessionStorage.getItem(e),b.debug("Using cached response",e,r),r!==n){try{r=JSON.parse(r)}catch(o){}return r}return!1}},write:{cachedResponse:function(r,o){return o&&""===o?void b.debug("Response empty, not caching",o):t.Storage===n?void b.error(R.noStorage):(e.isPlainObject(o)&&(o=JSON.stringify(o)),sessionStorage.setItem(r,o),void b.verbose("Storing cached response for url",r,o))}},query:function(){if(b.is.disabled())return void b.debug("Element is disabled API request aborted");if(b.is.loading()){if(!v.interruptRequests)return void b.debug("Cancelling request, previous request is still pending");b.debug("Interrupting previous request"),b.abort()}if(v.defaultData&&e.extend(!0,v.urlData,b.get.defaultData()),(v.serializeForm!==!1||D.is("form"))&&("json"==v.serializeForm?e.extend(!0,v.data,b.get.formData()):v.data=b.get.formData()),g=b.get.settings(),g===!1)return b.cancelled=!0,void b.error(R.beforeSend);if(b.cancelled=!1,v.url?(b.debug("Using specified url",f),f=b.add.urlData(v.url)):(f=b.add.urlData(b.get.templateURL()),b.debug("Added URL Data to url",f)),!f&&!b.is.mocked()){if(!b.is.form())return void b.error(R.missingURL,v.action);f=A.attr("action")||"",b.debug("No url or action specified, defaulting to form action",f)}return s=e.extend(!0,{},v,{type:v.method||v.type,data:m,url:v.base+f,beforeSend:v.beforeXHR,success:function(){},failure:function(){},complete:function(){}}),b.debug("Querying URL",s.url),b.verbose("Using AJAX settings",s),"local"===v.cache&&b.read.cachedResponse(f)?(b.debug("Response returned from local cache"),b.request=b.create.request(),void b.request.resolveWith(j,[b.read.cachedResponse(f)])):void(v.throttle?v.throttleFirstRequest||b.timer?(b.debug("Throttling request",v.throttle),clearTimeout(b.timer),b.timer=setTimeout(function(){b.timer&&delete b.timer,b.debug("Sending throttled request",m,s.method),b.send.request()},v.throttle)):(b.debug("Sending data",m,s.method),b.send.request(),b.timer=setTimeout(function(){},v.throttle)):(b.debug("Sending data",m,s.method),b.send.request()))},is:{disabled:function(){return A.filter(v.filter).length>0},form:function(){return A.is("form")},mocked:function(){return v.mockResponse||v.mockResponseAsync},input:function(){return A.is("input")},loading:function(){return b.request&&"pending"==b.request.state()}},was:{cancelled:function(){return b.cancelled||!1},succesful:function(){return b.request&&"resolved"==b.request.state()},failure:function(){return b.request&&"rejected"==b.request.state()},complete:function(){return b.request&&("resolved"==b.request.state()||"rejected"==b.request.state())}},add:{urlData:function(t,r){var o,s;return t&&(o=t.match(v.regExp.required),s=t.match(v.regExp.optional),r=r||v.urlData,o&&(b.debug("Looking for required URL variables",o),e.each(o,function(o,s){var i=-1!==s.indexOf("$")?s.substr(2,s.length-3):s.substr(1,s.length-2),a=e.isPlainObject(r)&&r[i]!==n?r[i]:A.data(i)!==n?A.data(i):D.data(i)!==n?D.data(i):r[i];return a===n?(b.error(R.requiredParameter,i,t),t=!1,!1):(b.verbose("Found required variable",i,a),void(t=t.replace(s,a)))})),s&&(b.debug("Looking for optional URL variables",o),e.each(s,function(o,s){var i=-1!==s.indexOf("$")?s.substr(3,s.length-4):s.substr(2,s.length-3),a=e.isPlainObject(r)&&r[i]!==n?r[i]:A.data(i)!==n?A.data(i):D.data(i)!==n?D.data(i):r[i];a!==n?(b.verbose("Optional variable Found",i,a),t=t.replace(s,a)):(b.verbose("Optional variable not found",i),t=-1!==t.indexOf("/"+s)?t.replace("/"+s,""):t.replace(s,""))}))),t}},send:{request:function(){b.set.loading(),b.request=b.create.request(),b.xhr=b.create.xhr(),v.onRequest.call(j,b.request,b.xhr)}},event:{trigger:function(e){b.query(),("submit"==e.type||"click"==e.type)&&e.preventDefault()},xhr:{always:function(){},done:function(e){var t=this,r=(new Date).getTime()-p,n=v.loadingDuration-r;n=n>0?n:0,setTimeout(function(){b.request.resolveWith(t,[e])},n)},fail:function(e,t,r){var o=this,s=(new Date).getTime()-p,i=v.loadingDuration-s;i=i>0?i:0,setTimeout(function(){e.readyState!==n&&0===e.readyState?b.request.rejectWith(o,[e,"aborted",r]):b.request.rejectWith(o,[e,t,r])},i)}},request:{complete:function(e){b.remove.loading(),v.onComplete.call(j,e,A)},done:function(t){var r=e.isFunction(v.onResponse)?v.onResponse.call(j,e.extend(!0,{},t)):!1;b.debug("API Response Received",t),"local"===v.cache&&f&&(b.write.cachedResponse(f,t),b.debug("Adding url to local cache",b.cache)),r&&(b.debug("Modified API response in onResponse callback",v.onResponse,r,t),t=r),"json"==v.dataType&&e.isFunction(v.successTest)?(b.debug("Checking JSON returned success",v.successTest,t),v.successTest(t)?v.onSuccess.call(j,t,A):(b.debug("JSON test specified by user and response failed",t),v.onFailure.call(j,t,A))):v.onSuccess.call(j,t,A)},fail:function(t,r,o){var i,a=v.error[r]!==n?v.error[r]:o,u=!1;if("aborted"==r&&(b.debug("Request Aborted (Most likely caused by page navigation or CORS Policy)",r,o),b.reset(),v.onAbort.call(j,r,A),u=!0),t!==n&&!u){if(200!=t.status&&o!==n&&""!==o)b.error(R.statusMessage+o,s.url);else if("error"==r&&"json"==v.dataType)try{i=e.parseJSON(t.responseText),i&&i.error!==n&&(a=i.error)}catch(c){b.error(R.JSONParse)}b.remove.loading(),v.errorDuration!==!1&&(b.set.error(),setTimeout(b.remove.error,v.errorDuration)),b.debug("API Request errored",a),v.onError.call(j,a,A)}v.onFailure.call(j,i,A)}}},create:{request:function(){return e.Deferred().always(b.event.request.complete).done(b.event.request.done).fail(b.event.request.fail)},xhr:function(){var t;return b.is.mocked()?void(v.mockResponse?e.isFunction(v.mockResponse)?(b.debug("Using sync mocked response callback",v.mockResponse),b.request.resolveWith(j,[v.mockResponse.call(j,v)])):(b.debug("Using mocked response",v.mockResponse),b.request.resolveWith(j,[v.mockResponse])):e.isFunction(v.mockResponseAsync)&&(t=function(e){b.verbose("Async callback returned response",e),e?b.request.resolveWith(j,[e]):b.request.rejectWith(j,[!0])},b.debug("Using async mocked response",v.mockResponseAsync),v.mockResponseAsync.call(j,v,t))):e.ajax(s).always(b.event.xhr.always).done(b.event.xhr.done).fail(b.event.xhr.fail)}},set:{error:function(){b.verbose("Adding error state to element",D),D.addClass(k.error)},loading:function(){b.verbose("Adding loading state to element",D),D.addClass(k.loading),p=(new Date).getTime()}},remove:{error:function(){b.verbose("Removing error state from element",D),D.removeClass(k.error)},loading:function(){b.verbose("Removing loading state from element",D),D.removeClass(k.loading)}},get:{request:function(){return b.request||!1},xhr:function(){return b.xhr||!1},settings:function(){var e;return e=v.beforeSend.call(j,v),e&&(e.success!==n&&(b.debug("Legacy success callback detected",e),b.error(R.legacyParameters,e.success),e.onSuccess=e.success),e.failure!==n&&(b.debug("Legacy failure callback detected",e),b.error(R.legacyParameters,e.failure),e.onFailure=e.failure),e.complete!==n&&(b.debug("Legacy complete callback detected",e),b.error(R.legacyParameters,e.complete),e.onComplete=e.complete)),e===n&&b.error(R.noReturnedValue),e!==n?e:v},defaultData:function(){var t={};return e.isWindow(P)||(b.is.input()?t.value=A.val():b.is.form()&&(t.text=A.text())),t},event:function(){return e.isWindow(P)||"now"==v.on?(b.debug("API called without element, no events attached"),!1):"auto"==v.on?A.is("input")?P.oninput!==n?"input":P.onpropertychange!==n?"propertychange":"keyup":A.is("form")?"submit":"click":v.on},formData:function(){var e;return A.serializeObject!==n?e=T.serializeObject():(b.error(R.missingSerialize),e=T.serialize()),b.debug("Retrieved form data",e),e},templateURL:function(e){var t;return e=e||A.data(y.action)||v.action||!1,e&&(b.debug("Looking up url for action",e,v.api),v.api[e]!==n?(t=v.api[e],b.debug("Found template url",t)):b.is.form()||b.is.mocked()||b.error(R.missingAction,v.action,v.api)),t}},abort:function(){var e=b.get.xhr();e&&"resolved"!==e.state()&&(b.debug("Cancelling API request"),e.abort())},reset:function(){b.remove.error(),b.remove.loading()},setting:function(t,r){if(b.debug("Changing setting",t,r),e.isPlainObject(t))e.extend(!0,v,t);else{if(r===n)return v[t];v[t]=r}},internal:function(t,r){if(e.isPlainObject(t))e.extend(!0,b,t);else{if(r===n)return b[t];b[t]=r}},debug:function(){v.debug&&(v.performance?b.performance.log(arguments):(b.debug=Function.prototype.bind.call(console.info,console,v.name+":"),b.debug.apply(console,arguments)))},verbose:function(){v.verbose&&v.debug&&(v.performance?b.performance.log(arguments):(b.verbose=Function.prototype.bind.call(console.info,console,v.name+":"),b.verbose.apply(console,arguments)))},error:function(){b.error=Function.prototype.bind.call(console.error,console,v.name+":"),b.error.apply(console,arguments)},performance:{log:function(e){var t,r,n;v.performance&&(t=(new Date).getTime(),n=a||t,r=t-n,a=t,u.push({Name:e[0],Arguments:[].slice.call(e,1)||"","Execution Time":r})),clearTimeout(b.performance.timer),b.performance.timer=setTimeout(b.performance.display,500)},display:function(){var t=v.name+":",r=0;a=!1,clearTimeout(b.performance.timer),e.each(u,function(e,t){r+=t["Execution Time"]}),t+=" "+r+"ms",i&&(t+=" '"+i+"'"),(console.group!==n||console.table!==n)&&u.length>0&&(console.groupCollapsed(t),console.table?console.table(u):e.each(u,function(e,t){console.log(t.Name+": "+t["Execution Time"]+"ms")}),console.groupEnd()),u=[]}},invoke:function(t,r,s){var i,a,u,c=w;return r=r||d,s=P||s,"string"==typeof t&&c!==n&&(t=t.split(/[\. ]/),i=t.length-1,e.each(t,function(r,o){var s=r!=i?o+t[r+1].charAt(0).toUpperCase()+t[r+1].slice(1):t;if(e.isPlainObject(c[s])&&r!=i)c=c[s];else{if(c[s]!==n)return a=c[s],!1;if(!e.isPlainObject(c[o])||r==i)return c[o]!==n?(a=c[o],!1):(b.error(R.method,t),!1);c=c[o]}})),e.isFunction(a)?u=a.apply(s,r):a!==n&&(u=a),e.isArray(o)?o.push(u):o!==n?o=[o,u]:u!==n&&(o=u),a}},l?(w===n&&b.initialize(),b.invoke(c)):(w!==n&&w.invoke("destroy"),b.initialize())}),o!==n?o:this},e.api.settings={name:"API",namespace:"api",debug:!0,verbose:!1,performance:!0,cache:!0,interruptRequests:!0,on:"auto",filter:".disabled",stateContext:!1,loadingDuration:0,errorDuration:2e3,action:!1,url:!1,base:"",urlData:{},defaultData:!0,serializeForm:!1,throttle:0,throttleFirstRequest:!0,method:"get",data:{},dataType:"json",mockResponse:!1,mockResponseAsync:!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:"Required dependency jquery-serialize-object missing, using basic serialize",missingURL:"No URL specified for api event",noReturnedValue:"The beforeSend callback must return a settings object, beforeSend ignored.",noStorage:"Caching respopnses 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:{form:"form"},metadata:{action:"action"}},e.api.settings.api={}}(jQuery,window,document);