cradova 3.5.8 → 3.6.1

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  <br/>
2
2
  <p align="center">
3
3
  <a href="https://github.com/uiedbook/cradova">
4
- <img src="icon.png" alt="Logo" width="80" height="80">
4
+ <img src="https://raw.githubusercontent.com/Uiedbook/cradova/main/icon.png" alt="Logo" width="80" height="80">
5
5
  </a>
6
6
 
7
7
  <h1 align="center">Cradova</h1>
@@ -33,8 +33,14 @@ Build Powerful ⚡ Web Apps with Ease
33
33
 
34
34
  # Cradova is 3
35
35
 
36
+ ## 2025 - What's New? Function as reactive components
37
+
38
+ this can't be better anywhere XD
39
+
36
40
  ```js
37
- const Cradova = new Comp(function () {
41
+ // functional components
42
+
43
+ const Cradova = function () {
38
44
  const [year, setYear] = useState(3, this);
39
45
 
40
46
  return h1("Cradova is " + year + " yrs old in ", {
@@ -44,9 +50,37 @@ const Cradova = new Comp(function () {
44
50
  });
45
51
  },
46
52
  });
47
- });
53
+ };
54
+
55
+ // NOTE: all cradova elements returns html elements
56
+
57
+ // converts to html and append to the Dom
58
+ document.body.appendChild(div(Cradova));
59
+ ```
60
+
61
+ ## 2024 - What's New? Signals pub/sub
62
+
63
+ ```js
64
+ import { Signal, getSignal, $if, $ifelse, div, h1 } from "cradova";
65
+
66
+ const signal = new Signal({ name: "john" });
67
+
68
+ function Hello() {
69
+ const name = getSignal("name", this).name;
70
+ return div(
71
+ $if(name === "john", h1("Hello john")),
72
+ $if(name === "paul", h1("Goodbye paul")),
73
+ $ifelse(name === "john", h1("Hello john"), h1("Hello Paul"))
74
+ );
75
+ }
76
+
77
+ signal.bind("name", this);
78
+ const html = div(Hello);
79
+ document.body.append(html);
48
80
 
49
- document.body.appendChild(Cradova.render());
81
+ setInterval(() => {
82
+ signal.publish("name", "paul");
83
+ }, 5000);
50
84
  ```
51
85
 
52
86
  ## 2023 - What's New? Conditionals
@@ -78,6 +112,20 @@ function whatsAllowed({ age }) {
78
112
  document.body.append(html, whatsAllowed({ age: 26 }));
79
113
  ```
80
114
 
115
+ ## 2023 - What's New? Router
116
+
117
+ ```js
118
+ Router.BrowserRoutes({
119
+ "/home": home,
120
+ });
121
+ // creates these routes
122
+ Router.navigate("/home", data);
123
+ ```
124
+
125
+ ## 2021 - first version
126
+
127
+ ...
128
+
81
129
  # Contents
82
130
 
83
131
  - [What is Cradova](#what-is-cradova)
@@ -158,7 +206,7 @@ This a collection of basic examples that can give you some ideas
158
206
  import {
159
207
  br,
160
208
  button,
161
- Comp,
209
+ Function,
162
210
  createSignal,
163
211
  div,
164
212
  h1,
@@ -206,7 +254,7 @@ Let's see a simple TodoList example
206
254
  ```js
207
255
  import {
208
256
  button,
209
- Comp,
257
+ Function,
210
258
  createSignal,
211
259
  div,
212
260
  h1,
@@ -237,7 +285,7 @@ const removeTodo = function (todo: string) {
237
285
  function TodoList() {
238
286
  // can be used to hold multiple references
239
287
  const referenceSet = useRef();
240
- // bind Comp to Signal
288
+ // bind Function to Signal
241
289
  todoStore.subscribe("todo", todoList);
242
290
  // vjs
243
291
  return main(
@@ -260,8 +308,8 @@ function TodoList() {
260
308
  );
261
309
  }
262
310
 
263
- const todoList = new Comp(function () {
264
- const data = this.subData;
311
+ const todoList = function () {
312
+ const data = this.pipes.get("todo");
265
313
  return div(
266
314
  data.map((item: any) =>
267
315
  p(item, {
@@ -272,7 +320,7 @@ const todoList = new Comp(function () {
272
320
  })
273
321
  )
274
322
  );
275
- });
323
+ };
276
324
  document.body.appendChild(TodoList());
277
325
  ```
278
326
 
@@ -285,29 +333,12 @@ Cradova Router is a module that allows you do the following:
285
333
 
286
334
  Create specified routes in you application help you handle navigation render a
287
335
  page on a route listen to Navigation changes create error boundary at page level
288
- apart from Comp level.
336
+ apart from Function level.
289
337
 
290
338
  let's try an example.
291
339
 
292
340
  ```js
293
- import { Page, Router } from "cradova";
294
-
295
- // Comp can be used as page template this way
296
-
297
- const template = new Comp(function (name) {
298
- // an effect run once after page renders
299
- const self = this;
300
- self.effect(() => {
301
- const name = new Promise((res) => {
302
- res("john doe");
303
- });
304
- setTimeout(async () => {
305
- self.recall(await name);
306
- }, 1000);
307
- });
308
- // effects can be used to make api calls needed for the page
309
- return div(name ? ">>>>>>>> Hello " + name : " loading...");
310
- });
341
+ import { Page, Router, useEffect } from "cradova";
311
342
 
312
343
  const home = new Page({
313
344
  name: "home page", // page title
@@ -365,11 +396,11 @@ this allow you manage rendering circle for each page in your app
365
396
 
366
397
  ---
367
398
 
368
- More info on Cradova Comp
399
+ More info on Cradova Function
369
400
 
370
401
  ---
371
402
 
372
- Cradova Comp is a dynamic component class, which ships simple abstractions like:
403
+ Cradova Function is a dynamic component class, which ships simple abstractions like:
373
404
 
374
405
  - Signal
375
406
  - useEffect
@@ -377,7 +408,7 @@ Cradova Comp is a dynamic component class, which ships simple abstractions like:
377
408
  - useRef
378
409
  - preRender
379
410
 
380
- these behaviors allow you manage rendering circle for Comps in your app
411
+ these behaviors allow you manage rendering circle for Functions in your app
381
412
 
382
413
  ---
383
414
 
@@ -391,7 +422,7 @@ with ability to:
391
422
 
392
423
  - create store
393
424
  - create actions and fire them
394
- - bind a Comp
425
+ - bind a Function
395
426
  - listen to changes
396
427
  - persist changes to localStorage
397
428
 
package/dist/index.js CHANGED
@@ -1 +1,819 @@
1
- class G{static compId=0;afterMount=[];beforeMountActive=[];afterDeactivate=[];dispatchEvent(H){let T=this[H];if(H.includes("Active")){for(let L=0;L<T.length;L++)T[L]();return}while(T.length!==0)T.shift()()}}var J=new G;class x{id=0;component;effects=[];effectuate=null;rendered=!1;published=!1;preRendered=null;reference=null;subData=null;publish=null;_state=[];_state_index=0;constructor(H){this.component=H.bind(this)}preRender(){this.preRendered=this.render()}render(){if(G.compId+=1,this.id=G.compId,this.effects=[],this.rendered=!1,!this.preRendered){this._state_index=0,this._state=[];let H=this.component();if(H instanceof HTMLElement)this.reference=H,this.effector.apply(this),this.rendered=!0,this.published=!0;else console.error(" ✘ Cradova err : Invalid html content, got - "+H);return H}else return this.preRendered}_effect(H){if(!this.rendered)this.effects.push(H.bind(this))}async effector(){for(let H=0;H<this.effects.length;H++){let T=await this.effects[H].apply(this);if(typeof T==="function")J.afterDeactivate.push(T)}if(this.effects=[],this.effectuate)this.effectuate(),this.effectuate=null}recall(){if(!this.rendered)this.effectuate=()=>{if(this.published)this.activate()};else if(this.published)setTimeout(()=>{this.activate()})}async activate(){if(this.published=!1,!this.rendered)return;this._state_index=0;let H=this.reference;if(document.contains(H)){let T=this.component();if(T instanceof HTMLElement)H.insertAdjacentElement("beforebegin",T),H.remove(),this.published=!0,this.reference=T,J.dispatchEvent("afterMount");else console.error(" ✘ Cradova err : Invalid html, got - "+T)}else this.reference=null,this.rendered=!1}}class W{pn;subs;pipe;constructor(H,T){if(this.pipe=H,this.subs={},T&&T.persistName){this.pn=T.persistName;let L=localStorage.getItem(T.persistName);if(L&&L!=="undefined")this.pipe=JSON.parse(L);if(typeof H==="object"){for(let M in H)if(!Object.prototype.hasOwnProperty.call(this.pipe,M))this.pipe[M]=H[M]}}}publish(H,T){this.pipe[H]=T;let L=this.subs[H]||[];for(let M=0;M<L.length;M++){let I=L[M];I.subData=T,I.recall()}if(this.pn)localStorage.setItem(this.pn,JSON.stringify(this.pipe))}subscribe(H,T){if(T instanceof x){if(this.subs[H]?.find((L)=>L.id===T.id))return;if(!this.subs[H])this.subs[H]=[T];else this.subs[H].push(T);if(this.pipe[H])T.subData=this.pipe[H],T.publish=(L)=>{this.publish(H,L)}}}clearPersist(){if(this.pn)localStorage.removeItem(this.pn)}}class U{_name;_html;_template=document.createElement("div");_dropped=!1;_snapshot;_snapshot_html;_deCB;constructor(H){let{template:T,name:L}=H;this._html=T,this._name=L||document.title,this._template.setAttribute("id","page"),this._snapshot=H.snapshotIsolation||!1}async _takeSnapShot(){if(A.doc.dataset.snapshot==="true")return;try{let H=await fetch(location.href);if(!H.ok)throw new Error("Failed to fetch the page");let T=await H.text(),M=new DOMParser().parseFromString(T,"text/html");M.title=this._name;let I=M.querySelector('[data-wrapper="app"]');if(I)I.setAttribute("data-snapshot","true"),I.innerHTML=this._snapshot_html;else{console.error("Wrapper or template is not found");return}let V=M.documentElement.outerHTML;await fetch(`${location.origin}`,{body:V,method:"POST",headers:{"Content-Type":"text/html","cradova-snapshot":location.href.slice(location.origin.length)}})}catch(H){console.error("Snapshot error:",H)}this._snapshot_html=void 0}set onDeactivate(H){this._deCB=H}drop(H){if(typeof H==="boolean"){this._dropped=H;return}else return this._dropped}async _activate(){if(this._dropped){history.go(-1);return}let H=this._html.apply(this);if(H instanceof HTMLElement)this._template.innerHTML="",this._template.appendChild(H);else throw new Error(` ✘ Cradova err: template function for the page returned ${H} instead of html`);if(document.title=this._name,A.doc.innerHTML="",J.dispatchEvent("beforeMountActive"),this._snapshot)this._snapshot_html=this._template.outerHTML;if(A.doc.appendChild(this._template),J.dispatchEvent("afterMount"),window.scrollTo({top:0,left:0,behavior:"instant"}),J.dispatchEvent("afterDeactivate"),this._snapshot)this._takeSnapShot()}}class z{doc=null;lastNavigatedRouteController;nextRouteController;lastNavigatedRoute;pageShow=null;pageHide=null;errorHandler;loadingPage=null;pageData={params:{}};routes={};paused=!1;route(H,T){if(!T)console.error(" ✘ Cradova err: not a valid page ",T);return this.routes[H]=T}async router(H,T){let L=window.location.href,M,I;if(this.paused){window.location.hash="paused";return}if(this.nextRouteController)M=this.nextRouteController,this.nextRouteController=void 0;else[M,I]=this.checker(L);if(typeof M!=="undefined")try{if(typeof M==="function"){if(this.loadingPage instanceof U)await this.loadingPage._activate();M=await M()}if(M?.default)M=M.default;if(!M){if(this.lastNavigatedRoute)history.pushState({},L,this.lastNavigatedRoute);return}if(I)this.pageData.params=I;await M._activate(),this.lastNavigatedRouteController&&this.lastNavigatedRouteController._deCB?.(),this.lastNavigatedRoute=L,this.lastNavigatedRouteController=M}catch(V){if(typeof this.errorHandler==="function")this.errorHandler(V,L);else console.error(V)}else if(this.routes["*"])await this.routes["*"]._activate()}checker(H){if(H[0]!=="/")H=H.slice(H.indexOf("/",8));if(this.routes[H])return[this.routes[H],{path:H}];if(H.includes("?")){let T,L={};if([H,T]=H.split("?"),new URLSearchParams(T).forEach((M,I)=>{L[I]=M}),this.routes[H])return[this.routes[H],L]}for(let T in this.routes){if(T.includes(":")){let L=H.split("/"),M=T.split("/");if(H.endsWith("/"))L.pop();let I=0,V=0;if(M.length===L.length){for(let D=0;D<M.length;D++){if(M[D].includes(":")){V++;continue}if(L[D]===M[D])I++}if(I+V===M.length){let D={};for(let O=0;O<M.length;O++)if(M[O].includes(":"))D[M[O].split(":")[1]]=L[O];return[this.routes[T],D]}}}if(T.includes("*")){let L=T.slice(0,-1);if(H.startsWith(L))return[this.routes[T],{extraPath:H.slice(L.length)}]}}return[]}}var A=new z;class S{static BrowserRoutes(H){for(let T in H){let L=H[T];if(typeof L==="object"&&typeof L.then==="function"||typeof L==="function")A.routes[T]=async()=>{let M=typeof L==="function"?await L():await L;return A.route(T,M)};else A.route(T,L)}S._mount()}static pauseNavigation(){A.paused=!0,window.location.hash="paused"}static resumeNavigation(){A.paused=!1,window.location.replace(window.location.pathname+window.location.search),history.go(-1)}static navigate(H,T){if(typeof H!=="string")console.error(" ✘ Cradova err: href must be a defined path but got "+H+" instead");let L=null,M;if(H.includes("."))window.location.href=H;else{if([L,M]=A.checker(H),L)A.nextRouteController=L,window.history.pushState({},"",H);A.pageData.params=M,A.pageData.data=T,A.router(null)}}static setLoadingPage(H){if(H instanceof U)A.loadingPage=H;else throw new Error(" ✘ Cradova err: Loading Page should be a cradova page class")}static get PageData(){return A.pageData}static addErrorHandler(H){if(typeof H==="function")A.errorHandler=H;else throw new Error(" ✘ Cradova err: callback for error event is not a function")}static _mount(){let H=document.querySelector("[data-wrapper=app]");if(H)A.doc=H;else throw new Error(`✘ Cradova err: please add '<div data-wrapper="app"></div>' to the body of your index.html file `);window.addEventListener("pageshow",()=>A.router()),window.addEventListener("popstate",(T)=>{T.preventDefault(),A.router()})}}class Y{tree={};bindAs(H){return[this,H]}elem(H){let T=this.tree[H];if(document.contains(T))return T;this.tree[H]=void 0}swap(H,T){[this.tree[H],this.tree[T]]=[this.tree[T],this.tree[H]]}_append(H,T){this.tree[H]=T}}var q=(H,T)=>{let L={},M=void 0;if(T.length!==0)for(let I=0;I<T.length;I++){let V=T[I];if(typeof V==="function")V=V();if(V instanceof x)V=V.render();if(V instanceof HTMLElement||V instanceof DocumentFragment){H.appendChild(V);continue}if(Array.isArray(V)){H.appendChild(K(V));continue}if(typeof V==="string"){M=V;continue}if(typeof V==="object"){Object.assign(L,V);continue}}else return H;if(typeof L==="object"&&H)for(let[I,V]of Object.entries(L)){if(I==="style"&&typeof V==="object"){Object.assign(H.style,V);continue}if(I==="href"){let D=V||"";if(!D.includes("://"))H.addEventListener("click",(O)=>{if(O.preventDefault(),S.navigate(H.href),D.includes("#")){let Q=D.split("#").at(-1);document.getElementById("#"+Q)?.scrollIntoView()}});H.setAttribute(I,V);continue}if(I==="onmount"){J.afterMount.push(()=>{typeof L.onmount==="function"&&L.onmount.apply(H)});continue}if(I.includes("data-")||I.includes("aria-")){H.setAttribute(I,V);continue}if(Array.isArray(V)){if(I=="ref"&&V[0]instanceof Y){V[0]._append(V[1],H);continue}}H[I]=V}if(M!==void 0)H.appendChild(document.createTextNode(M));return H},E=(H)=>{return(...T)=>q(document.createElement(H),T)};function K(H){let T=new DocumentFragment;for(let L of H)if(Array.isArray(L))T.appendChild(K(L));else{if(L instanceof x)L=L.render();if(typeof L==="function"){if(L=L(),typeof L==="function")L=L()}if(L instanceof HTMLElement||L instanceof DocumentFragment){T.appendChild(L);continue}if(typeof L==="string")T.appendChild(document.createTextNode(L))}return T}function b(H,...T){if(H)return T}function X(H,T,L){if(H)return T;return L}function y(H,...T){return(L)=>{if(L===H)return T;return}}function j(H,...T){let L;if(T.length){for(let M=0;M<T.length;M++)if(L=T[M](H),L)break}return L}function g(H,T){return Array.isArray(H)?H.map(T):void 0}var F=function(H){let T=document.createDocumentFragment();for(let L=0;L<H.length;L++){let M=H[L];if(typeof M==="function")M=M();if(M instanceof HTMLElement||M instanceof DocumentFragment){T.appendChild(M);continue}if(M instanceof String){T.appendChild(document.createTextNode(M));continue}console.error(" ✘ Cradova err: wrong element type"+M)}return T};function w(H,T){T._state_index+=1;let L=T._state_index;if(L>=T._state.length)T._state[L]=H;function M(I){if(typeof I==="function")I=I(T._state[L]);T._state[L]=I,T.recall()}return[T._state[L],M]}function n(H,T){T._effect(H)}function _(){return new Y}var c=E("a"),B=E("audio"),N=E("button"),f=E("canvas"),s=E("div"),R=E("footer"),C=E("form"),o=E("h1"),d=E("h2"),v=E("h3"),i=E("h4"),h=E("h5"),p=E("h6"),t=E("header"),u=E("i"),m=E("iframe"),l=E("img"),r=E("input"),a=E("label"),e=E("li"),HH=E("main"),TH=E("nav"),LH=E("ol"),MH=E("optgroup"),EH=E("option"),IH=E("p"),VH=E("section"),AH=E("select"),DH=E("source"),OH=E("span"),JH=E("textarea"),xH=E("ul"),GH=E("video"),SH=E("table"),UH=E("tbody"),YH=E("td"),qH=E("tr"),zH=(H,T)=>{let L=document.createElement("span");return L.innerHTML=H,q(L,T||[])},KH=(H)=>{let T=document.createElement("div");if(Array.isArray(H))T.innerHTML=H[0];else if(typeof H==="string")T.innerHTML=H;let L=new DocumentFragment;return L.append(...Array.from(T.children)),L};export{GH as video,w as useState,_ as useRef,n as useEffect,xH as ul,qH as tr,JH as textarea,YH as td,SH as tbody,UH as table,zH as svg,OH as span,DH as source,AH as select,VH as section,KH as raw,IH as p,EH as option,MH as optgroup,LH as ol,TH as nav,q as makeElement,HH as main,g as loop,e as li,a as label,r as input,l as img,m as iframe,u as i,t as header,p as h6,h as h5,i as h4,v as h3,d as h2,o as h1,F as frag,C as form,R as footer,s as div,E as cra,f as canvas,N as button,B as audio,c as a,W as Signal,S as Router,K as Rhoda,U as Page,J as CradovaEvent,x as Comp,j as $switch,X as $ifelse,b as $if,y as $case};
1
+ // src/primitives/functions.ts
2
+ var makeElement = (element, ElementChildrenAndPropertyList) => {
3
+ const props = {};
4
+ let text = undefined;
5
+ if (ElementChildrenAndPropertyList.length !== 0) {
6
+ for (let i = 0;i < ElementChildrenAndPropertyList.length; i++) {
7
+ let child = ElementChildrenAndPropertyList[i];
8
+ if (typeof child === "function") {
9
+ child = isArrowFunc(child) ? child() : toFunc(child);
10
+ }
11
+ if (child instanceof HTMLElement || child instanceof DocumentFragment) {
12
+ element.appendChild(child);
13
+ continue;
14
+ }
15
+ if (Array.isArray(child)) {
16
+ element.appendChild(unroll_child_list(child));
17
+ continue;
18
+ }
19
+ if (typeof child === "string") {
20
+ text = child;
21
+ continue;
22
+ }
23
+ if (typeof child === "object") {
24
+ Object.assign(props, child);
25
+ continue;
26
+ }
27
+ }
28
+ } else {
29
+ return element;
30
+ }
31
+ if (typeof props === "object" && element) {
32
+ for (const [prop, value] of Object.entries(props)) {
33
+ if (prop === "style" && typeof value === "object") {
34
+ Object.assign(element.style, value);
35
+ continue;
36
+ }
37
+ if (prop === "href") {
38
+ const href = value || "";
39
+ if (!href.includes("://")) {
40
+ element.addEventListener("click", (e) => {
41
+ e.preventDefault();
42
+ Router.navigate(element.href);
43
+ if (href.includes("#")) {
44
+ const l = href.split("#").at(-1);
45
+ document.getElementById("#" + l)?.scrollIntoView();
46
+ }
47
+ });
48
+ }
49
+ element.setAttribute(prop, value);
50
+ continue;
51
+ }
52
+ if (prop === "onmount") {
53
+ CradovaEvent.after_comp_is_mounted.push(() => {
54
+ typeof props["onmount"] === "function" && props["onmount"].apply(element);
55
+ });
56
+ continue;
57
+ }
58
+ if (prop.includes("data-") || prop.includes("aria-")) {
59
+ element.setAttribute(prop, value);
60
+ continue;
61
+ }
62
+ if (Array.isArray(value)) {
63
+ if (prop == "reference" && value[0] instanceof __raw_ref) {
64
+ value[0]._append(value[1], element);
65
+ continue;
66
+ }
67
+ }
68
+ element[prop] = value;
69
+ }
70
+ }
71
+ if (text !== undefined) {
72
+ element.appendChild(document.createTextNode(text));
73
+ }
74
+ return element;
75
+ };
76
+ var cra = (tag) => {
77
+ return (...Children_and_Properties) => makeElement(document.createElement(tag), Children_and_Properties);
78
+ };
79
+ function unroll_child_list(l) {
80
+ const fg = new DocumentFragment;
81
+ for (let ch of l) {
82
+ if (Array.isArray(ch)) {
83
+ fg.appendChild(unroll_child_list(ch));
84
+ } else {
85
+ if (typeof ch === "function") {
86
+ ch = isArrowFunc(ch) ? ch() : toFunc(ch);
87
+ if (typeof ch === "function") {
88
+ ch = isArrowFunc(ch) ? ch() : toFunc(ch);
89
+ }
90
+ }
91
+ if (ch instanceof HTMLElement || ch instanceof DocumentFragment) {
92
+ fg.appendChild(ch);
93
+ continue;
94
+ }
95
+ if (typeof ch === "string") {
96
+ fg.appendChild(document.createTextNode(ch));
97
+ }
98
+ }
99
+ }
100
+ return fg;
101
+ }
102
+ function $if(condition, ...elements) {
103
+ if (condition) {
104
+ return elements;
105
+ }
106
+ }
107
+ function $ifelse(condition, ifTrue, ifFalse) {
108
+ if (condition) {
109
+ return ifTrue;
110
+ }
111
+ return ifFalse;
112
+ }
113
+ function $case(value, ...elements) {
114
+ return (key) => {
115
+ if (key === value) {
116
+ return elements;
117
+ }
118
+ return;
119
+ };
120
+ }
121
+ function $switch(key, ...cases) {
122
+ let elements;
123
+ if (cases.length) {
124
+ for (let i = 0;i < cases.length; i++) {
125
+ elements = cases[i](key);
126
+ if (elements) {
127
+ break;
128
+ }
129
+ }
130
+ }
131
+ return elements;
132
+ }
133
+ function loop(datalist, component) {
134
+ return Array.isArray(datalist) ? datalist.map(component) : undefined;
135
+ }
136
+ var frag = function(children) {
137
+ const par = document.createDocumentFragment();
138
+ for (let i = 0;i < children.length; i++) {
139
+ let html = children[i];
140
+ if (typeof html === "function") {
141
+ html = html();
142
+ }
143
+ if (html instanceof HTMLElement || html instanceof DocumentFragment) {
144
+ par.appendChild(html);
145
+ continue;
146
+ }
147
+ if (html instanceof String) {
148
+ par.appendChild(document.createTextNode(html));
149
+ continue;
150
+ }
151
+ console.error(" ✘ Cradova err: wrong element type" + html);
152
+ }
153
+ return par;
154
+ };
155
+ function useState(newState, self) {
156
+ if (typeof self !== "function")
157
+ return null;
158
+ const Func = self;
159
+ Func._state_index += 1;
160
+ const idx = Func._state_index;
161
+ if (idx >= Func._state.length) {
162
+ Func._state[idx] = newState;
163
+ }
164
+ function setState(newState2) {
165
+ if (typeof newState2 === "function") {
166
+ newState2 = newState2(Func._state[idx]);
167
+ }
168
+ Func._state[idx] = newState2;
169
+ funcManager.recall(Func);
170
+ }
171
+ return [Func._state[idx], setState];
172
+ }
173
+ function useEffect(effect, self) {
174
+ funcManager._effect(self, effect);
175
+ if (typeof self !== "function")
176
+ return null;
177
+ }
178
+ function useRef() {
179
+ return new __raw_ref;
180
+ }
181
+ var getSignal = (func, name) => {
182
+ return func.pipes.get(name);
183
+ };
184
+ var sendSignal = (func, name, data) => {
185
+ const signal = func.signals.get(name);
186
+ if (signal) {
187
+ signal.publish(name, data);
188
+ } else {
189
+ console.error(" ✘ Cradova err : Invalid signal name " + name);
190
+ }
191
+ };
192
+ var isArrowFunc = (fn) => !fn.hasOwnProperty("prototype");
193
+ var DEFAULT_STATE = {
194
+ rendered: false,
195
+ published: false,
196
+ preRendered: null,
197
+ reference: null,
198
+ effectuate: null,
199
+ _state_index: 0
200
+ };
201
+ var toFunc = (func) => {
202
+ if (func.id)
203
+ return funcManager.render(func);
204
+ cradovaEvent.compId += 1;
205
+ func.id = cradovaEvent.compId;
206
+ Object.assign(func, DEFAULT_STATE);
207
+ func.signals = new Map;
208
+ func.pipes = new Map;
209
+ func.effects = [];
210
+ func._state = [];
211
+ return funcManager.render(func);
212
+ };
213
+ var funcManager = {
214
+ render(func) {
215
+ cradovaEvent.compId += 1;
216
+ func.id = cradovaEvent.compId;
217
+ func.effects = [];
218
+ func.rendered = false;
219
+ func._state_index = 0;
220
+ func._state = [];
221
+ const html = func.apply(func);
222
+ if (html instanceof HTMLElement) {
223
+ func.reference = html;
224
+ this.effector(func);
225
+ func.rendered = true;
226
+ func.published = true;
227
+ } else {
228
+ console.error(" ✘ Cradova err : Invalid html content, got - " + html);
229
+ }
230
+ return html;
231
+ },
232
+ _effect(func, fn) {
233
+ if (!func.rendered) {
234
+ func.effects.push(fn);
235
+ }
236
+ },
237
+ async effector(func) {
238
+ for (let i = 0;i < func.effects.length; i++) {
239
+ const fn = await func.effects[i].apply(func);
240
+ if (typeof fn === "function") {
241
+ CradovaEvent.after_page_is_killed.push(fn);
242
+ }
243
+ }
244
+ func.effects = [];
245
+ if (func.effectuate) {
246
+ func.effectuate();
247
+ func.effectuate = null;
248
+ }
249
+ },
250
+ recall(func) {
251
+ if (!func.rendered) {
252
+ func.effectuate = () => {
253
+ if (func.published) {
254
+ this.activate(func);
255
+ }
256
+ };
257
+ } else {
258
+ if (func.published) {
259
+ setTimeout(() => {
260
+ this.activate(func);
261
+ });
262
+ }
263
+ }
264
+ },
265
+ async activate(func) {
266
+ func.published = false;
267
+ if (!func.rendered) {
268
+ return;
269
+ }
270
+ func._state_index = 0;
271
+ const node = func.reference;
272
+ if (document.contains(node)) {
273
+ const html = func.apply(func);
274
+ if (html instanceof HTMLElement) {
275
+ node.insertAdjacentElement("beforebegin", html);
276
+ node.remove();
277
+ func.published = true;
278
+ func.reference = html;
279
+ CradovaEvent.dispatchEvent("after_comp_is_mounted");
280
+ } else {
281
+ console.error(" ✘ Cradova err : Invalid html, got - " + html);
282
+ }
283
+ } else {
284
+ func.reference = null;
285
+ func.rendered = false;
286
+ }
287
+ }
288
+ };
289
+
290
+ // src/primitives/dom-objects.ts
291
+ var a = cra("a");
292
+ var audio = cra("audio");
293
+ var button = cra("button");
294
+ var canvas = cra("canvas");
295
+ var div = cra("div");
296
+ var footer = cra("footer");
297
+ var form = cra("form");
298
+ var h1 = cra("h1");
299
+ var h2 = cra("h2");
300
+ var h3 = cra("h3");
301
+ var h4 = cra("h4");
302
+ var h5 = cra("h5");
303
+ var h6 = cra("h6");
304
+ var header = cra("header");
305
+ var i = cra("i");
306
+ var iframe = cra("iframe");
307
+ var img = cra("img");
308
+ var input = cra("input");
309
+ var label = cra("label");
310
+ var li = cra("li");
311
+ var main = cra("main");
312
+ var nav = cra("nav");
313
+ var ol = cra("ol");
314
+ var option = cra("option");
315
+ var p = cra("p");
316
+ var section = cra("section");
317
+ var select = cra("select");
318
+ var span = cra("span");
319
+ var textarea = cra("textarea");
320
+ var ul = cra("ul");
321
+ var video = cra("video");
322
+ var tbody = cra("table");
323
+ var table = cra("tbody");
324
+ var td = cra("td");
325
+ var tr = cra("tr");
326
+ var svg = (svg2, properties) => {
327
+ const span2 = document.createElement("span");
328
+ span2.innerHTML = svg2;
329
+ return makeElement(span2, properties || []);
330
+ };
331
+ var raw = (html) => {
332
+ const div2 = document.createElement("div");
333
+ if (Array.isArray(html)) {
334
+ div2.innerHTML = html[0];
335
+ } else {
336
+ if (typeof html === "string") {
337
+ div2.innerHTML = html;
338
+ }
339
+ }
340
+ const df = new DocumentFragment;
341
+ df.append(...Array.from(div2.children));
342
+ return df;
343
+ };
344
+
345
+ // src/primitives/classes.ts
346
+ class cradovaEvent {
347
+ static compId = 0;
348
+ after_comp_is_mounted = [];
349
+ after_page_is_killed = [];
350
+ dispatchEvent(eventName) {
351
+ const eventListeners = this[eventName];
352
+ if (eventName.includes("Active")) {
353
+ for (let i2 = 0;i2 < eventListeners.length; i2++) {
354
+ eventListeners[i2]();
355
+ }
356
+ return;
357
+ }
358
+ while (eventListeners.length !== 0) {
359
+ eventListeners.shift()();
360
+ }
361
+ }
362
+ }
363
+ var CradovaEvent = new cradovaEvent;
364
+
365
+ class Signal {
366
+ pn;
367
+ subs;
368
+ pipe;
369
+ constructor(initial, props) {
370
+ this.pipe = initial;
371
+ this.subs = {};
372
+ if (props && props.persistName) {
373
+ this.pn = props.persistName;
374
+ const key = localStorage.getItem(props.persistName);
375
+ if (key && key !== "undefined") {
376
+ this.pipe = JSON.parse(key);
377
+ }
378
+ if (typeof initial === "object") {
379
+ for (const key2 in initial) {
380
+ if (!Object.prototype.hasOwnProperty.call(this.pipe, key2)) {
381
+ this.pipe[key2] = initial[key2];
382
+ }
383
+ }
384
+ }
385
+ }
386
+ }
387
+ publish(eventName, data) {
388
+ this.pipe[eventName] = data;
389
+ const subs = this.subs[eventName] || [];
390
+ for (let i2 = 0;i2 < subs.length; i2++) {
391
+ const c = subs[i2];
392
+ c.pipes.set(eventName, this.pipe[eventName]);
393
+ funcManager.recall(c);
394
+ }
395
+ if (this.pn) {
396
+ localStorage.setItem(this.pn, JSON.stringify(this.pipe));
397
+ }
398
+ }
399
+ publishObject(events) {
400
+ const s = new Map;
401
+ for (const [eventName, data] of Object.entries(events)) {
402
+ this.pipe[eventName] = data;
403
+ const subs = this.subs[eventName] || [];
404
+ for (let i2 = 0;i2 < subs.length; i2++) {
405
+ const c = subs[i2];
406
+ c.pipes.set(eventName, this.pipe[eventName]);
407
+ s.set(c.id, c);
408
+ }
409
+ }
410
+ for (const [_, c] of s) {
411
+ c.recall();
412
+ }
413
+ if (this.pn) {
414
+ localStorage.setItem(this.pn, JSON.stringify(this.pipe));
415
+ }
416
+ }
417
+ subscribe(eventName, comp) {
418
+ if (typeof Function === "function") {
419
+ if (Array.isArray(eventName)) {
420
+ for (let i2 = 0;i2 < eventName.length; i2++) {
421
+ const event = eventName[i2];
422
+ if (this.pipe[event]) {
423
+ comp.pipes.set(event, this.pipe[event]);
424
+ comp.signals.set(event, this);
425
+ } else {
426
+ console.error(` ✘ Cradova err: ${event} is not a valid event for this Signal`);
427
+ }
428
+ if (this.subs[event]?.find((cmp) => cmp.id === comp.id)) {
429
+ return;
430
+ }
431
+ if (!this.subs[event]) {
432
+ this.subs[event] = [comp];
433
+ } else {
434
+ this.subs[event].push(comp);
435
+ }
436
+ }
437
+ return;
438
+ }
439
+ if (this.pipe[eventName]) {
440
+ comp.pipes.set(eventName, this.pipe[eventName]);
441
+ comp.signals.set(eventName, this);
442
+ } else {
443
+ console.error(` ✘ Cradova err: ${eventName} is not a valid event for this Signal`);
444
+ }
445
+ if (this.subs[eventName]?.find((cmp) => cmp.id === comp.id)) {
446
+ return;
447
+ }
448
+ if (!this.subs[eventName]) {
449
+ this.subs[eventName] = [comp];
450
+ } else {
451
+ this.subs[eventName].push(comp);
452
+ }
453
+ } else {
454
+ console.error(` ✘ Cradova err: ${comp} is not a valid component`);
455
+ }
456
+ }
457
+ clearPersist() {
458
+ if (this.pn) {
459
+ localStorage.removeItem(this.pn);
460
+ }
461
+ }
462
+ }
463
+
464
+ class Page {
465
+ _name;
466
+ _html;
467
+ _template;
468
+ _dropped = false;
469
+ _snapshot;
470
+ _snapshot_html;
471
+ _deCB;
472
+ constructor(pageParams) {
473
+ const { template, name } = pageParams;
474
+ if (typeof template !== "function") {
475
+ throw new Error(` ✘ Cradova err: template function for the page is not a function`);
476
+ }
477
+ this._html = template;
478
+ this._name = name || document.title;
479
+ this._snapshot = pageParams.snapshotIsolation || false;
480
+ }
481
+ async _takeSnapShot() {
482
+ if (RouterBox.doc.dataset["snapshot"] === "true")
483
+ return;
484
+ try {
485
+ const response = await fetch(location.href);
486
+ if (!response.ok)
487
+ throw new Error("Failed to fetch the page");
488
+ const html = await response.text();
489
+ const parser = new DOMParser;
490
+ const doc = parser.parseFromString(html, "text/html");
491
+ doc.title = this._name;
492
+ const wrapper = doc.querySelector('[data-wrapper="app"]');
493
+ if (wrapper) {
494
+ wrapper.setAttribute("data-snapshot", "true");
495
+ wrapper.innerHTML = this._snapshot_html;
496
+ } else {
497
+ console.error("Wrapper or template is not found");
498
+ return;
499
+ }
500
+ const snapshot = doc.documentElement.outerHTML;
501
+ await fetch(location.origin, {
502
+ body: snapshot,
503
+ method: "POST",
504
+ headers: {
505
+ "Content-Type": "text/html",
506
+ "cradova-snapshot": location.href.slice(location.origin.length)
507
+ }
508
+ });
509
+ } catch (error) {
510
+ console.error("Snapshot error:", error);
511
+ }
512
+ this._snapshot_html = undefined;
513
+ }
514
+ set onDeactivate(cb) {
515
+ this._deCB = cb;
516
+ }
517
+ drop(state) {
518
+ if (typeof state === "boolean") {
519
+ this._dropped = state;
520
+ return;
521
+ } else
522
+ return this._dropped;
523
+ }
524
+ async _activate() {
525
+ if (this._dropped) {
526
+ history.go(-1);
527
+ return;
528
+ }
529
+ if (this._name)
530
+ document.title = this._name;
531
+ this._template = div({ id: "page" }, this._html);
532
+ RouterBox.doc.innerHTML = "";
533
+ if (this._snapshot)
534
+ this._snapshot_html = this._template.outerHTML;
535
+ RouterBox.doc.appendChild(this._template);
536
+ CradovaEvent.dispatchEvent("after_comp_is_mounted");
537
+ window.scrollTo({
538
+ top: 0,
539
+ left: 0,
540
+ behavior: "instant"
541
+ });
542
+ CradovaEvent.dispatchEvent("after_page_is_killed");
543
+ if (this._snapshot)
544
+ this._takeSnapShot();
545
+ }
546
+ }
547
+
548
+ class RouterBoxClass {
549
+ doc = null;
550
+ lastNavigatedRouteController;
551
+ nextRouteController;
552
+ lastNavigatedRoute;
553
+ pageShow = null;
554
+ pageHide = null;
555
+ errorHandler;
556
+ loadingPage = null;
557
+ pageData = { params: {} };
558
+ routes = {};
559
+ paused = false;
560
+ route(path, page) {
561
+ if (!page) {
562
+ console.error(" ✘ Cradova err: not a valid page ", page);
563
+ }
564
+ return this.routes[path] = page;
565
+ }
566
+ async router(_e, _force) {
567
+ const url = window.location.href;
568
+ let route, params;
569
+ if (this.paused) {
570
+ window.location.hash = "paused";
571
+ return;
572
+ }
573
+ if (this.nextRouteController) {
574
+ route = this.nextRouteController;
575
+ this.nextRouteController = undefined;
576
+ } else {
577
+ [route, params] = this.checker(url);
578
+ }
579
+ if (typeof route !== "undefined") {
580
+ try {
581
+ if (typeof route === "function") {
582
+ if (this.loadingPage instanceof Page) {
583
+ await this.loadingPage._activate();
584
+ }
585
+ route = await route();
586
+ }
587
+ if (route?.default)
588
+ route = route.default;
589
+ if (!route) {
590
+ if (this.lastNavigatedRoute) {
591
+ history.pushState({}, url, this.lastNavigatedRoute);
592
+ }
593
+ return;
594
+ }
595
+ if (params) {
596
+ this.pageData.params = params;
597
+ }
598
+ await route._activate();
599
+ this.lastNavigatedRouteController && this.lastNavigatedRouteController._deCB?.();
600
+ this.lastNavigatedRoute = url;
601
+ this.lastNavigatedRouteController = route;
602
+ } catch (error) {
603
+ if (typeof this.errorHandler === "function") {
604
+ this.errorHandler(error, url);
605
+ } else {
606
+ console.error(error);
607
+ }
608
+ }
609
+ } else {
610
+ if (this.routes["*"]) {
611
+ await this.routes["*"]._activate();
612
+ }
613
+ }
614
+ }
615
+ checker(url) {
616
+ if (url[0] !== "/") {
617
+ url = url.slice(url.indexOf("/", 8));
618
+ }
619
+ if (this.routes[url]) {
620
+ return [this.routes[url], { path: url }];
621
+ }
622
+ if (url.includes("?")) {
623
+ let search;
624
+ const params = {};
625
+ [url, search] = url.split("?");
626
+ new URLSearchParams(search).forEach((val, key) => {
627
+ params[key] = val;
628
+ });
629
+ if (this.routes[url]) {
630
+ return [this.routes[url], params];
631
+ }
632
+ }
633
+ for (const path in this.routes) {
634
+ if (path.includes(":")) {
635
+ const urlFixtures = url.split("/");
636
+ const pathFixtures = path.split("/");
637
+ if (url.endsWith("/")) {
638
+ urlFixtures.pop();
639
+ }
640
+ let fixturesX = 0;
641
+ let fixturesY = 0;
642
+ if (pathFixtures.length === urlFixtures.length) {
643
+ for (let i2 = 0;i2 < pathFixtures.length; i2++) {
644
+ if (pathFixtures[i2].includes(":")) {
645
+ fixturesY++;
646
+ continue;
647
+ }
648
+ if (urlFixtures[i2] === pathFixtures[i2]) {
649
+ fixturesX++;
650
+ }
651
+ }
652
+ if (fixturesX + fixturesY === pathFixtures.length) {
653
+ const routesParams = {};
654
+ for (let i2 = 0;i2 < pathFixtures.length; i2++) {
655
+ if (pathFixtures[i2].includes(":")) {
656
+ routesParams[pathFixtures[i2].split(":")[1]] = urlFixtures[i2];
657
+ }
658
+ }
659
+ return [this.routes[path], routesParams];
660
+ }
661
+ }
662
+ }
663
+ if (path.includes("*")) {
664
+ const p2 = path.slice(0, -1);
665
+ if (url.startsWith(p2)) {
666
+ return [this.routes[path], { extraPath: url.slice(p2.length) }];
667
+ }
668
+ }
669
+ }
670
+ return [];
671
+ }
672
+ }
673
+ var RouterBox = new RouterBoxClass;
674
+
675
+ class Router {
676
+ static BrowserRoutes(obj) {
677
+ for (const path in obj) {
678
+ const page = obj[path];
679
+ if (typeof page === "object" && typeof page.then === "function" || typeof page === "function") {
680
+ RouterBox.routes[path] = async () => {
681
+ const paged = typeof page === "function" ? await page() : await page;
682
+ return RouterBox.route(path, paged);
683
+ };
684
+ } else {
685
+ RouterBox.route(path, page);
686
+ }
687
+ }
688
+ Router._mount();
689
+ }
690
+ static pauseNavigation() {
691
+ RouterBox["paused"] = true;
692
+ window.location.hash = "paused";
693
+ }
694
+ static resumeNavigation() {
695
+ RouterBox["paused"] = false;
696
+ window.location.replace(window.location.pathname + window.location.search);
697
+ history.go(-1);
698
+ }
699
+ static navigate(href, data) {
700
+ if (typeof href !== "string") {
701
+ console.error(" ✘ Cradova err: href must be a defined path but got " + href + " instead");
702
+ }
703
+ let route = null, params;
704
+ if (href.includes(".")) {
705
+ window.location.href = href;
706
+ } else {
707
+ [route, params] = RouterBox.checker(href);
708
+ if (route) {
709
+ RouterBox.nextRouteController = route;
710
+ window.history.pushState({}, "", href);
711
+ }
712
+ RouterBox.pageData.params = params;
713
+ RouterBox.pageData.data = data;
714
+ RouterBox.router(null);
715
+ }
716
+ }
717
+ static setLoadingPage(page) {
718
+ if (page instanceof Page) {
719
+ RouterBox.loadingPage = page;
720
+ } else {
721
+ throw new Error(" ✘ Cradova err: Loading Page should be a cradova page class");
722
+ }
723
+ }
724
+ static get PageData() {
725
+ return RouterBox.pageData;
726
+ }
727
+ static addErrorHandler(callback) {
728
+ if (typeof callback === "function") {
729
+ RouterBox["errorHandler"] = callback;
730
+ } else {
731
+ throw new Error(" ✘ Cradova err: callback for error event is not a function");
732
+ }
733
+ }
734
+ static _mount() {
735
+ let doc = document.querySelector("[data-wrapper=app]");
736
+ if (doc) {
737
+ RouterBox.doc = doc;
738
+ } else {
739
+ throw new Error(`✘ Cradova err: please add '<div data-wrapper="app"></div>' to the body of your index.html file `);
740
+ }
741
+ window.addEventListener("pageshow", () => RouterBox.router());
742
+ window.addEventListener("popstate", (_e) => {
743
+ _e.preventDefault();
744
+ RouterBox.router();
745
+ });
746
+ }
747
+ }
748
+
749
+ class __raw_ref {
750
+ tree = {};
751
+ bindAs(name) {
752
+ return [this, name];
753
+ }
754
+ elem(name) {
755
+ return this.tree[name];
756
+ }
757
+ _append(name, Element) {
758
+ this.tree[name] = Element;
759
+ }
760
+ }
761
+ export {
762
+ video,
763
+ useState,
764
+ useRef,
765
+ useEffect,
766
+ ul,
767
+ tr,
768
+ textarea,
769
+ td,
770
+ tbody,
771
+ table,
772
+ svg,
773
+ span,
774
+ sendSignal,
775
+ select,
776
+ section,
777
+ raw,
778
+ p,
779
+ option,
780
+ ol,
781
+ nav,
782
+ makeElement,
783
+ main,
784
+ loop,
785
+ li,
786
+ label,
787
+ input,
788
+ img,
789
+ iframe,
790
+ i,
791
+ header,
792
+ h6,
793
+ h5,
794
+ h4,
795
+ h3,
796
+ h2,
797
+ h1,
798
+ getSignal,
799
+ funcManager,
800
+ frag,
801
+ form,
802
+ footer,
803
+ div,
804
+ cradovaEvent,
805
+ cra,
806
+ canvas,
807
+ button,
808
+ audio,
809
+ a,
810
+ __raw_ref,
811
+ Signal,
812
+ Router,
813
+ Page,
814
+ CradovaEvent,
815
+ $switch,
816
+ $ifelse,
817
+ $if,
818
+ $case
819
+ };
@@ -1,74 +1,28 @@
1
- import { type browserPageType, type CradovaPageType } from "./types.js";
1
+ import type { browserPageType, CradovaPageType } from "./types.js";
2
2
  /**
3
3
  * Cradova event
4
4
  */
5
- declare class cradovaEvent {
5
+ export declare class cradovaEvent {
6
6
  static compId: number;
7
7
  /**
8
- * the events runs only once and removed.
9
- * these event are call and removed once when when a comp is rendered to the dom
8
+ * the events runs only once and removed to avoid duplication when added on the next rendering
9
+ * these event are call and removed once when when a Function is rendered to the dom
10
10
  * @param callback
11
11
  */
12
- afterMount: Function[];
13
- /**
14
- * the events runs many times.
15
- * these event are called before a comp is rendered to the dom
16
- * @param callback
17
- */
18
- beforeMountActive: Function[];
12
+ after_comp_is_mounted: Function[];
19
13
  /**
20
14
  * the events runs once after comps unmounts.
21
- * these event are called before a comp is rendered to the dom
15
+ * these event are called before a Function is rendered to the dom
22
16
  * @param callback
23
17
  */
24
- afterDeactivate: Function[];
18
+ after_page_is_killed: Function[];
25
19
  /**
26
20
  * Dispatch any event
27
21
  * @param eventName
28
22
  */
29
- dispatchEvent(eventName: "beforeMountActive" | "afterMount" | "afterDeactivate"): void;
23
+ dispatchEvent(eventName: "after_comp_is_mounted" | "after_page_is_killed"): void;
30
24
  }
31
25
  export declare const CradovaEvent: cradovaEvent;
32
- /**
33
- * Cradova Comp
34
- * -------
35
- * create dynamic components
36
- */
37
- export declare class Comp<Props extends Record<string, any> = any> {
38
- id: number;
39
- private component;
40
- private effects;
41
- private effectuate;
42
- private rendered;
43
- private published;
44
- private preRendered;
45
- private reference;
46
- subData: Props | null;
47
- publish: ((data: any) => void) | null;
48
- _state: Props[];
49
- _state_index: number;
50
- constructor(component: (this: Comp<Props>) => HTMLElement);
51
- preRender(): void;
52
- /**
53
- * Cradova Comp
54
- * ---
55
- * returns html with cradova reference
56
- * @param data
57
- * @returns () => HTMLElement
58
- */
59
- render(): HTMLElement;
60
- _effect(fn: () => Promise<void> | void): void;
61
- private effector;
62
- /**
63
- * Cradova Comp
64
- * ---
65
- * update comp component with new data and update the dom.
66
- * @param data
67
- * @returns
68
- */
69
- recall(): void;
70
- private activate;
71
- }
72
26
  /**
73
27
  * Cradova Signal
74
28
  * ----
@@ -94,14 +48,23 @@ export declare class Signal<Type extends Record<string, any>> {
94
48
  * @param data - data for the action
95
49
  */
96
50
  publish<T extends keyof Type>(eventName: T, data: Type[T]): void;
51
+ /**
52
+ * Cradova Signal
53
+ * ----
54
+ * fires an action if available
55
+ * @param key - string key of the action
56
+ * @param data - data for the action
57
+ */
58
+ publishObject<T extends keyof Type>(events: Record<T, Type[T]>): void;
97
59
  /**
98
60
  * Cradova Signal
99
61
  * ----
100
62
  * subscribe to an event
101
63
  *
102
- * @param Comp component to bind to.
64
+ * @param name of event.
65
+ * @param Func component to bind to.
103
66
  */
104
- subscribe<T extends keyof Type>(eventName: T, comp: Comp): void;
67
+ subscribe<T extends keyof Type>(eventName: T | T[], comp: any): void;
105
68
  /**
106
69
  * Cradova Signal
107
70
  * ----
@@ -125,7 +88,7 @@ export declare class Page {
125
88
  * this should be a cradova page component
126
89
  */
127
90
  _html: (this: Page) => HTMLElement;
128
- private _template;
91
+ _template?: HTMLElement;
129
92
  private _dropped;
130
93
  private _snapshot;
131
94
  private _snapshot_html?;
@@ -204,4 +167,27 @@ export declare class Router {
204
167
  static addErrorHandler(callback: (err?: unknown, pagePath?: string) => void): void;
205
168
  static _mount(): void;
206
169
  }
207
- export {};
170
+ /**
171
+ * Cradova
172
+ * ---
173
+ * make reference to dom elements
174
+ */
175
+ export declare class __raw_ref {
176
+ tree: Record<string, any>;
177
+ /**
178
+ * Bind a DOM element to a reference name.
179
+ * @param name - The name to reference the DOM element by.
180
+ */
181
+ bindAs(name: string): __raw_ref;
182
+ /**
183
+ * Retrieve a referenced DOM element.
184
+ * @param name - The name of the referenced DOM element.
185
+ */
186
+ elem<ElementType extends HTMLElement = HTMLElement>(name: string): ElementType | undefined;
187
+ /**
188
+ * Append a DOM element to the reference, overwriting any existing reference.
189
+ * @param name - The name to reference the DOM element by.
190
+ * @param element - The DOM element to reference.
191
+ */
192
+ _append(name: string, Element: HTMLElement): void;
193
+ }
@@ -22,12 +22,10 @@ export declare const li: (...Children_and_Properties: VJS_params_TYPE<HTMLLIElem
22
22
  export declare const main: (...Children_and_Properties: VJS_params_TYPE<HTMLElement>) => HTMLElement;
23
23
  export declare const nav: (...Children_and_Properties: VJS_params_TYPE<HTMLElement>) => HTMLElement;
24
24
  export declare const ol: (...Children_and_Properties: VJS_params_TYPE<HTMLOListElement>) => HTMLOListElement;
25
- export declare const optgroup: (...Children_and_Properties: VJS_params_TYPE<HTMLOptGroupElement>) => HTMLOptGroupElement;
26
25
  export declare const option: (...Children_and_Properties: VJS_params_TYPE<HTMLOptionElement>) => HTMLOptionElement;
27
26
  export declare const p: (...Children_and_Properties: VJS_params_TYPE<HTMLParagraphElement>) => HTMLParagraphElement;
28
27
  export declare const section: (...Children_and_Properties: VJS_params_TYPE<HTMLElement>) => HTMLElement;
29
28
  export declare const select: (...Children_and_Properties: VJS_params_TYPE<HTMLSelectElement>) => HTMLSelectElement;
30
- export declare const source: (...Children_and_Properties: VJS_params_TYPE<HTMLSourceElement>) => HTMLSourceElement;
31
29
  export declare const span: (...Children_and_Properties: VJS_params_TYPE<HTMLSpanElement>) => HTMLSpanElement;
32
30
  export declare const textarea: (...Children_and_Properties: VJS_params_TYPE<HTMLTextAreaElement>) => HTMLTextAreaElement;
33
31
  export declare const ul: (...Children_and_Properties: VJS_params_TYPE<HTMLUListElement>) => HTMLUListElement;
@@ -0,0 +1,8 @@
1
+ import type { CradovaFunc } from "./types";
2
+ export declare const funcManager: {
3
+ render(func: CradovaFunc): HTMLElement;
4
+ _effect(func: CradovaFunc, fn: () => Promise<void> | void): void;
5
+ effector(func: CradovaFunc): Promise<void>;
6
+ recall(func: CradovaFunc): void;
7
+ activate(func: CradovaFunc): Promise<void>;
8
+ };
@@ -1,36 +1,7 @@
1
- import { type VJS_params_TYPE } from "./types.js";
2
- import { Comp } from "./classes.js";
3
- /**
4
- * Cradova
5
- * ---
6
- * make reference to dom elements
7
- */
8
- declare class __raw_ref {
9
- tree: Record<string, any>;
10
- /**
11
- * Bind a DOM element to a reference name.
12
- * @param name - The name to reference the DOM element by.
13
- */
14
- bindAs(name: string): __raw_ref;
15
- /**
16
- * Retrieve a referenced DOM element.
17
- * @param name - The name of the referenced DOM element.
18
- */
19
- elem<ElementType extends HTMLElement = HTMLElement>(name: string): ElementType | undefined;
20
- /**
21
- * Swap referenced DOM element.
22
- */
23
- swap(name1: string, name2: string): void;
24
- /**
25
- * Append a DOM element to the reference, overwriting any existing reference.
26
- * @param name - The name to reference the DOM element by.
27
- * @param element - The DOM element to reference.
28
- */
29
- _append(name: string, Element: HTMLElement): void;
30
- }
1
+ import type { VJS_params_TYPE, CradovaFunc } from "./types.js";
2
+ import { __raw_ref } from "./classes.js";
31
3
  export declare const makeElement: <E extends HTMLElement>(element: E & HTMLElement, ElementChildrenAndPropertyList: VJS_params_TYPE<E>) => E;
32
4
  export declare const cra: <E extends HTMLElement>(tag: string) => (...Children_and_Properties: VJS_params_TYPE<E>) => E;
33
- export declare function Rhoda(l: VJS_params_TYPE<HTMLElement>): DocumentFragment;
34
5
  /**
35
6
  * @param {expression} condition
36
7
  * @param {function} elements[]
@@ -52,18 +23,18 @@ export declare const frag: (children: VJS_params_TYPE<HTMLElement>) => DocumentF
52
23
  * ---
53
24
  * Allows functional components to manage state by providing a state value and a function to update it.
54
25
  * @param initialValue
55
- * @param Comp
26
+ * @param Func
56
27
  * @returns [state, setState]
57
28
  */
58
- export declare function useState<S = unknown>(newState: S, Comp: Comp<any>): [S, (newState: S | ((preS: S) => S)) => void];
29
+ export declare function useState<S = unknown>(newState: S, self: any): [S, (newState: S | ((preS: S) => S)) => void];
59
30
  /**
60
31
  * Cradova
61
32
  * ---
62
- Allows side effects to be performed in functional components (Comps), such as fetching data or subscribing to events.
33
+ Allows side effects to be performed in functional components, such as fetching data or subscribing to events.
63
34
  * @param effect
64
35
  * @returns
65
36
  */
66
- export declare function useEffect(effect: () => void, Comp: Comp): void;
37
+ export declare function useEffect(effect: () => void, self: any): any;
67
38
  /**
68
39
  * Cradova
69
40
  * ---
@@ -71,4 +42,13 @@ Returns a mutable reference object of dom elements.
71
42
  * @returns reference
72
43
  */
73
44
  export declare function useRef(): __raw_ref;
45
+ export declare const getSignal: (func: CradovaFunc, name: string) => any;
46
+ export declare const sendSignal: (func: CradovaFunc, name: string, data: any) => void;
47
+ export declare const funcManager: {
48
+ render(func: CradovaFunc): HTMLElement;
49
+ _effect(func: CradovaFunc, fn: () => Promise<void> | void): void;
50
+ effector(func: CradovaFunc): Promise<void>;
51
+ recall(func: CradovaFunc): void;
52
+ activate(func: CradovaFunc): Promise<void>;
53
+ };
74
54
  export {};
@@ -1,5 +1,5 @@
1
1
  import * as CSS from "csstype";
2
- import { Comp, Page } from "./classes.js";
2
+ import { __raw_ref, Page, Signal } from "./classes.js";
3
3
  type DataAttributes = {
4
4
  [key: `data-${string}`]: string;
5
5
  };
@@ -24,13 +24,13 @@ type Attributes = {
24
24
  required?: string;
25
25
  frameBorder?: string;
26
26
  placeholder?: string;
27
- ref?: [any, string];
27
+ ref?: __raw_ref;
28
28
  autocomplete?: string;
29
29
  style?: CSS.Properties;
30
30
  recall?: (P: any) => void;
31
31
  onmount?: (this: HTMLElement & Attributes) => void;
32
32
  };
33
- export type VJS_params_TYPE<E extends HTMLElement> = (Comp | Comp[] | string | undefined | HTMLElement | HTMLElement[] | DocumentFragment | DocumentFragment[] | Attributes | Partial<Attributes> | (() => HTMLElement) | Partial<E> | Record<string, (this: E) => void> | Partial<DataAttributes> | Partial<AriaAttributes> | CSS.Properties<string | number>)[];
33
+ export type VJS_params_TYPE<E extends HTMLElement> = (string | undefined | HTMLElement | HTMLElement[] | DocumentFragment | DocumentFragment[] | Attributes | Partial<Attributes> | (() => HTMLElement) | Partial<E> | Record<string, (this: E) => void> | Partial<DataAttributes> | Partial<AriaAttributes> | CSS.Properties<string | number>)[];
34
34
  export interface RouterRouteObject {
35
35
  _html: ((this: Page, data?: unknown) => HTMLElement | DocumentFragment) | HTMLElement | DocumentFragment;
36
36
  _delegatedRoutes: number | boolean;
@@ -78,4 +78,17 @@ export type CradovaPageType = {
78
78
  snapshotIsolation?: boolean;
79
79
  };
80
80
  export type browserPageType<importType = Page> = importType | Promise<importType> | (() => Promise<importType>);
81
+ export type CradovaFunc = {
82
+ (): HTMLElement;
83
+ id?: number;
84
+ rendered: boolean;
85
+ published: boolean;
86
+ reference: HTMLElement | null;
87
+ signals: Map<string, Signal<any>>;
88
+ pipes: Map<string, any>;
89
+ _state: unknown[];
90
+ _state_index: number;
91
+ effects: (() => Promise<void> | void)[];
92
+ effectuate: ((this: any) => void) | null;
93
+ };
81
94
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cradova",
3
- "version": "3.5.8",
3
+ "version": "3.6.1",
4
4
  "description": "Build Powerful ⚡ Web Apps with Ease",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",
@@ -21,7 +21,6 @@
21
21
  "PWA",
22
22
  "webapp",
23
23
  "SPA",
24
- "Comps",
25
24
  "Signal",
26
25
  "VJS",
27
26
  "vjs specification",