ajo 0.1.18 → 0.1.20

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/dist/html.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const{create:p,assign:v,entries:g,hasOwn:x}=Object,{isArray:f,from:k}=Array,m="",c=e=>k(d(e)).join(""),d=function*(e){for(e of u(e))if(typeof e=="string")yield $(e);else{const{nodeName:t,skip:o,children:r=""}=e;let n="";for(const[l,i]of g(e))S.has(l)||l.startsWith("set:")||i==null||i===!1||(n+=i===!0?` ${l}`:` ${l}="${$(String(i))}"`);w.has(t)?yield`<${t}${n}>`:o?yield`<${t}${n}></${t}>`:(yield`<${t}${n}>`,typeof r=="string"&&r.startsWith(m)?yield r.slice(1):yield*d(r),yield`</${t}>`)}},u=function*(e,t={value:""},o=!0){for(e of f(e)?e:[e])if(!(e==null||typeof e=="boolean"))if(x(e,"nodeName")){const{value:r}=t,{nodeName:n}=e;if(r&&(yield r,t.value=""),typeof n=="function")if(n.constructor.name==="GeneratorFunction"){const l={},i=v({},n.attrs);for(const a in e){const y=e[a];a.startsWith("attr:")?i[a.slice(5)]=y:l[a]=y}i.nodeName=n.is??"div",i.children=N(n,l),yield i}else yield*u(n(e),t,!1);else yield e}else f(e)?yield*u(e,t,!1):t.value+=e;o&&t.value&&(yield t.value)},w=new Set("area,base,br,col,command,embed,hr,img,input,keygen,link,meta,param,source,track,wbr".split(",")),S=new Set("nodeName,key,skip,memo,ref,children".split(",")),$=e=>e.replace(/[&<>"']/g,t=>`&#${t.charCodeAt(0)};`);let s=null;const N=(e,t)=>{let o,r;try{const n=e.call(o={$args:t,$context:p(s?s.$context:null),render(){s!==o&&o.$next()},$next(){const l=s;s=o,r=c(n.next().value),s=l},$throw(l){r=c(n.throw(l).value)},$return(){n.return()}},t);o.$next()}catch(n){o.$throw(n)}finally{o.$return()}return m+r},b=(e,t=Symbol())=>function(o,r){return arguments.length===1?t in o.$context?o.$context[t]:e:o.$context[t]=r};exports.context=b;exports.html=d;exports.render=c;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const{isArray:$,from:p}=Array,m="",{create:g,assign:v,entries:x,prototype:{hasOwnProperty:w},hasOwn:S=(e,t)=>w.call(e,t)}=Object,c=e=>p(d(e)).join(""),d=function*(e){for(e of u(e))if(typeof e=="string")yield f(e);else{const{nodeName:t,skip:o,children:r=""}=e;let n="";for(const[i,s]of x(e))k.has(i)||i.startsWith("set:")||s==null||s===!1||(n+=s===!0?` ${i}`:` ${i}="${f(String(s))}"`);N.has(t)?yield`<${t}${n}>`:o?yield`<${t}${n}></${t}>`:(yield`<${t}${n}>`,typeof r=="string"&&r.startsWith(m)?yield r.slice(1):yield*d(r),yield`</${t}>`)}},u=function*(e,t={value:""},o=!0){for(e of $(e)?e:[e])if(!(e==null||typeof e=="boolean"))if(S(e,"nodeName")){const{value:r}=t,{nodeName:n}=e;if(r&&(yield r,t.value=""),typeof n=="function")if(n.constructor.name==="GeneratorFunction"){const i={},s=v({},n.attrs);for(const a in e){const y=e[a];a.startsWith("attr:")?s[a.slice(5)]=y:i[a]=y}s.nodeName=n.is??"div",s.children=O(n,i),yield s}else yield*u(n(e),t,!1);else yield e}else $(e)?yield*u(e,t,!1):t.value+=e;o&&t.value&&(yield t.value)},N=new Set("area,base,br,col,command,embed,hr,img,input,keygen,link,meta,param,source,track,wbr".split(",")),k=new Set("nodeName,key,skip,memo,ref,children".split(",")),f=e=>e.replace(/[&<>"']/g,t=>`&#${t.charCodeAt(0)};`);let l=null;const O=(e,t)=>{let o,r;try{const n=e.call(o={$args:t,$context:g((l==null?void 0:l.$context)??null),render(){l!==o&&o.$next()},$next(){const i=l;l=o,r=c(n.next().value),l=i},$throw(i){r=c(n.throw(i).value)},$return(){n.return()}},t);o.$next()}catch(n){o.$throw(n)}finally{o.$return()}return m+r},j=(e,t=Symbol())=>function(o,r){return arguments.length===0?l&&t in l.$context?l.$context[t]:e:arguments.length===1?t in o.$context?o.$context[t]:e:o.$context[t]=r};exports.context=j;exports.html=d;exports.render=c;
package/dist/html.js CHANGED
@@ -1,47 +1,47 @@
1
- const { create: p, assign: v, entries: x, hasOwn: g } = Object, { isArray: d, from: k } = Array, f = "", y = (e) => k(m(e)).join(""), m = function* (e) {
1
+ const { isArray: d, from: p } = Array, f = "", { create: x, assign: v, entries: g, prototype: { hasOwnProperty: w }, hasOwn: N = (e, t) => w.call(e, t) } = Object, $ = (e) => p(m(e)).join(""), m = function* (e) {
2
2
  for (e of c(e))
3
- if (typeof e == "string") yield $(e);
3
+ if (typeof e == "string") yield y(e);
4
4
  else {
5
5
  const { nodeName: t, skip: o, children: r = "" } = e;
6
6
  let n = "";
7
- for (const [i, l] of x(e))
8
- N.has(i) || i.startsWith("set:") || l == null || l === !1 || (n += l === !0 ? ` ${i}` : ` ${i}="${$(String(l))}"`);
9
- w.has(t) ? yield `<${t}${n}>` : o ? yield `<${t}${n}></${t}>` : (yield `<${t}${n}>`, typeof r == "string" && r.startsWith(f) ? yield r.slice(1) : yield* m(r), yield `</${t}>`);
7
+ for (const [i, s] of g(e))
8
+ S.has(i) || i.startsWith("set:") || s == null || s === !1 || (n += s === !0 ? ` ${i}` : ` ${i}="${y(String(s))}"`);
9
+ k.has(t) ? yield `<${t}${n}>` : o ? yield `<${t}${n}></${t}>` : (yield `<${t}${n}>`, typeof r == "string" && r.startsWith(f) ? yield r.slice(1) : yield* m(r), yield `</${t}>`);
10
10
  }
11
11
  }, c = function* (e, t = { value: "" }, o = !0) {
12
12
  for (e of d(e) ? e : [e])
13
13
  if (!(e == null || typeof e == "boolean"))
14
- if (g(e, "nodeName")) {
14
+ if (N(e, "nodeName")) {
15
15
  const { value: r } = t, { nodeName: n } = e;
16
16
  if (r && (yield r, t.value = ""), typeof n == "function")
17
17
  if (n.constructor.name === "GeneratorFunction") {
18
- const i = {}, l = v({}, n.attrs);
18
+ const i = {}, s = v({}, n.attrs);
19
19
  for (const a in e) {
20
20
  const u = e[a];
21
- a.startsWith("attr:") ? l[a.slice(5)] = u : i[a] = u;
21
+ a.startsWith("attr:") ? s[a.slice(5)] = u : i[a] = u;
22
22
  }
23
- l.nodeName = n.is ?? "div", l.children = S(n, i), yield l;
23
+ s.nodeName = n.is ?? "div", s.children = A(n, i), yield s;
24
24
  } else yield* c(n(e), t, !1);
25
25
  else yield e;
26
26
  } else d(e) ? yield* c(e, t, !1) : t.value += e;
27
27
  o && t.value && (yield t.value);
28
- }, w = new Set("area,base,br,col,command,embed,hr,img,input,keygen,link,meta,param,source,track,wbr".split(",")), N = new Set("nodeName,key,skip,memo,ref,children".split(",")), $ = (e) => e.replace(/[&<>"']/g, (t) => `&#${t.charCodeAt(0)};`);
29
- let s = null;
30
- const S = (e, t) => {
28
+ }, k = new Set("area,base,br,col,command,embed,hr,img,input,keygen,link,meta,param,source,track,wbr".split(",")), S = new Set("nodeName,key,skip,memo,ref,children".split(",")), y = (e) => e.replace(/[&<>"']/g, (t) => `&#${t.charCodeAt(0)};`);
29
+ let l = null;
30
+ const A = (e, t) => {
31
31
  let o, r;
32
32
  try {
33
33
  const n = e.call(o = {
34
34
  $args: t,
35
- $context: p(s ? s.$context : null),
35
+ $context: x((l == null ? void 0 : l.$context) ?? null),
36
36
  render() {
37
- s !== o && o.$next();
37
+ l !== o && o.$next();
38
38
  },
39
39
  $next() {
40
- const i = s;
41
- s = o, r = y(n.next().value), s = i;
40
+ const i = l;
41
+ l = o, r = $(n.next().value), l = i;
42
42
  },
43
43
  $throw(i) {
44
- r = y(n.throw(i).value);
44
+ r = $(n.throw(i).value);
45
45
  },
46
46
  $return() {
47
47
  n.return();
@@ -54,11 +54,11 @@ const S = (e, t) => {
54
54
  o.$return();
55
55
  }
56
56
  return f + r;
57
- }, A = (e, t = Symbol()) => function(o, r) {
58
- return arguments.length === 1 ? t in o.$context ? o.$context[t] : e : o.$context[t] = r;
57
+ }, O = (e, t = Symbol()) => function(o, r) {
58
+ return arguments.length === 0 ? l && t in l.$context ? l.$context[t] : e : arguments.length === 1 ? t in o.$context ? o.$context[t] : e : o.$context[t] = r;
59
59
  };
60
60
  export {
61
- A as context,
61
+ O as context,
62
62
  m as html,
63
- y as render
63
+ $ as render
64
64
  };
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const k=({children:i})=>i,b=function(i,e){const{length:t}=arguments;return(e??(e=v(null))).nodeName=i,"children"in e||t<3||(e.children=t===3?arguments[2]:O.call(arguments,2)),e},y=(i,e)=>{let t=e.firstChild;for(i of g(i)){let n=t;if(typeof i=="string"){for(;n&&n.nodeType!=3;)n=n.nextSibling;n?n.data!=i&&(n.data=i):n=document.createTextNode(i)}else{const{nodeName:o,key:a,skip:c,memo:s,ref:f,children:N}=i;for(;n&&!(n.localName===o&&(n.$key??(n.$key=a))==a);)n=n.nextSibling;if(n??(n=d(document.createElementNS(i.xmlns??o==="svg"?T:e.namespaceURI,o),{$key:a})),s==null||F(n.$memo,n.$memo=s)){const{$props:m}=n,x={};for(const l of w(d({},m,i))){if(C.has(l))continue;const u=x[l]=i[l];u!==(m==null?void 0:m[l])&&(l.startsWith("set:")?n[l.slice(4)]=u:u==null||u===!1?n.removeAttribute(l):n.setAttribute(l,u===!0?"":u))}n.$props=x,c||y(N,n),typeof f=="function"&&(n.$ref=f)(n)}}n===t?t=t.nextSibling:B(e,n,t)}for(;t;){const n=t.nextSibling;t.nodeType===1&&S(t),e.removeChild(t),t=n}},{isArray:$,prototype:{slice:O}}=Array,{create:v,keys:w,assign:d,hasOwn:A,setPrototypeOf:p,getPrototypeOf:h}=Object,T="http://www.w3.org/2000/svg",C=new Set("nodeName,key,skip,memo,ref,children".split(",")),F=(i,e)=>$(i)&&$(e)?i.some((t,n)=>t!==e[n]):i!==e,g=function*(i,e={value:""},t=!0){for(i of $(i)?i:[i])if(!(i==null||typeof i=="boolean"))if(A(i,"nodeName")){const{value:n}=e,{nodeName:o}=i;if(n&&(yield n,e.value=""),typeof o=="function")if(o.constructor.name==="GeneratorFunction"){const a={},c=d({},o.attrs);for(const s of w(i)){const f=i[s];s.startsWith("attr:")?c[s.slice(5)]=f:s==="key"||s==="memo"?c[s]=f:a[s]=f}c.nodeName=o.is??"div",c.skip=!0,c.ref=P.bind(null,o,a),yield c}else yield*g(o(i),e,!1);else yield i}else $(i)?yield*g(i,e,!1):e.value+=i;t&&e.value&&(yield e.value)},P=(i,e,t)=>{if(!t)return;t.$gen??(t.$gen=(new E(t),i)),t.$ref=j.bind(null,t);const{skip:n,...o}=e;d(t.$args??(t.$args={}),o),n||t.$next()},j=(i,e)=>e??i.$return(),B=(i,e,t)=>{if(e.contains(document.activeElement)){const n=e.nextSibling;for(;t&&t!=e;){const o=t.nextSibling;i.insertBefore(t,n),t=o}}else i.insertBefore(e,t)},S=i=>{for(const t of i.children)S(t);const{$ref:e}=i;typeof e=="function"&&e(null)};let r=null;class E{constructor(e){p(e,p(h(this),h(e))),e.$context=v((r==null?void 0:r.$context)??null)}render(){r!=null&&r.contains(this)||this.$next()}$next(){const e=r;r=this;try{y((this.$it??(this.$it=this.$gen.call(this,this.$args))).next().value,this),typeof this.$ref=="function"&&this.$ref(this)}catch(t){this.$throw(t)}finally{r=e}}$throw(e){var t;for(let n=this;n;n=n.parentNode)if(typeof((t=n.$it)==null?void 0:t.throw)=="function")try{return y(n.$it.throw(e).value,n)}catch{}throw e}$return(){var e;try{(e=this.$it)==null||e.return()}catch(t){this.$throw(t)}finally{this.$it=null}}}const W=(i,e=Symbol())=>function(t,n){return arguments.length===1?e in t.$context?t.$context[e]:i:t.$context[e]=n};exports.Fragment=k;exports.context=W;exports.h=b;exports.render=y;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S=({children:t})=>t,N=function(t,n){const{length:e}=arguments;return(n??(n=h(null))).nodeName=t,"children"in n||e<3||(n.children=e===3?arguments[2]:b.call(arguments,2)),n},d=(t,n)=>{let e=n.firstChild;for(t of g(t)){let i=e;if(typeof t=="string"){for(;i&&i.nodeType!=3;)i=i.nextSibling;i?i.data!=t&&(i.data=t):i=document.createTextNode(t)}else{const{nodeName:o,key:l,skip:c,memo:r,ref:f,children:w}=t;for(;i&&!(i.localName===o&&(i.$key??(i.$key=l))==l);)i=i.nextSibling;if(i??(i=m(document.createElementNS(t.xmlns??o==="svg"?O:n.namespaceURI,o),{$key:l})),r==null||F(i.$memo,i.$memo=r)){const{$props:$}=i,x={};for(const a of p(m({},$,t))){if(T.has(a))continue;const u=x[a]=t[a];u!==($==null?void 0:$[a])&&(a.startsWith("set:")?i[a.slice(4)]=u:u==null||u===!1?i.removeAttribute(a):i.setAttribute(a,u===!0?"":u))}i.$props=x,c||d(w,i),typeof f=="function"&&(i.$ref=f)(i)}}i===e?e=e.nextSibling:C(n,i,e)}for(;e;){const i=e.nextSibling;e.nodeType===1&&v(e),n.removeChild(e),e=i}},{isArray:y,prototype:{slice:b}}=Array,{create:h,assign:m,keys:p,prototype:{hasOwnProperty:k},hasOwn:A=(t,n)=>k.call(t,n)}=Object,O="http://www.w3.org/2000/svg",T=new Set("nodeName,key,skip,memo,ref,children".split(",")),F=(t,n)=>y(t)&&y(n)?t.some((e,i)=>e!==n[i]):t!==n,g=function*(t,n={value:""},e=!0){for(t of y(t)?t:[t])if(!(t==null||typeof t=="boolean"))if(A(t,"nodeName")){const{value:i}=n,{nodeName:o}=t;if(i&&(yield i,n.value=""),typeof o=="function")if(o.constructor.name==="GeneratorFunction"){const l={},c=m({},o.attrs);for(const r of p(t)){const f=t[r];r.startsWith("attr:")?c[r.slice(5)]=f:r==="key"||r==="memo"?c[r]=f:l[r]=f}c.nodeName=o.is??"div",c.skip=!0,c.ref=j.bind(null,o,l),yield c}else yield*g(o(t),n,!1);else yield t}else y(t)?yield*g(t,n,!1):n.value+=t;e&&n.value&&(yield n.value)},j=(t,n,e)=>{if(!e)return;e.$gen??(e.$gen=(m(e,E),e.$context??(e.$context=h((s==null?void 0:s.$context)??null)),t)),e.$ref=B.bind(null,e);const{skip:i,...o}=n;m(e.$args??(e.$args={}),o),i||e.$next()},B=(t,n)=>n??t.$return(),C=(t,n,e)=>{if(n.contains(document.activeElement)){const i=n.nextSibling;for(;e&&e!=n;){const o=e.nextSibling;t.insertBefore(e,i),e=o}}else t.insertBefore(n,e)},v=t=>{for(const e of t.children)v(e);const{$ref:n}=t;typeof n=="function"&&n(null)};let s=null;const E={render(){s!=null&&s.contains(this)||this.$next()},$next(){const t=s;s=this;try{d((this.$it??(this.$it=this.$gen.call(this,this.$args))).next().value,this),typeof this.$ref=="function"&&this.$ref(this)}catch(n){this.$throw(n)}finally{s=t}},$throw(t){var n;for(let e=this;e;e=e.parentNode)if(typeof((n=e.$it)==null?void 0:n.throw)=="function")try{return d(e.$it.throw(t).value,e)}catch{}throw t},$return(){var t;try{(t=this.$it)==null||t.return()}catch(n){this.$throw(n)}finally{this.$it=null}}},P=(t,n=Symbol())=>function(e,i){return arguments.length===0?s&&n in s.$context?s.$context[n]:t:arguments.length===1?n in e.$context?e.$context[n]:t:e.$context[n]=i};exports.Fragment=S;exports.context=P;exports.h=N;exports.render=d;
package/dist/index.js CHANGED
@@ -1,110 +1,106 @@
1
- const P = ({ children: i }) => i, W = function(i, e) {
2
- const { length: t } = arguments;
3
- return (e ?? (e = v(null))).nodeName = i, "children" in e || t < 3 || (e.children = t === 3 ? arguments[2] : S.call(arguments, 2)), e;
4
- }, d = (i, e) => {
5
- let t = e.firstChild;
6
- for (i of g(i)) {
7
- let n = t;
8
- if (typeof i == "string") {
9
- for (; n && n.nodeType != 3; ) n = n.nextSibling;
10
- n ? n.data != i && (n.data = i) : n = document.createTextNode(i);
1
+ const F = ({ children: t }) => t, W = function(t, n) {
2
+ const { length: e } = arguments;
3
+ return (n ?? (n = h(null))).nodeName = t, "children" in n || e < 3 || (n.children = e === 3 ? arguments[2] : N.call(arguments, 2)), n;
4
+ }, d = (t, n) => {
5
+ let e = n.firstChild;
6
+ for (t of g(t)) {
7
+ let i = e;
8
+ if (typeof t == "string") {
9
+ for (; i && i.nodeType != 3; ) i = i.nextSibling;
10
+ i ? i.data != t && (i.data = t) : i = document.createTextNode(t);
11
11
  } else {
12
- const { nodeName: o, key: a, skip: c, memo: s, ref: f, children: k } = i;
13
- for (; n && !(n.localName === o && (n.$key ?? (n.$key = a)) == a); ) n = n.nextSibling;
14
- if (n ?? (n = $(document.createElementNS(i.xmlns ?? o === "svg" ? A : e.namespaceURI, o), { $key: a })), s == null || C(n.$memo, n.$memo = s)) {
15
- const { $props: m } = n, x = {};
16
- for (const l of w($({}, m, i))) {
17
- if (O.has(l)) continue;
18
- const u = x[l] = i[l];
19
- u !== (m == null ? void 0 : m[l]) && (l.startsWith("set:") ? n[l.slice(4)] = u : u == null || u === !1 ? n.removeAttribute(l) : n.setAttribute(l, u === !0 ? "" : u));
12
+ const { nodeName: o, key: l, skip: c, memo: r, ref: f, children: w } = t;
13
+ for (; i && !(i.localName === o && (i.$key ?? (i.$key = l)) == l); ) i = i.nextSibling;
14
+ if (i ?? (i = m(document.createElementNS(t.xmlns ?? o === "svg" ? b : n.namespaceURI, o), { $key: l })), r == null || O(i.$memo, i.$memo = r)) {
15
+ const { $props: $ } = i, x = {};
16
+ for (const a of p(m({}, $, t))) {
17
+ if (A.has(a)) continue;
18
+ const u = x[a] = t[a];
19
+ u !== ($ == null ? void 0 : $[a]) && (a.startsWith("set:") ? i[a.slice(4)] = u : u == null || u === !1 ? i.removeAttribute(a) : i.setAttribute(a, u === !0 ? "" : u));
20
20
  }
21
- n.$props = x, c || d(k, n), typeof f == "function" && (n.$ref = f)(n);
21
+ i.$props = x, c || d(w, i), typeof f == "function" && (i.$ref = f)(i);
22
22
  }
23
23
  }
24
- n === t ? t = t.nextSibling : E(e, n, t);
24
+ i === e ? e = e.nextSibling : C(n, i, e);
25
25
  }
26
- for (; t; ) {
27
- const n = t.nextSibling;
28
- t.nodeType === 1 && N(t), e.removeChild(t), t = n;
26
+ for (; e; ) {
27
+ const i = e.nextSibling;
28
+ e.nodeType === 1 && v(e), n.removeChild(e), e = i;
29
29
  }
30
- }, { isArray: y, prototype: { slice: S } } = Array, { create: v, keys: w, assign: $, hasOwn: b, setPrototypeOf: p, getPrototypeOf: h } = Object, A = "http://www.w3.org/2000/svg", O = new Set("nodeName,key,skip,memo,ref,children".split(",")), C = (i, e) => y(i) && y(e) ? i.some((t, n) => t !== e[n]) : i !== e, g = function* (i, e = { value: "" }, t = !0) {
31
- for (i of y(i) ? i : [i])
32
- if (!(i == null || typeof i == "boolean"))
33
- if (b(i, "nodeName")) {
34
- const { value: n } = e, { nodeName: o } = i;
35
- if (n && (yield n, e.value = ""), typeof o == "function")
30
+ }, { isArray: y, prototype: { slice: N } } = Array, { create: h, assign: m, keys: p, prototype: { hasOwnProperty: S }, hasOwn: k = (t, n) => S.call(t, n) } = Object, b = "http://www.w3.org/2000/svg", A = new Set("nodeName,key,skip,memo,ref,children".split(",")), O = (t, n) => y(t) && y(n) ? t.some((e, i) => e !== n[i]) : t !== n, g = function* (t, n = { value: "" }, e = !0) {
31
+ for (t of y(t) ? t : [t])
32
+ if (!(t == null || typeof t == "boolean"))
33
+ if (k(t, "nodeName")) {
34
+ const { value: i } = n, { nodeName: o } = t;
35
+ if (i && (yield i, n.value = ""), typeof o == "function")
36
36
  if (o.constructor.name === "GeneratorFunction") {
37
- const a = {}, c = $({}, o.attrs);
38
- for (const s of w(i)) {
39
- const f = i[s];
40
- s.startsWith("attr:") ? c[s.slice(5)] = f : s === "key" || s === "memo" ? c[s] = f : a[s] = f;
37
+ const l = {}, c = m({}, o.attrs);
38
+ for (const r of p(t)) {
39
+ const f = t[r];
40
+ r.startsWith("attr:") ? c[r.slice(5)] = f : r === "key" || r === "memo" ? c[r] = f : l[r] = f;
41
41
  }
42
- c.nodeName = o.is ?? "div", c.skip = !0, c.ref = T.bind(null, o, a), yield c;
43
- } else yield* g(o(i), e, !1);
44
- else yield i;
45
- } else y(i) ? yield* g(i, e, !1) : e.value += i;
46
- t && e.value && (yield e.value);
47
- }, T = (i, e, t) => {
48
- if (!t) return;
49
- t.$gen ?? (t.$gen = (new F(t), i)), t.$ref = B.bind(null, t);
50
- const { skip: n, ...o } = e;
51
- $(t.$args ?? (t.$args = {}), o), n || t.$next();
52
- }, B = (i, e) => e ?? i.$return(), E = (i, e, t) => {
53
- if (e.contains(document.activeElement)) {
54
- const n = e.nextSibling;
55
- for (; t && t != e; ) {
56
- const o = t.nextSibling;
57
- i.insertBefore(t, n), t = o;
42
+ c.nodeName = o.is ?? "div", c.skip = !0, c.ref = T.bind(null, o, l), yield c;
43
+ } else yield* g(o(t), n, !1);
44
+ else yield t;
45
+ } else y(t) ? yield* g(t, n, !1) : n.value += t;
46
+ e && n.value && (yield n.value);
47
+ }, T = (t, n, e) => {
48
+ if (!e) return;
49
+ e.$gen ?? (e.$gen = (m(e, E), e.$context ?? (e.$context = h((s == null ? void 0 : s.$context) ?? null)), t)), e.$ref = B.bind(null, e);
50
+ const { skip: i, ...o } = n;
51
+ m(e.$args ?? (e.$args = {}), o), i || e.$next();
52
+ }, B = (t, n) => n ?? t.$return(), C = (t, n, e) => {
53
+ if (n.contains(document.activeElement)) {
54
+ const i = n.nextSibling;
55
+ for (; e && e != n; ) {
56
+ const o = e.nextSibling;
57
+ t.insertBefore(e, i), e = o;
58
58
  }
59
- } else i.insertBefore(e, t);
60
- }, N = (i) => {
61
- for (const t of i.children) N(t);
62
- const { $ref: e } = i;
63
- typeof e == "function" && e(null);
59
+ } else t.insertBefore(n, e);
60
+ }, v = (t) => {
61
+ for (const e of t.children) v(e);
62
+ const { $ref: n } = t;
63
+ typeof n == "function" && n(null);
64
64
  };
65
- let r = null;
66
- class F {
67
- constructor(e) {
68
- p(e, p(h(this), h(e))), e.$context = v((r == null ? void 0 : r.$context) ?? null);
69
- }
65
+ let s = null;
66
+ const E = {
70
67
  render() {
71
- r != null && r.contains(this) || this.$next();
72
- }
68
+ s != null && s.contains(this) || this.$next();
69
+ },
73
70
  $next() {
74
- const e = r;
75
- r = this;
71
+ const t = s;
72
+ s = this;
76
73
  try {
77
74
  d((this.$it ?? (this.$it = this.$gen.call(this, this.$args))).next().value, this), typeof this.$ref == "function" && this.$ref(this);
78
- } catch (t) {
79
- this.$throw(t);
75
+ } catch (n) {
76
+ this.$throw(n);
80
77
  } finally {
81
- r = e;
78
+ s = t;
82
79
  }
83
- }
84
- $throw(e) {
85
- var t;
86
- for (let n = this; n; n = n.parentNode) if (typeof ((t = n.$it) == null ? void 0 : t.throw) == "function") try {
87
- return d(n.$it.throw(e).value, n);
80
+ },
81
+ $throw(t) {
82
+ var n;
83
+ for (let e = this; e; e = e.parentNode) if (typeof ((n = e.$it) == null ? void 0 : n.throw) == "function") try {
84
+ return d(e.$it.throw(t).value, e);
88
85
  } catch {
89
86
  }
90
- throw e;
91
- }
87
+ throw t;
88
+ },
92
89
  $return() {
93
- var e;
90
+ var t;
94
91
  try {
95
- (e = this.$it) == null || e.return();
96
- } catch (t) {
97
- this.$throw(t);
92
+ (t = this.$it) == null || t.return();
93
+ } catch (n) {
94
+ this.$throw(n);
98
95
  } finally {
99
96
  this.$it = null;
100
97
  }
101
98
  }
102
- }
103
- const j = (i, e = Symbol()) => function(t, n) {
104
- return arguments.length === 1 ? e in t.$context ? t.$context[e] : i : t.$context[e] = n;
99
+ }, j = (t, n = Symbol()) => function(e, i) {
100
+ return arguments.length === 0 ? s && n in s.$context ? s.$context[n] : t : arguments.length === 1 ? n in e.$context ? e.$context[n] : t : e.$context[n] = i;
105
101
  };
106
102
  export {
107
- P as Fragment,
103
+ F as Fragment,
108
104
  j as context,
109
105
  W as h,
110
106
  d as render
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ajo",
3
- "version": "0.1.18",
3
+ "version": "0.1.20",
4
4
  "description": "ajo is a JavaScript view library for building user interfaces",
5
5
  "type": "module",
6
6
  "module": "./dist/index.js",
package/readme.md CHANGED
@@ -1,9 +1,9 @@
1
+ # Ajo
2
+
1
3
  <div align="center">
2
4
  <img src="https://github.com/cristianfalcone/ajo/raw/main/ajo.png" alt="ajo" width="372" />
3
5
  </div>
4
6
 
5
- <br />
6
-
7
7
  <div align="center">
8
8
  <a href="https://npmjs.org/package/ajo">
9
9
  <img src="https://badgen.now.sh/npm/v/ajo" alt="version" />
@@ -13,693 +13,384 @@
13
13
  </a>
14
14
  </div>
15
15
 
16
- # Ajo
16
+ Ajo is a lightweight and efficient JavaScript library for building dynamic user interfaces. It combines the best ideas from Incremental DOM and Crank.js to offer a unique approach to UI development.
17
17
 
18
- Ajo is a library designed for building dynamic UI components using JSX. Integrating ideas from Incremental DOM and Crank.js, Ajo offers a unique approach in the landscape of UI libraries.
18
+ ## Key Features
19
19
 
20
- Key features:
20
+ - Efficient in-place DOM updates
21
+ - Generator-based state management
22
+ - JSX syntax support
23
+ - Lightweight design
24
+ - Server-Side Rendering (SSR) support
21
25
 
22
- - **Efficient In-Place DOM Updating**: Ajo executes in-place DOM updates, directly applying the generated vDOM tree to the DOM. This approach avoids the need to store and diff a previous vDOM tree, leading to a reduced memory footprint.
23
- - **Generator-Based State Management**: Leverages JavaScript Generators for managing component states and effects, offering developers a robust tool for controlling UI lifecycle events.
24
- - **Minimalistic Rendering Approach**: Ajo’s rendering system is optimized for minimal overhead, enhancing the speed of DOM updates and overall application performance.
25
- - **JSX Syntax for Intuitive Development**: Supports JSX, making it easy for developers familiar with React or similar libraries to adopt and use Ajo effectively.
26
- - **Lifecycle Management for Components**: Provides a suite of lifecycle methods for stateful components, facilitating precise control over component behaviors during their lifecycle.
27
- - **Flexibility and Lightweight Design**: Ajo is designed to be both adaptable for various use cases and lightweight, ensuring minimal impact on project size.
26
+ ## Quick Start
28
27
 
29
- ## Install
28
+ ### Installation
30
29
 
31
- ```sh
30
+ ```bash
32
31
  npm install ajo
33
32
  ```
34
33
 
35
- ## Usage
36
-
37
- Render JSX into DOM element:
34
+ ### Basic Usage
38
35
 
39
36
  ```jsx
40
37
  /** @jsx h */
41
38
  import { h, render } from 'ajo'
42
39
 
43
- document.body.innerHTML = '<div>Hello World</div>'
44
-
45
- render(<div>Goodbye World</div>, document.body)
46
- ```
47
-
48
- Stateless component:
49
-
50
- ```jsx
51
- /** @jsx h */
52
- import { h, render } from 'ajo'
53
-
54
- const Greet = ({ name }) => <div>Hello {name}</div>
55
-
56
- render(<Greet name="World" />, document.body)
57
- ```
58
-
59
- Stateful component:
60
-
61
- ```jsx
62
- /** @jsx h */
63
- import { h, render } from 'ajo'
40
+ const Greeting = ({ name }) => <h1>Hello, {name}!</h1>
64
41
 
65
42
  function* Counter() {
66
-
67
43
  let count = 0
68
44
 
69
- const handleClick = () => {
45
+ const increment = () => {
70
46
  count++
71
47
  this.render()
72
48
  }
73
49
 
74
- while (true) yield (
75
- <button set:onclick={handleClick}>
76
- Current: {count}
77
- </button>
78
- )
50
+ while (true) {
51
+ yield (
52
+ <>
53
+ <p>Count: {count}</p>
54
+ <button set:onclick={increment}>Increment</button>
55
+ </>
56
+ )
57
+ }
79
58
  }
80
59
 
81
- render(<Counter />, document.body)
82
- ```
83
-
84
- ## API
85
-
86
- ### render(h, el)
87
-
88
- Renders a virtual DOM tree into the actual DOM element. It is the primary method used for updating the DOM with new content.
89
-
90
- When called, it efficiently updates `el` with the new content, adding, updating, or removing DOM nodes as needed.
91
-
92
- This function enables the declarative description of the UI to be transformed into actual UI elements in the browser. It's designed to be efficient, minimizing updates to the actual DOM to improve performance and user experience.
93
-
94
- #### Parameters:
95
-
96
- - **h** (Any): The virtual DOM tree to render. This can be any value, a simple string, a virtual DOM tree created by the `h` function, etc.
97
- - **el** (HTMLElement): The DOM element into which the `h` should be rendered. This is typically a container element in your application.
98
-
99
- #### Returns:
100
-
101
- - There is no return value for this function as its primary purpose is side-effect (DOM manipulation).
102
-
103
- #### Example Usage:
104
-
105
- ```jsx
106
- /** @jsx h */
107
- import { h, render } from 'ajo'
108
-
109
- // Create a simple, stateless component
110
- const App = () => <div>Hello, World!</div>
60
+ function* App() {
61
+ while (true) {
62
+ yield (
63
+ <>
64
+ <Greeting name="Ajo Developer" />
65
+ <Counter />
66
+ </>
67
+ )
68
+ }
69
+ }
111
70
 
112
- // Render the App component into the #root element
113
- render(<App />, document.getElementById('root'))
71
+ render(<App />, document.body)
114
72
  ```
115
- > In this example, the `App` component is a simple function returning a `div` with text content. The `render` function then mounts this component into the DOM element with the ID `root`.
116
-
117
- ### h(type, [props], [...children])
118
73
 
119
- Creates a virtual DOM tree for rendering. It's the core function for defining UI components in JSX syntax. The `h` function is a hyperscript function that returns a virtual DOM tree representing the UI component. This object can then be rendered to an actual DOM using the `render` function.
74
+ ## Core Concepts
120
75
 
121
- #### Parameters:
76
+ ### HTML Attributes vs DOM Properties
122
77
 
123
- - **type** (String | Function | Generator Function): The name of the tag for the DOM element you want to create. If it's a function, it's treated as a stateless component, and if it's a generator function, it's treated as a stateful component.
124
- - **props** (Object, optional): An object containing properties you want to set on the virtual DOM element.
125
- - **children** (Any, optional): Child virtual nodes. Can be a nested array of child nodes, a string, or any other renderable JSX elements. Booleans, null, and undefined child nodes will be ignored, which is useful for conditional rendering.
126
-
127
- #### Returns:
128
-
129
- - **Object**: A virtual DOM tree.
130
-
131
- #### Example Usage:
78
+ Ajo distinguishes between HTML attributes and DOM properties. Use regular attributes for HTML attributes, and the `set:` prefix to set DOM properties directly:
132
79
 
133
80
  ```jsx
134
- /** @jsx h */
135
- import { h } from 'ajo'
136
-
137
- // Creating a simple virtual element
138
- const myElement = h('div', { id: 'my-div' }, 'Hello World')
139
-
140
- // Creating a virtual tree for a stateless component with children
141
- const MyComponent = ({ class: className }) => h('div', { class: className },
142
- h('h1', null, 'Header'),
143
- 'Text Content',
144
- h('p', null, 'Paragraph'),
145
- )
146
-
147
- // Composing
148
- const MyApp = () => h(MyComponent, { class: 'my-class' })
149
-
150
- // Render into a DOM element
151
- render(h(MyApp), document.body)
81
+ <input
82
+ type="text"
83
+ id="username"
84
+ class="form-input"
85
+ placeholder="Enter username"
86
+ set:value={inputValue}
87
+ set:onclick={handleClick}
88
+ set:disabled={isDisabled}
89
+ />
152
90
  ```
153
- > You won't typically use the `h` function, it's automatically used when you write JSX code. The previous examples demonstrate how to use the `h` function directly if you need to.
154
-
155
- ### `Fragment({ children })`
156
91
 
157
- A utility component for grouping multiple elements without adding extra nodes to the DOM. It's particularly useful for returning multiple elements from components.
92
+ In this example:
93
+ - `type`, `id`, `class`, and `placeholder` are regular HTML attributes.
94
+ - `set:value`, `set:onclick`, and `set:disabled` are DOM properties set directly on the element.
158
95
 
159
- In JSX, fragments are typically represented with empty tags (`<>...</>`), but this function provides an alternative way to create them, especially useful in environments where the shorthand syntax might not be supported.
96
+ ### Special Attributes
160
97
 
161
- #### Example Usage:
98
+ Ajo uses special attributes for optimization and control:
99
+ - `key`: For efficient list rendering
100
+ - `skip`: To prevent rendering of child elements
101
+ - `memo`: For memoization of components or elements
102
+ - `ref`: To get references to DOM nodes or component instances
162
103
 
163
104
  ```jsx
164
- //* @jsx h */
165
- //* @jsxFrag Fragment */
166
- import { h, Fragment } from 'ajo'
167
-
168
- // Using the h function
169
- const MyComponent = () => {
170
- return h(Fragment, null,
171
- h('h1', null, 'Hello'),
172
- h('h2', null, 'World')
173
- )
174
- }
175
-
176
- // Or using JSX syntax
177
- const MyComponentJSX = () => (
178
- <>
179
- <h1>Hello</h1>
180
- <h2>World</h2>
181
- </>
182
- )
105
+ <TodoItem
106
+ key={todo.id}
107
+ memo={[todo.completed]}
108
+ ref={el => el ? todosRefs.add(el) : todosRefs.delete(todo.id)}
109
+ >
110
+ <TodoTitle>{todo.title}</TodoTitle>
111
+ <div set:innerHTML={marked(todo.content)} skip></div>
112
+ </TodoItem>
183
113
  ```
184
114
 
185
- ### `set:`
186
-
187
- The `set:` prefix in Ajo allows you to directly set properties on DOM elements from within your JSX. This is distinct from simply setting attributes, as it interacts with the properties of the DOM elements, much like how you would in plain JavaScript. Ideal for situations where setting a DOM property is more appropriate or efficient than setting an HTML attribute.
188
-
189
- #### Purpose:
115
+ ### Stateless and Stateful Components
190
116
 
191
- - The `set:` prefix is used for directly setting properties on DOM elements. This is crucial for cases where you need to interact with the DOM API, or when a property does not have a direct attribute equivalent.
117
+ Stateless components are simple functions:
192
118
 
193
- #### Usage:
194
-
195
- - Use `set:` to assign various types of properties to DOM elements, including but not limited to event handlers. It can be used for properties like `textContent`, `scrollTop`, custom properties, and more.
196
-
197
- #### Examples:
198
-
199
- **Assigning Text Content:**
200
119
  ```jsx
201
- function* MyComponent() {
202
- const text = "Hello, Ajo!"
203
- while (true) yield <div set:textContent={text} skip></div>
204
- }
120
+ const Greeting = ({ name }) => <h1>Hello, {name}!</h1>
205
121
  ```
206
- > Here, `set:textContent` directly sets the `textContent` property of the `div`'s DOM node. `skip` is used to prevent Ajo from overriding the `div`'s children.
207
122
 
208
- **Setting Inner HTML:**
209
- ```jsx
210
- function* MyComponent() {
211
- const html = "<p>Hello, Ajo!</p>"
212
- while (true) yield <div set:innerHTML={html} skip></div>
213
- }
214
- ```
215
- > In this case, `set:innerHTML` is used to set the `innerHTML` property of the `div`'s DOM element. `skip` is used to prevent Ajo from overriding the `div`'s children.
123
+ Stateful components use generator functions:
216
124
 
217
- **Event Handlers (e.g., onclick):**
218
125
  ```jsx
219
- function* MyComponent() {
220
- const handleClick = () => console.log('Clicked')
221
- while (true) yield <button set:onclick={handleClick}>Click Me</button>
126
+ function* Counter() {
127
+ let count = 0
128
+ while (true) {
129
+ yield (
130
+ <button set:onclick={() => { count++; this.render(); }}>
131
+ {count}
132
+ </button>
133
+ )
134
+ }
222
135
  }
223
136
  ```
224
- > `set:onclick` assigns the `handleClick` function as the click event listener for the button.
225
-
226
- ### Special Attributes in Ajo
227
-
228
- In Ajo, there are several special attributes (`key`, `skip`, `memo`, and `ref`) that have specific purposes and behaviors. Understanding these attributes is crucial for optimizing rendering and managing component lifecycle and references in your applications.
229
-
230
- #### `key` Attribute:
231
- - **Purpose:** The `key` attribute is used to track the identity of elements in lists or sequences. It's crucial for optimizing the rendering process, especially when dealing with dynamic lists where items can be added, removed, or reordered.
232
- - **Behavior:** When a list of elements is rendered, Ajo uses the `key` attribute to efficiently update the DOM. It identifies which elements have changed, need to be added, or can be reused. This minimizes DOM manipulations, leading to better performance.
233
- - **Example:** In a list of items rendered by a map function, each item should have a unique `key` prop, like `h('li', { key: item.id }, item.text)`.
234
-
235
- #### `skip` Attribute:
236
- - **Purpose:** The `skip` attribute is used to instruct Ajo to skip rendering for a specific element child nodes. It's useful for preventing certain parts of the DOM from being updated, like when using a third-party library that manipulates the DOM directly.
237
- - **Behavior:** When `skip` is set to `true` on an element, Ajo will not render or update that element's child nodes.
238
- - **Example:** `h('div', { skip: shouldSkip })` - here, if `shouldSkip` is `true`, Ajo will not render or update the `div`'s child nodes.
239
-
240
- #### `memo` Attribute:
241
- - **Purpose:** The `memo` attribute is used for memoization. It's a performance optimization technique to prevent unnecessary renders.
242
- - **Behavior:** When the `memo` attribute is provided, Ajo will shallow compare the memoized values with the new ones. If they are the same, Ajo will skip rendering the element attributes, properties and child nodes. For stateful components, this also prevents the component from re-rendering.
243
- - **Example:** `h(div, { memo: [dependency1, dependency2] })` - the element will re-render only if `dependency1` or `dependency2` change.
244
-
245
- #### `ref` Attribute:
246
- - **Purpose:** The `ref` attribute provides a way to access the underlying DOM element.
247
- - **Behavior:** When an element is mounted or updated, the `ref` callback is called with the DOM element as an argument. This allows you to store a reference to it for later use, such as focusing an input or measuring dimensions.
248
- - **Example:** `h('input', { ref: el => (this.inputNode = el) })` - stores a reference to the input element.
249
137
 
250
- ## Stateful Components
251
-
252
- Stateful components in Ajo are defined using generator functions. These components are designed with a minimalistic API for controlling rendering and state updates. They are equipped with several lifecycle methods that allow for advanced control over component behavior, error handling, and rendering processes.
253
-
254
- The following example demonstrates key features of stateful components in Ajo:
138
+ State handling in Ajo is straightforward:
139
+ - State is managed using regular variables within the generator function.
140
+ - The `this.render()` method triggers a re-render when state changes.
141
+ - Each iteration of the generator function represents a new render cycle.
255
142
 
256
143
  ```jsx
257
- function* ChatComponent(props) {
258
-
259
- // Define mutable state variables.
260
- let message = '', connected = false
261
-
262
- // Define event handlers.
263
- const handleMessageChange = event => {
264
-
265
- message = event.target.value
266
-
267
- this.render()
268
- }
269
-
270
- const send = () => {
271
-
272
- if (message) {
273
-
274
- connection.send(JSON.stringify({ user: props.user ?? 'Anonymous', message }))
275
-
276
- message = ''
277
-
278
- this.render()
279
- }
280
- }
281
-
282
- const handleConnectionOpen = () => {
283
- connected = true
284
- this.render()
285
- }
286
-
287
- const handleConnectionError = error => {
288
- // Throw error to be caught by the component itself or a parent component.
289
- this.$throw(new Error('Connection error: ' + error.message))
290
- }
291
-
292
- // Setup resources.
293
- const server = `ws://chat.com/${props.room}`
294
- const connection = new WebSocket(server)
295
-
296
- connection.onopen = handleConnectionOpen
297
- connection.onerror = handleConnectionError
298
-
299
- // 'this' is a DOM element, so we can use DOM APIs on it.
300
- this.classList.add('chat-component')
301
-
302
- try { // Optional try/finally block for cleanup logic.
303
-
144
+ function* Timer() {
145
+ let seconds = 0
146
+ const intervalId = setInterval(() => {
147
+ seconds++
148
+ this.render() // Trigger a re-render
149
+ }, 1000)
150
+
151
+ try {
304
152
  while (true) {
305
-
306
- try { // Optional try/catch block for error handling.
307
-
308
- // Compute derived values.
309
- const status = connected ? `You are connected as ${props.user ?? 'Anonymous'}.` : "Connecting to chat..."
310
-
311
- // Render the component UI.
312
- yield (
313
- <>
314
- <div class="status-message">{status}</div>
315
- <div class="connection-status">{connected ? 'Connected' : 'Connecting...'}</div>
316
- <input type="text" value={message} set:onchange={handleMessageChange} />
317
- <button set:onclick={send}>Send</button>
318
- </>
319
- )
320
- } catch (e) {
321
- // Handle any errors that occur during rendering or state updates.
322
- yield <pre>Error: {e.message}</pre>
323
- }
153
+ yield <div>Seconds: {seconds}</div>
324
154
  }
325
155
  } finally {
326
- // Cleanup logic: release resources, close connections, etc.
327
- connection.close()
156
+ clearInterval(intervalId) // Cleanup
328
157
  }
329
158
  }
330
159
  ```
331
160
 
332
- ### Default Rendering Behavior
333
-
334
- By default, when a stateful component is rendered in Ajo, it wraps its yielded content within a `<div>` element. This `<div>` becomes the context of the component's generator function, referred to as `this` within the function.
161
+ ### Component Lifecycle
335
162
 
336
- For example:
163
+ Stateful components have a simple lifecycle:
164
+ - Initialization: When the generator is first called
165
+ - Rendering: Each time the generator yields
166
+ - Cleanup: When the generator's `finally` block is executed
337
167
 
338
- ```javascript
339
- function* MyComponent() {
340
- // The 'this' variable here refers to the default 'div' wrapper element
168
+ ```jsx
169
+ function* LifecycleDemo() {
170
+ console.log('Initialized')
171
+ try {
172
+ while (true) {
173
+ console.log('Rendering')
174
+ yield <div>Hello, Ajo!</div>
175
+ }
176
+ } finally {
177
+ console.log('Cleanup')
178
+ }
341
179
  }
342
180
  ```
343
- > This default behavior ensures a consistent and predictable wrapper for your component's content, making it easier to manage and style.
344
181
 
345
- ### Customizing the Wrapper Element
182
+ ### attr: Attributes
346
183
 
347
- While the default wrapper is a `<div>`, Ajo provides the flexibility to change this to any other HTML element type. This is particularly useful for semantic correctness or when integrating with existing HTML structures, especially in SSR scenarios.
184
+ Use the `attr:` prefix to add HTML attributes to a component's root element:
348
185
 
349
- To specify a different element type for the wrapper, set the `is` property on the Generator Function of your component. For example:
350
-
351
- ```javascript
352
- function* MyCustomRow() {
353
- // The 'this' variable here refers to the default 'tr' wrapper element
186
+ ```jsx
187
+ function* CustomButton(props) {
188
+ while (true) yield <>{props.children}</>
354
189
  }
190
+ CustomButton.is = 'button'
355
191
 
356
- MyCustomRow.is = 'tr'
192
+ // Usage
193
+ <CustomButton attr:class="primary" attr:id="submit-btn">
194
+ Click me
195
+ </CustomButton>
357
196
  ```
358
- > This code will instruct Ajo to render a `<tr>` element instead of the default `<div>`. This capability is crucial for rendering and hydrating any type of HTML element when using stateful components.
359
197
 
360
- ### Wrapper Element Default Attributes
198
+ ### Component.attrs and Component.is
361
199
 
362
- When a stateful component is rendered in Ajo, you can specify default attributes for all components instances of that type. This is useful for setting default attributes that are common to all instances of a component, such as `class` or `style`.
200
+ Use `Component.attrs` to set default attributes for a component:
363
201
 
364
- To specify default attributes for a component, set the `attrs` property on the Generator Function of your component. For example:
365
-
366
- ```javascript
367
- function* MyComponent() {
368
- // ...
202
+ ```jsx
203
+ function* CustomButton(props) {
204
+ while (true) yield <>{props.children}</>
369
205
  }
370
-
371
- MyComponent.attrs = { class: 'my-class' }
206
+ CustomButton.attrs = { class: 'btn btn-primary' }
372
207
  ```
373
- > This code will instruct Ajo to set the `class` attribute to `my-class` on all instances of `MyComponent`.
374
208
 
375
- ### `attr:`
209
+ Use `Component.is` to specify the HTML element for a component:
376
210
 
377
- - **Purpose:** The `attr:` prefix is used in Ajo to explicitly set attributes to the underlying DOM element of a stateful component.
378
- This prefix distinguishes regular HTML attributes from component arguments, making it easier to identify and manage them.
379
-
380
- - **Behavior:**
381
- - When a stateful component is rendered in Ajo, any property on it that starts with `attr:` is treated as a regular HTML attribute and is applied to the component's underlying DOM element.
382
- - This mechanism ensures that the arguments are clearly identified and separated from the HTML attributes.
383
-
384
- - **Usage:**
385
- - Use `attr:` prefixed attributes when you need to pass attributes to a component's underlying DOM element.
386
-
387
- - **Example:**
388
211
  ```jsx
389
- function* ParentComponent() {
390
-
391
- const someData = { /* ... */ }
392
- const handleEvent = () => { /* ... */ }
393
-
394
- yield <ChildComponent
395
- attr:class="my-class"
396
- data={someData}
397
- onEvent={handleEvent}
398
- />
399
- }
400
-
401
- function* ChildComponent(props) { // props is an object containing data and onEvent
402
- // ...
212
+ function* CustomInput(props) {
213
+ while (true) yield <>{props.children}</>
403
214
  }
215
+ CustomInput.is = 'input'
404
216
  ```
405
- > In this example, `ParentComponent` renders `ChildComponent`, passing `someData` and `handleEvent` as arguments. `attr:class` is a regular HTML attribute and is not passed to the component's generator function, it is applied to the DOM element associated with the component.
406
-
407
- This `attr:` prefixed attribute system in Ajo enhances the clarity and readability of component composition. It makes the intent of passing DOM attributes more explicit, reducing confusion between function arguments and HTML attributes.
408
217
 
409
- ### SSR and Hydration
410
-
411
- In the context of Server-Side Rendering (SSR), this features allows Ajo to gracefully hydrate existing SSR-generated DOM elements. Ajo can extend the functionality of built-in browser DOM elements without relying on Web Components or standards like Declarative Shadow DOM. It provides a streamlined, efficient method for enhancing and manipulating built-in elements, offering a more practical solution compared to the complexities of Web Components.
218
+ ## API
412
219
 
413
- ## Lifecycle methods
220
+ ### `ajo` module
414
221
 
415
- Stateful components in Ajo are equipped with several methods that allow for advanced control over component behavior, error handling, and rendering processes. These methods are called lifecycle methods and are invoked at different stages of the component's lifecycle.
222
+ #### `h(type, props?, ...children)`
416
223
 
417
- ### `this.$next()`
224
+ Creates virtual DOM elements.
418
225
 
419
- The `$next` method is used within stateful components in Ajo to advance the component's generator function to its next yield point. This method is crucial for rendering the next state of the component.
226
+ ```javascript
227
+ const element = h('div', { class: 'container' }, 'Hello, Ajo!')
228
+ ```
420
229
 
421
- #### Purpose:
230
+ #### `render(vnode, container)`
422
231
 
423
- - **Synchronous Rendering:** `this.$next()` is used to render the next state of the component. It advances the generator function to the next yield, reflecting any changes in state or props right away.
232
+ Renders a virtual DOM tree into a DOM element.
424
233
 
425
- #### Usage:
234
+ ```javascript
235
+ render(h(App), document.body)
236
+ ```
426
237
 
427
- - **In Response to State Changes:** Typically, `this.$next()` is called in scenarios where the component's state has changed and an update to the DOM is required.
238
+ #### `Fragment({ children })`
428
239
 
429
- #### Example:
240
+ A component for grouping elements without adding extra nodes to the DOM.
430
241
 
431
242
  ```jsx
432
- function* Counter() {
243
+ const List = () => (
244
+ <Fragment>
245
+ <li>Item 1</li>
246
+ <li>Item 2</li>
247
+ </Fragment>
248
+ )
249
+ ```
433
250
 
434
- let count = 0
251
+ #### `context(defaultValue)`
435
252
 
436
- const increment = () => {
253
+ Creates a context with an optional default value.
437
254
 
438
- count++
255
+ ```javascript
256
+ const ThemeContext = context('light')
439
257
 
440
- this.$next()
441
- }
258
+ // In a stateless component:
259
+ const StatelessComponent = () => {
260
+ const theme = ThemeContext()
261
+ return <div>Current theme: {theme}</div>
262
+ }
442
263
 
264
+ // In a stateful component:
265
+ function* StatefulComponent() {
443
266
  while (true) {
444
- yield <button set:onclick={increment}>{count}</button>
267
+ const theme = ThemeContext(this)
268
+ yield <div>Current theme: {theme}</div>
445
269
  }
446
270
  }
447
- ```
448
- > In this example, `Counter` uses `this.$next()` in its `increment` function to render the updated count whenever the button is clicked.
449
-
450
- ```jsx
451
- function* DataFetcher() {
452
-
453
- let data = null
454
-
455
- const fetchData = async () => {
456
-
457
- data = await fetchSomeData()
458
-
459
- // Queue a re-render to update the component with the fetched data:
460
- this.$next()
461
- }
462
271
 
272
+ // Setting context value:
273
+ function* App() {
274
+ ThemeContext(this, 'dark')
463
275
  while (true) {
464
276
  yield (
465
- <div>
466
- <button set:onclick={fetchData}>Fetch Data</button>
467
- {data && <DisplayData data={data} />}
468
- </div>
277
+ <>
278
+ <FunctionalComponent />
279
+ <StatefulComponent />
280
+ </>
469
281
  )
470
282
  }
471
283
  }
472
284
  ```
473
- > In this example, `DataFetcher` uses `this.$next()` to update its display after data is fetched.
474
-
475
- ### `this.$throw()`
476
- > **Note:** `this.$throw()` is automatically called when an error is thrown from a component's generator function.
477
-
478
- The `$throw` method in Ajo stateful components is designed for error propagation within the component hierarchy. It allows developers to throw errors from a child component to be caught and handled by itself or a parent component, facilitating a structured approach to error management.
479
-
480
- #### Purpose:
481
-
482
- - **Error Propagation:** `this.$throw()` is used to send errors from the current component up to its parents component, akin to creating an error boundary.
483
-
484
- #### Usage:
485
-
486
- - **Handling Uncaught Exceptions:** Typically used within event handlers or asynchronous operations where errors might occur. Instead of handling these errors locally within the component, `this.$throw()` sends them to the parent component for a more centralized handling approach.
487
- - **Creating Error Boundaries:** Useful in scenarios where a parent component is designed to handle errors from its child components, maintaining separation of concerns and cleaner code.
488
-
489
- #### Example:
490
-
491
- ```jsx
492
- function* ChildComponent() {
493
-
494
- const handleErrorProneOperation = async () => {
495
- try {
496
-
497
- // operation that might throw an error
498
- await doSomething()
499
285
 
500
- } catch (err) {
501
-
502
- // Propagate error to parent component
503
- this.$throw(err)
504
- }
505
- }
286
+ #### Stateful Components and Component Methods
506
287
 
507
- while (true) {
508
- yield <button set:onclick={handleErrorProneOperation}>Click Me</button>
509
- }
510
- }
288
+ Ajo's stateful components are implemented as generator functions and have access to several special methods:
511
289
 
512
- function* ParentComponent() {
290
+ ```javascript
291
+ function* StatefulComponent(props) {
292
+ // Component logic here
513
293
  while (true) {
514
- try {
515
- yield <ChildComponent />
516
- } catch (err) {
517
- yield <div>Error: {err.message}</div>
518
- }
294
+ yield (/* JSX */)
519
295
  }
520
296
  }
521
297
  ```
522
- > In this example, `ChildComponent` uses `this.$throw()` within an event handler to propagate errors upwards to its parent component, `ParentComponent`. The parent component then catches the error and renders it to the DOM.
523
-
524
- ### `this.$return()`
525
- > **Note:** `this.$return()` is automatically called when a stateful component is unmounted.
526
-
527
- The `$return` method in Ajo is used to reset and restart the generator function of a stateful component. It effectively ends the current execution of the component's generator function, and optionally re-execute it from scratch allowing for a complete reset of the component's state and behavior.
528
-
529
- #### Purpose:
530
-
531
- - **Component Reset:** `this.$return()` is used to restart a component's generator function from the beginning, resetting its internal state and re-initializing it as needed.
532
298
 
533
- #### Usage:
299
+ Component methods:
534
300
 
535
- - **Re-initializing Components:** Ideal for use cases where the component needs to reset its state completely, such as in response to significant prop changes or to reinitialize after certain user interactions.
536
- - **Refreshing Component State:** Helps in scenarios where the existing state and logic of a component need to be discarded and started afresh.
301
+ - `this.render()`: Triggers a re-render of the component. It's the primary method for updating the component's UI after state changes.
537
302
 
538
- #### Example:
539
-
540
- ```jsx
541
- function* MultiStepForm({ initialData }) {
542
-
543
- let currentStep = 0
544
- let formData = { ...initialData }
545
-
546
- const handleNextStep = () => {
547
-
548
- // Logic to move to the next step
549
- currentStep++
550
-
551
- // Re-render with the next step
552
- this.render()
303
+ ```javascript
304
+ function* Counter() {
305
+ let count = 0
306
+ const increment = () => {
307
+ count++
308
+ this.render() // Re-render to reflect the new count
309
+ }
310
+ while (true) {
311
+ yield <button set:onclick={increment}>{count}</button>
312
+ }
553
313
  }
314
+ ```
554
315
 
555
- const handleRestart = () => {
316
+ - `this.$next()`: Advances the generator to the next yield point. It's automatically called by `this.render()` and is rarely used directly.
556
317
 
557
- // Reset the generator function
558
- this.$return()
318
+ - `this.$throw(error)`: Throws an error in the generator. Useful for error propagation and creating error boundaries. Ajo automatically calls this method when an error occurs during rendering.
559
319
 
560
- // Re-render the component in its initial state
561
- this.render()
562
- }
563
-
564
- while (true) {
565
- switch(currentStep) {
566
- case 0:
567
- yield <StepOne
568
- data={formData}
569
- onNext={handleNextStep}
570
- onRestart={handleRestart}
571
- />
572
- break
573
- case 1:
574
- yield <StepTwo
575
- data={formData}
576
- onNext={handleNextStep}
577
- onRestart={handleRestart}
578
- />
579
- break
580
- default:
581
- yield <FinalStep
582
- data={formData}
583
- onRestart={handleRestart}
584
- />
320
+ ```javascript
321
+ function* ErrorBoundary(props) {
322
+ try {
323
+ while (true) {
324
+ yield <div>{props.children}</div>
325
+ }
326
+ } catch (error) {
327
+ yield <div>An error occurred: {error.message}</div>
585
328
  }
586
329
  }
587
- }
588
- ```
589
- > In `handleRestart`, `this.$return()` is first called to reset the generator function. This effectively ends the current execution of the component's generator function and prepares it to start from the beginning. Immediately after, `this.$next()` is called to trigger a re-render of the component. This ensures that after the state is reset, the component's UI is also updated to reflect its initial state.
590
-
591
- ## Server-Side Rendering (SSR)
592
-
593
- Ajo supports Server-Side Rendering (SSR), enabling components to be rendered to HTML in server-side JavaScript environments. This feature enhances the capabilities of Ajo for projects requiring SEO-friendly pages and faster initial page loads.
594
-
595
- ### SSR Implementation with `ajo/html`
596
-
597
- For SSR in Ajo, use the `render` and `html` functions from the `ajo/html` module. These functions are designed to convert a virtual DOM tree into an HTML string or HTML chunks for streaming, suitable for server-side environments.
598
-
599
- ### Client-Side Hydration
600
-
601
- Once HTML is rendered on the server, it can be hydrated on the client-side by Ajo to become interactive. The client-side `render` function can render into the root element containing the SSR-generated DOM.
602
-
603
- ### Example Usage
604
-
605
- Server-side:
606
-
607
- ```javascript
608
- import express from 'express'
609
- import { render } from 'ajo/html'
610
- import { App } from './components'
330
+ ```
611
331
 
612
- const app = express()
332
+ - `this.$return()`: Completes the generator execution. It's automatically called by Ajo when a component is unmounted, but can be used manually to reset a component's state.
613
333
 
614
- app.get('/', (req, res) => {
615
-
616
- const html = render(<App />)
617
-
618
- res.send(`
619
- <!DOCTYPE html>
620
- <html>
621
- <head>
622
- <title>My App</title>
623
- </head>
624
- <body>
625
- <div id="root">${html}</div>
626
- </body>
627
- </html>`)
628
- })
629
-
630
- app.listen(3000)
631
- ```
632
-
633
- Client-side:
634
-
635
- ```javascript
636
- import { render } from 'ajo'
637
- import { App } from './components'
638
-
639
- // Hydrate the #root element with the server-rendered DOM
640
- render(<App />, document.getElementById('root'))
641
- ```
642
-
643
- ### Streaming HTML Chunks
644
-
645
- The `html` function is designed to be used with various streaming technologies. Its output can be seamlessly integrated into different streaming environments, offering developers the flexibility to choose the streaming solution that best fits their project requirements.
646
-
647
- This streaming capability is useful for progressively rendering content, enhancing Time to First Paint (TTFP) and user experience. It allows browsers to begin rendering content as soon as the initial chunks arrive.
648
-
649
- ## SSR API
334
+ ```javascript
335
+ function* ResetableComponent() {
336
+ let count = 0
337
+ const reset = () => {
338
+ this.$return() // Reset the generator
339
+ this.render() // Re-render from the beginning
340
+ }
341
+ while (true) {
342
+ yield (
343
+ <div>
344
+ <p>Count: {count}</p>
345
+ <button set:onclick={() => { count++; this.render(); }}>Increment</button>
346
+ <button set:onclick={reset}>Reset</button>
347
+ </div>
348
+ )
349
+ }
350
+ }
351
+ ```
650
352
 
651
- ### `render(h: Any): String`
353
+ - `this.$args`: Provides access to the current args of the component.
652
354
 
653
- Renders a virtual DOM tree (`h`) into a complete HTML string.
355
+ ```javascript
356
+ function* DynamicGreeting() {
357
+ while (true) {
358
+ yield <h1>Hello, {this.$args.name}!</h1>
359
+ }
360
+ }
361
+ ```
654
362
 
655
- #### Parameters:
363
+ These methods provide powerful control over the component's lifecycle and state management, allowing for efficient and flexible UI updates. Note that `this.$throw()` and `this.$return()` are often called automatically by Ajo in response to errors or component unmounting, respectively, but can also be used manually when needed.
656
364
 
657
- - **h** (Any): The virtual DOM tree to render. This can be any value, a simple string, or a virtual DOM tree created by the `h` function.
365
+ ### `ajo/html` module
658
366
 
659
- #### Returns:
367
+ For server-side rendering:
660
368
 
661
- - A string representation of the rendered HTML.
369
+ #### `render(vnode)`
662
370
 
663
- #### Example Usage:
371
+ Renders a virtual DOM tree to an HTML string.
664
372
 
665
373
  ```javascript
666
374
  import { render } from 'ajo/html'
667
375
  import { App } from './components'
668
376
 
669
377
  const html = render(<App />)
670
- // The `html` can be sent as part of an HTTP response
671
378
  ```
672
379
 
673
- ### `html(h: Any): Generator`
674
-
675
- A generator function that iterates through a virtual DOM tree, yielding HTML strings.
380
+ #### `html(vnode)`
676
381
 
677
- #### Parameters:
678
-
679
- - **h** (Any): The virtual DOM tree to iterate through.
680
-
681
- #### Yield:
682
-
683
- - Yields HTML strings corresponding to each node in the virtual DOM.
684
-
685
- #### Usage:
686
-
687
- - Suitable for streaming HTML chunks to the client, compatible with any streaming technology.
688
-
689
- #### Example Usage:
382
+ Generates an iterator of HTML strings for streaming.
690
383
 
691
384
  ```javascript
692
385
  import { html } from 'ajo/html'
693
386
  import { App } from './components'
694
387
 
695
388
  for (const chunk of html(<App />)) {
696
- stream.push(chunk)
389
+ // Send chunk to the client
390
+ stream.write(chunk)
697
391
  }
698
392
  ```
699
393
 
700
- ## Acknowledgments
701
- Ajo takes heavy inspiration from [Incremental DOM](https://github.com/google/incremental-dom) and [Crank.js](https://github.com/bikeshaving/crank)
702
-
703
394
  ## License
704
395
 
705
- ISC © [Cristian Falcone](cristianfalcone.com)
396
+ ISC © [Cristian Falcone](cristianfalcone.com)
package/types.ts CHANGED
@@ -6,7 +6,7 @@ declare module 'ajo' {
6
6
 
7
7
  type Props = Record<string, unknown>
8
8
 
9
- type AjoNode<TTag extends Type> = { nodeName: TTag } & TagProps<TTag>
9
+ type VNode<TTag extends Type> = { nodeName: TTag } & TagProps<TTag>
10
10
 
11
11
  type Children = any
12
12
 
@@ -31,7 +31,7 @@ declare module 'ajo' {
31
31
  [K in keyof TAttribute as `attr:${Exclude<K, symbol>}`]: TAttribute[K]
32
32
  }
33
33
 
34
- type Context<TArguments = Props> = {
34
+ type ComponentThis<TArguments = Props> = {
35
35
  $args: TArguments,
36
36
  $context: { [key: symbol]: unknown },
37
37
  render: () => void,
@@ -43,7 +43,7 @@ declare module 'ajo' {
43
43
  type Function<TArguments = Props> = (args: TArguments) => Children
44
44
 
45
45
  type Component<TArguments = Props, TTag extends Tag = 'div'> = {
46
- (this: ElementType<TTag> & Context<TArguments>, args: TArguments): Iterator<Children, unknown, unknown>
46
+ (this: ElementType<TTag> & ComponentThis<TArguments>, args: TArguments): Iterator<Children, unknown, unknown>
47
47
  } & (TTag extends 'div' ? { is?: TTag } : { is: TTag })
48
48
 
49
49
  type Ref<TComponent> = TComponent extends Component<infer TArguments, infer TTag>
@@ -67,9 +67,9 @@ declare module 'ajo' {
67
67
  : never
68
68
 
69
69
  function Fragment({ children }: ElementChildrenAttribute): typeof children
70
- function h<TTag extends Tag>(tag: TTag, props?: TagProps<TTag> | null, ...children: Array<unknown>): AjoNode<TTag>
70
+ function h<TTag extends Tag>(tag: TTag, props?: TagProps<TTag> | null, ...children: Array<unknown>): VNode<TTag>
71
71
  function render(h: Children, el: Element): void
72
- function context<T>(fallback?: T): { (el: ThisParameterType<Component<unknown, Tag>>, value?: T): T }
72
+ function context<T>(fallback?: T): (el?: ThisParameterType<Component<unknown, Tag>>, value?: T) => T
73
73
  }
74
74
 
75
75
  declare namespace JSX {