vaderjs 1.3.3-alpha-27 → 1.3.3-alpha-29

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.
Files changed (3) hide show
  1. package/package.json +1 -1
  2. package/runtime/router.js +54 -26
  3. package/vader.js +30 -16
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-27",
5
+ "version": "1.3.3-alpha-29",
6
6
  "bin": {
7
7
  "vader": "./vader.js"
8
8
  },
package/runtime/router.js CHANGED
@@ -101,9 +101,8 @@ class VaderRouter{
101
101
  if (part.startsWith(':')) {
102
102
  const paramName = part.slice(1);
103
103
  params[paramName] = hashParts[index];
104
- }else if(part.startsWith('*')){
105
- // remove queries from this par
106
- params[0] = hashParts.slice(index).join('/').split('?')[0];
104
+ }else if(part.startsWith('*')){
105
+ params[0] = hashParts.slice(index)
107
106
  }
108
107
  });
109
108
  return params;
@@ -131,38 +130,56 @@ class VaderRouter{
131
130
  handleRoute(hash) {
132
131
  hash = hash.slice(1);
133
132
  let status = 200;
133
+ let paramsCatchall = {}
134
134
  let route = this.routes.find((route) => {
135
-
136
135
  if (route.path === hash) {
137
136
  return true;
138
137
  }
139
- const routePathParts = route.path.split('/');
140
- const hashParts = hash.split('/');
141
- if (routePathParts.length !== hashParts.length) {
142
- return false;
143
- }else if(routePathParts[routePathParts.length-1].startsWith('*')){
138
+
139
+ if (route.path.includes('*') || route.path.includes(':')) {
140
+ const routeParts = route.path.split('/');
141
+ const hashParts = hash.split('/');
142
+
143
+ if (routeParts.length !== hashParts.length && !route.path.endsWith('*')) {
144
+ return false;
145
+ }
146
+
147
+ for (let index = 0; index < routeParts.length; index++) {
148
+ const routePart = routeParts[index];
149
+ const hashPart = hashParts[index];
150
+
151
+ if (routePart.startsWith(':') || routePart.startsWith('*')) {
152
+
153
+ continue;
154
+ }
155
+
156
+ if (routePart !== hashPart) {
157
+
158
+ return false;
159
+ }
160
+ }
161
+
144
162
  return true;
145
163
  }
146
- const params = this.extractParams( route.path, hash);
164
+
165
+ const params = this.extractParams(route.path, hash);
147
166
  return Object.keys(params).length > 0;
148
167
  });
149
168
 
169
+
150
170
  if (!route) {
151
- route = this.routes.find((route) => {
171
+ route = this.routes.find((errorRoute) => {
172
+ if (errorRoute.path === '/404') {
173
+ this.error = true;
174
+ return true;
175
+ } else if (!this.error && errorRoute.path !== '/404') {
152
176
 
153
- if(route.path === '/404'){
154
- return true;
155
- }else{
156
- window.location.hash = this.basePath
157
- }
177
+ }
158
178
  });
159
-
160
- route ? status = 200 :
161
-
162
- status = 404;
179
+
180
+ status = route ? 200 : 404;
163
181
  }
164
-
165
-
182
+
166
183
  const queryParams = this.extractQueryParams(hash);
167
184
  const params = route && route.path ? this.extractParams(route.path, hash) : {};
168
185
  const req = {
@@ -204,8 +221,8 @@ class VaderRouter{
204
221
  },
205
222
  render: async (/**@type {Component} */ Component, req, res) => {
206
223
 
207
- if(!Component.default || !Component.constructor){
208
- let message = !Component.default ? 'default' : 'constructor';
224
+ if(!Component || !Component.default || !Component.constructor){
225
+ let message = !Component || !Component.default ? 'default' : 'constructor';
209
226
  switch(message){
210
227
  case 'default':
211
228
  throw new Error(`Component must have a default export ex: return {default: Component}`);
@@ -225,6 +242,7 @@ class VaderRouter{
225
242
  if(!document.querySelector('#root')){
226
243
  throw new Error('Root element not found, please add an element with id root');
227
244
  }
245
+ Component.router.use = this.use.bind(this)
228
246
  Component.state = {}
229
247
  Component.reset();
230
248
  Component.components = {}
@@ -234,6 +252,16 @@ class VaderRouter{
234
252
  Component.bindMount();
235
253
  Component.onMount()
236
254
 
255
+
256
+ },
257
+ setQuery: (query) => {
258
+ let queryString = '';
259
+ Object.keys(query).forEach((key, index) => {
260
+ queryString += `${index === 0 ? '?' : '&'}${key}=${query[key]}`;
261
+ });
262
+ let route = window.location.hash.split('?')[0];
263
+ queryString = queryString.replace('/', '-').replaceAll('/', '-')
264
+ window.location.hash = `${route}${queryString}`;
237
265
  },
238
266
  send: (data) => {
239
267
  document.querySelector('#root').innerHTML = data;
@@ -250,16 +278,16 @@ class VaderRouter{
250
278
  }else{
251
279
  throw new Error('Selector must be a string');
252
280
  }
253
- },
281
+ }
254
282
  };
255
283
  this.middlewares.forEach((middleware) => {
256
284
  middleware(req, res);
257
285
  });
258
286
 
259
287
  route ? route.handler(req, res) : null;
260
-
261
288
  }
262
289
 
290
+
263
291
  }
264
292
 
265
293
  window.VaderRouter = VaderRouter;
package/vader.js CHANGED
@@ -98,8 +98,10 @@ function Compiler(func) {
98
98
  let ref = Math.random().toString(36).substring(2);
99
99
  let old = `${attributeName}${attributeValue}`;
100
100
 
101
- let newvalue =
102
- attributeValue.split("=>")[1] || attributeValue.split("=>")[1].trim();
101
+ //ex: (params)=>{console.log(params)} => console.log(params
102
+ // do not split all =>
103
+ let newvalue = attributeValue.split("=>").slice(1).join("=>").trim();
104
+
103
105
 
104
106
  newvalue = newvalue.trim();
105
107
 
@@ -574,8 +576,8 @@ function Compiler(func) {
574
576
  .replaceAll(`={\``, ':`')
575
577
  .replaceAll('`}', '`')
576
578
  .replaceAll(",,", ',')
577
-
578
- .replaceAll(/=([A-z])/g, ":$1")
579
+ .replaceAll(/=(?=(?:(?:[^"']*["'][^"']*['"])*[^"']*$))/g, ':');
580
+
579
581
  props = props.replace(/:('[^']*'|"[^"]*")/g, ':$1,');
580
582
  // ANY VALUE NUMBER BOOLEAN OR STRING
581
583
  props = props.replace(/=(\d+)/g, ':$1,');
@@ -644,29 +646,42 @@ async function Build() {
644
646
  });
645
647
 
646
648
  // Process files in the 'pages' directory
649
+ let appjs = '';
650
+ let hasWritten = []
651
+ const writejs = () =>{
652
+ writer(process.cwd() + '/dist/app.js', appjs)
653
+ }
647
654
  for await (let file of glb) {
648
655
  // Normalize file paths
649
656
  let origin = file.replace(/\\/g, '/');
650
657
  let fileName = origin.split('/pages/')[1].split('.jsx')[0].replace('.jsx', '') + '.jsx';
651
658
  let isBasePath = fileName === 'index.jsx';
652
659
 
653
- // Extract URL-related information from the file path
654
- let aburl = origin.split('pages')[1].split('.jsx')[0].replace('.jsx', '').replace('/index', '').replace('/_', '/:').replace('/[', '/:').replace(']', '');
655
- aburl.includes('[') ? aburl = '/' + aburl.split('[')[0].replace('/', '') : null;
660
+ // Extract all dynamic parameters from the file path [param1]/[param2]/[param3
661
+ let aburl = origin.split('/pages')[1].split('.jsx')[0].replace('.jsx', '').split('[').join(':').split(']').join('');
662
+
663
+ if(aburl.includes('...')){
664
+ // this is a catch all route
665
+ // it should be /pages/[...]/index.jsx or /pages/[...].jsx
666
+ aburl = aburl.split('...').join('*').split(':*').join('*')
667
+ aburl = aburl.replaceAll('./index', '')
668
+
669
+ }
656
670
 
657
671
  // Create an object with URL and pathname properties
658
672
  let obj = {
659
- url: isBasePath ? '/' : aburl,
673
+ url: isBasePath ? '/' : aburl.replaceAll('index', ''),
660
674
  pathname: `/pages/${origin.split('pages/')[1].split('.jsx')[0].replace('.jsx', '')}.jsx`,
661
675
  fullpath: origin,
662
676
  };
663
677
 
678
+
664
679
  // Read and compile file content
665
680
  let data = await fs.readFileSync(origin, "utf8");
666
681
  data = Compiler(data)
667
682
 
668
683
  await writer(process.cwd() + "/dist/pages/" + fileName, data);
669
-
684
+
670
685
  // Generate routing logic
671
686
  let js = `
672
687
  router.get('${obj.url}', async (req, res) => {
@@ -674,13 +689,11 @@ async function Build() {
674
689
  })
675
690
  //@desc ${obj.pathname}
676
691
  ` + '\n';
677
-
678
- // Update 'app.js' file with routing logic
679
- let before = fs.existsSync(process.cwd() + "/dist/app.js") ? await reader(process.cwd() + "/dist/app.js") : '';
680
- let newfile = before + '\n' + js;
681
- if (!before.includes(`//@desc ${obj.pathname}`)) {
682
- await writer(process.cwd() + "/dist/app.js", newfile);
683
- }
692
+ appjs += js
693
+
694
+ writejs()
695
+
696
+
684
697
 
685
698
  let beforeHTML = fs.existsSync(process.cwd() + "/dist/index.html") ? await reader(process.cwd() + "/dist/index.html") : '';
686
699
  if(!beforeHTML.includes(`<link rel="prefetch" href="/pages/${origin.split('pages/')[1] }" as="fetch">`)){
@@ -688,6 +701,7 @@ async function Build() {
688
701
  await writer(process.cwd() + "/dist/index.html", newHTML);
689
702
  }
690
703
  }
704
+
691
705
 
692
706
 
693
707
  const scannedSourceFiles = await glob("**/**.{jsx,js}", {