wishthis/node_modules/fomantic-ui/dist/components/api.min.js
2022-06-08 12:36:39 +02:00

11 lines
No EOL
16 KiB
JavaScript

/*
* # Fomantic UI - 2.9.0-beta.293+2a71b5e
* 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,O,j,F){"use strict";P.isWindow=P.isWindow||function(e){return null!=e&&e===e.window},O=void 0!==O&&O.Math==Math?O:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")(),P.api=P.fn.api=function(q){var x,e=P.isFunction(this)?P(O):P(this),A=e.selector||"",k=(new Date).getTime(),S=[],T=q,w="string"==typeof T,D=[].slice.call(arguments,1);return e.each(function(){var s,n,r,e,a,o,f=P.isPlainObject(q)?P.extend(!0,{},P.fn.api.settings,q):P.extend({},P.fn.api.settings),t=f.namespace,i=f.metadata,u=f.selector,c=f.error,d=f.className,l="."+t,g="module-"+t,p=P(this),m=p.closest(u.form),b=f.stateContext?[O,j].indexOf(f.stateContext)<0?P(j).find(f.stateContext):P(f.stateContext):p,v=this,h=b[0],y=p.data(g),R={initialize:function(){w||(o=f.data,R.bind.events()),R.instantiate()},instantiate:function(){R.verbose("Storing instance of module",R),y=R,p.data(g,y)},destroy:function(){R.verbose("Destroying previous module for",v),p.removeData(g).off(l)},bind:{events:function(){var e=R.get.event();e?(R.verbose("Attaching API events to element",e),p.on(e+l,R.event.trigger)):"now"==f.on&&(R.debug("Querying API endpoint immediately"),R.query())}},decode:{json:function(e){if(e!==F&&"string"==typeof e)try{e=JSON.parse(e)}catch(e){}return e}},read:{cachedResponse:function(e){var t;if(O.Storage!==F)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){t&&""===t?R.debug("Response empty, not caching",t):O.Storage===F?R.error(c.noStorage):(P.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()}if(f.defaultData&&P.extend(!0,f.urlData,R.get.defaultData()),f.serializeForm&&(f.data=R.add.formData(o||f.data)),!1===(n=R.get.settings()))return R.cancelled=!0,void R.error(c.beforeSend);if(R.cancelled=!1,(r=R.get.templatedURL())||R.is.mocked()){if((r=R.add.urlData(r))||R.is.mocked()){if(n.url=f.base+r,s=P.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",s.url),R.verbose("Using AJAX settings",s),"local"===f.cache&&R.read.cachedResponse(r))return R.debug("Response returned from local cache"),R.request=R.create.request(),void 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,s.method),R.send.request()},f.throttle)):(R.debug("Sending request",e,s.method),R.send.request(),R.timer=setTimeout(function(){},f.throttle)):(R.debug("Sending request",e,s.method),R.send.request())}}else R.error(c.missingURL)}},should:{removeError:function(){return!0===f.hideError||"auto"===f.hideError&&!R.is.form()}},is:{disabled:function(){return 0<p.filter(u.disabled).length},expectingJSON:function(){return"json"===f.dataType||"jsonp"===f.dataType},form:function(){return p.is("form")||b.is("form")},mocked:function(){return f.mockResponse||f.mockResponseAsync||f.response||f.responseAsync},input:function(){return p.is("input")},loading:function(){return!!R.request&&"pending"==R.request.state()},abortedRequest:function(e){return e&&e.readyState!==F&&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()&&P.isFunction(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,s){var e,t;return o&&(e=o.match(f.regExp.required),t=o.match(f.regExp.optional),s=s||f.urlData,e&&(R.debug("Looking for required URL variables",e),P.each(e,function(e,t){var r=-1!==t.indexOf("$")?t.slice(2,-1):t.slice(1,-1),n=P.isPlainObject(s)&&s[r]!==F?s[r]:p.data(r)!==F?p.data(r):b.data(r)!==F?b.data(r):s[r];if(n===F)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),P.each(t,function(e,t){var r=-1!==t.indexOf("$")?t.slice(3,-1):t.slice(2,-1),n=P.isPlainObject(s)&&s[r]!==F?s[r]:p.data(r)!==F?p.data(r):b.data(r)!==F?b.data(r):s[r];o=n!==F?(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=P.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},P.each(P('input[type="file"]',m),function(e,r){P.each(P(r)[0].files,function(e,t){n.push({name:r.name,value:t})})}),P.each(n,function(e,t){if(f.regExp.validate.test(t.name)){var r,n="checkbox"===P('[name="'+t.name+'"]',m).attr("type"),o=parseFloat(t.value),s=n&&"on"===t.value||"true"===t.value||(String(o)===t.value?o:"false"!==t.value&&t.value),a=t.name.match(f.regExp.key)||[],i=t.name.replace(/\[\]$/,"");i in u?Array.isArray(c[i])?c[i].push(s):c[i]=[c[i],s]:(u[i]=0,c[i]=s),s=c[i];for(;(r=a.pop())!==F;)""!=r||Array.isArray(s)?f.regExp.fixed.test(r)?s=d([],r,s):f.regExp.named.test(r)&&(s=d({},r,s)):s=d([],u[i]++,s);l=P.extend(!0,l,s)}})),r=e?(R.debug("Extending existing data with form data",r,l),t?(P.each(Object.keys(r),function(e,t){l.append(t,r[t])}),l):P.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=(new Date).getTime()-a,o=f.loadingDuration-o,s=!!P.isFunction(f.onResponse)&&(R.is.expectingJSON()&&!f.rawResponse?f.onResponse.call(n,P.extend(!0,{},e)):f.onResponse.call(n,e)),o=0<o?o:0;s&&(R.debug("Modified API response in onResponse callback",f.onResponse,s,e),e=s),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=(new Date).getTime()-a,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,p,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,p,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,p,e),!0;"invalid"==t?R.debug("JSON did not pass success test. A server-side error has most likely occurred",n):"error"==t&&e!==F&&(R.debug("XHR produced a server error",t,r),(e.status<200||300<=e.status)&&r!==F&&""!==r&&R.error(c.statusMessage+r,s.url),f.onError.call(h,o,p,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,p,e)}}},create:{request:function(){return P.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=P.Deferred().always(R.event.xhr.complete).done(R.event.xhr.done).fail(R.event.xhr.fail);return e?(e=P.isFunction(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}])):P.isFunction(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=P.ajax(s).always(R.event.xhr.always).done(R.event.xhr.done).fail(R.event.xhr.fail);return R.verbose("Created server request",e,s),e}},set:{error:function(){R.verbose("Adding error state to element",b),b.addClass(d.error)},loading:function(){R.verbose("Adding loading state to element",b),b.addClass(d.loading),a=(new Date).getTime()}},remove:{error:function(){R.verbose("Removing error state from element",b),b.removeClass(d.error)},loading:function(){R.verbose("Removing loading state from element",b),b.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!!P.isPlainObject(e)&&(R.is.expectingJSON()?R.decode.json(e.responseText):e.responseText)},errorFromRequest:function(e,t,r){return P.isPlainObject(e)&&e.error!==F?e.error:f.error[t]!==F?f.error[t]:r},request:function(){return R.request||!1},xhr:function(){return R.xhr||!1},settings:function(){var e=f.beforeSend.call(p,f);return e&&(e.success!==F&&(R.debug("Legacy success callback detected",e),R.error(c.legacyParameters,e.success),e.onSuccess=e.success),e.failure!==F&&(R.debug("Legacy failure callback detected",e),R.error(c.legacyParameters,e.failure),e.onFailure=e.failure),e.complete!==F&&(R.debug("Legacy complete callback detected",e),R.error(c.legacyParameters,e.complete),e.onComplete=e.complete)),e===F&&R.error(c.noReturnedValue),!1===e?e:e!==F?P.extend(!0,{},e):P.extend(!0,{},f)},urlEncodedValue:function(e){var t=O.decodeURIComponent(e),r=O.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 P.isWindow(v)||(R.is.input()?e.value=p.val():R.is.form()||(e.text=p.text())),e},event:function(){return P.isWindow(v)||"now"==f.on?(R.debug("API called without element, no events attached"),!1):"auto"==f.on?p.is("input")?v.oninput!==F?"input":v.onpropertychange!==F?"propertychange":"keyup":p.is("form")?"submit":"click":f.on},templatedURL:function(e){if(e=e||p.data(i.action)||f.action||!1,r=p.data(i.url)||f.url||!1)return R.debug("Using specified url",r),r;if(e){if(R.debug("Looking up url for action",e,f.api),f.api[e]===F&&!R.is.mocked())return void R.error(c.missingAction,f.action,f.api);r=f.api[e]}else R.is.form()&&(r=p.attr("action")||b.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),P.isPlainObject(e))P.extend(!0,f,e);else{if(t===F)return f[e];P.isPlainObject(f[e])?P.extend(!0,f[e],t):f[e]=t}},internal:function(e,t){if(P.isPlainObject(e))P.extend(!0,R,e);else{if(t===F)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=(new Date).getTime())-(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),P.each(S,function(e,t){r+=t["Execution Time"]}),e+=" "+r+"ms",A&&(e+=" '"+A+"'"),(console.group!==F||console.table!==F)&&0<S.length&&(console.groupCollapsed(e),console.table?console.table(S):P.each(S,function(e,t){console.log(t.Name+": "+t["Execution Time"]+"ms")}),console.groupEnd()),S=[]}},invoke:function(n,e,t){var o,s,r,a=y;return e=e||D,t=v||t,"string"==typeof n&&a!==F&&(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(a[r])&&e!=o)a=a[r];else{if(a[r]!==F)return s=a[r],!1;{if(!P.isPlainObject(a[t])||e==o)return a[t]!==F?s=a[t]:R.error(c.method,n),!1;a=a[t]}}})),P.isFunction(s)?r=s.apply(t,e):s!==F&&(r=s),Array.isArray(x)?x.push(r):x!==F?x=[x,r]:r!==F&&(x=r),s}};w?(y===F&&R.initialize(),R.invoke(T)):(y!==F&&y.invoke("destroy"),R.initialize())}),x!==F?x: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:!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:/\{\$*[A-z0-9]+\}/g,optional:/\{\/\$*[A-z0-9]+\}/g,validate:/^[a-z_][a-z0-9_-]*(?:\[[a-z0-9_-]*\])*$/i,key:/[a-z0-9_-]+|(?=\[\])/gi,push:/^$/,fixed:/^\d+$/,named:/^[a-z0-9_-]+$/i},className:{loading:"loading",error:"error"},selector:{disabled:".disabled",form:"form"},metadata:{action:"action",url:"url"}}}(jQuery,window,document);