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