vaderjs 1.3.3-alpha-47 → 1.3.3-alpha-48
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/package.json +1 -1
- package/runtime/router.js +1 -1
- package/runtime/vader.js +1 -1
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("/"),
|
|
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):{},a={headers:{},params:o,query:n,path:t,method:r?r.method:"get"};window.$CURRENT_URL=a.path,window.$FULL_URL=window.location.href.replace("#","");const i={status:e,log:t=>{void 0===t?console.log(`${a.path} ${a.method} ${i.status} ${a.timestamp}`):console.table({"Request Path":a.path,"Request Method":r.method,"Response Status":i.status,"Request Timestamp":a.timestamp})},refresh:()=>{this.handleRoute(window.location.hash)},redirect:t=>{!t.startsWith("/")&&(t=`/${t}`),window.location.hash=`#${t}`},render:async(t,e,s)=>{try{let a=new Component;if("function"==typeof(r=t.default)&&/^class\s/.test(Function.prototype.toString.call(r))){let e=new t.default;a.state=e.state,console.log(a.state),a=e}else{let r=t.default.toString(),i=r.split("this.key")[1].split("=")[1].split('"')[1],l=(r.match(/return\s*`([\s\S]*)`/),r.split("return")[1].split("`")[0]);l=l.replace(/,\s*$/,""),a.key=i;let h={key:a.key,render:()=>t.default.apply?t.default.apply(a,[e,s]):new t.default,request:e,response:s,params:o,queryParams:n,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)};a.render=h.render,a=h}if(!document.querySelector("#root"))throw new Error("Root element not found, please add an element with id root");a.reset(),a.components={},a.request=e,a.response=s,a.router.use&&!a.isChild?await new Promise((async t=>{if(await a.router.use(e,s),e.pause){let s=setInterval((()=>{e.pause||(t(),clearInterval(s))}),1e3)}else t()})):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(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(a,i)})),r&&r.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=[];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 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");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;else{e.default&&(e=e.default);let s=new Component(t),o=e.toString(),i=o.includes("this.key")?o.split("this.key")[1].split("=")[1].split('"')[1]:null,u=(o.match(/return\s*`([\s\S]*)`/),o.split("return")[1].split("`")[0]);u=u.replace(/,\s*$/,""),t.children=n.join("");let a=e.apply(s,[t]);s.key=i,t.key=i,r={key:t.key?t.key:i,render:()=>a,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]=r),this.children.push(r),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 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(this.key)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{const e=document.querySelector(`[key="${this.key}"]`);if(e){let t=(new DOMParser).parseFromString(this.render(),"text/html").body.firstChild;e.replaceWith(t)}else console.error("Target element not found.")}}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+=this.key;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){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,useRef,useReducer,useState,strictMount};
|