vaderjs 1.4.1-li7iuy47 → 1.4.1-lv56aadeg5
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/@integrations/ssg.js +15 -40
- package/README.md +5 -5
- package/binaries/main.js +4 -2
- package/package.json +1 -1
- package/runtime/router.js +1 -1
- package/runtime/vader.js +1 -1
package/@integrations/ssg.js
CHANGED
|
@@ -48,14 +48,15 @@ let server = http.createServer((req, res) => {
|
|
|
48
48
|
});
|
|
49
49
|
|
|
50
50
|
const generateHTML = (routeData) => {
|
|
51
|
+
console
|
|
51
52
|
|
|
52
|
-
let { path, file, isParam, params, query, pathname } = routeData;
|
|
53
|
+
let { path, file, isParam, params,kind, isCatchAll, query, pathname } = routeData;
|
|
54
|
+
console.log(path, file, isParam, isCatchAll, query, pathname)
|
|
53
55
|
let baseFolder = file.split('/').filter(f => f !== 'dist').join('/')
|
|
54
56
|
if (file.includes('./dist')) {
|
|
55
57
|
baseFolder = file.split('./dist')[1]
|
|
56
58
|
}
|
|
57
|
-
|
|
58
|
-
let isCatchAll = false;
|
|
59
|
+
|
|
59
60
|
|
|
60
61
|
let html = `
|
|
61
62
|
<!DOCTYPE html>
|
|
@@ -74,44 +75,16 @@ const generateHTML = (routeData) => {
|
|
|
74
75
|
import Router from '/router.js'
|
|
75
76
|
|
|
76
77
|
const rt = new Router
|
|
77
|
-
${
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
if (!param.jsFile) return "";
|
|
81
|
-
let ranName = Math.random()
|
|
82
|
-
.toString(36)
|
|
83
|
-
.substring(7)
|
|
84
|
-
.replace(".", "");
|
|
85
|
-
let pd = Object.keys(param.paramData)[0];
|
|
86
|
-
let baseFolder = path
|
|
87
|
-
.split("/")
|
|
88
|
-
.filter((f) => f !== "pages")
|
|
89
|
-
.join("/");
|
|
90
|
-
|
|
91
|
-
if(pd === '$catchall'){
|
|
92
|
-
isCatchAll = true;
|
|
93
|
-
console.log('catchall')
|
|
94
|
-
return `
|
|
95
|
-
import c${ranName} from '${param.jsFile}'
|
|
96
|
-
rt.get($SERVER ? '/' : '/${baseFolder}/*', c${ranName})
|
|
97
|
-
`
|
|
98
|
-
}
|
|
78
|
+
${Object.keys(routeData.params).length > 0 ? Object.keys(routeData.params).map((param, i) => {
|
|
79
|
+
return `rt.get('/${pathname}/:${param}', ' ${baseFolder}')`
|
|
80
|
+
}): ''}
|
|
99
81
|
|
|
100
|
-
return `
|
|
101
|
-
|
|
102
|
-
import c${ranName} from '${param.jsFile}'
|
|
103
|
-
rt.get('/${baseFolder}/:${pd}', c${ranName})
|
|
104
|
-
`;
|
|
105
|
-
})
|
|
106
|
-
.join("")
|
|
107
|
-
: ""
|
|
108
|
-
}
|
|
109
82
|
let c = await import('${baseFolder}')
|
|
110
83
|
if(Object.keys(c).includes('$prerender') && c.$prerender === false){
|
|
111
84
|
document.head.setAttribute('prerender', 'false')
|
|
112
85
|
}
|
|
113
86
|
${
|
|
114
|
-
!isCatchAll ? `rt.get($SERVER? '/' : '${pathname}', c)` :
|
|
87
|
+
!isCatchAll ? `rt.get($SERVER? '/' : '${pathname}', c)` : `rt.get($SERVER? '/' : '${pathname}/*', c)`
|
|
115
88
|
}
|
|
116
89
|
|
|
117
90
|
rt.listen()
|
|
@@ -129,6 +102,9 @@ const generateHTML = (routeData) => {
|
|
|
129
102
|
const ssg = async (config) => {
|
|
130
103
|
return new Promise(async (resolve, reject) => {
|
|
131
104
|
let { pages, output } = config;
|
|
105
|
+
if(!fs.existsSync(`${process.cwd()}/_dev/meta/routes.json`)){
|
|
106
|
+
process.exit()
|
|
107
|
+
}
|
|
132
108
|
let routes = JSON.parse(fs.readFileSync(`${process.cwd()}/_dev/meta/routes.json`).toString())
|
|
133
109
|
for (var i in routes) {
|
|
134
110
|
let route = routes[i];
|
|
@@ -169,12 +145,11 @@ const ssg = async (config) => {
|
|
|
169
145
|
}
|
|
170
146
|
})
|
|
171
147
|
}
|
|
172
|
-
|
|
173
|
-
if(context){
|
|
174
|
-
|
|
175
|
-
|
|
148
|
+
|
|
149
|
+
if(context){
|
|
150
|
+
server.listen(8700);
|
|
151
|
+
await ssg({ pages: './pages', output: './dist' })
|
|
176
152
|
}
|
|
177
|
-
|
|
178
153
|
|
|
179
154
|
export default {
|
|
180
155
|
name: 'Vaderjs Static Site Generator',
|
package/README.md
CHANGED
|
@@ -33,7 +33,7 @@ Tip: Each folder can be deep nested up to 4 levels!
|
|
|
33
33
|
/pages/index.jsx = /
|
|
34
34
|
/pages/home/[page].jsx = /home/:page
|
|
35
35
|
/pages/path/index.jsx = /path/
|
|
36
|
-
/pages/test/[...]/index.jsx = /path/test/*
|
|
36
|
+
/pages/test/[[...catchall]]/index.jsx = /path/test/*
|
|
37
37
|
/pages/route/[param1]/[param2].jsx = /path/route/:param1/:param2
|
|
38
38
|
```
|
|
39
39
|
Keyword folders - all files are passed from these folders to the `dist` folder
|
|
@@ -80,7 +80,7 @@ vader's compiler automatically handles routing so you wont need to! - it uses a
|
|
|
80
80
|
/pages/index.jsx = /
|
|
81
81
|
/pages/home/[page].jsx = /home/:page
|
|
82
82
|
/pages/path/index.jsx = /path/
|
|
83
|
-
/pages/path/[...].jsx = /path/*
|
|
83
|
+
/pages/path/[[...catchall]].jsx = /path/*
|
|
84
84
|
|
|
85
85
|
```
|
|
86
86
|
For pages that have [params] you can derive it using this.request
|
|
@@ -163,7 +163,7 @@ Vaderjs has two types of in javascript styling - css modules and inline jsx styl
|
|
|
163
163
|
```jsx
|
|
164
164
|
|
|
165
165
|
// inline
|
|
166
|
-
<button style={{color:'red'}}>Button</button>
|
|
166
|
+
<button style={{color:'red', "@mobile":{color:'green'}}}>Button</button>
|
|
167
167
|
|
|
168
168
|
// css module
|
|
169
169
|
|
|
@@ -203,12 +203,12 @@ export default class MyApp extends Component{
|
|
|
203
203
|
console.log(ref.current) // p tag
|
|
204
204
|
}, this)
|
|
205
205
|
return <>
|
|
206
|
-
<p ref={ref}>Count is {count}</p>
|
|
206
|
+
<p ref={ref}>Count is {count()}</p>
|
|
207
207
|
{/**
|
|
208
208
|
pass anything used from the toplevel render to the lowerlevel function params to be able to invoke!
|
|
209
209
|
**/}
|
|
210
210
|
<button onclick={()=>{
|
|
211
|
-
setCount(
|
|
211
|
+
setCount(count() + 1)
|
|
212
212
|
}}>Increment</button>
|
|
213
213
|
</>
|
|
214
214
|
|
package/binaries/main.js
CHANGED
|
@@ -148,6 +148,8 @@ const cssToObj = (css) => {
|
|
|
148
148
|
if (line.endsWith("{")) {
|
|
149
149
|
// Start of a block, extract the selector
|
|
150
150
|
currentSelector = line.slice(0, -1).trim();
|
|
151
|
+
currentSelector = currentSelector.replace(/-./g, (x) => x[1].toUpperCase());
|
|
152
|
+
currentSelector =currentSelector.replace('.', '')
|
|
151
153
|
styles[currentSelector] = {};
|
|
152
154
|
} else if (line.endsWith("}")) {
|
|
153
155
|
// End of a block
|
|
@@ -155,6 +157,7 @@ const cssToObj = (css) => {
|
|
|
155
157
|
} else if (line.includes(":") && currentSelector) {
|
|
156
158
|
// Inside a block and contains key-value pair
|
|
157
159
|
let [key, value] = line.split(":").map((part) => part.trim());
|
|
160
|
+
key = key.replace(/-./g, (x) => x[1].toUpperCase());
|
|
158
161
|
styles[currentSelector][key] = value;
|
|
159
162
|
}
|
|
160
163
|
});
|
|
@@ -172,8 +175,7 @@ function handleReplaceMents(data) {
|
|
|
172
175
|
path = path.replace(/'/g, "").trim().replace(/"/g, "").trim();
|
|
173
176
|
path = path.replaceAll(".jsx", ".js");
|
|
174
177
|
path = path.replaceAll("../", "");
|
|
175
|
-
let css = fs.readFileSync(process.cwd() + "/" + path, "utf8");
|
|
176
|
-
css = css.replaceAll(".", "");
|
|
178
|
+
let css = fs.readFileSync(process.cwd() + "/" + path, "utf8");
|
|
177
179
|
let styles = cssToObj(css);
|
|
178
180
|
let style = JSON.stringify(styles);
|
|
179
181
|
let newLine = `let ${name} = ${style}`;
|
package/package.json
CHANGED
package/runtime/router.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import t from"./vader.js";let e=[];export default class Router{constructor(t,e){this.routes=[],this.middlewares=[],this.errorMiddlewares=[],this.listeners=[],this.basePath=t}get(t,e){this.routes.push({method:"get",path:t,handler:e})}use(t){this.middlewares.push(t)}matchingRoute(){return routes.find((t=>t.url===window.location.pathname||window.location.pathname.split("/")[1]===t.url.split("/")[1]||void 0))}listen(t,e){t||(t=Math.random().toString(36).substring(7)),this.listeners.push(t),window.onpopstate=async t=>{
|
|
1
|
+
import t from"./vader.js";let e=[];export default class Router{constructor(t,e){this.routes=[],this.middlewares=[],this.errorMiddlewares=[],this.listeners=[],this.basePath=t}get(t,e){this.routes.push({method:"get",path:t,handler:e})}use(t){this.middlewares.push(t)}matchingRoute(){return routes.find((t=>t.url===window.location.pathname||window.location.pathname.split("/")[1]===t.url.split("/")[1]||void 0))}listen(t,e){t||(t=Math.random().toString(36).substring(7)),this.listeners.push(t),window.onpopstate=async t=>{let e=window.location.pathname;if(e.includes("#noNavigation"))return;let r=`/${e.split("/")[1]}`,n=(new DOMParser).parseFromString(await fetch(r,{cache:"reload"}).then((t=>t.text())),"text/html").documentElement,o=(n.querySelector("head"),n.querySelector("body"));document.querySelector("#app").innerHTML=o.querySelector("#app").innerHTML;let s=document.createElement("script");s.id="router",s.innerHTML=o.querySelector('script[id="router"]').innerHTML,s.setAttribute("type","module"),document.body.removeChild(document.getElementById("router")),document.body.appendChild(s)},window.location.pathname.includes("#noNavigation")||(console.log("no navigation"),this.handleRoute(window.location.pathname)),e&&e()}render(e){document.querySelector("#app").innerHTML="",t.render(e,document.querySelector("#app"))}extractParams(t,e){const r=t.split("/").filter((t=>""!==t)),n=e.split("/").filter((t=>""!==t)),o={};return r.forEach(((t,e)=>{if(t.startsWith(":")){const r=t.slice(1);o[r]=n[e]}else if(t.startsWith("*")){n.slice(e).forEach(((t,e)=>{o[e]=t}))}})),o}extractQueryParams(t){const e=t.split("?")[1];if(!e)return{};const r={};return e.split("&").forEach((t=>{const[e,n]=t.split("=");r[e]=n})),r}checkroute(t){return(t=t.endsWith("/")?t.slice(0,-1):t).includes("index.html")&&(t=t.replace("index.html","")),t.includes("?")&&(t=t.split("?")[0]),this.routes.find((e=>{if(console,e.path===t)return!0;if(""===t&&"/"===e.path)return!0;if(e.path.includes("*")||e.path.includes(":")){const r=e.path.split("/").filter((t=>""!==t)),n=t.split("/").filter((t=>""!==t));if(this.basePath&&n.shift(),console.log(r,n),r.length!==n.length&&!e.path.endsWith("*"))return!1;for(let t=0;t<r.length;t++){const e=r[t],o=n[t];if(!e.startsWith(":")&&!e.startsWith("*")&&e!==o)return!1}return!0}const r=this.extractParams(e.path,t);return Object.keys(r).length>0}))}handleRoute(r){let n=200,o={},s=r,a=this.checkroute(r);a||(n=404,a=this.routes.find((t=>"*"===t.path)),a&&(o=this.extractParams(a.path,r)));const i=this.extractQueryParams(s),l=a&&a.path?this.extractParams(a.path,s):o;Object.keys(l).forEach((t=>{l[t]=l[t].split("?")?l[t].split("?")[0]:l[t]}));const c={headers:{},params:l,query:i,path:r,fileUrl:window.location.href.split(window.location.origin)[1],url:window.location.href,method:a?a.method:"get",pause:!1,timestamp:Date.now()};window.$CURRENT_URL=c.path,window.$basePath=" ",window.$FULL_URL=window.location.href.replace("#","");const h={status:n,log:t=>{void 0===t?console.log(`${c.path} ${c.method} ${h.status} ${c.timestamp}`):console.table({"Request Path":c.path,"Request Method":a.method,"Response Status":h.status,"Request Timestamp":c.timestamp})},refresh:()=>{this.handleRoute(window.location.pathname)},redirect:t=>{!t.startsWith("/")&&(t=`/${t}`),window.history.pushState({},"",t),window.dispatchEvent(new Event("popstate"))},render:async e=>{e?.default&&(e=e.default),document.querySelector("#app").innerHTML="",t.render(e,document.querySelector("#app"),{passProps:{router:{req:c,res:h}}})},setQuery:t=>{if($SERVER)return;let e="";Object.keys(t).forEach(((r,n)=>{e+=`${0===n?"?":"&"}${r}=${t[r]}`}));let r=window.location.pathname.split("?")[0];e=e.replace("/","-").replaceAll("/","-"),c.query={...c.query,...t},window.history.pushState({},"",`${r}${e}`)},getQuery:t=>{let e=window.location.search,r=new URLSearchParams(e);return t?r.get(t.key):r},send:t=>{document.querySelector("#app").innerHTML=t},json:t=>{const e=document.querySelector("#app");e.innerHTML="";const r=document.createElement("pre");r.textContent=JSON.stringify(t,null,2),e.appendChild(r)}};e.forEach((t=>{t(c,h)})),a?h.render(a.handler):h.status(404).send("Not Found")}}
|
package/runtime/vader.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
let e=[],t={},r={};export const Mounted=(t,r,s=!1)=>{let n=setInterval((()=>{switch(!0){case s&&e.includes(r.key):return clearInterval(n);case s&&!e.includes(r.key):e.push(r.key),t();break;case!document.querySelector(`[key="${r.key}"]`):return;default:t(),clearInterval(n)}}),100)};export class Component{constructor(e){this.state=r[this.constructor.name]||{},this.__internalInstance=null,this.key=e?.key||Math.random(),this.checkMount(),this.mounted=!1,this.props=e,this.useKey=e=>{this.props.key=e,this.key=e}}setState(e){this.state=Object.assign({},this.state,e),this.updateInstance(this.__internalInstance)}useState(e,t){this.state[e]||(this.state[e]=t);let r=this.state[e];const state=()=>this.state[e];return[state,t=>{this.state[e]=t,this.updateInstance(this.__internalInstance),r=state()}]}useRef(e,t){return this.state[e]||(this.state[e]=t),{current:this.state[e]}}onMount(){}domDifference(e,t){let r=[];for(let s=0;s<e.length;s++){let n=e[s],a=t[s];n&&a&&n.childNodes.length>0&&a.childNodes.length>0&&r.push(...this.domDifference(Array.from(n.childNodes),Array.from(a.childNodes))),n.nodeValue!==a.nodeValue&&r.push({type:"replace",old:n,new:a})}return r}checkMount(){if(this.mounted)return;setInterval((()=>{document.querySelector(`[key="${this.key}"]`)&&!this.mounted&&(this.mounted=!0,this.onMount())}))}updateChangedElements(e){e.forEach((e=>{if(e)switch(e.type){case"replace":if(e.old.panrntNode&&"BODY"===e.old.parentNode.nodeName)return;e.old.replaceWith(e.new.cloneNode(!0));break;case"remove":e.old.remove();break;case"attributeSwap":let t=Array.from(e.old.attributes),r=Array.from(e.new.attributes);t.forEach((t=>{e.old.removeAttribute(t.name)})),r.forEach((t=>{e.old.setAttribute(t.name,t.value)}));break;case"add":e.old.appendChild(e.new.cloneNode(!0))}}))}updateInstance(e){let t=document.querySelector(`[key="${this.key}"]`)||document.querySelector("#app").firstChild,r=s.render(e,t,{return:!0}),n=this.domDifference(Array.from(t.childNodes),Array.from(r.childNodes));console.log(n),this.updateChangedElements(n)}parseStyle(e){let t="";return Object.keys(e).forEach((r=>{let s=e[r];r=r.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g,"$1-$2").toLowerCase(),t+=`${r}:${s};`})),t}}export const useState=e=>{this.state[key]||(this.state[key]=e);let t=this.state[key];const getUpdatedState=()=>this.state[key]||e;return t=getUpdatedState(),[getUpdatedState,e=>{t=e,this.state[key]=e,this.updateInstance(this.__internalInstance)}]};export const useReducer=(e,t)=>{const[r,s]=useState(t);return[r,t=>{const n=e(r,t);s(n)}]};export const useRef=e=>{this.state[key]||(this.state[key]=e);let t=this.state[key];return t=(()=>this.state[key]||e)(),[t,e=>{t=e,this.state[key]=e,this.updateInstance(this.__internalInstance)}]};export class Html extends Component{constructor(e){super(e),this.key=e?.key||"DOCUMENT_ROOT",this.props=e,this.checkMount()}render(){return $SERVER?(this.props.lang&&document.documentElement.setAttribute("lang",this.props.lang),s.createElement("div",{children:this.props.children,key:this.key})):s.createElement("div",{children:this.props.children,key:this.key})}onMount(){this.props?.parent&&this.props?.parent&&this.props.parent.onMount()}}export class Head extends Component{constructor(e){super(e),this.head=document.createElement("div"),this.useKey("head"),this.hasRefreshed=!1}render(){if($SERVER||this.props.refresh&&!t[this.key]){Array.isArray(this.props.children)&&this.props.children.forEach((e=>{let r=s.render(e,this.head,{return:!0}),n=this.head.querySelectorAll("*");for(let e=0;e<n.length;e++)n[e].isEqualNode(r)&&console.log("Equal");console.log(this.key,"key"),this.head.appendChild(r),t[this.key]=!0})),Object.keys(this.props).includes("children")&&!Array.isArray(this.props.children)&&this.head.appendChild(s.render(this.props.children,this.head,{return:!0}));let e=document.head;this.head.querySelectorAll("*").forEach((t=>{switch(t.tagName){case"TITLE":e.querySelector("title")&&e.querySelector("title").remove(),e.appendChild(t);break;case"META":return void(e.querySelector(`meta[name="${t.name}"]`)||e.appendChild(t));case"LINK":if($SERVER)return console.log("Server"),void(e.querySelector(`link[href="${t.href}"]`)||e.appendChild(t));case"SCRIPT":if(!t.hasAttribute("eager"))return void(document.querySelector(`script[src="${t.src}"]`)||e.appendChild(t));if(document.querySelector(`script[srcid="${t.src}"]`))return;fetch(t.src).then((e=>e.text())).then((r=>{let s=document.createElement("script");s.innerHTML=r,s.setAttribute("srcid",t.src),s.setAttribute("type",t.type),s.setAttribute("async",t.async||!1),s.setAttribute("defer",t.defer||!1),e.querySelector(`script[srcid="${t.src}"]`)||e.prepend(s)})).catch((e=>{console.warn("Error fetching script",e)}));break;default:console.warn("Unknown tag",t.tagName)}}))}return""}}export class Link extends Component{constructor(e){super(e),this.key=e?.key||Math.random(),this.props=e,this.checkMount()}render(){let e={...this.props,href:this.props?.href,onClick:e=>{switch(e.preventDefault(),!0){case"outside"===this.props.action:console.log("Outside"),e.preventDefault(),window.open(this.props.href,"_blank");break;case"function"==typeof this.props.action:this.props.action(e);break;default:e.preventDefault(),window.history.pushState({},"",this.props.href),window.dispatchEvent(new Event("popstate"))}},key:this.key};return s.createElement("a",e,this.props?.key,null)}}let s=new class vjsx{constructor(){this._vjsx=!0}isClass(e){return/^\s*class\s+/.test(e.toString())}instanizeClass(e,t={}){if("string"==typeof e||"object"==typeof e)return e;switch(this.isClass(e)){case!0:let s=new e(t);return r[e.name]=s.state,s.state=r[e.name],s.$$typeof="vjsx",s.type=e.name,s.key=t?.key||s.name,s.props=t,s.__internalInstance=()=>s.render(s.props),s.render();case!1:let n=new Component;n.key=e.name+Math.random(),e.$$typeof="vjsx",e.useState=n.useState.bind(n),e.setState=n.setState.bind(n),r[e.name]=n.state,n.state=r[e.name],e.state=n.state;let a={},o={};return t?.router&&(a=t.router.req,o=t.router.res),n.__internalInstance=()=>e.bind(n)(t,a,o),e.apply?e.apply(n,[t,a,o]):e}}createElement(e,t,r,...s){let n="function"==typeof e,a=s.find((e=>"vjsx"===e?.$$typeof));if(n)return t.key=r||t?.key||Math.random(),t.parent=a,this.instanizeClass(e,t);let o={type:e,RootParent:a,props:{...t,key:t?.key||Math.random(),children:Array.isArray(t.children)?t.children:[t.children]}};return"TEXT_ELEMENT"===("string"==typeof o?"TEXT_ELEMENT":o.type)?function createTextElement(e){return{type:"TEXT_ELEMENT",props:{nodeValue:e,children:[]}}}(o):o}render(e,t,r){let s=this.instanizeClass(e,r?.passProps);if(r&&r?.passProps&&r?.passProps?.router){let e=r.passProps.router.req;r.passProps.router.res;e.pause}if(!s.type)return;let n="TEXT_ELEMENT"===s.type?document.createTextNode(""):document.createElement(s.type),isListener=e=>e.startsWith("on");if(s.props&&(s.props.key&&(s.key=s.props.key),Object.keys(s.props).filter(isListener).forEach((e=>{let t=e.toLowerCase().substring(2);n.addEventListener(t,s.props[e].bind(s))})),Object.keys(s.props).filter((e=>!isListener(e))).forEach((e=>{switch(!0){case"className"===e||"class"===e||"classname"===e:n.setAttribute("class",s.props[e]),delete s.props[e];break;case"ref"===e:if(Array.isArray(s.props[e].current))return void s.props[e].current.push(n);s.props[e].current=n,n.removeAttribute("ref");break;case"htmlFor"===e:n.setAttribute("for",s.props[e]);break;case"style"===e:n.setAttribute("style",Component.prototype.parseStyle(s.props[e]));break;default:"children"!==e&&n.setAttribute(e,s.props[e])}"TEXT_ELEMENT"!==s.type||(n.nodeValue=s.props[e])}))),s.props&&s.props.children&&Array.isArray(s.props.children)&&s.props?.children&&s.props.children.forEach((e=>{if("number"!=typeof e&&"string"!=typeof e||(e=e.toString()),Array.isArray(e))return void e.forEach((e=>{null!==e&&this.render(e,n,!0)}));if(!e)return;let t="function"==typeof e?this.instanizeClass(e):e;"TEXT_ELEMENT"!==(t?.type?t.type:"TEXT_ELEMENT")?this.render(t,n):n.appendChild(document.createTextNode(t))})),r?.return)return n;s.key&&n.setAttribute("key",s.key),!r?.return&&document.body.contains(t)&&(s?.RootParent?.onMount(),t.innerHTML=""),t.appendChild(n)}},n={createElement:s.createElement,useState:useState,instanizeClass:s.instanizeClass,render:s.render,useRef:useRef,isClass:s.isClass,Head:Head,Html:Html,Mounted:Mounted,Component:Component,Link:Link};export default n;
|
|
1
|
+
let e=[],t={},s={};export const Mounted=(t,s,r=!1)=>{let n=setInterval((()=>{switch(!0){case r&&e.includes(s.key):return clearInterval(n);case r&&!e.includes(s.key):e.push(s.key),t();break;case!document.querySelector(`[key="${s.key}"]`):return;default:t(),clearInterval(n)}}),100)};export class Component{constructor(e){this.state=s[this.constructor.name]||{},this.__internalInstance=null,this.key=e?.key||Math.random(),this.checkMount(),this.mounted=!1,this.props=e,this.useKey=e=>{this.props.key=e,this.key=e}}setState(e){this.state=Object.assign({},this.state,e),this.updateInstance(this.__internalInstance)}useState(e,t){this.state[e]||(this.state[e]=t);let s=this.state[e];const state=()=>this.state[e];return[state,t=>{this.state[e]=t,this.updateInstance(this.__internalInstance),s=state()}]}useRef(e,t){return this.state[e]||(this.state[e]=t),{current:this.state[e]}}onMount(){}domDifference(e,t){let s=[];for(let r=0;r<e.length;r++){let n=e[r],a=t[r];n&&a&&n.childNodes.length>0&&a.childNodes.length>0&&s.push(...this.domDifference(Array.from(n.childNodes),Array.from(a.childNodes))),n.nodeValue!==a.nodeValue&&s.push({type:"replace",old:n,new:a})}return s}checkMount(){if(this.mounted)return;setInterval((()=>{document.querySelector(`[key="${this.key}"]`)&&!this.mounted&&(this.mounted=!0,this.onMount())}))}updateChangedElements(e){e.forEach((e=>{if(e)switch(e.type){case"replace":if(e.old.panrntNode&&"BODY"===e.old.parentNode.nodeName)return;e.old.replaceWith(e.new.cloneNode(!0));break;case"remove":e.old.remove();break;case"attributeSwap":let t=Array.from(e.old.attributes),s=Array.from(e.new.attributes);t.forEach((t=>{e.old.removeAttribute(t.name)})),s.forEach((t=>{e.old.setAttribute(t.name,t.value)}));break;case"add":e.old.appendChild(e.new.cloneNode(!0))}}))}updateInstance(e){let t=document.querySelector(`[key="${this.key}"]`)||document.querySelector("#app").firstChild,s=r.render(e,t,{return:!0}),n=this.domDifference(Array.from(t.childNodes),Array.from(s.childNodes));console.log(n),this.updateChangedElements(n)}parseStyle(e,t,s={useImportant:!1}){let r="",n=document.head.querySelector("#vader-stylesheet")||document.createElement("style");return n.setAttribute("id","vader-stylesheet"),Object.keys(e).forEach((a=>{let i=e[a],o="",l="";switch(!0){case a.includes("hover"):return o=a.split("hover(")[1].replace(/\)/g,""),l=`.${o}:hover{${this.parseStyle(i,t,{useImportant:!0})}};`,n.innerHTML.includes(l)||(n.innerHTML+=l),void t.classList.add(o);case a.includes("transition"):let e=`transition:${i} ${s.useImportant?" !important":""};`;r+=e;break;case a.includes("@mobile"):o=a.split("@mobile")[1].replace(/\(/g,"").replace(/\)/g,""),l=`@media (max-width: 768px){.${o}{${this.parseStyle(i,t,{useImportant:!0})}};}`,document.querySelector("#vader-stylesheet").innerHTML.includes(l)||(document.head.querySelector("#vader-stylesheet").innerHTML+=l),t.classList.add(o);break;case a.includes("@tablet"):o=a.split("@tablet")[1].replace(/\(/g,"").replace(/\)/g,""),l=`@media (min-width: 769px) and (max-width: 1024px){.${o}{${this.parseStyle(i,t,{useImportant:!0})}};}`,document.querySelector("#vader-stylesheet").innerHTML.includes(l)||(document.head.querySelector("#vader-stylesheet").innerHTML+=l),t.classList.add(o);break;case a.includes("@desktop"):o=a.split("@desktop")[1].replace(/\(/g,"").replace(/\)/g,""),l=`@media (min-width: 1025px){.${o}{${this.parseStyle(i,t,{useImportant:!0})}};}`,document.querySelector("#vader-stylesheet").innerHTML.includes(l)||(document.head.querySelector("#vader-stylesheet").innerHTML+=l),t.classList.add(o);break;case a.includes("transform"):let c=`transform:${i} ${s.useImportant?" !important":""};`;r+=c;break;case a.includes("animation"):r+=`animation:${i};`;break;case a.includes("active"):o=a.split("active(")[1].replace(/\)/g,""),l=`.${o}:active{${this.parseStyle(i,t,{useImportant:!0})}};`,n.innerHTML.includes(l)||(n.innerHTML+=l),t.classList.add(o);break;case a.includes("body"):let d=`body{${this.parseStyle(i,t)}};`;return void(document.head.querySelector("#vader-stylesheet").innerHTML.includes(`body{${this.parseStyle(i,t)}};`)||(document.head.querySelector("#vader-stylesheet").innerHTML+=d));case a.includes("focus"):o=a.split("focus(")[1].replace(/\)/g,"");let p=`.${o}:focus{${this.parseStyle(i,t,{useImportant:!0,noReturn:!0})}};`;n.innerHTML.includes(p)||(n.innerHTML+=p),t.classList.add(o);break;case a.includes("before"):o=a.split("before(")[1].replace(/\)/g,"");let h=`.${o}::before{${this.parseStyle(i,t,{useImportant:!0,noReturn:!0})}};`;n.innerHTML.includes(h)||(n.innerHTML+=h),t.classList.add(o);break;case a.includes("after"):o=a.split("after(")[1].replace(/\)/g,"");let u=`.${o}::after{${this.parseStyle(i,t,{useImportant:!0,noReturn:!0})}};`;n.innerHTML.includes(u)||(n.innerHTML+=u),t.classList.add(o);break;case a.includes("placeholder"):o=a.split("placeholder(")[1].replace(/\)/g,"");let y=`.${o}::placeholder{${this.parseStyle(i,t,{useImportant:!0,noReturn:!0})}};`;n.innerHTML.includes(y)||(n.innerHTML+=y),t.classList.add(o);break;case a.includes("first-child"):o=a.split("first-child(")[1].replace(/\)/g,"");let m=`.${o}:first-child{${this.parseStyle(i,t,{useImportant:!0,noReturn:!0})}};`;n.innerHTML.includes(m)||(n.innerHTML+=m),t.classList.add(o);break;case a.includes("last-child"):o=a.split("last-child(")[1].replace(/\)/g,"");let f=`.${o}:last-child{${this.parseStyle(i,t,{useImportant:!0,noReturn:!0})}};`;n.innerHTML.includes(f)||(n.innerHTML+=f),t.classList.add(o);break;case a.includes("nth-child"):o=a.split("nth-child(")[1].replace(/\)/g,"").split("(")[0];let k=`.${o}:nth-child(${a.split("nth-child(")[1].replace(/\)/g,"").split("(")[1]}){${this.parseStyle(i,t,{useImportant:!0,noReturn:!0})}};`;n.innerHTML.includes(k)||(n.innerHTML+=k),t.classList.add(o);break;case a.includes(">"):let b=`${a}{${this.parseStyle(i,t)}};`;n.innerHTML.includes(b)||(n.innerHTML+=b),t.classList.add(o)}a=a.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g,"$1-$2").toLowerCase(),r+=`${a}:${i} ${s.useImportant?" !important":""};`})),document.head.querySelector("#vader-stylesheet")||document.head.appendChild(n),r}}export const useState=e=>{this.state[key]||(this.state[key]=e);let t=this.state[key];const getUpdatedState=()=>this.state[key]||e;return t=getUpdatedState(),[getUpdatedState,e=>{t=e,this.state[key]=e,this.updateInstance(this.__internalInstance)}]};export const useReducer=(e,t)=>{const[s,r]=useState(t);return[s,t=>{const n=e(s,t);r(n)}]};export const useRef=e=>{this.state[key]||(this.state[key]=e);let t=this.state[key];return t=(()=>this.state[key]||e)(),[t,e=>{t=e,this.state[key]=e,this.updateInstance(this.__internalInstance)}]};export class Html extends Component{constructor(e){super(e),this.key=e?.key||"DOCUMENT_ROOT",this.props=e,this.checkMount()}render(){return $SERVER?(this.props.lang&&document.documentElement.setAttribute("lang",this.props.lang),r.createElement("div",{children:this.props.children,key:this.key})):r.createElement("div",{children:this.props.children,key:this.key})}onMount(){this.props?.parent&&this.props?.parent&&this.props.parent.onMount()}}export class Head extends Component{constructor(e){super(e),this.head=document.createElement("div"),this.useKey("head"),this.hasRefreshed=!1}render(){if($SERVER||this.props.refresh&&!t[this.key]){Array.isArray(this.props.children)&&this.props.children.forEach((e=>{let s=r.render(e,this.head,{return:!0}),n=this.head.querySelectorAll("*");for(let e=0;e<n.length;e++)n[e].isEqualNode(s)&&console.log("Equal");console.log(this.key,"key"),this.head.appendChild(s),t[this.key]=!0})),Object.keys(this.props).includes("children")&&!Array.isArray(this.props.children)&&this.head.appendChild(r.render(this.props.children,this.head,{return:!0}));let e=document.head;this.head.querySelectorAll("*").forEach((t=>{switch(t.tagName){case"TITLE":e.querySelector("title")&&e.querySelector("title").remove(),e.appendChild(t);break;case"META":return void(e.querySelector(`meta[name="${t.name}"]`)||e.appendChild(t));case"LINK":if($SERVER)return console.log("Server"),void(e.querySelector(`link[href="${t.href}"]`)||e.appendChild(t));case"SCRIPT":if(!t.hasAttribute("eager"))return void(document.querySelector(`script[src="${t.src}"]`)||e.appendChild(t));if(document.querySelector(`script[srcid="${t.src}"]`))return;fetch(t.src).then((e=>e.text())).then((s=>{let r=document.createElement("script");r.innerHTML=s,r.setAttribute("srcid",t.src),r.setAttribute("type",t.type),r.setAttribute("async",t.async||!1),r.setAttribute("defer",t.defer||!1),e.querySelector(`script[srcid="${t.src}"]`)||e.prepend(r)})).catch((e=>{console.warn("Error fetching script",e)}));break;default:console.warn("Unknown tag",t.tagName)}}))}return""}}export class Link extends Component{constructor(e){super(e),this.key=e?.key||Math.random(),this.props=e,this.checkMount()}render(){let e={...this.props,href:this.props?.href,onClick:e=>{switch(e.preventDefault(),!0){case"outside"===this.props.action:console.log("Outside"),e.preventDefault(),window.open(this.props.href,"_blank");break;case"function"==typeof this.props.action:this.props.action(e);break;default:e.preventDefault(),window.history.pushState({},"",this.props.href),window.dispatchEvent(new Event("popstate"))}},key:this.key};return r.createElement("a",e,this.props?.key,null)}}let r=new class vjsx{constructor(){this._vjsx=!0}isClass(e){return/^\s*class\s+/.test(e.toString())}instanizeClass(e,t={}){if("string"==typeof e||"object"==typeof e)return e;switch(this.isClass(e)){case!0:let r=new e(t);return s[e.name]=r.state,r.state=s[e.name],r.$$typeof="vjsx",r.type=e.name,r.key=t?.key||r.name,r.props=t,r.__internalInstance=()=>r.render(r.props),r.render();case!1:let n=new Component;n.key=e.name+Math.random(),e.$$typeof="vjsx",e.useState=n.useState.bind(n),e.setState=n.setState.bind(n),s[e.name]=n.state,n.state=s[e.name],e.state=n.state;let a={},i={};return t?.router&&(a=t.router.req,i=t.router.res),n.__internalInstance=()=>e.bind(n)(t,a,i),e.apply?e.apply(n,[t,a,i]):e}}createElement(e,t,s,...r){let n="function"==typeof e,a=r.find((e=>"vjsx"===e?.$$typeof));if(n)return t.key=s||t?.key||Math.random(),t.parent=a,this.instanizeClass(e,t);let i={type:e,RootParent:a,props:{...t,key:t?.key||Math.random(),children:Array.isArray(t.children)?t.children:[t.children]}};return"TEXT_ELEMENT"===("string"==typeof i?"TEXT_ELEMENT":i.type)?function createTextElement(e){return{type:"TEXT_ELEMENT",props:{nodeValue:e,children:[]}}}(i):i}render(e,t,s){let r=this.instanizeClass(e,s?.passProps);if(s&&s?.passProps&&s?.passProps?.router){let e=s.passProps.router.req;s.passProps.router.res;e.pause}if(!r.type)return;let n="TEXT_ELEMENT"===r.type?document.createTextNode(""):document.createElement(r.type),isListener=e=>e.startsWith("on");if(r.props&&(r.props.key&&(r.key=r.props.key),Object.keys(r.props).filter(isListener).forEach((e=>{let t=e.toLowerCase().substring(2);n.addEventListener(t,r.props[e].bind(r))})),Object.keys(r.props).filter((e=>!isListener(e))).forEach((e=>{switch(!0){case"className"===e||"class"===e||"classname"===e:n.setAttribute("class",r.props[e]),delete r.props[e];break;case"ref"===e:if(Array.isArray(r.props[e].current))return void r.props[e].current.push(n);r.props[e].current=n,n.removeAttribute("ref");break;case"htmlFor"===e:n.setAttribute("for",r.props[e]);break;case"style"===e:n.setAttribute("style",Component.prototype.parseStyle(r.props[e],n));break;default:"children"!==e&&n.setAttribute(e,r.props[e])}"TEXT_ELEMENT"!==r.type||(n.nodeValue=r.props[e])}))),r.props&&r.props.children&&Array.isArray(r.props.children)&&r.props?.children&&r.props.children.forEach((e=>{if("number"!=typeof e&&"string"!=typeof e||(e=e.toString()),Array.isArray(e))return void e.forEach((e=>{null!==e&&this.render(e,n,!0)}));if(!e)return;let t="function"==typeof e?this.instanizeClass(e):e;"TEXT_ELEMENT"!==(t?.type?t.type:"TEXT_ELEMENT")?this.render(t,n):n.appendChild(document.createTextNode(t))})),s?.return)return n;r.key&&n.setAttribute("key",r.key),!s?.return&&document.body.contains(t)&&(r?.RootParent?.onMount(),t.innerHTML=""),t.appendChild(n)}},n={createElement:r.createElement,useState:useState,instanizeClass:r.instanizeClass,render:r.render,useRef:useRef,isClass:r.isClass,Head:Head,Html:Html,Mounted:Mounted,Component:Component,Link:Link};export default n;
|