wishthis/node_modules/fomantic-ui/dist/components/api.min.js
2022-05-29 11:24:36 +02:00

11 lines
No EOL
15 KiB
JavaScript

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