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,r,t,n){"use strict";e.api=e.fn.api=function(t){var o,a=e(e.isFunction(this)?r:this),s=a.selector||"",i=(new Date).getTime(),c=[],u=arguments[0],l="string"==typeof u,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(){l||(m.create.cache(),m.bind.events()),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)},bind:{events:function(){var e=m.get.event();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())}},read:{cachedResponse:function(e){var r;return m.cache||m.create.cache(),r=m.cache.response[e]!==n?m.cache.response[e]:!1,m.debug("Using cached response",e,r),r}},write:{cachedResponse:function(e,r){return m.cache||m.create.cache(),r&&""===r?void m.debug("Response empty, not caching",r):(m.verbose("Storing cached response for url",e,r),void(m.cache.response[e]=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)}return 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),"local"===p.cache&&m.read.cachedResponse(f)?(m.request=m.create.request(),void m.request.resolveWith(T,[m.read.cachedResponse(f)])):void(m.is.loading()?(m.debug("Repeated request throttled",p.throttle),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 s=-1!==a.indexOf("$")?a.substr(2,a.length-3):a.substr(1,a.length-2),i=e.isPlainObject(t)&&t[s]!==n?t[s]:k.data(s)!==n?k.data(s):D.data(s)!==n?D.data(s):t[s];return i===n?(m.error(y.requiredParameter,s,r),r=!1,!1):(m.verbose("Found required variable",s,i),void(r=r.replace(a,i)))})),a&&(m.debug("Looking for optional URL variables",o),e.each(a,function(o,a){var s=-1!==a.indexOf("$")?a.substr(3,a.length-4):a.substr(2,a.length-3),i=e.isPlainObject(t)&&t[s]!==n?t[s]:k.data(s)!==n?k.data(s):D.data(s)!==n?D.data(s):t[s];i!==n?(m.verbose("Optional variable Found",s,i),r=r.replace(a,i)):(m.verbose("Optional variable not found",s),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()-i,n=p.loadingDuration-t;n=n>0?n:0,setTimeout(function(){m.request.resolveWith(r,[e])},n)},fail:function(e,r,t){var o=this,a=(new Date).getTime()-i,s=p.loadingDuration-a;s=s>0?s:0,setTimeout(function(){e.readyState!==n&&0===e.readyState?m.request.rejectWith(o,[e,"aborted",t]):m.request.rejectWith(o,[e,r,t])},s)}},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),"local"===p.cache&&f&&(m.write.cachedResponse(f,r),m.debug("Adding url to local cache",m.cache)),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)},fail:function(t,o,a){var s,i=p.error[o]!==n?p.error[o]:a;if("aborted"==o)return m.debug("Request Aborted (Most likely caused by page navigation or CORS Policy)",o,a),m.reset(),void p.onAbort.call(T,o,k);if(t!==n){if(200!=t.status&&a!==n&&""!==a)m.error(y.statusMessage+a,r.url);else if("error"==o&&"json"==p.dataType)try{s=e.parseJSON(t.responseText),s&&s.error!==n&&(i=s.error)}catch(c){m.error(y.JSONParse)}m.remove.loading(),p.errorDuration!==!1&&(m.set.error(),setTimeout(m.remove.error,p.errorDuration)),m.debug("API Request error:",i),p.onError.call(T,i,k)}}}},create:{cache:function(){m.verbose("Creating local response cache"),m.cache={response:{}}},request:function(){return e.Deferred().always(m.event.request.complete).done(m.event.request.done).fail(m.event.request.fail)},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())},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=i||r,t=r-n,i=r,c.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;i=!1,clearTimeout(m.performance.timer),e.each(c,function(e,r){t+=r["Execution Time"]}),r+=" "+t+"ms",s&&(r+=" '"+s+"'"),(console.group!==n||console.table!==n)&&c.length>0&&(console.groupCollapsed(r),console.table?console.table(c):e.each(c,function(e,r){console.log(r.Name+": "+r["Execution Time"]+"ms")}),console.groupEnd()),c=[]}},invoke:function(r,t,a){var s,i,c,u=S;return t=t||d,a=P||a,"string"==typeof r&&u!==n&&(r=r.split(/[\. ]/),s=r.length-1,e.each(r,function(t,o){var a=t!=s?o+r[t+1].charAt(0).toUpperCase()+r[t+1].slice(1):r;if(e.isPlainObject(u[a])&&t!=s)u=u[a];else{if(u[a]!==n)return i=u[a],!1;if(!e.isPlainObject(u[o])||t==s)return u[o]!==n?(i=u[o],!1):(m.error(y.method,r),!1);u=u[o]}})),e.isFunction(i)?c=i.apply(a,t):i!==n&&(c=i),e.isArray(o)?o.push(c):o!==n?o=[o,c]:c!==n&&(o=c),i}},l?(S===n&&m.initialize(),m.invoke(u)):(S!==n&&S.invoke("destroy"),m.initialize())}),o!==n?o:this},e.api.settings={name:"API",namespace:"api",debug:!0,verbose:!1,performance:!0,cache:"local",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(e){},onRequest:function(e,r){},onResponse:!1,onSuccess:function(e,r){},onComplete:function(e,r){},onFailure:function(e,r){},onError:function(e,r){},onAbort:function(e,r){},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);