adhara
Version:
foundation for any kind of website: microframework
1 lines • 108 kB
JavaScript
class TemplateEngineHelpers{static getHelpers(currentHelpers){let if_helper=currentHelpers.if;return{addAttr:function(attributes,default_attributes){if(attributes||default_attributes){let attrData=[];default_attributes=default_attributes&&"string"==typeof default_attributes?JSON.parse(default_attributes):{};let class_names=attributes&&(attributes.className||attributes.class)||"";return class_names+=default_attributes.hasOwnProperty("class")?" "+default_attributes.class:"",(attributes=Object.assign(default_attributes,attributes)).class=class_names,loop(attributes,function(key,value){if(key&&void 0!==value){if("style"===key){let css_values=[];loop(value,function(css_prop,css_value){css_values.push(css_prop+":"+css_value+";")}),value=css_values.join("")}"string"==typeof value&&(value='"'+value.replace(/"/g,'\\"')+'"'),attrData.push(key+"="+value)}}),new window.Handlebars.SafeString(attrData.join(" "))}},addProps:function(){let properties=Array.prototype.slice.call(arguments);return properties.splice(0,properties.length-1).join(" ")},selectedClass:function(selected,selectedClassName){return!0===selected?selectedClassName:""},include:function(template_name,context){return new window.Handlebars.SafeString(TemplateUtils.execute(template_name,context))},math:function(param1,operation,param2){let lvalue=parseFloat(String(param1)),rvalue=parseFloat(String(param2));return{"+":lvalue+rvalue,"-":lvalue-rvalue,"*":lvalue*rvalue,"/":lvalue/rvalue,"%":lvalue%rvalue}[operation]},i18n:function(i18nKey){let subs=Array.prototype.slice.call(arguments);return subs=subs.splice(1,subs.length-2),Adhara.i18n.get(i18nKey,subs)},get:function(object,path){return getValueFromJSON(object,path)},if:function(param1,operator,param2,options){return"object"==typeof operator?if_helper.call(this,param1,operator):evaluateLogic(param1,operator,param2)?options.fn(this):options.inverse(this)},mIf:function(){let arr=[!0,"and",!0],args_len=arguments.length-1,options=arguments[args_len];for(let i=0;i<args_len;i++)0===i?arr[0]=arguments[i]:i%2==1?arr[1]=arguments[i]:(arr[2]=arguments[i],arr[0]=evaluateLogic(arr[0],arr[1],arr[2]));return arr[0]?options.fn(this):options.inverse(this)},eIf:function(param1,operator,param2){return evaluateLogic(param1,operator,param2)},global:function(global_letiable){return 0===global_letiable.indexOf("Adhara.")?getValueFromJSON(Adhara,global_letiable.substring("Adhara.".length)):getValueFromJSON(window,global_letiable)},loop:function(looper,options){let structure="";for(let i=0;i<looper.length;i++)structure+=options.fn(looper[i]);return structure},append:function(){let args=Array.prototype.slice.call(arguments);return args.pop(),args.map(arg=>"object"==typeof arg?JSON.stringify(arg):arg).join("")},make_json:function(str){return JSON.parse(str)},make_context:function(){let context={};for(let i=0;i<arguments.length-1;i+=2)context[arguments[i]]=arguments[i+1];return context},fn_call:function(fn){return call_fn.apply(this,Array.prototype.slice.call(arguments).slice(0,-1))},loopObject:function(looper,options){let structure="";return loop(looper,function(key,value){structure+=options.fn({key:key,value:value})}),structure},iterate_range:function(start,step,end,options){let str_buf="";for(let i=start;i<=end;i+=step)str_buf+=options.fn(i);return str_buf},route:function(url){return new Handlebars.SafeString(`href="${Adhara.router.transformURL(url)}" route`)}}}static registerHelpers(){window.Handlebars.registerHelper(TemplateEngineHelpers.getHelpers(window.Handlebars.helpers))}}function handleForm(form){if(form.submitting)return;let apiData;if(form.submitting=!0,!!form.querySelector('input[type="file"]'))apiData=new FormData(form);else{let formData=jQuery(form).serializeArray();apiData={},jQuery.each(formData,function(i,fieldData){apiData[fieldData.name]=fieldData.value})}let format_fn=form.getAttribute("format-data");format_fn&&(apiData=call_fn(format_fn,apiData)),!1!==apiData&&RestAPI[form.getAttribute("api-method")]({url:form.action.split(window.location.host)[1],data:apiData,successMessage:form.getAttribute("success-message"),handleError:"false"!==form.getAttribute("handle-error"),success:function(data){"true"===form.getAttribute("form-clear")&&form.reset(),jQuery(form).trigger("success",data)},failure:function(message){jQuery(form).trigger("failure",message)}})}function registerAdharaUtils(){Adhara.templateEngine.helpersHandler.registerHelpers(),jQuery(document).on("submit","form.api-form",function(event){event.preventDefault(),handleForm(this)}),jQuery(document).on("success","form.dialog-form",function(){this.close.click()})}function evaluateLogic(param1,operator,param2){return"in"===operator?param2&&-1!==param2.indexOf(param1):"not_in"===operator?param2&&-1===param2.indexOf(param1):"contains"===operator?param1&&-1!==param1.indexOf(param2):"not_contains"===operator?param1&&-1===param1.indexOf(param2):"has"===operator?param1&¶m1.hasOwnProperty(param2):{"||":param1||param2,"&&":param1&¶m2,"|":param1|param2,"&":param1¶m2,"==":param1==param2,"===":param1===param2,"!=":param1!=param2,"!==":param1!==param2,">":param1>param2,"<":param1<param2,">=":param1>=param2,"<=":param1<=param2,equals:param1==param2,and:param1&¶m2,or:param1||param2}[operator]}function getValueFromJSON(object,path,identifier){try{if(!path)return object;let keys=path.split(".");for(let i=0;i<keys.length;i++){let key_in=keys[i];if(-1!==key_in.indexOf("[")){let arr=key_in.split("["),arrName=arr[0],index=arr[1].split("]")[0];if(isNaN(index)){let rite=object[arrName],separator=index.substring(identifier.length,index.length),formattedVal="";for(let j=0;j<rite.length;j++)j>0&&(formattedVal+=separator),formattedVal+=getValueFromJSON(rite[j],path.split(".").splice(i+1).join("."),identifier);object=formattedVal}else object=object[arrName][index];break}object=object[key_in]}return object}catch(e){return}}function setValueToJson(object,path,value){let keys=path.split(".");loop(keys,function(i,key){i+1<keys.length?(object.hasOwnProperty(key)||(object[key]={}),object=object[key]):object[key]=value})}function call_fn(fn){if(!fn)return;let args=Array.prototype.slice.call(arguments);if(args.splice(0,1),"function"==typeof fn)return fn.apply(fn,args);try{if((fn=getValueFromJSON(window,fn))&&fn!==window)return fn.apply(window[fn],args)}catch(e){throw"TypeError"===e.name&&-1!==e.message.indexOf("is not a function")?new Error("error executing function : "+fn):e}}function call_fn_or_def(fn){let args=Array.prototype.slice.call(arguments),def_fn=args.pop();return"function"!=typeof def_fn&&"function"!=typeof window[def_fn]&&(args.push(def_fn),def_fn=void 0),fn?call_fn.apply(call_fn,args):def_fn?(args[0]=def_fn,call_fn.apply(call_fn,args)):void 0}function loop(object,cbk,reverseIterate){let i,loop_size;if(object instanceof Array)if(loop_size=object.length,reverseIterate)for(i=loop_size-1;i>=0&&!1!==cbk(i,object[i]);i--);else for(i=0;i<loop_size&&!1!==cbk(i,object[i]);i++);else{let keys=Object.keys(object);for(loop_size=keys.length,i=0;i<loop_size&&!1!==cbk(keys[i],object[keys[i]]);i++);}}let TemplateUtils={};!function(){let preCompiledCache={};TemplateUtils.execute=function(template_or_template_string,context,cache){let template=window.Handlebars.templates[template_or_template_string];return!template&&window.Handlebars.hasOwnProperty("compile")&&(!1!==cache?(template=preCompiledCache[template_or_template_string])||(template=preCompiledCache[template_or_template_string]=window.Handlebars.compile(template_or_template_string)):template=window.Handlebars.compile(template_or_template_string)),template(context)}}();class Internationalize{constructor(key_map){this.key_map=key_map}getValue(key,subs,default_value){if(!key)return;let value=this.key_map[key];if(void 0===value&&(value=getValueFromJSON(this.key_map,key)),void 0===value)return default_value;subs=subs||[];let placeholders=value.match(/{[0-9]+}/g)||[];for(let i=0;i<placeholders.length;i++){let sub=subs[i]||"";try{-1!==sub.indexOf(".")&&(sub=this.get(sub))}catch(e){}value=value.replace(new RegExp("\\{"+i+"\\}","g"),sub)}return value.trim()}get(key,subs){return this.getValue(key,subs,key)}}function MutateViews(baseClass,...mixins){class base extends baseClass{constructor(...args){super(...args),mixins.forEach(mixin=>{copyProps(this,new mixin(...args))})}}function copyProps(target,source){Object.getOwnPropertyNames(source).concat(Object.getOwnPropertySymbols(source)).forEach(prop=>{prop.match(/^(?:constructor|prototype|arguments|caller|name|bind|call|apply|toString|length)$/)||Object.defineProperty(target,prop,Object.getOwnPropertyDescriptor(source,prop))})}return mixins.forEach(mixin=>{copyProps(base.prototype,mixin.prototype),copyProps(base,mixin)}),base}function cloneObject(obj){let clone=obj instanceof Array?[]:{};for(let i in obj)null!=obj[i]&&"object"==typeof obj[i]?clone[i]=cloneObject(obj[i]):clone[i]=obj[i];return clone}class Time{static async sleep(millis){return new Promise((resolve,reject)=>{setTimeout(resolve,millis)})}}class AdharaTicker{constructor(interval,exponential_factor,min_interval){this.interval=0===interval?interval:interval||2e3,this.exponential_factor=exponential_factor||1,this.min_interval=min_interval||0,this.initial_interval=interval,this.timeoutId=null}scheduleNextTick(){this.pause(),this.interval<=this.min_interval||(this.timeoutId=window.setTimeout(()=>{this.onExecute()},this.interval))}next(){this.scheduleNextTick()}onExecute(){this.interval*=this.exponential_factor,this.on_execute(this.next)}start(execute){this.on_execute=execute,this.scheduleNextTick()}pause(){window.clearTimeout(this.timeoutId)}resume(){this.scheduleNextTick()}stop(){this.pause(),this.interval=this.initial_interval}restart(){this.stop(),this.scheduleNextTick()}}let AdharaRouter=null;(()=>{"use strict";let curr_path,registeredUrlPatterns={},baseURI="",queryParams={},pathParams={},historyStack=[],currentUrl=void 0,currentRoute=void 0,listeners={},middlewares=[];function getFullUrl(){return window.location.href}function getPathName(){return AdharaRouter.transformURL(window.location.pathname)}function getFullPath(){return getPathName()+window.location.search+window.location.hash}function getSearchString(){return window.location.search.substring(1)}function isCurrentPath(new_path){function stripSlash(path){return 0===path.indexOf("/")?path.substring(1):path}return stripSlash(getFullPath())===stripSlash(new_path)}function matchUrl(){let path=getPathName(),matchFound=!1;for(let regex in registeredUrlPatterns)if(registeredUrlPatterns.hasOwnProperty(regex)&&!matchFound){let formed_regex=new RegExp(regex);if(formed_regex.test(path)){return matchFound=!0,{opts:registeredUrlPatterns[regex],path:path,params:formed_regex.exec(path)}}}}function matchAndCall(){let matchOptions=matchUrl();if(matchOptions){let{opts:opts,path:path,params:params}=matchOptions;if(params.splice(0,1),opts&&opts.fn){let _pathParams={};for(let[index,param]of params.entries())_pathParams[opts.path_param_keys[index]]=param;currentRoute=opts,pathParams=_pathParams,currentUrl=getFullUrl(),fetchQueryParams(),function(params,proceed){let i=0;!function _proceed(){let middleware_fn=middlewares[i++];middleware_fn?call_fn(middleware_fn,params,_proceed):proceed()}()}({view_name:opts.view_name,path:path,query_params:getQueryParams(),path_params:_pathParams},()=>{params.push(queryParams),opts.fn.constructor instanceof AdharaView.constructor?Adhara.onRoute(opts.fn,params):opts.fn.apply(this,params)})}}return!!matchOptions}function updateHistoryStack(){curr_path&&historyStack.push(curr_path),curr_path=getFullPath()}let settingURL=!1;function getQueryParams(){let qp={};return getSearchString()?loop(getSearchString().split("&"),function(i,paramPair){paramPair=paramPair.split("="),qp[decodeURIComponent(paramPair[0])]=decodeURIComponent(paramPair[1])}):qp={},qp}function fetchQueryParams(){queryParams=getQueryParams()}function generateCurrentUrl(){let url=getPathName(),params=[];return loop(queryParams,function(key,value){params.push(encodeURIComponent(key)+"="+encodeURIComponent(value))}),params.length&&(url+="?"+params.join("&")),url}function _route(route_type,route_options){route_type&&route_type!==AdharaRouter.RouteTypes.SET?route_type===AdharaRouter.RouteTypes.NAVIGATE?AdharaRouter.navigateTo(generateCurrentUrl(),route_options&&route_options.force||!1):route_type===AdharaRouter.RouteTypes.OVERRIDE?AdharaRouter.overrideURL(generateCurrentUrl()):route_type===AdharaRouter.RouteTypes.UPDATE&&AdharaRouter.updateURL(generateCurrentUrl()):AdharaRouter.setURL(generateCurrentUrl())}const STATE_KEY="__adhara_router__";class Router{static transformURL(url){return url.startsWith(baseURI)?url:baseURI+url}static register_one(pattern,view_name,fn,meta){let path_param_keys=[],regex=/{{([a-zA-Z$_][a-zA-Z0-9$_]*)}}/g,match=regex.exec(pattern);for(;null!=match;)path_param_keys.push(match[1]),match=regex.exec(pattern);pattern=pattern.replace(new RegExp("\\{\\{[a-zA-Z$_][a-zA-Z0-9$_]*\\}\\}","g"),""),pattern=(pattern="^"+this.transformURL(pattern.substring(1))).replace(/[?]/g,"\\?"),registeredUrlPatterns[pattern]={view_name:view_name,fn:fn,path_param_keys:path_param_keys,meta:meta}}static deRegister(regex){registeredUrlPatterns[regex]=void 0}static register(list){for(let conf of list)this.register_one(conf.url,conf.view_name,conf.view,conf.meta)}static configure(router_configuration){if(router_configuration.base_uri&&(baseURI=router_configuration.base_uri),router_configuration.routes&&Router.register(router_configuration.routes),router_configuration.on_route_listeners)for(let listener_name in router_configuration.on_route_listeners)router_configuration.on_route_listeners.hasOwnProperty(listener_name)&&Router.onRoute(listener_name,router_configuration.on_route_listeners[listener_name]);if(router_configuration.middlewares)for(let middleware_fn of router_configuration.middlewares)Router.registerMiddleware(middleware_fn)}static onRoute(listener_name,listener_fn){listeners[listener_name]=listener_fn}static offRouteListener(listener_name){listeners[listener_name]=void 0}static registerMiddleware(middleware_fn){"function"==typeof middleware_fn&&middlewares.push(middleware_fn)}static route(){if(settingURL)settingURL=!1;else{if(!matchAndCall())throw new Error("No route registered for this url : "+getPathName())}loop(listeners,function(listener_name,listener_fn){call_fn(listener_fn)})}static getCurrentRoute(){return currentRoute||(currentRoute=matchUrl().opts),currentRoute}static getCurrentPageName(){return AdharaRouter.getCurrentRoute().view_name}static getCurrentURL(){return getFullPath()}static getCurrentPath(){return getPathName()}static getCurrentHash(){return window.location.hash.substring(1)}static go(url){if(isCurrentPath(url))return!1;history.pushState({[STATE_KEY]:!0},parent.document.title,url);let state=history.state;return updateHistoryStack(),pathParams={},void 0!==state&&""!==state&&(!0!==state[STATE_KEY]&&!0!==state.data[STATE_KEY]||this.route()),!0}static setURL(url){url=this.transformURL(url),settingURL=!0,this.go(url)||(settingURL=!1)}static overrideURL(url){url=this.transformURL(url),history.replaceState({[STATE_KEY]:!0},parent.document.title,url)}static updateURL(url){settingURL=!0,this.overrideURL(url)}static navigateTo(url,force){if(isCurrentPath(url=this.transformURL(url)))force&&this.route();else{this.go(url)&&fetchQueryParams()}}static goBack(backwardURL){if(!backwardURL&&!(backwardURL=historyStack.slice(-1)[0]))return!1;backwardURL=this.transformURL(backwardURL);let backwardIndex=historyStack.lastIndexOf(backwardURL);if(-1===backwardIndex)this.navigateTo(backwardURL);else{let stackLen=historyStack.length,negativeIndex=backwardIndex-stackLen;historyStack.splice(stackLen+negativeIndex,-negativeIndex),history.go(negativeIndex)}}static peekStack(){return historyStack.slice()}static getQueryParam(param_name){return getFullUrl()!==currentUrl&&(currentUrl=getFullUrl(),fetchQueryParams()),queryParams[param_name]}static getPathParam(param_name){return pathParams[param_name]}static updateQueryParams(new_params,drop_existing,route_type,route_options){route_type||(route_type=this.RouteTypes.NAVIGATE),drop_existing?queryParams=new_params:Object.assign(queryParams,new_params),_route(route_type,route_options)}static removeQueryParams(param_keys,route_type,route_options){loop(param_keys,function(idx,key){delete queryParams[key]}),_route(route_type,route_options)}static getURLPatternByPageName(view_name){let matched_pattern=null;return loop(registeredUrlPatterns,function(pattern,options){if(options.view_name===view_name)return matched_pattern=pattern,!1}),matched_pattern}}AdharaRouter=Router,window.onpopstate=(e=>{AdharaRouter.route()}),AdharaRouter.RouteTypes=Object.freeze({NAVIGATE:"navigate",OVERRIDE:"override",SET:"set",UPDATE:"update"}),AdharaRouter.enableAllAnchors=!0,AdharaRouter.listen=function(){function hasAttribute(elem,attribute_name){return elem.hasAttribute(attribute_name)}function routeHandler(event){let re=function(event){return"A"!==event.target.nodeName?event.currentTarget:event.target}(event);if((AdharaRouter.enableAllAnchors||hasAttribute(re,"route"))&&hasAttribute(re,"href")&&!hasAttribute(re,"skiprouting")){let target=this.getAttribute("target"),miniURL=this.getAttribute("href").trim(),isHash=0===miniURL.indexOf("#");if(target&&"_self"!==target||-1!==miniURL.indexOf("javascript")||isHash)return;let url=miniURL;try{if(new URL(url).host!==window.location.host)return}catch(e){}let go_back=this.getAttribute("data-back"),force="false"!==this.getAttribute("data-force");if(go_back)return AdharaRouter.goBack(url);AdharaRouter.navigateTo(url,force),url&&(event.preventDefault(),event.stopPropagation())}}jQuery(document).on("click","a",routeHandler),jQuery(document).on("click","[route]",routeHandler)},updateHistoryStack()})();let Toast={make:function(title,content,type){return Adhara.app?Adhara.app.toast(title,content,type):window.ToastHandler?window.ToastHandler[type](content,title):void console.log(`No toast handler found. Toast message: type-${type}, title-${title}, content=${content}`)},error:function(message){return Toast.make("Error!",message,"error")},success:function(message){return Toast.make("Success",message,"success")}},AdharaDefaultToaster={};function deserialize(str,context){if("object"==typeof context&&context.blob){let data=JSON.parse(str);return new context.blob(data)}if(context){let data=JSON.parse(str);return new context.blob(data)}throw new Error(`context passed is invalid: ${context}`)}function isPrimitive(ob){return ob!==Object(ob)}!function(){let notifyQueue=0;AdharaDefaultToaster.make=function(title,content,type){let maxNotificationsHeight=window.innerHeight-200,currentNotificationsHeight=0;jQuery.each(jQuery(".notification"),function(){currentNotificationsHeight+=jQuery(this).height()+40});let proceed=currentNotificationsHeight<maxNotificationsHeight,notifyTimeout=0===notifyQueue?0:2e3;content||"failure"!==type||(content="Error occurred...");let nid=performance.now();return setTimeout(function(){0===notifyQueue&&proceed?(notifyQueue++,function(title,content,type,id){id="notification_"+id;let $notificationDiv=jQuery('<div class="notification '+type+'" id="'+id+'"/>'),$title=jQuery('<strong style="display:block" />').text(title),$content=jQuery("<p />").html(content);$notificationDiv.append($title).append($content),jQuery("body").append($notificationDiv);let existing_notifications=jQuery(".notification");existing_notifications.length>0&&jQuery.each(existing_notifications,function(index,value){if(jQuery(this).attr("id")!==id){let new_top=parseFloat(jQuery(this).css("top"))+$notificationDiv.height()+40;jQuery(this).animate({top:new_top+"px"},"fast")}}),jQuery("#"+id).animate({right:"0px"},"fast",function(){notifyQueue--}),setTimeout(function(){jQuery("#"+id).animate({opacity:"0.5"},"fast",function(){jQuery("#"+id).hide("slide",{direction:"right"},"slow",function(){setTimeout(function(){jQuery("#"+id).remove()},1e3)})})},5e3)}(title,content,type,nid)):AdharaDefaultToaster.make(title,content,type)},notifyTimeout),{remove:function(){jQuery("#notification_"+nid).remove()}}}}();class Serializable{static _validateData(data){if(isPrimitive(data))return!0;if("object"!=typeof data||null===data||data instanceof Array)return!0;{let eq_success=function equivalence(ob1,ob2){if(isPrimitive(ob1)&&isPrimitive(ob2))return ob1===ob2;if(isPrimitive(ob1)!==isPrimitive(ob2))return!1;for(let key in ob1)if(ob1.hasOwnProperty(key)&&!equivalence(ob1[key],ob2[key]))return!1;return!0}(JSON.parse(JSON.stringify(data)),data);return eq_success||console.warn("Equivalence check failed for the data. Data is not serializable.",data),eq_success}}constructor(data){if(!Serializable._validateData(data))throw new Error(`blob must be initialized with serializable(tree-like, non-array) object: ${data}`)}serialize(){throw new Error("Need to define method: serialize")}}class DataBlob extends Serializable{constructor(data){if(super(data),!data)return;if(this._data=data,!1===this.validate(data))throw new Error(`assigned data does not clear the custom validation: ${data}`);this.onInit()}onInit(){}static get _context(){return"base"}get data(){return this._data}set data(data){if(!Serializable._validateData(data))throw new Error(`blob must represent a non-array, tree-like object ${data}`);if(!1===this.validate(data))throw new Error(`assigned data does not clear the custom validation: ${data}`);this._data=data}get packet(){return this.serialize()}validate(){return!0}_formatTimeBit(value){return(1===value.toString().length?"0":"")+value.toString()}_formatTime(date){return`${this._formatTimeBit(date.getHours())}:${this._formatTimeBit(date.getMinutes())}:${this._formatTimeBit(date.getSeconds())}`}_formatDate(date){return`${this._formatTimeBit(date.getMonth()+1)}/${this._formatTimeBit(date.getDate())}/${date.getFullYear()}`}}let NetworkMethods={GET:"get",POST:"post",PUT:"put",DELETE:"delete",PATCH:"patch"};class NetworkProvider{get baseURL(){return"/"}formatResponse(data){return data}getCookie(cookie_name){let cookieValue=null;if(document.cookie&&""!==document.cookie){let cookies=document.cookie.split(";");for(let i=0;i<cookies.length;i++){let cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,cookie_name.length+1)===cookie_name+"="){cookieValue=decodeURIComponent(cookie.substring(cookie_name.length+1));break}}}return cookieValue}get headers(){return{"Content-Type":"application/json"}}isFullURL(link){return link.startsWith("http://")||link.startsWith("https://")||link.startsWith("//")}formatURL(url){if(this.isFullURL(url))return url;let baseURL=this.baseURL;return baseURL.endsWith("/")&&(baseURL=baseURL.substr(0,baseURL.length-1)),url.startsWith("/")&&(url=url.substr(1)),baseURL+"/"+url}handleSuccess(fns,fne,d,s,x){if("nocontent"!==s)return"success"===s?(x.getResponseHeader("Content-Disposition"),call_fn(fns,d,x)):void call_fn(fne,d,x)}handleFailure(fne,x,s,e){0===x.readyState&&0===x.status&&""===e&&(e="Unable to connect to server"),call_fn(fne,e,x)}ajax(o){"get"!==o.type&&o.data instanceof Object&&(Object.keys(o.data).length?o.data=JSON.stringify(o.data):delete o.data),"get"!==o.type&&"delete"!==o.type&&(o.headers["Content-Type"]="application/json"),jQuery.ajax(o)}multipart(o){let xhr=new XMLHttpRequest;xhr.open(o.type.toUpperCase(),o.url),loop(o.headers,function(header,value){xhr.setRequestHeader(header,value)}),xhr.onreadystatechange=function(){xhr.readyState===XMLHttpRequest.DONE&&(200===xhr.status?o.success(xhr.responseText,"success",xhr):o.error(xhr,"error",xhr.responseText))},xhr.send(o.data)}async send(o){return new Promise((resolve,reject)=>{o.success=((d,s,x)=>{this.handleSuccess((d,s)=>{resolve([d,x])},(d,x)=>{reject([d,x])},d,s,x,o.handleError,o.successMessage)}),o.error=((x,s,e)=>{this.handleFailure((e,x)=>{reject([e,x])},x,s,e)}),o.data instanceof FormData?this.multipart(o):this.ajax(o)})}preFlightIntercept(method,url,data){}_preFlightIntercept(method,url,data){this.preFlightIntercept(method,url,data)}postResponseIntercept(method,url,data,response,xhr){}_postResponseIntercept(method,url,data,response,xhr){this.postResponseIntercept(method,url,data,response,xhr)}postErrorResponseIntercept(method,url,data,response,xhr){}_postErrorResponseIntercept(method,url,data,response,xhr){this.postErrorResponseIntercept(method,url,data,response,xhr)}async _send(method,url,data,options){url=this.formatURL(url),this._preFlightIntercept(method,url,null);try{let[r,x]=await this.send(Object.assign({url:url,headers:this.headers,method:method,data:data},options));return this._postResponseIntercept(method,url,null,r,x),this.formatResponse(r)}catch(e){throw console.log("API errored out::",e),this._postErrorResponseIntercept(method,url,data,e[0],e[1]),e[0]}}async get(url,data,options){return"object"==typeof data&&(data=Object.entries(data).map(([k,v])=>`${k}=${v}`).join("&")),await this._send(NetworkMethods.GET,url,data,options)}async post(url,data,options){return await this._send(NetworkMethods.POST,url,data,options)}async put(url,data,options){return await this._send(NetworkMethods.PUT,url,data,options)}async delete(url,options){return await this._send(NetworkMethods.DELETE,url,data,options)}}class DataInterface{constructor(network){this.network=network||new NetworkProvider}}class Context{constructor(key,view){this.key=key,this.view=view}set parentContext(parent_context){this._parentContext=parent_context,this._parentContext.childContext=this}get parentContext(){return this._parentContext||Adhara.container.context}set childContext(child_context){this._childContexts||(this._childContexts=[]),this._childContexts.push(child_context)}get childContexts(){return this._childContexts}getViewFromRenderTree(classRef,instanceKey){return this.searchViewInCurrentTreeAndUp(classRef,instanceKey)||this.searchViewInWholeTree(classRef,instanceKey)}checkKey(contextKey,instanceKey){return!instanceKey||contextKey===instanceKey}searchViewInCurrentTreeAndUp(classRef,instanceKey){return classRef===Adhara.container.constructor?Adhara.container:this.view!==Adhara.container?this.parentContext.view.constructor===classRef&&this.checkKey(this.parentContext.key,instanceKey)?this.parentContext.view:this.parentContext.getViewFromRenderTree(classRef,instanceKey):void 0}searchViewInWholeTree(classRef,instanceKey){return this.searchViewInCurrentTreeAndUp(Adhara.container.constructor).context.searchChildren(classRef,instanceKey)}searchChildren(classRef,instanceKey){for(let context of this.childContexts)if(context.view.constructor===classRef&&this.checkKey(context.key,instanceKey))return context.view;for(let context of this.childContexts){let matchedView=context.searchChildren(classRef,instanceKey);if(matchedView)return matchedView}}}class AdharaEventHandler{constructor(){this._event_listeners={},this._registerEvents(this.events)}get events(){return[]}_registerEvents(event_names){for(let event_name of event_names)this._event_listeners[event_name]=[],this["on"+event_name]=(handler=>{this._event_listeners[event_name].push(handler)}),this["off"+event_name]=(handler=>{this._event_listeners[event_name].splice(this._event_listeners[event_name].indexOf(handler),1)})}trigger(event_name,...data){for(let event_handler of this._event_listeners[event_name])event_handler.apply(event_handler,data)}}class AdharaView extends AdharaEventHandler{constructor(settings={}){super(),this.settings=settings;let{key:key,c:c}=this.settings;this.ts=`d${performance.now().toString().replace(".","-")}`,this.context=new Context(key||this.ts,this),this._parentContainer=c,Adhara.addViewToInstances(this),this.is_active=!1,this._registerEvents(["ViewRendered","SubViewsRendered","ViewFormatted","ViewDestroyed"]),this.fetching_data=!1,this.onInit(),this.rendered=!1,this.initialized=!0}onInit(){}get template(){if(this.settings.t)return this.settings.t;if(Adhara.router.getCurrentPageName())return Adhara.router.getCurrentPageName().replace(/_/g,"-");{let className=this.constructor.name.toLowerCase();return className.endsWith("view")?className.slice(0,className.length-4):className}}get parentContainer(){return this._parentContainer}set parentContainer(_){this._parentContainer=_}getCustomTemplate(type){for(let ViewClass of Adhara.viewHierarchy)if(ViewClass.isPrototypeOf(this.constructor)&&Adhara.app.customViewConfig[type]&&Adhara.app.customViewConfig[type][ViewClass.name])return Adhara.app.customViewConfig[type][ViewClass.name]}get errorTemplate(){return this.getCustomTemplate("error")||null}get fetchingDataTemplate(){return this.getCustomTemplate("fetching_data")||""}get noDataTemplate(){return this.getCustomTemplate("no_data")||""}getTemplate(){return this.fetching_data?this.fetchingDataTemplate:this.errors&&this.errorTemplate||this.template}get isImmortal(){return!1}isActive(){return Adhara.isActiveView(this)&&this.is_active}create(){Adhara.addToActiveViews(this),this.is_active=!0,this.fetch().then(()=>{this.render()}),this.render()}async fetch(){this.fetching_data=!0,await this.fetchData(),this.fetching_data=!1}async fetchData(){}_getHTML(template){return Adhara.app.renderTemplate(template||this.getTemplate(),this)}static of(context,tag){return context.getViewFromRenderTree(this,tag)}get r(){return{d:Adhara.app.d}}getParentContainerElement(){return document.querySelector(this.parentContainer)}querySelector(css_selector){return this.getParentContainerElement().querySelector(css_selector)}querySelectorAll(css_selector){return this.getParentContainerElement().querySelectorAll(css_selector)}setState(){this.render()}render(){let container=this.getParentContainerElement();container?(container.innerHTML=this._getHTML(),this.fetching_data||(this.trigger("ViewRendered"),this._format(container),setTimeout(()=>{this.format(container),this.trigger("ViewFormatted")},0),this.renderSubViews(),this.trigger("SubViewsRendered"),this.rendered=!0)):console.warn(`No container defined/available for ${this.constructor.name}, selecting with ${this.parentContainer}`)}get contentContainer(){throw new Error("implement this method")}get subViews(){return[]}renderSubViews(){for(let sub_view of this.subViews||[])Adhara.createView(sub_view,this)}_format(container){for(let action of["click","change","blur","focus","scroll","contextmenu","copy","cut","dblclick","drag","dragend","dragenter","dragleave","dragover","dragstart","drop","focus","focusin","focusout","input","invalid","mousedown","mouseenter","mouseleave","mouseover","mouseout","mouseup","paste","scroll","show","toggle","wheel","keyup","keydown","keypress"]){let onActionElements=container.querySelectorAll(`[data-on${action}]`);for(let actionElement of onActionElements)"true"!==actionElement.dataset[`_ae_${action}_`]&&(actionElement.addEventListener(action,event=>{let data=actionElement.dataset,action_key=`on${action}`;if(this[data[action_key]])this[data[action_key]](event,data,this);else{let fn=getValueFromJSON(window,data[action_key]);if(!fn)throw new Error(`Invalid function: ${data[action_key]} in View ${this.constructor.name}`);fn(event,data,this)}}),actionElement.dataset[`_ae_${action}_`]="true")}}format(container){}refresh(){Adhara.createView(this)}onDestroy(){}destroy(){this.onDestroy(),this.trigger("ViewDestroyed"),this.is_active=!1;try{this.getParentContainerElement().innerHTML=""}catch(e){}}}class AdharaListView extends AdharaView{constructor(parentViewInstance){super(parentViewInstance),this._page_number=1,this.searchText=null,this._rows=[]}get template(){return"adhara-list"}get allowedListTypes(){return[]}get defaultListType(){if(this.allowedListTypes.length)return this.allowedListTypes[0];throw new Error("override `get listType`")}get listType(){return this._listType?this._listType:this.defaultListType}get nextType(){if(this.allowedListTypes.length>1){let currentIndex=this.allowedListTypes.indexOf(this.listType);return this.allowedListTypes[currentIndex+1]||this.allowedListTypes[0]}return null}changeViewType(event,data){this._listType=data.viewtype,this.setState(),this.onViewTypeChanged(this.listType)}onViewTypeChanged(new_view_type){}get listTemplate(){return AdharaListView.DEFAULT_TEMPLATES[this.listType].listTemplate}get headerTemplate(){return AdharaListView.DEFAULT_TEMPLATES[this.listType].headerTemplate}get itemTemplate(){return AdharaListView.DEFAULT_TEMPLATES[this.listType].itemTemplate}get title(){return""}get isPaginationRequired(){return!1}get columns(){return[]}set rows(_){this._rows=_}get rows(){return this._rows}get noDataAvailable(){return"No Data Available"}get menuTemplate(){return"adhara-list-menu"}get footerTemplate(){return"adhara-list-footer"}get buttons(){return[]}get rowCount(){return AdharaListView.rowCount}get pageNumber(){return this._page_number}get isFirstPage(){return 1===this._page_number}get isLastPage(){return this.rows.length<this.rowCount}previousPage(){this.setPage(this.pageNumber-1),this.pageChange()}nextPage(){this.setPage(this.pageNumber+1),this.pageChange()}firstPage(){this.setPage(1),this.pageChange()}setPage(page_number){this._page_number=page_number}pageChange(){this.fetch()}getPayload(){return this.isPaginationRequired?Object.assign({},super.getPayload(),AdharaListView.getPagePayload(this.pageNumber)):super.getPayload()}search(){}onSearchToggle(event,data){event.target===document.activeElement?event.target.classList.add("active"):event.target.classList.remove("active")}onSearchCapture(event,data){event.target.value!==this.searchText&&(this.searchText=event.target.value,this.onSearch(event.target.value))}onSearch(text){console.error(`TODO Search is enabled for this list view.\n So, implement onSearch... search text: "${text}"`)}updateResults(){this.getParentContainerElement().querySelector(".list-contents").innerHTML=Adhara.app.renderTemplate(this.listTemplate,this)}format(container){if(null!==this.searchText){let $search=container.querySelector('input[type="search"]');$search.focus(),$search.setSelectionRange(this.searchText.length,this.searchText.length)}super.format(container)}}AdharaListView.rowCount=5,AdharaListView.getPagePayload=(page=>({page:page})),AdharaListView.VIEW_TYPES={CARD_VIEW:"card",GRID_VIEW:"grid",TEMPLATE_VIEW:"template"},AdharaListView.DEFAULT_TEMPLATES={[AdharaListView.VIEW_TYPES.CARD_VIEW]:{listTemplate:"adhara-card",itemTemplate:"adhara-card-content"},[AdharaListView.VIEW_TYPES.GRID_VIEW]:{listTemplate:"adhara-list-grid"},[AdharaListView.VIEW_TYPES.TEMPLATE_VIEW]:{listTemplate:"adhara-list-template",headerTemplate:"adhara-list-template-header",itemTemplate:"adhara-list-template-item"}};class AdharaMutableView extends AdharaView{constructor(settings={}){settings.key=settings.key||settings.name,super(settings),this.parentContainer=this.parentContainer||`[data-field="${settings.name}"]`,this._name=settings.name,this._fields=settings.fields,this.mutator=null,this._registerEvents(["Saved","Cancelled"])}onInit(){this._mutable_data={},this.fieldMap={},this.rendered_fields=[]}get name(){return this._name||""}get fullName(){return(this.mutator&&this.mutator.name?this.mutator.name+".":"")+this.name}get safeName(){return this.name.replace(".","-")}get key(){return this.name}get fields(){return this._fields||[]}get mutableFields(){return this.fields.filter(f=>f instanceof FormField||f instanceof AdharaMutableView)}set mutableData(_){this._mutable_data=_}get mutableData(){return this._mutable_data}getFieldValue(field_name){let d=getValueFromJSON(this.mutableData,this.fieldMap[field_name].name);return void 0===d&&(d=this.fieldMap[field_name].value),d}setFieldValue(field_name,value){let field=this.formElement[field_name];"checkbox"===field.type?field.checked=!0:field.value=value}getMutatedData(){let data={};for(let field of this.rendered_fields)setValueToJson(data,field.name,field.serialize());return data}getField(field_name){return this.fieldMap[field_name]}async submitData(data){throw new Error("Must override `submitData`")}enhanceFieldForSubViewRendering(field){this.fieldMap[field.name]=field,field.mutator=this;let _v=this.getFieldValue(field.name);return field instanceof AdharaMutableView?_v&&_v instanceof Array&&_v.length&&(field.mutableData=_v):field.value=_v,field}get subViews(){let fields=this.mutableFields.map(_=>this.enhanceFieldForSubViewRendering(_));return this.rendered_fields=fields.slice(),fields}onMutableDataChanged(){}onFieldValueChanged(field_name,value,old_value){}_onFieldValueChanged(field_name,value,old_value,{event:event,data:data}={}){setValueToJson(this._mutable_data,this.fieldMap[field_name].name,value),this.onFieldValueChanged(field_name,value,old_value),this.onMutableDataChanged()}}class AdharaFormView extends AdharaMutableView{get duplicateSubmissions(){return!1}get clearFormOnSuccess(){return"true"===this.formElement.getAttribute("form-clear")}onSuccess(data){Toast.success("Success")}onError(error){Toast.error(error)}onValidationError(error){Toast.error(error.message)}validate(data){}formatData(data){return data}get formElement(){if(this._formElement&&document.body.contains(this._formElement)||(this._formElement=this.getParentContainerElement().querySelector("form")),!this._formElement)throw new Error("No from element discovered!");return this._formElement}get handleFileUploads(){return!0}updateFormState(submitting){try{this.formElement.submitting=submitting,this.handleSubmitButton(),submitting||this.reSubmitIfRequired()}catch(e){}}get submitButton(){return this.formElement.querySelector('[type="submit"]')}get cancelButton(){return this.formElement.querySelector('[data-cancel="true"]')}handleSubmitButton(){if(this.duplicateSubmissions)return;let submit_button=this.submitButton;submit_button?this.formElement.submitting?(submit_button.dataset.tosubmit=submit_button.innerHTML,submit_button.innerHTML=submit_button.dataset.inprogress||Adhara.i18n.getValue("form.processing",[],"")||submit_button.dataset.tosubmit,submit_button.disabled=!0):(submit_button.dataset.inprogress=submit_button.innerHTML,submit_button.innerHTML=submit_button.dataset.tosubmit,submit_button.disabled=!1):console.warn("Unable to discover 'Submit button'. Duplicate submission are not handled.")}async executeDataSubmission(apiData){await this.submitData(apiData),this.trigger("Saved",apiData)}async _handleForm(){let form=this.formElement;if(!form.checkValidity())return form.reportValidity();if(form.submitting)return!1;let apiData=this.getMutatedData();try{this.validate(apiData)}catch(e){return this.onValidationError(e)}apiData=this.formatData(apiData),this.updateFormState(!0);try{await this.executeDataSubmission(apiData)}catch(e){return!1}finally{this.updateFormState(!1)}return!0}_format(container){super._format(container),this.errors||"true"!==this.formElement.dataset._ae_&&(this.formElement.dataset._ae_="true",this.formElement.addEventListener("submit",event=>{event.preventDefault(),this.submit()}),this.cancelButton&&this.cancelButton.addEventListener("click",event=>{this.trigger("Cancelled")}))}reSubmitIfRequired(){this.duplicateSubmissions&&this.re_submit&&this._handleForm().then(_=>this.re_submit=!_)}submit(){this._handleForm().then(_=>this.re_submit=!_)}}class AdharaDetailView extends AdharaMutableView{onInit(){this._entityData={},this.fieldMap={},this.rendered_fields=[]}get fields(){return[]}set entityData(_){this._entityData=_}get entityData(){return this._entityData}getFieldValue(field_name){return getValueFromJSON(this.entityData,this.fieldMap[field_name].key)}get formFields(){return this.fields.filter(f=>f instanceof FormField)}enhanceFieldForSubViewRendering(field){return(field=super.enhanceFieldForSubViewRendering(field)).readonly=!0,field}}class FormField extends AdharaView{constructor(name,config={},settings){super(settings=settings||{}),this.name=name,this._value=config.value,this.mutator=null,this.readonly=config.readonly,this.config=config||{}}get parentContainer(){return super.parentContainer||`[data-field="${this.name}"]`}set parentContainer(_){super.parentContainer=_}clone(key){return new this.constructor(this.name,Object.assign({},cloneObject(this.config)),Object.assign({},cloneObject(this.settings),{key:key}))}get template(){return"adhara-form-fields/index"}get labelTemplate(){return"adhara-form-fields/label"}get fieldTemplate(){}get helpTemplate(){return"adhara-form-fields/help"}get safeName(){return this.name.replace(/\./g,"-")}get showLabel(){return!1!==this.config.label}get displayName(){return this.config.field_display_name||Adhara.i18n.get(`${this.mutator?this.mutator.fullName:""}.${this.name}.label`)}get labelAttributes(){return Object.assign({for:this.safeName},this.config.label_attributes)}get labelProperties(){return(this.config.label_properties||[]).slice()}get placeholder(){if(this.config.placeholder)return"string"==typeof this.config.placeholder?this.config.placeholder:Adhara.i18n.get([this.mutator?this.mutator.fullName:"",this.name,"placeholder"].filter(_=>_).join("."))}get defaultFieldAttributes(){return{class:"form-control"}}get fieldAttributes(){return Object.assign({id:this.safeName,name:this.safeName,placeholder:this.placeholder||""},this.config.attributes||this.defaultFieldAttributes)}get fieldProperties(){let _p=(this.config.label_properties||[]).slice();return this.config.required&&_p.push("required"),_p}get helpText(){return this.config.help_text}get isNullable(){return!0===this.config.nullable}getField(){return document.querySelector(this.parentContainer+" [name='"+this.safeName+"']")}queryValue(target){return(target||this.getField()).value}queryRaw(target){return this.queryValue(target)}onDataChange(event,data){let old_value=this.value;this.value=this.queryValue(event&&event.target),this.mutator._onFieldValueChanged(this.name,this.value,old_value,{event:event,data:data})}set value(_){this._value=_}get value(){return this._value}serialize(){return this.value}}class InputField extends FormField{get fieldTemplate(){return"adhara-form-fields/input"}get inputType(){return this.config.input_type||"text"}queryValue(target){let _=super.queryValue(target);if(""===_.trim())return null;let converter="query_"+this.inputType;return this[converter]&&this[converter](_,target||this.getField())||_}query_number(value,field){return+value}query_checbox(value,field){return field.checked}}InputField.BUTTON="button",InputField.CHECKBOX="checkbox",InputField.COLOR="color",InputField.DATE="date",InputField.DATETIME_LOCAL="datetime-local",InputField.EMAIL="email",InputField.FILE="file",InputField.IMAGE="image",InputField.MONTH="month",InputField.NUMBER="number",InputField.PASSWORD="password",InputField.RADIO="radio",InputField.RANGE="range",InputField.RESET="reset",InputField.SEARCH="search",InputField.SUBMIT="submit",InputField.TEL="tel",InputField.TEXT="text",InputField.TIME="time",InputField.URL="url",InputField.WEEK="week";class TextArea extends FormField{get fieldTemplate(){return"adhara-form-fields/textarea"}}class SelectField extends FormField{get fieldTemplate(){return"adhara-form-fields/select"}set value(_){super.value=_}get value(){return void 0===super.value?null:super.value}get options(){let _o=this.config.options||[];return this.isNullable&&_o.unshift({value:null,display:this.placeholder||"----------"}),_o}format(container){this.value=this.queryValue()}queryRaw(target){let $f=target||this.getField();return{value:$f.value,display:$f.children[$f.selectedIndex].innerText}}}class RadioField extends FormField{get fieldTemplate(){return"adhara-form-fields/radio"}}class CheckboxField extends InputField{get template(){return"adhara-form-fields/checkbox"}queryValue(target){return(target||this.getField()).checked}get defaultFieldAttributes(){return{}}}class FieldSetRepeater extends AdharaMutableView{onInit(){super.onInit(),this.fieldMap=null,this.mutableData=this.mutableData instanceof Array&&this.mutableData.length?this.mutableData:[{}],this.fieldSetMap=[]}get template(){return"adhara-form-fields/repeater"}get isHorizontal(){return this.settings.style===FieldSetRepeater.style.HORIZONTAL}get repeaterFieldSetClass(){return this.isHorizontal?"d-inline-block":"d-flex"}addFieldSet(event,data){this.mutableData.push({}),this.setState()}removeFieldSet(event,data){this.mutableData.length>1&&(this.mutableData.splice(data.idx,1),this.setState())}get subViews(){let repeated_fields=[];for(let field of this.mutableFields)for(let i=0;i<this.mutableData.length;i++){let _field=field.clone(`repeater-${this.safeName}-${i}`);_field.mutator=this,_field.parentContainer=`#fieldset-${i}-${this.safeName} [data-field=${_field.safeName}]`,this.isHorizontal||(_field.config.label=0===i),_field.config.list_index=i,_field.config.attributes["data-repeaterIndex"]=i,this.fieldSetMap[i]||(this.fieldSetMap[i]={}),this.fieldSetMap[i][_field.name]=_field,_field.value=this.getFieldValueByIndex(_field.name,i),repeated_fields.push(_field)}return this.rendered_fields=repeated_fields.slice(),repeated_fields}filterSerializedRows(data){return this.settings.serializedRowFilter?this.settings.serializedRowFilter(data):data.filter(datum=>!!Object.values(datum).filter(_=>_).length)}getFieldValue(field_name){throw new Error("invalid function call for a repeater field set")}getFieldValueByIndex(field_name,row_index){return getValueFromJSON(this.mutableData[row_index],this.fieldSetMap[row_index][field_name].name)}serialize(){let data=[];for(let field of this.rendered_fields)data[field.config.list_index]||(data[field.config.list_index]={}),setValueToJson(data[field.config.list_index],field.name,field.serialize());return this.filterSerializedRows(data)}onFieldValueChangedForIndex(field_name,value,old_value,index){}_onFieldValueChanged(field_name,value,old_value,{event:event,data:data}={}){let index=data.repeaterindex||data.list_index;setValueToJson(this.mutableData[index],this.fieldSetMap[index][field_name].name,value),this.onFieldValueChangedForIndex(field_name,value,old_value,index),this.onMutableDataChanged()}}FieldSetRepeater.style={HORIZONTAL:"h",VERTICAL:"v"};class AdharaGridView extends AdharaListView{get listType(){return AdharaListView.VIEW_TYPES.GRID_VIEW}get tableClass(){return"table-bordered table-hover"}}class AdharaTemplateView extends AdharaListView{get listType(){return AdharaListView.VIEW_TYPES.TEMPLATE_VIEW}get tableClass(){return"table-bordered table-hover"}get containerAttributes(){return{}}}class AdharaCardView extends AdharaListView{get listType(){return AdharaListView.VIEW_TYPES.CARD_VIEW}get containerClass(){return""}get cardSizeClass(){return"col-md-4"}}class AdharaDialogView extends AdharaView{onInit(){this._modalId="adhara-dialog-id-"+Date.now(),this.destroy=this.destroy.bind(this)}get template(){return"adhara-dialog"}get titleTemplate(){return"Adhara Dialog"}get messageTemplate(){return"Adhara Dialog Message!"}get buttons(){return[{attributes:{type:"button",class:"btn btn-secondary","data-dismiss":"modal"},text:"Close"}]}get modalId(){return this._modalId}get wrapperId(){return`${this.modalId}-wrapper`}get modalElement(){return this._modalElemnt&&document.body.contains(this._modalElemnt[0])||(this._modalElemnt=$("#"+this.modalId)),this._modalElemnt}get isAutoShow(){return!0}get destroyOnClose(){return!0}getParentContainerElement(){return document.querySelector("#"+this.wrapperId)}render(){this.destroy();let dialog_elements=document.querySelectorAll("#"+this.modalId);if(dialog_elements&&dialog_elements.length)for(let i=0;i<dialog_elements.length;i++)dialog_elements[i].remove();let wrapper=document.createElement("div");wrapper.id=this.wrapperId,wrapper.classList.add("adhara-dialog"),document.querySelector("body").appendChild(wrapper),super.render()}format(){this.isAutoShow&&this.show()}show(){this.modalElement.modal("show"),this.destroyOnClose&&setTimeout(()=>{this.modalElement.on("hidden.bs.modal",this.destroy)},0)}hide(){this.modalElement.modal("hide")}onDestroy(){let wrapper_element=document.getElementById(this.wrapperId);wrapper_element&&wrapper_element.remove()}}class AdharaTabView extends AdharaView{onInit(){this.containerId=`d${Date.now()}`}get template(){return"adhara-tab-view"}get containerClass(){return"nav nav-pills"}get tabNavClass(){return"custom-tabs-line tabs-line-bottom left-aligned"}get tabListClass(){return"nav"}get tabs(){return[]}get currentTab(){let current_tab_link_from_url=Adhara.router.getCurrentURL(),current_Tab=this.tabs.filter(tab=>tab.link===current_tab_link_from_url);return current_Tab.length?current_Tab[0]:this._current_Tab||this.tabs[0]}get tabsList(){let current_tab_id=this.currentTab.id;return this.tabs.map(tab=>(tab.className=tab.id===current_tab_id?"active":"",tab))}changeCurrentTab(tabId){this._current_Tab=this.tabs.filter(tab=>tab.id===tabId)[0],this.setState()}onLinklessTabClick(event,data){this.changeCurrentTab(data.tabid)}get nextSelector(){return".btn-next"}get previousSelector(){return".btn-previous"}onTabShow(){}onTabClick(){}onTabChange(){}format(){}get contentContainer(){return".tab-content .tab-pane"}get subViews(){let cTab=this.currentTab.view;return cTab.parentContainer=`#${this.containerId} .tab-content .tab-pane.active`,[cTab]}}class AdharaAppContainerView extends AdharaView{get template(){return"app-container"}get isImmortal(){return!0}get contentContainer(){return"main"}}class AdharaDialogFormView extends(MutateViews(AdharaFormView,AdharaDialogView)){primaryAction(){this.submit()}get primaryActionTitle(){return"Save"}get submitButton(){return this.getParentContainerElement().querySelector("button.btn-primary")}get buttons(){return this.primaryActionTitle?[super.buttons[0],{attributes:{type:"button",class:"btn btn-primary","data-onclick":"primaryAction"},text:this.primaryActionTitle}]:super.buttons}}class AdharaStorage{select(database_name,dataset_name){throw new Error("return a StorageOperator instance from this method. create a `class xStorageOperator extends AdharaStorageOperator{...}`")}}class AdharaStorageOperator{constructor(dataset){this.dataset=dataset}store(key,value){throw new Error("Override `store` method")}retrieve(key){throw new Error("Override `retrieve` method")}remove(key){throw new Error("Override `remove` method")}removeAll(){return this.removeMultiple(()=>!0)}removeMul