vaderjs 1.3.3-alpha-52 → 1.3.3-alpha-54
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/README.md +11 -3
- package/package.json +1 -1
- package/runtime/router.js +1 -1
- package/runtime/vader.js +1 -1
package/README.md
CHANGED
|
@@ -84,11 +84,14 @@ import Mycomponent from './src/mycomponent.jsx'
|
|
|
84
84
|
export default class extends Component {
|
|
85
85
|
constructor() {
|
|
86
86
|
super();
|
|
87
|
-
this.key =
|
|
87
|
+
this.key = 2 // you can explicitly set key
|
|
88
88
|
}
|
|
89
89
|
render() {
|
|
90
90
|
return <>
|
|
91
|
-
|
|
91
|
+
${/**
|
|
92
|
+
or set it directly to the element and hydration will grab it
|
|
93
|
+
**/}
|
|
94
|
+
<div key={2}>
|
|
92
95
|
<p>Hello World</p>
|
|
93
96
|
</div>
|
|
94
97
|
<Mycomponent ..props />
|
|
@@ -106,11 +109,16 @@ Function based components
|
|
|
106
109
|
import Mycomponent from './src/mycomponent.jsx'
|
|
107
110
|
// function components have direct access to request and response both param way and using this.request or this.response!
|
|
108
111
|
export default function(req, res){
|
|
109
|
-
this.key = ''
|
|
112
|
+
this.key = '' // you can explicitly set key
|
|
110
113
|
|
|
111
114
|
return <>
|
|
115
|
+
${/**
|
|
116
|
+
or set it directly to the element and hydration will grab it
|
|
117
|
+
**/}
|
|
118
|
+
<div key="somevalue">
|
|
112
119
|
<h1>hello world</>
|
|
113
120
|
<Mycomponent ...props />
|
|
121
|
+
</div>
|
|
114
122
|
</>
|
|
115
123
|
}
|
|
116
124
|
|
package/package.json
CHANGED
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):{},
|
|
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;
|
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=[];export const strictMount=(e,t)=>{let n=setInterval((()=>{mounts.find((t=>t.key===e))&&(clearInterval(n),t())}),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
|
|
1
|
+
window.Vader={version:"1.3.3"},window.componentRegistry={};let errors={"SyntaxError: Unexpected token '<'":"You forgot to enclose tags in a fragment <></>"},mounts=[];export const strictMount=(e,t)=>{let n=setInterval((()=>{mounts.find((t=>t.key===e))&&(clearInterval(n),t())}),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 o=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");if(s(e.default?e.default:e))o.props=t,o.children=n,o.props.children=n.join(""),o.parentNode=this,o.request=this.request,o.response=this.response,o.key=t.key||null;else{e.default&&(e=e.default);let s=new Component(t),r=e.toString(),i=r.includes("this.key")?r.split("this.key")[1].split("=")[1].split('"')[1]:null,u=(r.match(/return\s*`([\s\S]*)`/),r.split("return")[1].split("`")[0]);u=u.replace(/,\s*$/,""),t.children=n.join("");let l=e.apply(s,[t]);s.key=i,t.key=i,o={key:t.key?t.key:i,render:()=>l,request:this.request,response:this.response,reset:s.reset.bind(s),onMount:s.onMount.bind(s),parentNode:this,useState:s.useState.bind(s),useReducer:s.useReducer.bind(s),useRef:s.useRef.bind(s),router:{use:s.router.use.bind(s)},bindMount:s.bindMount.bind(s),memoize:s.memoize.bind(s),createComponent:s.createComponent.bind(s),isChild:!0,parseStyle:s.parseStyle.bind(s),components:{},onUnmount:s.onUnmount.bind(s),onMount:s.onMount.bind(s),functions:[],memoizes:[]}}return this.components[t.key]||(this.components[t.key]=o),this.children.push(o),this.components[t.key]}reset(){console.log("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 o=e[s],r=t[s];o&&r&&!o.isEqualNode(r)&&n.push({type:"replace",old:o,new:r.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}"]`),o=this.domDifference(n,s);this.updateChangedElements(o)}else{let e=this.key?document.querySelector(`[key="${this.key}"]`):null,t=(new DOMParser).parseFromString(this.render(),"text/html").body.firstChild;if(!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');let n=e.querySelectorAll("*"),s=t.querySelectorAll("*"),o=this.domDifference(n,s);this.updateChangedElements(o)}}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,o,...r){s=s+this.key||2022;let i={},u=(o=o.replace(/,,/g,",")).replaceAll(",,",",");for(var l in r){let e=r[l];i[u.split(",")[l]]=e}o=o.replace(",,",",");let a=new Function(`${o}`,`\n return (async (${o}) => { \n ${e.toString()}\n })(${Object.keys(i).join(",")}) \n `);return a=a.bind(this),this.functions.find((e=>e.ref===s))||document.addEventListener(`$dispatch_#id=${s}`,(n=>{let{name:o,event:r}=n.detail;if(o===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(r,...Object.values(n)):a(...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,o)=>{this.state[e]=t,this.hydrate(o),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){return[(()=>this.state[e])(),t=>{const s=n?n(this.state[e],t):t;this.state[e]=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};
|