vaderjs 1.7.1 → 1.7.2

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 (2) hide show
  1. package/index.ts +107 -122
  2. package/package.json +1 -1
package/index.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  //@ts-nocheck
2
- let isClassComponent = function(element) {
2
+ let isClassComponent = function (element) {
3
3
  return element.toString().startsWith("class");
4
4
  };
5
5
 
@@ -29,8 +29,8 @@ declare global {
29
29
  * console.log(params.name) // John
30
30
  * console.log(params.age) // 20
31
31
  */
32
- let params: { [key: string]: string };
33
- let localStorage : []
32
+ let params: { [key: string]: string };
33
+ let localStorage: []
34
34
  }
35
35
  //@ts-ignore
36
36
  globalThis.isServer = typeof window === "undefined";
@@ -61,10 +61,10 @@ export const useFetch = (url: string, options: any) => {
61
61
  * @returns
62
62
  */
63
63
  export const useAsyncState = (promise: Promise<any>) => {
64
- return [null, () => {}];
64
+ return [null, () => { }];
65
65
  }
66
- export const useEffect = (callback:any, dependencies: any[] = []) => {
67
- dependencies = dependencies.map((dep) => JSON.stringify(dep));
66
+ export const useEffect = (callback: any, dependencies: any[] = []) => {
67
+ dependencies = dependencies.map((dep) => JSON.stringify(dep));
68
68
  if (dependencies.length === 0) {
69
69
  callback();
70
70
  }
@@ -73,7 +73,7 @@ export const useEffect = (callback:any, dependencies: any[] = []) => {
73
73
  // make a switch function component
74
74
 
75
75
 
76
- export const A = (props: {
76
+ export const A = (props: {
77
77
  /**
78
78
  * @description Set the elements classlist
79
79
  */
@@ -87,28 +87,28 @@ export const A = (props: {
87
87
  onClick: () => void;
88
88
  onChange: () => void;
89
89
  }, children: any) => {
90
- function handleClick(e) {
90
+ function handleClick(e) {
91
91
  e.preventDefault();
92
- if(props.openInNewTab){
92
+ if (props.openInNewTab) {
93
93
  window.open(props.href, "_blank");
94
94
  return void 0;
95
95
  }
96
96
  window.history.pushState({}, "", props.href);
97
97
  window.dispatchEvent(new PopStateEvent("popstate"));
98
98
  window.location.reload();
99
- return void 0;
100
- }
101
- return {
99
+ return void 0;
100
+ }
101
+ return {
102
102
  type: "a",
103
- props: {...props, onClick: handleClick},
103
+ props: { ...props, onClick: handleClick },
104
104
  children: children || [],
105
105
  }
106
106
  }
107
107
 
108
108
 
109
109
  export const Fragment = (props: any, children: any) => {
110
- return {
111
- type:null,
110
+ return {
111
+ type: null,
112
112
  props: props,
113
113
  children
114
114
  }
@@ -136,14 +136,12 @@ export const e = (element, props, ...children) => {
136
136
  instance = new Component;
137
137
  instance.render = element;
138
138
  instance.Mounted = true;
139
- let firstEl = instance.render({key: instance.key, children: children, ...props}, children);
139
+ let firstEl = instance.render({ key: instance.key, children, ...props }, children);
140
140
  instance.children = children;
141
- if (!firstEl) {
142
- return {type: "div", props: {key: instance.key, ...props}, children: children};
143
- }
144
-
145
- firstEl.props = { key: instance.key, ...firstEl.props, ...props };
146
- return { type: "ghost", props:{}, children: [firstEl]}
141
+ if (!firstEl)
142
+ firstEl = { type: "div", props: { key: instance.key, ...props }, children };
143
+ firstEl.props = { key: instance.key, ...firstEl.props, ...props };
144
+ return firstEl;
147
145
  default:
148
146
  return { type: element, props: props || {}, children: children || [] };
149
147
  }
@@ -164,7 +162,7 @@ export function Switch({ children }) {
164
162
  return child;
165
163
  }
166
164
  }
167
- return { type: "div", props: {}, children: [] };
165
+ return { type: "div", props: {}, children: [] };
168
166
  }
169
167
 
170
168
  /**
@@ -182,14 +180,16 @@ export function Match({ when, children }) {
182
180
  * @param persist - persist state on reload
183
181
  * @returns {T, (newState: any, Element: string) => void, key}
184
182
  */
185
- export const useState = <T>(initialState: T, persist: false) => {
186
- const setState = (newState: T) => {
187
- initialState = newState;
188
- }
189
-
190
183
 
191
- return [() => initialState, setState];
192
- }
184
+ export const useState = (initialState, persist) => {
185
+ const setState = (newState) => {
186
+ initialState = newState;
187
+ };
188
+ const getVal = () => {
189
+ return initialState;
190
+ };
191
+ return [getVal, setState];
192
+ };
193
193
 
194
194
  if (!isServer) {
195
195
  window.effects = []
@@ -214,16 +214,16 @@ if (!isServer) {
214
214
  * render(<App name="John" />, document.getElementById("root"));
215
215
  */
216
216
 
217
- // create a hidden object on window
218
- //
219
- if(!isServer){
217
+ // create a hidden object on window
218
+ //
219
+ if (!isServer) {
220
220
  Object.defineProperty(window, "state", {
221
221
  value: [],
222
222
  writable: true,
223
223
  enumerable: true,
224
224
  })
225
225
 
226
- }else{
226
+ } else {
227
227
  globalThis.state = []
228
228
  }
229
229
  export class Component {
@@ -247,118 +247,103 @@ export class Component {
247
247
  this.element = null;
248
248
  this.effectCalls = []
249
249
  this.errorThreshold = 1000
250
- this.maxIntervalCalls = 10
250
+ this.maxIntervalCalls = 10
251
251
  this.eventRegistry = new WeakMap();
252
252
  this.refs = []
253
253
  }
254
254
  useRef = (key, value) => {
255
- if(!this.refs.find((r)=> r.key == key)){
256
- this.refs.push({key, value});
257
- }
255
+ if (!this.refs.find((r) => r.key == key)) {
256
+ this.refs.push({ key, value });
257
+ }
258
258
 
259
- return this.refs.find((r)=> r.key == key).value;
259
+ return this.refs.find((r) => r.key == key).value;
260
260
  }
261
261
  useEffect(callback, dependencies = []) {
262
262
  const callbackId = callback.toString();
263
263
 
264
264
  if (!this.effectCalls.some(s => s.id === callbackId)) {
265
- this.effectCalls.push({ id: callbackId, count: 0, lastCall: Date.now(), runOnce: dependencies.length === 0 });
265
+ this.effectCalls.push({ id: callbackId, count: 0, lastCall: Date.now(), runOnce: dependencies.length === 0 });
266
266
  }
267
267
 
268
268
  const effectCall = this.effectCalls.find(s => s.id === callbackId);
269
269
 
270
270
  const executeCallback = () => {
271
- const now = Date.now();
272
- const timeSinceLastCall = now - effectCall.lastCall;
271
+ const now = Date.now();
272
+ const timeSinceLastCall = now - effectCall.lastCall;
273
273
 
274
- if (timeSinceLastCall < this.errorThreshold) {
275
- effectCall.count += 1;
276
- if (effectCall.count > this.maxIntervalCalls) {
277
- throw new Error(`Woah wayy too many calls, ensure you are not overlooping you can change the maxThresholdCalls and errorThreshold depending on needs`)
278
- }
279
- } else {
280
- effectCall.count = 1;
274
+ if (timeSinceLastCall < this.errorThreshold) {
275
+ effectCall.count += 1;
276
+ if (effectCall.count > this.maxIntervalCalls) {
277
+ throw new Error(`Woah wayy too many calls, ensure you are not overlooping you can change the maxThresholdCalls and errorThreshold depending on needs`)
281
278
  }
279
+ } else {
280
+ effectCall.count = 1;
281
+ }
282
282
 
283
- effectCall.lastCall = now;
283
+ effectCall.lastCall = now;
284
284
 
285
- setTimeout(() => {
286
- try {
285
+ setTimeout(() => {
286
+ try {
287
287
 
288
- effects.push(callbackId);
288
+ effects.push(callbackId);
289
289
 
290
- callback()
291
- } catch (error) {
292
- console.error(error);
293
- }
294
- }, 0);
290
+ callback()
291
+ } catch (error) {
292
+ console.error(error);
293
+ }
294
+ }, 0);
295
295
  };
296
296
 
297
- if (dependencies.length === 0 && this.Mounted && this.effect.length === 0 && !effects.includes(callbackId)){
298
- executeCallback();
299
- this.effect.push(callbackId);
297
+ if (dependencies.length === 0 && this.Mounted && this.effect.length === 0 && !effects.includes(callbackId)) {
298
+ executeCallback();
299
+ this.effect.push(callbackId);
300
300
  } else {
301
- // Check if dependencies have changed
302
- let dependenciesChanged = false;
303
- if (dependencies.length !== this.effect.length) {
301
+ // Check if dependencies have changed
302
+ let dependenciesChanged = false;
303
+ if (dependencies.length !== this.effect.length) {
304
+ dependenciesChanged = true;
305
+ } else {
306
+ for (let i = 0; i < dependencies.length; i++) {
307
+ if (this.effect[i] !== dependencies[i]) {
304
308
  dependenciesChanged = true;
305
- } else {
306
- for (let i = 0; i < dependencies.length; i++) {
307
- if (this.effect[i] !== dependencies[i]) {
308
- dependenciesChanged = true;
309
- break;
310
- }
311
- }
309
+ break;
310
+ }
312
311
  }
312
+ }
313
313
 
314
- if (dependenciesChanged) {
315
- this.effect = [...dependencies];
316
- executeCallback();
317
- }
314
+ if (dependenciesChanged) {
315
+ this.effect = [...dependencies];
316
+ executeCallback();
317
+ }
318
318
  }
319
- }
320
- useState(key, defaultValue, persist = false) {
321
-
319
+ } useState(key, defaultValue, persist = false) {
322
320
  if (typeof window === "undefined")
323
321
  return [defaultValue, () => {
324
322
  }];
325
-
326
- let value = this.state.find((v) => v.key == key) ? this.state.find((v) => v.key == key).value : defaultValue;
327
-
328
- if(!this.state.find(i => i.key === key)){
329
- this.state.push({key: key, value: defaultValue})
330
- }
323
+ let value = sessionStorage.getItem("state_" + key) ? JSON.parse(sessionStorage.getItem("state_" + key)).value : defaultValue;
331
324
  if (typeof value === "string") {
332
325
  try {
333
326
  value = JSON.parse(value);
334
327
  } catch (error) {
335
328
  }
336
329
  }
337
-
338
- const clear = () =>{
339
- this.state = this.state.filter((v) => v.key !== key);
330
+ if (!window["listener" + key] && !isServer) {
331
+ window["listener" + key] = true;
332
+ window.addEventListener("beforeunload", () => {
333
+ !persist && sessionStorage.removeItem("state_" + key);
334
+ });
340
335
  }
341
336
  const setValue = (newValue) => {
342
- // If newValue is a function, call it with the current value
343
337
  if (typeof newValue === "function") {
344
- const item = this.state.find(i => i.key === key);
345
- newValue = item ? newValue(item.value) : newValue;
338
+ newValue = newValue(value);
346
339
  }
347
-
348
-
349
- let itemIndex = this.state.findIndex(i => i.key === key);
350
-
351
- if (itemIndex !== -1) {
352
- this.state[itemIndex].value = newValue;
353
- } else {
354
- this.state.push({ key: key, value: newValue });
355
- }
356
-
340
+ sessionStorage.setItem("state_" + key, JSON.stringify({ value: newValue }));
357
341
  this.forceUpdate(this.key);
358
342
  };
359
-
360
-
361
- return [value, setValue, clear];
343
+ const getVal = () => {
344
+ return sessionStorage.getItem("state_" + key) ? JSON.parse(sessionStorage.getItem("state_" + key)).value : defaultValue;
345
+ };
346
+ return [getVal, setValue];
362
347
  }
363
348
  useFetch(url, options) {
364
349
  const loadingKey = "loading_" + url;
@@ -372,7 +357,7 @@ export class Component {
372
357
  setLoading(false);
373
358
  setData(data2);
374
359
  this.forceUpdate(this.key);
375
- setTimeout(()=> {
360
+ setTimeout(() => {
376
361
  _clear1()
377
362
  _clear2()
378
363
  clear()
@@ -420,9 +405,9 @@ export class Component {
420
405
  this.Reconciler.update(el, newl);
421
406
  }
422
407
  Reconciler = {
423
- update:(oldElement, newElement) => {
408
+ update: (oldElement, newElement) => {
424
409
  if (!oldElement || !newElement) return;
425
-
410
+
426
411
  // If nodes are the same type and can be updated
427
412
  if (this.Reconciler.shouldUpdate(oldElement, newElement)) {
428
413
  // Update attributes of the parent
@@ -431,13 +416,13 @@ export class Component {
431
416
  oldElement.removeAttribute(name);
432
417
  }
433
418
  });
434
-
419
+
435
420
  Array.from(newElement.attributes).forEach(({ name, value }) => {
436
421
  if (oldElement.getAttribute(name) !== value) {
437
422
  oldElement.setAttribute(name, value);
438
423
  }
439
424
  });
440
-
425
+
441
426
  // Update the parent content (if text content differs)
442
427
  if (oldElement.childNodes.length === 1 && oldElement.firstChild.nodeType === Node.TEXT_NODE) {
443
428
  if (oldElement.textContent !== newElement.textContent) {
@@ -445,18 +430,18 @@ export class Component {
445
430
  }
446
431
  return; // No children to reconcile if it's a text node
447
432
  }
448
-
433
+
449
434
  // Reconcile child nodes
450
435
  const oldChildren = Array.from(oldElement.childNodes);
451
436
  const newChildren = Array.from(newElement.childNodes);
452
-
437
+
453
438
  const maxLength = Math.max(oldChildren.length, newChildren.length);
454
439
  for (let i = 0; i < maxLength; i++) {
455
440
  if (i >= oldChildren.length) {
456
441
  // Add new children
457
442
  const newChildClone = newChildren[i].cloneNode(true);
458
443
  oldElement.appendChild(newChildClone);
459
-
444
+
460
445
  // Transfer events for the new child
461
446
  const newChildEvents = this.eventRegistry.get(newChildren[i]) || [];
462
447
  newChildEvents.forEach(({ type, handler }) => {
@@ -470,7 +455,7 @@ export class Component {
470
455
  this.Reconciler.update(oldChildren[i], newChildren[i]);
471
456
  }
472
457
  }
473
-
458
+
474
459
  // Reapply events to the parent
475
460
  const parentEvents = this.eventRegistry.get(newElement) || [];
476
461
  parentEvents.forEach(({ type, handler }) => {
@@ -479,14 +464,14 @@ export class Component {
479
464
  } else {
480
465
  const oldChildren = Array.from(oldElement.childNodes);
481
466
  const newChildren = Array.from(newElement.childNodes);
482
-
467
+
483
468
  const maxLength = Math.max(oldChildren.length, newChildren.length);
484
469
  for (let i = 0; i < maxLength; i++) {
485
470
  if (i >= oldChildren.length) {
486
471
  // Add new children
487
472
  const newChildClone = newChildren[i].cloneNode(true);
488
473
  oldElement.appendChild(newChildClone);
489
-
474
+
490
475
  // Transfer events for the new child
491
476
  const newChildEvents = this.eventRegistry.get(newChildren[i]) || [];
492
477
  newChildEvents.forEach(({ type, handler }) => {
@@ -502,7 +487,7 @@ export class Component {
502
487
  }
503
488
  }
504
489
  },
505
-
490
+
506
491
  shouldUpdate: (oldElement, newElement, isChild = false) => {
507
492
  if (oldElement.nodeType !== newElement.nodeType) {
508
493
  return oldElement.innerHTML !== newElement.innerHTML ? { type: "innerHTML" } : true;
@@ -519,7 +504,7 @@ export class Component {
519
504
  return true;
520
505
  }
521
506
  if (newElement.attributes) {
522
- for (let i = 0;i < newElement.attributes.length; i++) {
507
+ for (let i = 0; i < newElement.attributes.length; i++) {
523
508
  let attr = newElement.attributes[i];
524
509
  if (oldElement.getAttribute(attr.name) !== attr.value) {
525
510
  return { type: "attribute", name: attr.name, value: attr.value };
@@ -534,9 +519,9 @@ export class Component {
534
519
  if (!element) return document.createElement("div");
535
520
  // create either a element or svg element
536
521
  let svg = ["svg", "path", "circle", "rect", "line", "polyline", "polygon", "ellipse", "g"];
537
- let el = svg.includes(element.type) ? document.createElementNS("http://www.w3.org/2000/svg", element.type) : document.createElement(element.type);
522
+ let el = svg.includes(element.type) ? document.createElementNS("http://www.w3.org/2000/svg", element.type) : document.createElement(element.type);
538
523
  let isText = typeof element === "string" || typeof element === "number" || typeof element === "boolean";
539
- if (isText && element){
524
+ if (isText && element) {
540
525
  el.innerHTML = element;
541
526
  } else {
542
527
  let attributes = element.props;
@@ -563,21 +548,21 @@ export class Component {
563
548
  if (key.startsWith("on")) {
564
549
  el.addEventListener(key.substring(2).toLowerCase(), attributes[key]);
565
550
  this.eventRegistry.set(el, [...this.eventRegistry.get(el) || [], { event: key.substring(2).toLowerCase(), handler: attributes[key] }]);
566
- this.addEventListener(el,key.substring(2).toLowerCase(), attributes[key])
551
+ this.addEventListener(el, key.substring(2).toLowerCase(), attributes[key])
567
552
  continue;
568
553
  }
569
554
  el.setAttribute(key, attributes[key]);
570
555
  }
571
556
  if (children === undefined)
572
557
  return el;
573
- for (let i = 0;i < children.length; i++) {
558
+ for (let i = 0; i < children.length; i++) {
574
559
  let child = children[i];
575
560
  if (Array.isArray(child)) {
576
561
  child.forEach((c) => {
577
562
  el.appendChild(this.parseToElement(c));
578
563
  });
579
564
  }
580
- if (typeof child === "function") {
565
+ if (typeof child === "function") {
581
566
  let comp = memoizeClassComponent(Component);
582
567
  comp.Mounted = true;
583
568
  comp.render = child;
@@ -586,7 +571,7 @@ export class Component {
586
571
  el.appendChild(el2);
587
572
  } else if (typeof child === "object") {
588
573
  el.appendChild(this.parseToElement(child));
589
- } else if(child){
574
+ } else if (child) {
590
575
  let span = document.createTextNode(child)
591
576
  el.appendChild(span);
592
577
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vaderjs",
3
- "version": "1.7.1",
3
+ "version": "1.7.2",
4
4
  "description": "A simple and powerful JavaScript library for building modern web applications.",
5
5
  "bin": {
6
6
  "vaderjs": "./main.js"