"use strict";const Orns=(e,t,n)=>{const r=new OrnCollection(e),i=r.element();if(!i)return void(Orn.debug&&console.log(`ORN: Container not found for selector "${e}"`,t,e));i.scope=new Proxy(t,OrnProxy);const a=(n=new OrnTemplate(void 0!==n?n:r.element())).ProcesS();for(;r.element().firstChild;)r.element().removeChild(r.element().firstChild);a.map(e=>{let n=t instanceof Array?t:[t];OrnParser.Output(OrnParser.Process(OrnParser.Clone(e),!1,0,n),r.element(),void 0!==t.svg)});for(var s=r.find("orn-component"),o=0;o<s.length;o++){let e=new OrnCollection(s[o]);if(void 0===e._Loaded){var l=new(new Function([],"return "+e.element().identifier)())(e.element(),e.element().shared);e.element().component=l,void 0!==l.Init&&l.Init(),e._Loaded=!0}}return r},Orn=async(e,t,n)=>{const r=new OrnCollection(e),i=r.element();if(!i)return void(Orn.debug&&console.log(`ORN: Container not found for selector "${e}"`,t,e));i.scope=new Proxy(t,OrnProxy),n=new OrnTemplate(void 0!==n?n:r.element());const a=await n.Process();for(;r.element().firstChild;)r.element().removeChild(r.element().firstChild);a.map(e=>{let n=t instanceof Array?t:[t];var i=OrnParser.Process(OrnParser.Clone(e),!1,0,n);OrnParser.Output(i,r.element(),void 0!==t.svg)});for(var s=r.find("orn-component"),o=0;o<s.length;o++){let e=new OrnCollection(s[o]);if(void 0===e._Loaded){e.attr("src")&&(await Orn.Include(e.attr("src")),e.attr("src",!1,!0));var l=new(new Function([],"return "+e.element().identifier)())(e.element(),e.element().shared);e.element().component=l,void 0!==l.Init&&await l.Init(),e._Loaded=!0}}for(s=r.find("orn-template"),o=0;o<s.length;o++){let e=s[o],n=e.getAttribute("src");if(n){if(!e._Loaded){var c=e.shared,h=[];t instanceof Array?(h=t).push(c):h=[t,c],await Orn(e,h,n),e._Loaded=!0}}else Orn.debug&&console.log("ORN: Template src not found:",e)}return r},OrnVoice={dispose:function(){},Get:(e,t)=>{Selector(e).css("orn-voice-input-active",!0);try{var n=n||webkitSpeechRecognition,r=new n;r.continuous=!1,r.interimResults=!1,r.lang="en-US",r.start(),r.onspeechend=()=>{r.stop(),Selector(e).css("orn-voice-input-active",!1)},r.onresult=e=>{for(var n=e.resultIndex;n<e.results.length;++n){var r=e.results[n][0].transcript.trim();e.results[n].isFinal&&t(r)}}}catch(e){}}},OrnProxy={get(e,t){if("isProxy"==t)return!0;if(e[t]instanceof Array){var n=[];return e[t].forEach(e=>{var t=new Proxy(e,OrnProxy);n.push(t)}),e[t]=n,e[t]}return"object"!=typeof e[t]||e[t].isProxy||null===e[t]?e[t]:new Proxy(e[t],OrnProxy)},set(e,t,n){e[t]=n,(r=Selector("input, textarea, select")).each(r=>{void 0!==r.__listen&&e==r.__listen.target&&t==r.__listen.key&&(r.value=n)});for(var r=OrnTemplate.TextNodes(document.body),i=0;i<r.length;i++){var a=r[i];void 0!==a.__listen&&-1!=a.__listen.keys.indexOf(t)&&a.__listen.target()}return!0}};Orn.Include=async e=>{if(Orn.Include.queue||(Orn.Include.queue={}),"string"==typeof e){var t=e;if(t.match(/\.css/)){if(!document.querySelector('link[href="'+t+'"]')){const e=document.createElement("link");e.type="text/css",e.rel="stylesheet",e.href=t,new OrnCollection("head").append(e)}}else{var n=document.querySelector('script[src="'+t+'"]');n?await new Promise((e,r)=>{Orn.Sleep((function(){return void 0===Orn.Include.queue[t]?(e(),!0):"ERROR"==Orn.Include.queue[t]&&(r(),n.parentNode.removeChild(n),!0)}))}):await new Promise((e,n)=>{var r=t.match(/\.js/);Orn.Include.queue[t]=!0;const i=document.createElement(r?"script":"img");i.onload=function(){delete Orn.Include.queue[t],e()},i.onerror=function(){Orn.Include.queue[t]="ERROR",n()},i.async=!0,r&&document.body.appendChild(i),i.src=t})}}else for(var r=0;r<e.length;r++)await Orn.Include(e[r])},Orn.Sleep=e=>{e()||setTimeout((function(){Orn.Sleep(e)}))};class OrnTemplate{constructor(e){this.template=e}async Process(){return this.IsElement()?this.Parse(this.template).children:this.IsURL()?await this.LoadHTML():this.VDOM(this.template)}async LoadHTML(){const e=this.template;if(void 0===OrnTemplate.cache[e]){OrnTemplate.cache[e]=!0;var t=await fetch(e,{cache:"force-cache"});if(!t.ok)throw Error(e+" not found or internet connection error.");t=await t.text(),OrnTemplate.cache[e]=this.VDOM(t)}return!0===OrnTemplate.cache[e]&&await new Promise((t,n)=>{Orn.Sleep((function(){return!0!==OrnTemplate.cache[e]&&(t(),!0)}))}),OrnTemplate.cache[e]}ProcesS(){return this.IsElement()?this.Parse(this.template).children:this.VDOM(this.template)}IsURL(){return!this.template.match(/(\<.*\>)|\n/gi)}IsElement(){return"string"!=typeof this.template}VDOM(e){let t=document.createElement("div");return t.innerHTML=e,this.Parse(t).children}Parse(e,t){var n={tag:e.nodeName.toLowerCase(),attributes:[]};if("#comment"!=n.tag){if("option"==n.tag&&(n.html=e.text),"#text"==n.tag)return n.text=e.textContent,n;if("style"==n.tag)return document.body.append(e),n;for(var r=0;r<e.attributes.length;r++){var i=e.attributes[r];if(n.attributes.push({name:i.name,value:i.value}),"orn-module"==i.name&&!t){var a=i.value;if(OrnTemplate.cache[a])return OrnTemplate.cache[a];OrnTemplate.cache[a]=this.Parse(e,!0)}}if("orn-component"==n.tag&&!t){let t=e.getAttribute("identifier");if(t&&!e.getAttribute("src")&&!e.getAttribute("orn-src"))return OrnTemplate.cache[t]||(OrnTemplate.cache[t]=this.Parse(e,!0)),OrnTemplate.cache[t]}n.children=[];for(var s=0;s<e.childNodes.length;s++){var o=e.childNodes[s];if("orn-component"!=o.nodeName.toLowerCase()||o.getAttribute("src")||o.getAttribute("orn-src"))l=this.Parse(o);else{let e=o.getAttribute("identifier");OrnTemplate.cache[e]||(OrnTemplate.cache[e]=this.Parse(o));var l={tag:OrnTemplate.cache[e].tag,attributes:OrnTemplate.cache[e].attributes}}n.children.push(l)}return n}}static TextNodes(e){var t=[];for(e=e.firstChild;e;e=e.nextSibling)3==e.nodeType?t.push(e):t=t.concat(OrnTemplate.TextNodes(e));return t}}class OrnCollection extends Array{constructor(e,t){super(),!t||t instanceof Array||(t=[t]),t=t||[document];for(let i=0;i<t.length;i++){var n=[];if(e instanceof Array)n=e;else if("object"==typeof e)n=[e];else if(e){var r=e.split(",");for(let e=0;e<r.length;e++)n=n.concat(Array.from(t[i].querySelectorAll(r[e])))}for(let e=0;e<n.length;e++)this.push(n[e])}}get(){return this}element(e){return!!this.length&&this[e||0]}parent(){return new OrnCollection(!!this.length&&this[0].parentNode)}first(){return new OrnCollection(this[0])}last(){return new OrnCollection(this[this.length-1])}next(){return new OrnCollection(this[0].nextSibling)}prev(){return new OrnCollection(this[0].previousSibling)}siblings(e){e=e||"*";var t=this,n=new OrnCollection(Array.from(this.length&&this.element().parentNode?this.element().parentNode.children:[]));return n.filter((function(n){return n!=t.element()&&n.matches(e)}))}empty(){return this.forEach(e=>{for(;e.firstChild;)e.removeChild(e.firstChild)}),this}remove(){this.forEach(e=>{e.parentNode&&e.parentNode.removeChild(e)})}css(e,t){if(void 0===t)return this.length&&this.element().classList.contains(e);const n=e.split(" ");return!1===t?(this.forEach(e=>{n.forEach(t=>{e.classList.remove(t)})}),this):(this.forEach(e=>{n.forEach(t=>{e.classList.add(t)})}),this)}style(e,t){return void 0===t?this.element().style.getPropertyValue(e):(this.forEach(n=>{!1===t&&n.style.removeProperty(e),n.style.setProperty(e,t)}),this)}toggle(e,t){return void 0!==t?this.forEach(n=>{n.innerHTML=n.innerHTML==t?e:t}):this.forEach(t=>{t.classList.toggle(e)}),this}hide(){return this.forEach(e=>{e.style.display="none"}),this}show(){return this.forEach(e=>{e.style.removeProperty("display")}),this}append(e,t){return this.forEach(n=>{if("string"==typeof e){var r=document.createElement("div");r.innerHTML=e.trim(),e=r.firstElementChild}void 0!==t&&n.firstChild?n.insertBefore(e,n.firstElementChild):n.append(e)}),this}html(e){return void 0===e?this.length?this.element().innerHTML:"":(this.forEach(t=>{t.innerHTML=e}),this)}find(e){return new OrnCollection(e,this)}attr(e,t,n){return t||n?(this.forEach(r=>{n?r.removeAttribute(e,t):r.setAttribute(e,t)}),this):this.element().getAttribute(e)}each(e){return this.forEach(t=>{e.call(t,t)}),this}event(e,t){return t?(this.forEach(n=>{n.addEventListener(e,e=>{t.call(n,e)})}),this):(this.forEach(t=>{var n=document.createEvent("HTMLEvents");n.initEvent(e,!0,!0),t.dispatchEvent(n)}),this)}delegate(e,t,n,r){this.each(i=>{i.addEventListener(t,t=>{for(var r=new OrnCollection(e),i=!1,a=t.target;a;)r.each(e=>{a==e&&(i=a,t.stopPropagation())}),a=a.parentNode;i&&n.call(i,t)},void 0!==r)})}offset(e){var t=this.element();return{width:t.offsetWidth,height:t.offsetHeight,left:t.offsetLeft,top:t.offsetTop}}children(e){var t=[];return this.each(e=>{t=t.concat(Array.from(e.children))}),new OrnCollection(t)}ancestor(e,t){let n=new OrnCollection(e).element();t||(t=this.element());var r=t.parentNode;return!(!r||r==document.body)&&(n==r?r:this.ancestor(e,r))}}class OrnParser{constructor(e,t,n,r,i){this.scope=i,this.node=e,this.parent=t,this.index=n,this.attribute=r}static Clone(e){var t;if(null==e||"object"!=typeof e)return e;if(e instanceof Date)return(t=new Date).setTime(e.getTime()),t;if(e instanceof Array){t=[];for(var n=0,r=e.length;n<r;n++)t[n]=OrnParser.Clone(e[n]);return t}if(e instanceof Object){for(var i in t={},e)e.hasOwnProperty(i)&&(t[i]=OrnParser.Clone(e[i]));return t}throw new Error("Unable to copy obj! Its type isn't supported.")}static Process(e,t,n,r){if(void 0===n&&(n=0),!e||!e.tag)return void(Orn.debug&&console.log("ORN: Invalid HTML tag",arguments));const i=e.tag;if("#comment"===i)return e;if("#text"===i){var a=e.text.match(/\{\{(.*?)\}\}/gi);if(null!==a){u=new OrnParser(e,t,n,!1,r);for(var s=[],o=[],l=0;l<a.length;l++){let t=a[l].replace(/\{\{|\}\}/gi,"");s.push(t);let n=u.Parse(t);e.text=e.text.replace(a[l],n);let r=t.split(".");o.push(r[r.length-1])}e.__listen=((e,t)=>n=>{n.__listen={keys:o,target:()=>{for(var r="",i=0;i<t.length;i++)r+=" "+e.Parse(t[i]);n.textContent=r}}})(u,s)}return e}var c=!1;const h=e.attributes.find(e=>"orn-repeat"==e.name);if(!h){for(let i=0;i<e.attributes.length;i++){let a=e.attributes[i];if(/^orn-/.test(a.name)&&!c){a.index=i;var u=new OrnParser(e,t,n,a,r);switch(!0){case"orn-module"===a.name:break;case/^orn-on/.test(a.name):u.OnEvent();break;case"orn-show"===a.name:u.Show();break;case"orn-model"===a.name:u.InputModel();break;case"orn-class"===a.name:u.CSSClass();break;case"orn-style"===a.name:u.CSSStyle();break;case"orn-if"===a.name:u.Condition()||(c=!0);break;case"orn-checked"===a.name||"orn-selected"===a.name||"orn-disabled"===a.name:u.InputState();break;default:u.Attribute()}}}if(e.children&&e.children.length)for(let t in e.children){var d=e.children[t];OrnParser.Process(d,e,t,r)}return e}h.index=e.attributes.indexOf(h),new OrnParser(e,t,n,h,r).Repeat()}static Output(e,t,n){if(e&&e.tag){if(!e.text){if(n)r=document.createElementNS("http://www.w3.org/2000/svg",e.tag);else var r=document.createElement(e.tag);if(e.html){var i=e.html;"function"==typeof e.html&&(i=e.html(r)),r.innerHTML=i}void 0!==e.__listen&&e.__listen(r);for(var a=0;a<e.attributes.length;a++){var s=e.attributes[a];void 0!==s.value&&(s.name[0]+s.name[1]==="on"?r.addEventListener(s.name.replace("on",""),function(e){return function(t){this.model&&this.model(t),"string"!=typeof e?e(t,r):new Function("a",e).call(this,t,r)}}(s.value)):"value"===s.name?r.value=s.value:"model"===s.name?(r.model=function(e){return function(t){this.event=t,"string"!=typeof e?e(this):new Function("a",e).call(this)}}(s.value),function(e,t){t.addEventListener("change",(function(e){this.model(e)})),t.addEventListener("keyup",(function(e){this.model(e)}))}(s.value,r)):"show"===s.name?(r.show=function(e){return function(){"string"!=typeof e?e(this):new Function("a",e).call(this)}}(s.value),r.setAttribute("orn-show","")):null!==s.value&&("function"==typeof s.value&&(s.value=s.value(r)),"object"!=typeof s.value&&"identifier"!=s.name||new Function(["value"],`this.${s.name} = value`).call(r,s.value),r.setAttribute(s.name,s.value)))}if(e.children)for(var o=0;o<e.children.length;o++)r.isOption="option"==e.tag,OrnParser.Output(e.children[o],r,n);return null!==e.position&&void 0!==e.position?t.insertBefore(r,t.childNodes[e.position]):t.appendChild(r),r}var l=e.text;if("function"==typeof e.text&&(l=e.text(r)),t.isOption)t.text=l;else{r=document.createTextNode(l);t.appendChild(r),void 0!==e.__listen&&e.__listen(r)}}}Parse(e){var t=e;const n=this.Args();try{t=new Function(n.arg,"return "+e).apply(this.scope[0],n.val)}catch(n){t=null,Orn.debug&&console.log(`ORN: Expression "${e}" not found in scope`,this.scope)}return t}Args(){const e={arg:[],val:[]};for(let t in this.scope)for(let n in this.scope[t])e.arg.push(n),e.val.push(this.scope[t][n]);return e.arg.push("event"),e.arg.push("element"),e.val.push(!1),e.val.push(!1),e}Repeat(){let e=this.attribute.value.split(" as "),t=this.Parse(e[0].replace(/ \n\t\r/gi,""));if(!t)return;e=e[1].replace(/ \n\t\r/gi,"").split(":");const n=e[0],r=e[1];var i=0;this.parent||console.log("orn-repeat must be in a container",this.attribute.value),this.parent.children[this.index]=!1;for(let e in t){if(!t.hasOwnProperty(e))return;var a=OrnParser.Clone(this.node);a.attributes.splice(this.attribute.index,1);let s={};s[n]=isNaN(e)?e:1*e,s[r]=t[e];let o=[...this.scope,s],l=OrnParser.Process(a,this.parent,0,o);l.position=1*this.index+i++,this.parent.children.push(l)}}Data(){let e=this.Parse(this.attribute.value);"object"==typeof e&&(e=JSON.stringify(e)),this.node.attributes[this.attribute.index]={name:this.attribute.name.replace("orn-",""),value:e}}OnEvent(){const e=this.Args();var t,n,r,i,a=this.attribute.value;if(a.match(/([a-xA-z]+[a-zA-z0-9_]*)\((.*?)\)/gi))try{let n=a.replace(/\((.*?)\)/gi,"");t=new Function(e.arg,`\n                            try{ \n                                return typeof this.${n}!='undefined' ? this.${a} : ${a}\n                            }catch(e){\n                                try{\n                                    return ${a};\n                                }catch(e){\n                                    \n                                }\n                            }\n                    `)}catch(e){return void(Orn.debug&&console.log(`ORN: orn-on expression "${a}" not found in provided scope:`,this.scope))}else t=new Function(e.arg,"return "+a.replace(/\n/g,""));this.node.attributes[this.attribute.index]={name:this.attribute.name.replace("orn-",""),value:(n=t,r=e.val,i=this,function(e,t){r[r.length-2]=e,r[r.length-1]=t,n.apply(i.scope[0],r)})}}Show(){var e,t;this.node.attributes[this.attribute.index]={name:"show",value:(e=this,t=this.attribute.value,function(n){var r=!1;try{r=new Function(["o"],"return o."+t)(e.scope[0])}catch(n){r=e.Parse(t)}r?n.style.removeProperty("display"):n.style.display="none"})}}InputModel(){var e=this.node.attributes.find(e=>"type"===e.name);this.node.attributes[this.attribute.index]={name:"model",value:((t,n)=>{var r=t.Parse(n);return i=>{switch(!0){case e&&("checkbox"==e.value||"radio"==e.value):if(r instanceof Array){var a=-1===r.indexOf(i.value);i.checked?a&&r.push(i.value):!a&&r.splice(r.indexOf(i.value),1)}else i.checked?r=i.value:"radio"!==i.type&&(r="");break;case"SELECT"===t.node.tag:if(i.multiple){r=[];for(var s=0;s<i.options.length;s++){var o=i.options[s];o.selected&&r.push(o.value||o.text)}}else r=i.value;break;default:r instanceof Array?-1===r.indexOf(i.value)&&r.push(i.value):r=i.value}var l=n.split("."),c=l.slice(0,l.length-1).join("."),h=l[l.length-1];return c=c.length?this.Parse(""+c):this.scope[0],new Proxy(c,OrnProxy)[h]=r,n}})(this,this.attribute.value)}}InputState(){this.Parse(this.attribute.value)&&(this.node.attributes[this.attribute.index]={name:this.attribute.name.replace("orn-",""),value:!0})}CSSClass(){var e=this.node.attributes.find(e=>"class"===e.name);e||(e={name:"class",value:""},this.node.attributes.push(e));var t=this.Parse(this.attribute.value);if(delete this.attribute.value,"string"==typeof t)e.value+=" "+t;else if("object"==typeof t)for(let n in t)t[n]&&(e.value+=" "+n);else"function"==typeof t&&(e.value+=" "+t(this.scope))}CSSStyle(){var e=this.node.attributes.find(e=>"style"===e.name);e||(e={name:"style",value:""},this.node.attributes.push(e));var t=this.Parse(this.attribute.value);if(delete this.attribute.value,"string"==typeof t)e.value+=";"+t;else if("object"==typeof t)for(let n in t)t[n]&&(e.value+=";"+n)}Condition(){var e=this.Parse(this.attribute.value);return delete this.attribute.value,!!e||(this.node.tag=!1,this.node.children=[],this.parent&&(this.parent.children[this.index]=!1),!1)}Attribute(){if("orn-value"===this.attribute.name){if("TEXTAREA"===this.node.tag)this.node.html=this.Parse(this.attribute.value);else{let e=this.Parse(this.attribute.value);this.node.attributes[this.attribute.index]={name:this.attribute.name.replace("orn-",""),value:e||""}}var e=this.attribute.value.split("."),t=e.slice(0,e.length-1).join(".");const r=this.Args();try{t=new Function(r.arg,"return "+t).apply(this.scope[0],r.val)}catch(e){}return t||(t=this.scope[0]),void(this.node.__listen=(n=t,t=>{t.__listen={key:e[e.length-1],target:n}}))}var n;let r=this.Parse(this.attribute.value);this.node.attributes[this.attribute.index]={name:this.attribute.name.replace("orn-",""),value:r||""}}}class FetchWrapper{constructor(e,t,n){void 0===t&&(t={}),void 0===n&&(n={}),n.noerror&&(this.noerror=!0),this.url=e,this.config={headers:{},credentials:"same-origin"},"undefined"!=typeof AbortController&&(this.controller=new AbortController,this.config.signal=this.controller.signal),n.post?(this.config.method="POST",this.config.body=Fetch.FD(t)):this.url=`${this.url}${-1==this.url.indexOf("?")?"?":"&"}${Fetch.QS(t)}`,n.offline&&(this.config.headers.offline=!0),n.persist&&(this.config.headers.persist=!0)}Abort(){this.controller&&this.controller.abort()}async Load(){var e=!1;try{if(!(e=await fetch(this.url,this.config)).ok)throw Error();e="application/json"==e.headers.get("content-type")?await e.json():await e.text()}catch(e){}return e}}var Selector=e=>new OrnCollection(e),Fetch=(e,t,n)=>new FetchWrapper(e,t,n);Fetch.QS=(e,t,n)=>{if(void 0===n&&(n=[]),!e||"object"!=typeof e||e instanceof Date||e instanceof File){const r=null==e?"":e;n.push(`${t}=${r}`)}else Object.keys(e).forEach(r=>{Fetch.QS(e[r],t?`${t}[${r}]`:r,n)});return t||(n=n.join("&")),n},Fetch.FD=(e,t,n)=>{if(void 0===n&&(n=new FormData),!e||"object"!=typeof e||e instanceof Date||e instanceof File){const r=null==e?"":e;n.append(t,r)}else Object.keys(e).forEach(r=>{Fetch.FD(e[r],t?`${t}[${r}]`:r,n)});return n},(()=>{OrnTemplate.cache={},Orn.debug=!1,OrnTemplate.cache={},setInterval((function(){let e=document.querySelectorAll('*[orn-show=""]');if(e)for(let t=0;t<e.length;t++)e[t].show&&e[t].show()}),50);try{document.createEvent("TouchEvent"),Orn.touch={}}catch(e){Orn.touch=!1}Selector("body").delegate(".orn-touch-listener","touchstart",(function(e){Orn.touch.moved=0,Orn.touch.starter=[],Orn.touch.started=[];for(var t=0;t<e.touches.length;t++){var n=e.touches[t];Orn.touch.starter.push({el:document.elementFromPoint(n.clientX,n.clientY)}),Orn.touch.started.push({x:n.clientX,y:n.clientY})}})),Selector("body").delegate(".orn-touch-listener","touchmove",(function(e){var t=document.elementFromPoint(e.touches[0].clientX,e.touches[0].clientY);t.dispatchEvent(new CustomEvent("touchover",{detail:{target:t}}))})),Selector("body").delegate(".orn-touch-listener","touchend",(function(e){var t=e.changedTouches[0].clientX-Orn.touch.started[0].x;e.changedTouches[0].clientY,Orn.touch.started[0].y,t>0&&this.dispatchEvent(new CustomEvent("touchmoveright",{detail:{target:this}})),t<0&&this.dispatchEvent(new CustomEvent("touchmoveleft",{detail:{target:this}}))}))})();