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

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