vaderjs 1.3.3-alpha-59 → 1.3.3-alpha-61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client/index.js CHANGED
@@ -1,17 +1,8 @@
1
- window.Vader = {
2
- version: "1.3.3",
3
- };
4
- window.componentRegistry = {};
5
- let errors = {
6
- "SyntaxError: Unexpected token '<'": "You forgot to enclose tags in a fragment <></>",
7
- }
8
-
9
- let mounts = [];
10
1
  /**
11
2
  * @method strictMount
12
3
  * @description This method allows you to await until the component is mounted before running a callback
13
- * @param {*} key
14
- * @param {*} callback
4
+ * @param {Component key} key
5
+ * @param {Function} callback
15
6
  */
16
7
  export const strictMount = (key, callback) => {
17
8
 
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "vaderjs",
3
3
  "description": "A Reactive library aimed to helping you build reactive applications inspired by react.js",
4
4
  "module": "vader.js",
5
- "version": "1.3.3-alpha-59",
5
+ "version": "1.3.3-alpha-61",
6
6
  "bin": {
7
7
  "vader": "./vader.js"
8
8
  },
package/runtime/router.js CHANGED
@@ -1 +1 @@
1
- import{Component}from"./vader.js";let middlewares=[];class VaderRouter{constructor(t,e){this.routes=[],this.middlewares=[],this.errorMiddlewares=[],this.listeners=[],this.basePath=t}get(t,e){this.routes.push({path:t,handler:e,method:"get"})}use(t){console.log(t),this.middlewares.push(t)}listen(t,e){t||(t=Math.random().toString(36).substring(7)),this.listeners.push(t),1===this.listeners.length?this.handleRoute(window.location.hash):this.listeners.pop(),e&&e(),window.onhashchange=()=>{this.handleRoute(window.location.hash)}}extractParams(t,e){const s=t.split("/"),r=e.split("/"),n={};return s.forEach(((t,e)=>{if(t.startsWith(":")){const s=t.slice(1);n[s]=r[e]}else if(t.startsWith("*")){r.slice(e).forEach(((t,e)=>{n[e]=t}))}})),n}extractQueryParams(t){const e=t.split("?")[1];if(!e)return{};const s={};return e.split("&").forEach((t=>{const[e,r]=t.split("=");s[e]=r})),s}handleRoute(t){let e=200,s=t=t.slice(1),r=this.routes.find((e=>{if(e.path===t)return!0;if(""===t&&"/"===e.path)return!0;if(t.includes("?")&&(t=t.split("?")[0]),e.path.includes("*")||e.path.includes(":")){const s=e.path.split("/"),r=t.split("/");if(s.length!==r.length&&!e.path.endsWith("*"))return!1;for(let t=0;t<s.length;t++){const e=s[t],n=r[t];if(!e.startsWith(":")&&!e.startsWith("*")&&e!==n)return!1}return!0}const r=this.extractParams(e.path,s);return Object.keys(r).length>0}));r||(r=this.routes.find((t=>{if(t.path.includes("/404"))return this.error=!0,!0;!this.error&&t.path.includes("/404")&&(window.location.hash=this.basePath)})),e=r?200:404);const n=this.extractQueryParams(s),o=r&&r.path?this.extractParams(r.path,s):{},i={headers:{},params:o,query:n,path:t,method:r?r.method:"get"};window.$CURRENT_URL=i.path,window.$FULL_URL=window.location.href.replace("#","");const a={status:e,log:t=>{void 0===t?console.log(`${i.path} ${i.method} ${a.status} ${i.timestamp}`):console.table({"Request Path":i.path,"Request Method":r.method,"Response Status":a.status,"Request Timestamp":i.timestamp})},refresh:()=>{this.handleRoute(window.location.hash)},redirect:t=>{!t.startsWith("/")&&(t=`/${t}`),window.location.hash=`#${t}`},render:async(t,e,s)=>{try{let i=new Component;if("function"==typeof(r=t.default)&&/^class\s/.test(Function.prototype.toString.call(r))){let e=new t.default;i.state=e.state,console.log(i.state),i=e}else{let r=t.default.toString(),a=r.split("this.key")[1]?r.split("this.key")[1].split("=")[1].split(";")[0].trim():r.split('key="')?r.split('key="')[1].split('"')[0]:null,l=(r.match(/return\s*`([\s\S]*)`/),r.split("return")[1].split("`")[0]);l=l.replace(/,\s*$/,""),i.key=a;let h={key:i.key,render:()=>t.default.apply?t.default.apply(i,[e,s]):new t.default,request:e,response:s,params:o,queryParams:n,reset:i.reset.bind(i),onMount:i.onMount.bind(i),useState:null,router:{use:i.router.use.bind(i)},bindMount:i.bindMount.bind(i),memoize:i.memoize.bind(i),createComponent:i.createComponent.bind(i),isChild:!1,useState:i.useState.bind(i),parseStyle:i.parseStyle.bind(i),bind:i.bind.bind(i),hydrate:i.hydrate.bind(i)};i.render=h.render,i=h}if(!document.querySelector("#root"))throw new Error("Root element not found, please add an element with id root");i.reset(),i.components={},i.request=e,i.response=s,i.router.use&&!i.isChild?await new Promise((async t=>{if(await i.router.use(e,s),e.pause){let s=setInterval((()=>{e.pause||(t(),clearInterval(s))}),1e3)}else t()})):i.router.use&&i.isChild&&console.warn("Router.use() is not supported in child components");const a=await i.render();document.querySelector("#root").innerHTML=a,i.bindMount(),i.onMount()}catch(t){console.error(t)}var r},setQuery:t=>{let e="";Object.keys(t).forEach(((s,r)=>{e+=`${0===r?"?":"&"}${s}=${t[s]}`}));let s=window.location.hash.split("?")[0];e=e.replace("/","-").replaceAll("/","-"),window.location.hash=`${s}${e}`},send:t=>{document.querySelector("#root").innerHTML=t},json:t=>{const e=document.querySelector("#root");e.innerHTML="";const s=document.createElement("pre");s.textContent=JSON.stringify(t,null,2),e.appendChild(s)}};middlewares.forEach((t=>{t(i,a)})),r&&r.handler(i,a)}}window.VaderRouter=VaderRouter;export default VaderRouter;
1
+ import{Component}from"./vader.js";let middlewares=[];class VaderRouter{constructor(e,t){this.routes=[],this.middlewares=[],this.errorMiddlewares=[],this.listeners=[],this.basePath=e}get(e,t){this.routes.push({path:e,handler:t,method:"get"})}use(e){console.log(e),this.middlewares.push(e)}listen(e,t){e||(e=Math.random().toString(36).substring(7)),this.listeners.push(e),1===this.listeners.length?this.handleRoute(window.location.hash):this.listeners.pop(),t&&t(),window.onhashchange=()=>{this.handleRoute(window.location.hash)}}extractParams(e,t){const s=e.split("/"),n=t.split("/"),r={};return s.forEach(((e,t)=>{if(e.startsWith(":")){const s=e.slice(1);r[s]=n[t]}else if(e.startsWith("*")){n.slice(t).forEach(((e,t)=>{r[t]=e}))}})),r}extractQueryParams(e){const t=e.split("?")[1];if(!t)return{};const s={};return t.split("&").forEach((e=>{const[t,n]=e.split("=");s[t]=n})),s}handleRoute(e){let t=200,s=e=e.slice(1),n=this.routes.find((t=>{if(t.path===e)return!0;if(""===e&&"/"===t.path)return!0;if(e.includes("?")&&(e=e.split("?")[0]),t.path.includes("*")||t.path.includes(":")){const s=t.path.split("/"),n=e.split("/");if(s.length!==n.length&&!t.path.endsWith("*"))return!1;for(let e=0;e<s.length;e++){const t=s[e],r=n[e];if(!t.startsWith(":")&&!t.startsWith("*")&&t!==r)return!1}return!0}const n=this.extractParams(t.path,s);return Object.keys(n).length>0}));n||(n=this.routes.find((e=>{if(e.path.includes("/404"))return this.error=!0,!0;!this.error&&e.path.includes("/404")&&(window.location.hash=this.basePath)})),t=n?200:404);const r=this.extractQueryParams(s),o=n&&n.path?this.extractParams(n.path,s):{},a={headers:{},params:o,query:r,path:e,url:window.location.href+e,method:n?n.method:"get",pause:e=>{a.pause=e},timestamp:Date.now()};window.$CURRENT_URL=a.path,window.$FULL_URL=window.location.href.replace("#","");const i={status:t,log:e=>{void 0===e?console.log(`${a.path} ${a.method} ${i.status} ${a.timestamp}`):console.table({"Request Path":a.path,"Request Method":n.method,"Response Status":i.status,"Request Timestamp":a.timestamp})},refresh:()=>{this.handleRoute(window.location.hash)},redirect:e=>{!e.startsWith("/")&&(e=`/${e}`),window.location.hash=`#${e}`},render:async(e,t,s)=>{function n(e){return"function"==typeof e&&/^class\s/.test(Function.prototype.toString.call(e))}try{let a=new Component;if(n(e.default)){let t=new e.default;a.state=t.state,console.log(a.state),a=t}else{let n=e.default.toString(),i=n.split("this.key")[1]?n.split("this.key")[1].split("=")[1].split(";")[0].trim():n.split('key="')?n.split('key="')[1].split('"')[0]:null,l=(n.match(/return\s*`([\s\S]*)`/),n.split("return")[1].split("`")[0]);l=l.replace(/,\s*$/,""),a.key=i;let u={key:a.key,render:()=>e.default.apply?e.default.apply(a,[t,s]):new e.default,request:t,response:s,params:o,queryParams:r,reset:a.reset.bind(a),onMount:a.onMount.bind(a),useState:null,router:{use:a.router.use.bind(a)},bindMount:a.bindMount.bind(a),memoize:a.memoize.bind(a),createComponent:a.createComponent.bind(a),isChild:!1,useState:a.useState.bind(a),parseStyle:a.parseStyle.bind(a),bind:a.bind.bind(a),hydrate:a.hydrate.bind(a),js:l};a.render=u.render,a=u}if(!document.querySelector("#root"))throw new Error("Root element not found, please add an element with id root");a.reset(),a.components={},a.request=t,a.response=s,a.router.use&&!a.isChild?await new Promise((async r=>{if(n(e.default))switch(await a.router.use(t,s),t.pause){case!0:console.log("pausing",t.pause);let e=setInterval((()=>{t.pause?console.log("still pausing",t.pause):(console.log("resuming"),clearInterval(e),r())}),1e3);break;case!1:r()}else switch(new Function("req","res",a.js).apply(a,[t,s]),await a.router.use(t,s),t.pause){case!0:console.log("pausing",t.pause);let e=setInterval((()=>{t.pause?console.log("still pausing request",t.url):(console.log("resuming"),clearInterval(e),r())}),1e3);break;case!1:r()}})):a.router.use&&a.isChild&&console.warn("Router.use() is not supported in child components");const i=await a.render();document.querySelector("#root").innerHTML=i,a.bindMount(),a.onMount()}catch(e){console.error(e)}},setQuery:e=>{let t="";Object.keys(e).forEach(((s,n)=>{t+=`${0===n?"?":"&"}${s}=${e[s]}`}));let s=window.location.hash.split("?")[0];t=t.replace("/","-").replaceAll("/","-"),window.location.hash=`${s}${t}`},send:e=>{document.querySelector("#root").innerHTML=e},json:e=>{const t=document.querySelector("#root");t.innerHTML="";const s=document.createElement("pre");s.textContent=JSON.stringify(e,null,2),t.appendChild(s)}};middlewares.forEach((e=>{e(a,i)})),n&&n.handler(a,i)}}window.VaderRouter=VaderRouter;export default VaderRouter;
package/runtime/vader.js CHANGED
@@ -1 +1 @@
1
- window.Vader={version:"1.3.3"},window.componentRegistry={};let errors={"SyntaxError: Unexpected token '<'":"You forgot to enclose tags in a fragment <></>"},mounts=[],hasRan=[];export const strictMount=(e,t)=>{let n=setInterval((()=>{document.querySelector(`[key="${e}"]`)&&!hasRan.includes(e)&&(clearInterval(n),t(),hasRan.push(e))}),120)};export class Component{constructor(){this.state={},this.key=null,this.components={},this.mounted=!1,this.checkIFMounted(),this.memoizes=[],this.functions=[],this.children=[],this.parentNode={},this.request={headers:{},method:"GET",params:{},path:"",query:{}},this.response={json:e=>{},send:e=>{},redirect:e=>{},render:async e=>{},log:e=>{},setQuery:e=>{}},this.router={use:e=>{}}}createComponent(e,t,n){function s(e){return"function"==typeof e&&/^class\s/.test(Function.prototype.toString.call(e))}let r=s(e)?new e(t):null;if(!e)throw new Error("Component must be defined");if(!t.key)throw new Error("new components must have a key");let o=new Component(t);if(s(e.default?e.default:e))r.props=t,r.children=n,r.props.children=n.join(""),r.parentNode=this,r.request=this.request,r.response=this.response,r.key=t.key||null,o=r;else{e.default&&(e=e.default);let s=e.toString(),i=s.split("this.key")[1]?s.split("this.key")[1].split("=")[1].split(";")[0].trim():s.split('key="')?s.split('key="')[1].split('"')[0]:null;t.children=n.join(""),o.key=i,t.key=i,r={key:t.key?t.key:i,render:()=>e.apply(o,[t]),request:this.request,response:this.response,reset:o.reset.bind(o),onMount:o.onMount.bind(o),parentNode:this,useState:o.useState.bind(o),useReducer:o.useReducer.bind(o),useRef:o.useRef.bind(o),router:{use:o.router.use.bind(o)},bindMount:o.bindMount.bind(o),memoize:o.memoize.bind(o),createComponent:o.createComponent.bind(o),isChild:!0,parseStyle:o.parseStyle.bind(o),components:{},onUnmount:o.onUnmount.bind(o),onMount:o.onMount.bind(o),hydrate:o.hydrate.bind(o),functions:[],memoizes:[],state:{}},o.render=r.render.bind(r),o=r}return this.components[t.key]||(this.components[t.key]=o),this.children.push(o),this.components[t.key]}reset(){Object.keys(this.components).forEach((e=>{this.components[e].onUnmount(),delete this.components[e]})),this.state={},this.children=[]}memoize(e){if(!e.key)throw new Error("Component must have a static key");if(!0==!this.memoizes.includes(e.key))this.memoizes.push(e.key),this.components[e.key]=e;let t=this.components[e.key];t.bindMount(),t.parentNode=this,t.props=e.props,t.request=this.request,t.response=this.response;let n=t.render();return n&&n.split(">,").length>1&&(n=n.replaceAll(">,",">")),`<div key="${e.key}">${n}</div>`}parseStyle(e){let t="";return Object.keys(e).forEach((n=>{let s=e[n];n=n.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g,"$1-$2").toLowerCase(),t+=`${n}:${s};`})),t}bindMount(){mounts.push(this)}domDifference(e,t){let n=[];for(let s=0;s<e.length;s++){let r=e[s],o=t[s];r&&o&&!r.isEqualNode(o)&&n.push({type:"replace",old:r,new:o.cloneNode(!0)})}return n}updateChangedElements(e){e.forEach((e=>{switch(e.type){case"replace":e.old.parentNode.replaceChild(e.new,e.old);break;case"remove":e.old.remove();break;case"add":e.old.appendChild(e.new.cloneNode(!0))}}))}hydrate(e){if(e){let t=(new DOMParser).parseFromString(this.render(),"text/html").body.firstChild,n=document.body.querySelectorAll(`[ref="${e}"]`),s=t.querySelectorAll(`[ref="${e}"]`),r=this.domDifference(n,s);this.updateChangedElements(r)}else{let e=this.key?document.querySelector(`[key="${this.key}"]`):null,t=(new DOMParser).parseFromString(this.render(),"text/html").body;if(t=document.createElement("div").appendChild(t),!e&&(e=document.querySelector(`[key="${t.attributes?.key?.value||null}"]`)),!e)return void console.error('Hydration failed, component not found got ensure you have set key="a value" on the component or this.key inside of function or render method body');t.querySelectorAll("*").forEach((e=>{e.attributes.length>0&&e.hasAttribute("key")&&document.querySelector(`[key="${e.attributes.key.value}"]`)&&e.innerHTML!==document.querySelector(`[key="${e.attributes.key.value}"]`).innerHTML&&document.querySelector(`[key="${e.attributes.key.value}"]`).replaceWith(e)}))}}patch(e,t){const n=this.domDifference(e,t);this.updateChangedElements(n)}handleObject(obj){try{obj=JSON.parse(obj)}catch(e){}return eval(obj)}bind(e,t,n,s,r,...o){s=s+this.key||2022;let i={},u=(r=r.replace(/,,/g,",")).replaceAll(",,",",");for(var a in o){let e=o[a];i[u.split(",")[a]]=e}r=r.replace(",,",",");let l=new Function(`${r}`,`\n return (async (${r}) => { \n ${e.toString()}\n })(${Object.keys(i).join(",")}) \n `);return l=l.bind(this),this.functions.find((e=>e.ref===s))||document.addEventListener(`$dispatch_#id=${s}`,(n=>{let{name:r,event:o}=n.detail;if(r===s){let n=this.functions.find((e=>e.ref===s)).params;Object.keys(n).forEach((e=>{n[e]instanceof CustomEvent&&delete n[e],void 0===n[e]?delete n[e]:n[e]})),t?e(o,...Object.values(n)):l(...Object.values(n))}})),window.callFunction=(e,t)=>{document.dispatchEvent(new CustomEvent(`$dispatch_#id=${e}`,{detail:{name:e,params:null,event:t}}))},this.functions.find((e=>e.ref===s))?!t&&(this.functions.find((e=>e.ref===s)).params=i):this.functions.push({ref:s,params:i}),n?e:`((event)=>{event.target.ev = event; callFunction('${s}', event.target.ev)})(event)`}useState(e,t){this.state[e]||(this.state[e]=t);let n=()=>this.state[e],s=n();return[s,(t,r)=>{this.state[e]=t,this.hydrate(r),s=n()}]}useRef(e=null,t){this.state[e]||(this.state[e]=t);return{bind:e+this.key,current:(()=>document.querySelector(`[ref="${e+this.key}"]`)||t)()}}useReducer(e=null,t,n=null){this.state[e]||(this.state[e]=t);const s=()=>this.state[e];let r=s();return[s(),(t,o)=>{const i=n(r,t)??t;this.state[e]=i,this.hydrate(o),r=s()}]}render(){}checkIFMounted(){new MutationObserver((e=>{e.forEach((e=>{e.target.querySelector(`[key="${this.key}"]`)&&!this.mounted&&(this.onMount(),this.mounted=!0),Array.from(e.removedNodes).find((e=>e.attributes&&e.attributes.key&&e.attributes.key.value===this.key))&&(this.onUnmount(),this.reset())}))})).observe(document.body,{childList:!0,subtree:!0})}onMount(){}onUnmount(){}}export const useState=(e,t)=>{states[e]||(states[e]=t);return[states[e],(t,n)=>{states[e]=t,this.hydrate(n)}]};export const useReducer=(e,t)=>[e,e=>{}];export const useRef=e=>({current:e,bind:""});export default{Component:Component,useRef:useRef,useReducer:useReducer,useState:useState,strictMount:strictMount};
1
+ window.Vader={version:"1.3.3"},window.componentRegistry={};let errors={"SyntaxError: Unexpected token '<'":"You forgot to enclose tags in a fragment <></>"},mounts=[],hasRan=[];export const strictMount=(e,t)=>{let n=setInterval((()=>{document.querySelector(`[key="${e}"]`)&&!hasRan.includes(e)&&(clearInterval(n),t(),hasRan.push(e))}),120)};export class Component{constructor(){this.state={},this.key=null,this.components={},this.mounted=!1,this.checkIFMounted(),this.memoizes=[],this.functions=[],this.children=[],this.parentNode={},this.request={headers:{},method:"GET",params:{},path:"",query:{}},this.response={json:e=>{},send:e=>{},redirect:e=>{},render:async e=>{},log:e=>{},setQuery:e=>{}},this.router={use:e=>{}}}createComponent(e,t,n){function s(e){return"function"==typeof e&&/^class\s/.test(Function.prototype.toString.call(e))}let r=s(e)?new e(t):null;if(!e)throw new Error("Component must be defined");let o=new Component(t);if(s(e.default?e.default:e))r.props=t,r.children=n,r.props.children=n.join(""),r.parentNode=this,r.request=this.request,r.response=this.response,r.key=t.key||null,o=r;else{e.default&&(e=e.default);let s=e.toString(),i=s.split("this.key")[1]?s.split("this.key")[1].split("=")[1].split(";")[0].trim():s.split('key="')?s.split('key="')[1].split('"')[0]:null;t.children=n.join(""),o.key=i,t.key=i,r={key:t.key?t.key:i,render:()=>e.apply(o,[t]),request:this.request,response:this.response,reset:o.reset.bind(o),onMount:o.onMount.bind(o),parentNode:this,useState:o.useState.bind(o),useReducer:o.useReducer.bind(o),useRef:o.useRef.bind(o),router:{use:o.router.use.bind(o)},bindMount:o.bindMount.bind(o),memoize:o.memoize.bind(o),createComponent:o.createComponent.bind(o),isChild:!0,parseStyle:o.parseStyle.bind(o),components:{},onUnmount:o.onUnmount.bind(o),onMount:o.onMount.bind(o),hydrate:o.hydrate.bind(o),functions:[],memoizes:[],bind:o.bind.bind(o),state:{}},o.render=r.render.bind(r),o=r}return this.components[t.key]||(this.components[t.key]=o),this.children.push(o),this.components[t.key]}reset(){Object.keys(this.components).forEach((e=>{this.components[e].onUnmount(),delete this.components[e]})),this.state={},this.children=[]}memoize(e){if(!e.key)throw new Error("Component must have a static key");if(!0==!this.memoizes.includes(e.key))this.memoizes.push(e.key),this.components[e.key]=e;let t=this.components[e.key];t.bindMount(),t.parentNode=this,t.props=e.props,t.request=this.request,t.response=this.response;let n=t.render();return n&&n.split(">,").length>1&&(n=n.replaceAll(">,",">")),`<div key="${e.key}">${n}</div>`}parseStyle(e){let t="";return Object.keys(e).forEach((n=>{let s=e[n];n=n.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g,"$1-$2").toLowerCase(),t+=`${n}:${s};`})),t}bindMount(){mounts.push(this)}domDifference(e,t){let n=[];for(let s=0;s<e.length;s++){let r=e[s],o=t[s];r&&o&&!r.isEqualNode(o)&&n.push({type:"replace",old:r,new:o.cloneNode(!0)})}return n}updateChangedElements(e){e.forEach((e=>{switch(e.type){case"replace":e.old.parentNode.replaceChild(e.new,e.old);break;case"remove":e.old.remove();break;case"add":e.old.appendChild(e.new.cloneNode(!0))}}))}hydrate(e){if(e){let t=(new DOMParser).parseFromString(this.render(),"text/html").body.firstChild,n=document.body.querySelectorAll(`[ref="${e}"]`),s=t.querySelectorAll(`[ref="${e}"]`),r=this.domDifference(n,s);this.updateChangedElements(r)}else{let e=this.key?document.querySelector(`[key="${this.key}"]`):null,t=(new DOMParser).parseFromString(this.render(),"text/html").body;if(t=document.createElement("div").appendChild(t),!e&&(e=document.querySelector(`[key="${t.attributes?.key?.value||null}"]`)),!e)return void console.error('Hydration failed, component not found got ensure you have set key="a value" on the component or this.key inside of function or render method body');t.querySelectorAll("*").forEach((e=>{e.hasAttribute("key")&&e.innerHTML!==document.querySelector(`[key="${e.attributes.key.value}"]`).innerHTML&&document.querySelector(`[key="${e.attributes.key.value}"]`).replaceWith(e)}))}}patch(e,t){const n=this.domDifference(e,t);this.updateChangedElements(n)}handleObject(obj){try{obj=JSON.parse(obj)}catch(e){}return eval(obj)}bind(e,t,n,s,...r){n=n+this.key||2022;let o={},i=(s=s.replace(/,,/g,",")).replaceAll(",,",",");for(var u in r){let e=r[u];o[i.split(",")[u]]=e}s=s.replace(",,",",");let a=null;try{a=new Function(`event, ${s}`,` \n return (async (event, ${s}) => { \n ${e.toString()}\n })(event, ${Object.keys(o).join(",")}) \n `)}catch(e){let{message:t}=e;console.error(`Error in function ${n} ${t}`)}return a=a.bind(this),this.functions.find((e=>e.ref===n))||document.addEventListener(`$dispatch_#id=${n}`,(e=>{let{name:t,event:s}=e.detail;if(t===n){let e=this.functions.find((e=>e.ref===n)).params;Object.keys(e).forEach((t=>{e[t]instanceof CustomEvent&&delete e[t],void 0===e[t]?delete e[t]:e[t]})),a(s,...Object.values(e))}})),window.callFunction=(e,t)=>{document.dispatchEvent(new CustomEvent(`$dispatch_#id=${e}`,{detail:{name:e,params:null,event:t}}))},!this.functions.find((e=>e.ref===n))&&this.functions.push({ref:n,params:o}),t?e:`((event)=>{event.target.ev = event; callFunction('${n}', event.target.ev)})(event)`}useState(e,t){this.state[e]||(this.state[e]=t);let n=()=>this.state[e],s=n();return[s,(t,r)=>{this.state[e]=t,this.hydrate(r),s=n()}]}useRef(e=null,t){this.state[e]||(this.state[e]=t);return{bind:e+this.key,current:(()=>document.querySelector(`[ref="${e+this.key}"]`)||t)()}}useReducer(e=null,t,n=null){this.state[e]||(this.state[e]=t);const s=()=>this.state[e];let r=s();return[s(),(t,o)=>{const i=n(r,t)??t;this.state[e]=i,this.hydrate(o),r=s()}]}render(){}checkIFMounted(){new MutationObserver((e=>{e.forEach((e=>{e.target.querySelector(`[key="${this.key}"]`)&&!this.mounted&&(this.onMount(),this.mounted=!0),Array.from(e.removedNodes).find((e=>e.attributes&&e.attributes.key&&e.attributes.key.value===this.key))&&(this.onUnmount(),this.reset())}))})).observe(document.body,{childList:!0,subtree:!0})}onMount(){}onUnmount(){}}export const useState=(e,t)=>{states[e]||(states[e]=t);return[states[e],(t,n)=>{states[e]=t,this.hydrate(n)}]};export const useReducer=(e,t)=>[e,e=>{}];export const useRef=e=>({current:e,bind:""});export default{Component:Component,useRef:useRef,useReducer:useReducer,useState:useState,strictMount:strictMount};
package/vader.js CHANGED
@@ -30,6 +30,8 @@ Object.keys(dirs).map((key, index) => {
30
30
 
31
31
  function Compiler(func, file) {
32
32
  let string = func;
33
+ // Remove block comments
34
+
33
35
  let returns = []
34
36
  let comments = string.match(/\{\s*\/\*.*\*\/\s*}/gs)?.map((comment) => comment.trim());
35
37
 
@@ -104,30 +106,59 @@ function Compiler(func, file) {
104
106
  let [, attributeName, attributeValue] = functionMatch;
105
107
  let attribute = {};
106
108
 
107
- if (attributeValue && attributeValue.includes("=>")) {
108
- let ref = Math.random().toString(36).substring(2);
109
- let old = `${attributeName}${attributeValue}`;
110
-
111
- //ex: (params)=>{console.log(params)} => console.log(params
112
- // do not split all =>
113
- let newvalue = attributeValue.split("=>").slice(1).join("=>").trim();
114
-
109
+ if (attributeValue && attributeValue.includes("=>") || attributeValue && attributeValue.includes("function")) {
110
+ let functionparams = [];
111
+ // ref with no numbers
112
+ let ref = Math.random().toString(36).substring(2).split('').filter((e) => !Number(e)).join('')
113
+ let old = `${attributeName}${attributeValue}`
114
+ functionNames.forEach((name) => {
115
+ string.split("\n").forEach((line) => {
116
+ if (line.includes(name) && line.includes("function")) {
117
+ line = line.trim();
118
+ line = line.replace(/\s+/g, " ");
119
+
120
+ let ps = line.split("(").slice(1).join("(").split(")")[0].trim();
121
+
122
+ // remove comments
123
+ ps = ps.match(/\/\*.*\*\//gs)
124
+ ? ps.replace(ps.match(/\/\*.*\*\//gs)[0], "")
125
+ : ps;
126
+ functionparams.push({ ref: ref, name: name, params: ps });
127
+
128
+ }
129
+ });
130
+ });
131
+ let elementMatch = string.match(/<([a-zA-Z0-9_-]+)([^>]*)>/gs);
132
+ let isJSXComponent = false;
133
+ elementMatch.forEach((element) => {
134
+ element = element.trim().replace(/\s+/g, " ");
135
+ if (element.includes(attributeName)) {
136
+ let elementTag = element
137
+ .split("<")[1]
138
+ .split(">")[0]
139
+ .split(" ")[0];
140
+ isJSXComponent = elementTag.match(/^[A-Z]/) ? true : false;
141
+ }
142
+ });
143
+ let newvalue = attributeValue.includes('=>') ? attributeValue.split("=>").slice(1).join("=>").trim() : attributeValue.split("function").slice(1).join("function").trim()
144
+
115
145
 
116
146
  newvalue = newvalue.trim();
117
147
 
118
148
  //remove starting {
119
149
  newvalue = newvalue.replace("{", "");
120
150
 
151
+
121
152
  let params = attributeValue
122
153
  .split("=>")[0]
123
154
  .split("(")[1]
124
155
  .split(")")[0]
125
156
  .trim();
157
+
158
+ // remove comments
126
159
  params = params.match(/\/\*.*\*\//gs)
127
160
  ? params.replace(params.match(/\/\*.*\*\//gs)[0], "")
128
- : params;
129
-
130
- let functionparams = [];
161
+ : params;
131
162
  // split first {}
132
163
  newvalue = newvalue.trim();
133
164
 
@@ -142,86 +173,30 @@ function Compiler(func, file) {
142
173
  case newvalue.endsWith("}"):
143
174
  newvalue = newvalue.replace("}", "");
144
175
  break;
176
+ }
177
+ // replace trailing }
178
+ newvalue = newvalue.trim();
179
+ if (newvalue.endsWith("}")) {
180
+ newvalue = newvalue.replace("}", "");
145
181
  }
146
-
147
-
148
-
149
- let currentParams = params
150
- let name = functionNames.map((name) => { return newvalue.includes(name) ? name : null }).filter(Boolean)[0]
151
- switch (true) {
152
- case name:
153
-
154
- if (newvalue.includes('function')) {
155
- return
156
- }
157
-
158
- name && string.split("\n").forEach((line) => {
159
- if (line.includes(name) && line.includes("function")) {
160
- line = line.trim();
161
- line = line.replace(/\s+/g, " ");
162
-
163
- let ps = line.split("(").slice(1).join("(").split(")")[0].trim();
164
-
165
- // remove comments
166
- ps = ps.match(/\/\*.*\*\//gs)
167
- ? ps.replace(ps.match(/\/\*.*\*\//gs)[0], "")
168
- : ps;
169
-
170
- functionparams.push({ ref: ref, name: name, params: ps });
171
- }
172
- });
173
- let isJSXComponent = false;
174
- let elementMatch = string.match(/<([a-zA-Z0-9_-]+)([^>]*)>/gs);
175
- elementMatch.forEach((element) => {
176
- element = element.trim().replace(/\s+/g, " ");
177
- if (element.includes(attributeName)) {
178
- let elementTag = element
179
- .split("<")[1]
180
- .split(">")[0]
181
- .split(" ")[0];
182
- isJSXComponent = elementTag.match(/^[A-Z]/) ? true : false;
183
- }
184
- });
185
-
186
- let functionParmas = functionparams.map((param) => { return param.params }).join(',')
187
- let suppliedParams = newvalue.split("(")[1].split(")")[0].trim();
188
-
189
- let replacement = `this.bind(${name}, true, ${isJSXComponent ? true : false}, '${ref}', "${functionParmas}", event, ${suppliedParams || null})`
190
- let newattribute = `${attributeName}="\${${replacement}}", usesEvent="true", eventType="${attributeName}",data-ref="${ref}", `
191
-
192
- string = string.replace(old, newattribute);
193
- break;
194
- default:
195
- let elementMatch1 = string.match(/<([a-zA-Z0-9_-]+)([^>]*)>/gs);
196
- let isJSXComponent1 = false;
197
- elementMatch1.forEach((element) => {
198
- element = element.trim().replace(/\s+/g, " ");
199
- if (element.includes(attributeName)) {
200
- let elementTag = element
201
- .split("<")[1]
202
- .split(">")[0]
203
- .split(" ")[0];
204
- isJSXComponent1 = elementTag.match(/^[A-Z]/) ? true : false;
205
- }
206
-
207
- });
208
-
209
-
210
- let otherdata = {};
211
- params ? (otherdata["params"] = params) : null;
212
- otherdata["jsx"] = isJSXComponent1;
213
- otherdata["ref"] = ref;
214
- // since js is all in one line split it
215
- newvalue = newvalue.split('\n').map(line => line.trim() ? line.trim() + ';' : line).join('\n');
216
- let paramString = params ? params.split(' ').map(param => param + ',').join('') : "";
217
- paramString = paramString.replaceAll(',,', ',')
218
- let jsxAttribute = `${attributeName}=function(${paramString}){${newvalue}}.bind(this),`
219
- let newattribute2 = `${attributeName}="\${this.bind(\`${newvalue}\`, false, ${isJSXComponent1 ? true : false}, '${ref}', "${paramString}", ${params || null})}", usesEvent="true", eventType="${attributeName}",data-ref="${ref}", `
220
- newattribute2 = newattribute2.replace(/\s+/g, " ")
221
- string = string.replace(old, isJSXComponent1 ? jsxAttribute : newattribute2);
222
- break;
223
- }
224
-
182
+ console.log(newvalue)
183
+ functionparams.length > 0 ? params = params + ',' + functionparams.map((e) => e.name).join(',') : null
184
+ newvalue = newvalue.split('\n').map(line => line.trim() ? line.trim() + ';' : line).join('\n');
185
+ newvalue = newvalue.replaceAll(',,', ',')
186
+ let paramnames = params ? params.split(',').map((e) => e.trim()) : null
187
+ paramnames = paramnames ? paramnames.filter((e) => e.length > 0) : null
188
+ // remove comments
189
+ paramnames = paramnames ? paramnames.map((e) => e.match(/\/\*.*\*\//gs) ? e.replace(e.match(/\/\*.*\*\//gs)[0], "") : e) : null
190
+
191
+ let bind = isJSXComponent ? `${attributeName}=function(${params}){${newvalue}}.bind(this)` : `${attributeName} = "\$\{this.bind("${newvalue.replace(/\s+g/, " ")}", ${isJSXComponent}, "${ref}", "${paramnames ? paramnames.map((e, index)=> {
192
+ if(e.length < 1) return ''
193
+ if(e.length > 0){
194
+ index == 0 ? e : ',' + e
195
+ }
196
+ return e
197
+ }) : ''}" ${params ? params.split(',').map((e) => e.trim()).filter(Boolean).map((e) => `,${e}`).join('') : ''})}"`
198
+ bind = bind.replaceAll(/\s+/g, " ");
199
+ string = string.replace(old, bind);
225
200
  }
226
201
  }
227
202
 
@@ -528,7 +503,21 @@ function Compiler(func, file) {
528
503
 
529
504
 
530
505
 
506
+ // replace all comments
507
+
531
508
  string = string.replaceAll('vaderjs/client', '/vader.js')
509
+ // replace ${... with ${
510
+
511
+ string = string.replaceAll(/\$\{[^{]*\.{3}/gs, (match) => {
512
+ if (match.includes('...')) {
513
+ // Your logic for replacement goes here
514
+ // For example, you can replace '...' with some other string
515
+ return match.replace('...', '');
516
+ }
517
+
518
+ return match;
519
+ });
520
+
532
521
  string = string.replaceAll("<>", "`").replaceAll("</>", "`");
533
522
  string = parseComponents(string);
534
523
 
@@ -539,6 +528,7 @@ function Compiler(func, file) {
539
528
 
540
529
  string = string.replaceAll('../src', './src')
541
530
  string += `\n\n //wascompiled`;
531
+
542
532
 
543
533
  string = string.replaceAll("undefined", "");
544
534
  const parse = (css) => {
@@ -585,7 +575,7 @@ function Compiler(func, file) {
585
575
  case path && path.includes('module.css'):
586
576
  let css = await fs.readFileSync(process.cwd() + path, 'utf8')
587
577
  css = css.replaceAll('.', '')
588
- console
578
+
589
579
  if (!name) {
590
580
  throw new Error('Could not find name for css module ' + path + ' at' + beforeimport + ' file' + file)
591
581
  }
@@ -761,7 +751,8 @@ async function Build() {
761
751
  ecma: " 2016",
762
752
  module: true,
763
753
  compress: true,
764
- mangle: true
754
+ mangle: true,
755
+ keep_fnames: true,
765
756
  })
766
757
  await writer(process.cwd() + "/dist/pages/" + fileName.replace('.jsx', '.js'), minified.code)
767
758
  } catch (error) {
@@ -829,6 +820,7 @@ async function Build() {
829
820
  ecma: " 2016",
830
821
  module: true,
831
822
  compress: true,
823
+ keep_fnames: true,
832
824
  })
833
825
  await writer(process.cwd() + "/dist/src/" + name.replace('.jsx', '.js'), minified.code)
834
826
  } catch (error) {