wishthis/semantic/dist/components/api.min.js
2023-08-17 11:47:40 +02:00

11 lines
No EOL
16 KiB
JavaScript

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