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