wishthis/semantic/dist/components/api.min.js
2022-02-23 22:46:34 +01:00

11 lines
No EOL
15 KiB
JavaScript

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