@snupo/jmc 1.0.62 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/LICENSE +21 -0
  2. package/dist/base.d.ts +3 -2
  3. package/dist/base.d.ts.map +1 -1
  4. package/dist/base.js +11 -13
  5. package/dist/base.js.map +1 -1
  6. package/dist/events.js +1 -0
  7. package/dist/events.js.map +1 -1
  8. package/dist/h.d.ts +14 -7
  9. package/dist/h.d.ts.map +1 -1
  10. package/dist/h.js +7 -4
  11. package/dist/h.js.map +1 -1
  12. package/dist/index.d.ts +2 -1
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +2 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/jmc.d.ts +1 -12
  17. package/dist/jmc.d.ts.map +1 -1
  18. package/dist/jmc.js +80 -119
  19. package/dist/jmc.js.map +1 -1
  20. package/dist/jsx-dev-runtime.d.ts +5 -0
  21. package/dist/jsx-dev-runtime.d.ts.map +1 -0
  22. package/dist/jsx-dev-runtime.js +6 -0
  23. package/dist/jsx-dev-runtime.js.map +1 -0
  24. package/dist/jsx-runtime.d.ts +14 -0
  25. package/dist/jsx-runtime.d.ts.map +1 -0
  26. package/dist/jsx-runtime.js +10 -0
  27. package/dist/jsx-runtime.js.map +1 -0
  28. package/dist/jsx.d.ts +39 -46
  29. package/dist/jsx.d.ts.map +1 -1
  30. package/dist/jsx.js.map +1 -1
  31. package/dist/lib.d.ts +5 -3
  32. package/dist/lib.d.ts.map +1 -1
  33. package/dist/lib.js +4 -5
  34. package/dist/lib.js.map +1 -1
  35. package/dist/props.d.ts +11 -0
  36. package/dist/props.d.ts.map +1 -0
  37. package/dist/props.js +43 -0
  38. package/dist/props.js.map +1 -0
  39. package/dist/update.d.ts +10 -0
  40. package/dist/update.d.ts.map +1 -0
  41. package/dist/update.js +48 -0
  42. package/dist/update.js.map +1 -0
  43. package/package.json +29 -3
  44. package/readme.md +303 -34
  45. package/src/base.ts +11 -15
  46. package/src/events.ts +1 -1
  47. package/src/h.ts +29 -18
  48. package/src/index.ts +2 -1
  49. package/src/jmc.ts +90 -138
  50. package/src/jsx-dev-runtime.ts +8 -0
  51. package/src/jsx-runtime.ts +17 -0
  52. package/src/jsx.ts +18 -30
  53. package/src/lib.ts +10 -8
  54. package/src/props.ts +43 -0
  55. package/src/update.ts +54 -0
  56. package/dist/updateview.d.ts +0 -17
  57. package/dist/updateview.d.ts.map +0 -1
  58. package/dist/updateview.js +0 -43
  59. package/dist/updateview.js.map +0 -1
  60. package/src/updateview.ts +0 -48
package/dist/lib.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"lib.d.ts","sourceRoot":"","sources":["../src/lib.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,eAAe,EAAE,CAAC,EAAE,CAAC,EAAE,SAAS,EAAE,MAAM,KAAK,CAAC;AAGtE,MAAM,MAAM,YAAY,CAAC,CAAC,IAAI;IAAE,QAAQ,EAAE,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;CAAG,CAAA;AAE5H,eAAO,MAAM,IAAI,GAAI,UAAU;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,EAAE,IAAI,QAAQ,KAAG,SAAS,GAAG,IAAqC,CAAA;AAElH,8BAAsB,OAAO,CAAC,CAAC,SAAS,CAAC,GAAG,EAAE,CAAE,YAAW,eAAe;IAGnD,KAAK,EAAE,CAAC;IAD3B,OAAO,EAAG,WAAW,CAAA;gBACF,KAAK,EAAE,CAAC;IAG3B,OAAO;IACP,MAAM,CAAC,EAAE,CAAC,EAAE,GAAG,GAAG,OAAO,GAAG,IAAI;IAChC,QAAQ,CAAC,IAAI,IAAI,CAAC;IAG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AAO,CAA0B;CACrD;AAED,wBAAgB,EAAE,CAAC,GAAG,cAAc,EAAE,CAAC,MAAM,GAAG,CAAC,GAAG,SAAS,CAAC,EAAE,GAAG,MAAM,CAIxE;AAED,eAAO,MAAM,YAAY,GAAI,GAAG,IAAI,SAA+B,CAAA"}
package/dist/lib.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { updateview } from './jmc.js';
2
2
  export const When = ({ cond }, cn) => cond ? { kind: 4, cn } : null;
3
- export class JMXComp {
3
+ export class Component {
4
4
  props;
5
- element; // assigned by jmx framework
5
+ element; // assigned by jmc. a placeholder Comment while view() renders nothing
6
6
  constructor(props) {
7
7
  this.props = props;
8
8
  }
@@ -11,12 +11,11 @@ export class JMXComp {
11
11
  update(uc) { }
12
12
  // utility: updates the component's view
13
13
  updateview() { updateview(this.element); }
14
- get ismounted() { return this.element; }
14
+ get ismounted() { return !!this.element; }
15
15
  }
16
16
  export function cc(...namesOrObjects) {
17
17
  return namesOrObjects
18
- .filter(x => x !== undefined)
19
- .flatMap(n => (n.trim ? n : Object.keys(n).filter(k => n[k]))) // n.trim distinguishes string from J
18
+ .flatMap(n => typeof n == 'string' ? n : Object.keys(n ?? {}).filter(k => n?.[k])) // objects contribute their truthy keys
20
19
  .join(' ');
21
20
  }
22
21
  export const focuselement = (e) => e.focus();
package/dist/lib.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"lib.js","sourceRoot":"","sources":["../src/lib.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAA;AAIrC,MAAM,CAAC,MAAM,IAAI,GAAG,CAAC,EAAE,IAAI,EAAqB,EAAE,EAAY,EAAoB,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAA;AAElH,MAAM,OAAgB,OAAO;IAGN;IADnB,OAAO,CAAc,CAAC,4BAA4B;IAClD,YAAmB,KAAQ;QAAR,UAAK,GAAL,KAAK,CAAG;IAAI,CAAC;IAEhC,YAAY;IACZ,OAAO,KAAK,CAAC;IACb,MAAM,CAAC,EAAQ,IAAoB,CAAC;IAGpC,wCAAwC;IACxC,UAAU,KAAK,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA,CAAC,CAAC;IACzC,IAAI,SAAS,KAAc,OAAO,IAAI,CAAC,OAAc,CAAA,CAAC,CAAC;CAC1D;AAED,MAAM,UAAU,EAAE,CAAC,GAAG,cAA0C;IAC5D,OAAO,cAAc;SAChB,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC;SAC5B,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAE,CAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,qCAAqC;SAC1G,IAAI,CAAC,GAAG,CAAC,CAAA;AAClB,CAAC;AAED,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,CAAO,EAAE,EAAE,CAAE,CAAiB,CAAC,KAAK,EAAE,CAAA","sourcesContent":["import type { Children, IClassComponent, H, J, HFragment } from './h';\r\nimport { updateview } from './jmc.js'\r\n\r\nexport type DeepReadonly<T> = { readonly [K in keyof T]: T[K] extends Record<string, unknown> ? DeepReadonly<T[K]> : T[K]; }\r\n\r\nexport const When = ({ cond }: { cond: boolean }, cn: Children): HFragment | null => cond ? { kind: 4, cn } : null\r\n\r\nexport abstract class JMXComp<P extends J = {}> implements IClassComponent {\r\n\r\n element!: HTMLElement // assigned by jmx framework\r\n constructor(public props: P) { }\r\n\r\n // overrides\r\n mounted() { }\r\n update(uc?: any): boolean | void { }\r\n abstract view(): H\r\n\r\n // utility: updates the component's view\r\n updateview() { updateview(this.element) }\r\n get ismounted(): boolean { return this.element as any }\r\n}\r\n\r\nexport function cc(...namesOrObjects: (string | J | undefined)[]): string {\r\n return namesOrObjects\r\n .filter(x => x !== undefined)\r\n .flatMap(n => (n.trim ? n : Object.keys(n).filter(k => (n as J)[k]))) // n.trim distinguishes string from J\r\n .join(' ') \r\n}\r\n\r\nexport const focuselement = (e: Node) => (e as HTMLElement).focus()"]}
1
+ {"version":3,"file":"lib.js","sourceRoot":"","sources":["../src/lib.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAA;AAOrC,MAAM,CAAC,MAAM,IAAI,GAAG,CAAC,EAAE,IAAI,EAAqB,EAAE,EAAY,EAAoB,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAA;AAElH,MAAM,OAAgB,SAAS;IAGR;IADnB,OAAO,CAAc,CAAC,sEAAsE;IAC5F,YAAmB,KAAQ;QAAR,UAAK,GAAL,KAAK,CAAG;IAAI,CAAC;IAEhC,YAAY;IACZ,OAAO,KAAK,CAAC;IACb,MAAM,CAAC,EAAQ,IAAoB,CAAC;IAGpC,wCAAwC;IACxC,UAAU,KAAK,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA,CAAC,CAAC;IACzC,IAAI,SAAS,KAAc,OAAO,CAAC,CAAC,IAAI,CAAC,OAAO,CAAA,CAAC,CAAC;CACrD;AAED,MAAM,UAAU,EAAE,CAAC,GAAG,cAA0C;IAC5D,OAAO,cAAc;SAChB,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,IAAI,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,uCAAuC;SACzH,IAAI,CAAC,GAAG,CAAC,CAAA;AAClB,CAAC;AAED,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,CAAO,EAAE,EAAE,CAAE,CAAiB,CAAC,KAAK,EAAE,CAAA","sourcesContent":["import type { Children, IClassComponent, HU, J, HFragment } from './h.js'\r\nimport { updateview } from './jmc.js'\r\n\r\nexport type UC = J // update context\r\nexport type FComponentT<P> = (pcn: P, cn?: Children) => HU // a function component with typed props\r\n\r\nexport type DeepReadonly<T> = { readonly [K in keyof T]: T[K] extends Record<string, unknown> ? DeepReadonly<T[K]> : T[K]; }\r\n\r\nexport const When = ({ cond }: { cond: boolean }, cn: Children): HFragment | null => cond ? { kind: 4, cn } : null\r\n\r\nexport abstract class Component<P extends J = {}> implements IClassComponent {\r\n\r\n element!: HTMLElement // assigned by jmc. a placeholder Comment while view() renders nothing\r\n constructor(public props: P) { }\r\n\r\n // overrides\r\n mounted() { }\r\n update(uc?: any): boolean | void { }\r\n abstract view(): HU\r\n\r\n // utility: updates the component's view\r\n updateview() { updateview(this.element) }\r\n get ismounted(): boolean { return !!this.element }\r\n}\r\n\r\nexport function cc(...namesOrObjects: (string | J | undefined)[]): string {\r\n return namesOrObjects\r\n .flatMap(n => typeof n == 'string' ? n : Object.keys(n ?? {}).filter(k => n?.[k])) // objects contribute their truthy keys\r\n .join(' ')\r\n}\r\n\r\nexport const focuselement = (e: Node) => (e as HTMLElement).focus()"]}
@@ -0,0 +1,11 @@
1
+ import type { J } from './h.js';
2
+ /** settings to tweak jmc */
3
+ export declare const jmcconfig: {
4
+ /** marks component roots with a comp="Name" attribute */
5
+ debug: boolean;
6
+ /** prop names always set as attributes, never as properties */
7
+ attributes: Set<string>;
8
+ };
9
+ /** applies now over old and returns the applied values, with thunks evaluated, to serve as old on the next call */
10
+ export declare let setprops: (e: Element & J, old: J | undefined, now: J) => J;
11
+ //# sourceMappingURL=props.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"props.d.ts","sourceRoot":"","sources":["../src/props.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,CAAC,EAAE,MAAM,QAAQ,CAAA;AAE/B,4BAA4B;AAC5B,eAAO,MAAM,SAAS;IAClB,yDAAyD;;IAEzD,+DAA+D;;CAElE,CAAA;AAcD,mHAAmH;AACnH,eAAO,IAAI,QAAQ,GAAI,GAAG,OAAO,GAAG,CAAC,EAAE,KAAK,CAAC,YAAK,EAAE,KAAK,CAAC,KAAG,CAmB5D,CAAA"}
package/dist/props.js ADDED
@@ -0,0 +1,43 @@
1
+ /** settings to tweak jmc */
2
+ export const jmcconfig = {
3
+ /** marks component roots with a comp="Name" attribute */
4
+ debug: false,
5
+ /** prop names always set as attributes, never as properties */
6
+ attributes: new Set(['selected', 'viewBox']),
7
+ };
8
+ const isproperty = (e, name, value) => !jmcconfig.attributes.has(name) &&
9
+ (value instanceof Object || ( // objects and functions
10
+ e.namespaceURI !== 'http://www.w3.org/2000/svg' &&
11
+ name in e &&
12
+ name !== 'style'));
13
+ let removeprop = (e, p, old) => {
14
+ if (isproperty(e, p, old))
15
+ e[p] = typeof old === 'boolean' ? false : '';
16
+ if (!(old instanceof Object))
17
+ e.removeAttribute(p); // reflected properties (title, id, ...) leave an empty attribute otherwise
18
+ };
19
+ /** applies now over old and returns the applied values, with thunks evaluated, to serve as old on the next call */
20
+ export let setprops = (e, old = {}, now) => {
21
+ // evaluate thunks into a copy: now is h.p, which gets rendered again and must keep its thunks
22
+ now = Object.fromEntries(Object.entries(now).map(([k, v]) => [k, v?.thunk ? v() : v]));
23
+ // removals
24
+ for (let p in old)
25
+ if (!(p in now))
26
+ removeprop(e, p, old[p]);
27
+ // updates
28
+ for (let p in now) {
29
+ let v = now[p];
30
+ if (v !== old[p] && !(v == null && old[p] == null)) { // strict: 0 vs '' or 1 vs true are changes. null vs undefined is not
31
+ if (v == null)
32
+ removeprop(e, p, old[p]);
33
+ else if (isproperty(e, p, v))
34
+ e[p] = v;
35
+ else if (v === false && !p.startsWith('aria-'))
36
+ e.removeAttribute(p); // aria-*="false" is meaningful
37
+ else
38
+ e.setAttribute(p, v);
39
+ }
40
+ }
41
+ return now;
42
+ };
43
+ //# sourceMappingURL=props.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"props.js","sourceRoot":"","sources":["../src/props.ts"],"names":[],"mappings":"AAEA,4BAA4B;AAC5B,MAAM,CAAC,MAAM,SAAS,GAAG;IACrB,yDAAyD;IACzD,KAAK,EAAE,KAAK;IACZ,+DAA+D;IAC/D,UAAU,EAAE,IAAI,GAAG,CAAC,CAAC,UAAU,EAAE,SAAS,CAAC,CAAC;CAC/C,CAAA;AAED,MAAM,UAAU,GAAG,CAAC,CAAU,EAAE,IAAY,EAAE,KAAU,EAAE,EAAE,CACxD,CAAC,SAAS,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC;IAC/B,CAAC,KAAK,YAAY,MAAM,IAAI,EAAE,wBAAwB;IAClD,CAAC,CAAC,YAAY,KAAK,4BAA4B;QAC/C,IAAI,IAAI,CAAC;QACT,IAAI,KAAK,OAAO,CAAC,CAAC,CAAA;AAE1B,IAAI,UAAU,GAAG,CAAC,CAAc,EAAE,CAAS,EAAE,GAAQ,EAAE,EAAE;IACrD,IAAI,UAAU,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC;QAAE,CAAC,CAAC,CAAC,CAAC,GAAG,OAAO,GAAG,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAA;IACvE,IAAI,CAAC,CAAC,GAAG,YAAY,MAAM,CAAC;QAAE,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,CAAA,CAAC,2EAA2E;AAClI,CAAC,CAAA;AAED,mHAAmH;AACnH,MAAM,CAAC,IAAI,QAAQ,GAAG,CAAC,CAAc,EAAE,MAAS,EAAE,EAAE,GAAM,EAAK,EAAE;IAC7D,8FAA8F;IAC9F,GAAG,GAAG,MAAM,CAAC,WAAW,CAAC,MAAM,CAA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=\"Name\" attribute */\r\n debug: false,\r\n /** prop names always set as attributes, never as properties */\r\n attributes: new Set(['selected', 'viewBox']),\r\n}\r\n\r\nconst isproperty = (e: Element, name: string, value: any) =>\r\n !jmcconfig.attributes.has(name) &&\r\n (value instanceof Object || ( // objects and functions\r\n e.namespaceURI !== 'http://www.w3.org/2000/svg' &&\r\n name in e &&\r\n name !== 'style'))\r\n\r\nlet removeprop = (e: Element & J, p: string, old: any) => {\r\n if (isproperty(e, p, old)) e[p] = typeof old === 'boolean' ? false : ''\r\n if (!(old instanceof Object)) e.removeAttribute(p) // reflected properties (title, id, ...) leave an empty attribute otherwise\r\n}\r\n\r\n/** applies now over old and returns the applied values, with thunks evaluated, to serve as old on the next call */\r\nexport let setprops = (e: Element & J, old: J = {}, now: J): J => {\r\n // evaluate thunks into a copy: now is h.p, which gets rendered again and must keep its thunks\r\n now = Object.fromEntries(Object.entries(now).map(([k, v]) => [k, v?.thunk ? v() : v]))\r\n\r\n // removals\r\n for (let p in old)\r\n if (!(p in now)) removeprop(e, p, old[p])\r\n\r\n // updates\r\n for (let p in now) {\r\n let v = now[p]\r\n if (v !== old[p] && !(v == null && old[p] == null)) { // strict: 0 vs '' or 1 vs true are changes. null vs undefined is not\r\n if (v == null) removeprop(e, p, old[p])\r\n else if (isproperty(e, p, v)) e[p] = v\r\n else if (v === false && !p.startsWith('aria-')) e.removeAttribute(p) // aria-*=\"false\" is meaningful\r\n else e.setAttribute(p, v)\r\n }\r\n }\r\n return now\r\n}\r\n"]}
@@ -0,0 +1,10 @@
1
+ import type { Command } from './h.js';
2
+ /** synchronously runs all queued updates. selectors are resolved now, and each node is updated once per depth and uc */
3
+ export declare const flush: () => void;
4
+ /** batches updates until the next microtask */
5
+ export declare const updateviewmicro: (...cmds: Command[]) => void;
6
+ /** batches updates until the next animation frame */
7
+ export declare const updateviewaf: (...cmds: Command[]) => void;
8
+ /** updates immediately, together with all queued updates */
9
+ export declare const updateviewsync: (...cmds: Command[]) => void;
10
+ //# sourceMappingURL=update.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"update.d.ts","sourceRoot":"","sources":["../src/update.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAe,MAAM,QAAQ,CAAA;AAmBlD,wHAAwH;AACxH,eAAO,MAAM,KAAK,QAAO,IAWxB,CAAA;AAWD,+CAA+C;AAC/C,eAAO,MAAM,eAAe,YATiC,OAAO,EAAE,KAAG,IASb,CAAA;AAE5D,qDAAqD;AACrD,eAAO,MAAM,YAAY,YAZoC,OAAO,EAAE,KAAG,IAYT,CAAA;AAEhE,4DAA4D;AAC5D,eAAO,MAAM,cAAc,GAAI,GAAG,MAAM,OAAO,EAAE,KAAG,IAGnD,CAAA"}
package/dist/update.js ADDED
@@ -0,0 +1,48 @@
1
+ import { updateview } from './jmc.js';
2
+ let pendings = [];
3
+ let isScheduled = false;
4
+ /** resolves a call's commands into pendings, so depth and uc stay with their own call */
5
+ let enqueue = (cmds) => {
6
+ if (!cmds.some(c => typeof c == 'string' || c instanceof Node))
7
+ cmds = [...cmds, 'body']; // like updateview()
8
+ let depth = 999;
9
+ let uc;
10
+ for (const c of cmds)
11
+ if (typeof c == 'number')
12
+ depth = c;
13
+ else if (typeof c == 'string' || c instanceof Node)
14
+ pendings.push([c, depth, uc]);
15
+ else
16
+ uc = c;
17
+ };
18
+ /** synchronously runs all queued updates. selectors are resolved now, and each node is updated once per depth and uc */
19
+ export const flush = () => {
20
+ isScheduled = false;
21
+ const ps = pendings;
22
+ pendings = [];
23
+ const done = [];
24
+ for (const [target, depth, uc] of ps)
25
+ for (const n of typeof target == 'string' ? document.querySelectorAll(target) : [target])
26
+ if (!done.some(([t, d, u]) => t == n && d == depth && u == uc)) {
27
+ done.push([n, depth, uc]);
28
+ updateview(depth, uc ?? {}, n);
29
+ }
30
+ };
31
+ /** queues the update and schedules a flush, so that all calls before it collapse into one batch */
32
+ let batch = (schedule) => (...cmds) => {
33
+ enqueue(cmds);
34
+ if (!isScheduled) {
35
+ isScheduled = true;
36
+ schedule(flush);
37
+ }
38
+ };
39
+ /** batches updates until the next microtask */
40
+ export const updateviewmicro = batch(f => queueMicrotask(f));
41
+ /** batches updates until the next animation frame */
42
+ export const updateviewaf = batch(f => requestAnimationFrame(f)); // looked up on call, so importing works without a DOM
43
+ /** updates immediately, together with all queued updates */
44
+ export const updateviewsync = (...cmds) => {
45
+ enqueue(cmds);
46
+ flush();
47
+ };
48
+ //# sourceMappingURL=update.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"update.js","sourceRoot":"","sources":["../src/update.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAA;AAMrC,IAAI,QAAQ,GAAc,EAAE,CAAA;AAC5B,IAAI,WAAW,GAAG,KAAK,CAAA;AAEvB,yFAAyF;AACzF,IAAI,OAAO,GAAG,CAAC,IAAe,EAAE,EAAE;IAC9B,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,CAAC,IAAI,QAAQ,IAAI,CAAC,YAAY,IAAI,CAAC;QAAE,IAAI,GAAG,CAAC,GAAG,IAAI,EAAE,MAAM,CAAC,CAAA,CAAC,oBAAoB;IAC7G,IAAI,KAAK,GAAG,GAAG,CAAA;IACf,IAAI,EAAiB,CAAA;IACrB,KAAK,MAAM,CAAC,IAAI,IAAI;QAChB,IAAI,OAAO,CAAC,IAAI,QAAQ;YAAE,KAAK,GAAG,CAAC,CAAA;aAC9B,IAAI,OAAO,CAAC,IAAI,QAAQ,IAAI,CAAC,YAAY,IAAI;YAAE,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,CAAA;;YAC5E,EAAE,GAAG,CAAC,CAAA;AACnB,CAAC,CAAA;AAED,wHAAwH;AACxH,MAAM,CAAC,MAAM,KAAK,GAAG,GAAS,EAAE;IAC5B,WAAW,GAAG,KAAK,CAAA;IACnB,MA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EvH,4DAA4D;AAC5D,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,GAAG,IAAe,EAAQ,EAAE;IACvD,OAAO,CAAC,IAAI,CAAC,CAAA;IACb,KAAK,EAAE,CAAA;AACX,CAAC,CAAA","sourcesContent":["import { updateview } from './jmc.js'\r\nimport type { Command, J, Selector } from './h.js'\r\n\r\n// one queued update: a target with the depth and update context of the call that queued it\r\ntype Pending = [target: Selector, depth: number, uc: J | undefined]\r\n\r\nlet pendings: Pending[] = []\r\nlet isScheduled = false\r\n\r\n/** resolves a call's commands into pendings, so depth and uc stay with their own call */\r\nlet enqueue = (cmds: Command[]) => {\r\n if (!cmds.some(c => typeof c == 'string' || c instanceof Node)) cmds = [...cmds, 'body'] // like updateview()\r\n let depth = 999\r\n let uc: J | undefined\r\n for (const c of cmds)\r\n if (typeof c == 'number') depth = c\r\n else if (typeof c == 'string' || c instanceof Node) pendings.push([c, depth, uc])\r\n else uc = c\r\n}\r\n\r\n/** synchronously runs all queued updates. selectors are resolved now, and each node is updated once per depth and uc */\r\nexport const flush = (): void => {\r\n isScheduled = false\r\n const ps = pendings\r\n pendings = []\r\n const done: Pending[] = []\r\n for (const [target, depth, uc] of ps)\r\n for (const n of typeof target == 'string' ? document.querySelectorAll(target) : [target])\r\n if (!done.some(([t, d, u]) => t == n && d == depth && u == uc)) {\r\n done.push([n, depth, uc])\r\n updateview(depth, uc ?? {}, n)\r\n }\r\n}\r\n\r\n/** queues the update and schedules a flush, so that all calls before it collapse into one batch */\r\nlet batch = (schedule: (f: () => void) => void) => (...cmds: Command[]): void => {\r\n enqueue(cmds)\r\n if (!isScheduled) {\r\n isScheduled = true\r\n schedule(flush)\r\n }\r\n}\r\n\r\n/** batches updates until the next microtask */\r\nexport const updateviewmicro = batch(f => queueMicrotask(f))\r\n\r\n/** batches updates until the next animation frame */\r\nexport const updateviewaf = batch(f => requestAnimationFrame(f)) // looked up on call, so importing works without a DOM\r\n\r\n/** updates immediately, together with all queued updates */\r\nexport const updateviewsync = (...cmds: Command[]): void => {\r\n enqueue(cmds)\r\n flush()\r\n}\r\n"]}
package/package.json CHANGED
@@ -1,7 +1,23 @@
1
1
  {
2
2
  "name": "@snupo/jmc",
3
+ "description": "Minimal JSX/TSX view library that syncs directly with the real DOM",
4
+ "keywords": [
5
+ "jsx",
6
+ "tsx",
7
+ "dom",
8
+ "view",
9
+ "ui",
10
+ "typescript"
11
+ ],
3
12
  "author": "snupo",
4
- "version": "1.0.62",
13
+ "license": "MIT",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/snuup/jmc.git"
17
+ },
18
+ "homepage": "https://github.com/snuup/jmc#readme",
19
+ "bugs": "https://github.com/snuup/jmc/issues",
20
+ "version": "1.1.0",
5
21
  "publishConfig": {
6
22
  "access": "public"
7
23
  },
@@ -12,8 +28,17 @@
12
28
  ".": {
13
29
  "types": "./dist/index.d.ts",
14
30
  "import": "./dist/index.js"
31
+ },
32
+ "./jsx-runtime": {
33
+ "types": "./dist/jsx-runtime.d.ts",
34
+ "import": "./dist/jsx-runtime.js"
35
+ },
36
+ "./jsx-dev-runtime": {
37
+ "types": "./dist/jsx-dev-runtime.d.ts",
38
+ "import": "./dist/jsx-dev-runtime.js"
15
39
  }
16
40
  },
41
+ "sideEffects": false,
17
42
  "files": [
18
43
  "dist",
19
44
  "src"
@@ -21,10 +46,11 @@
21
46
  "scripts": {
22
47
  "prebuild": "rimraf dist",
23
48
  "build": "tsc -p tsconfig.json",
49
+ "test": "vitest run",
24
50
  "release": "release-it patch"
25
51
  },
26
52
  "devDependencies": {
27
- "@vitest/coverage-v8": "^4.1.10",
53
+ "@vitest/coverage-v8": "4.1.10",
28
54
  "happy-dom": "^16.8.1",
29
55
  "release-it": "^21.0.2",
30
56
  "rimraf": "^6.1.3",
@@ -34,7 +60,7 @@
34
60
  "release-it": {
35
61
  "hooks": {
36
62
  "before:init": [
37
- "pnpm vitest"
63
+ "pnpm vitest run"
38
64
  ],
39
65
  "after:bump": "pnpm build"
40
66
  },
package/readme.md CHANGED
@@ -1,34 +1,303 @@
1
- embrace typescript
2
- embrace jsx / tsx
3
- simplicity to a level where everybody can read, fix, expand the code
4
-
5
- 1. model
6
- - is a pojo
7
- no magic as in vue or svelte
8
- no insane functional optics and lenses, no toolkits, needed to change a property value in the state
9
- no proxificiation of the pojo, just the instance must remain stable
10
-
11
- 2. controller
12
- - only the controller modifies the model, which shall be treated immutable for other code parts like the view
13
- - controller actions modify the model and update the relevant parts of the view.
14
- while this need to consider which parts of the view require an update after the current action,
15
- this causes only minimal effort to the programmer - in contrast to the "reactive" frameworks who try to free
16
- the programmer from this task not considering the complexity they add during this endeavour:
17
- no inefficient comparisons between old and new state as in react-redux glue code
18
- no magic as in vue or svelte, sooner or later one needs to understand the hidden magic operations
19
-
20
- 3. view
21
- - is the dom, described as statically typed jsx, namely tsx
22
- typescript compiler team went to incredible heights making jsx perfectly safe.
23
- writing the view is to a good part similar as in react, having invented jsx from hyperscript is the good part of react
24
- - updates of the the view can be as fine granular as desired, their scope is specified by a dom element
25
- - while jsx expression are traditionally transformed into virtual dom representations that are then syncd with the real dome,
26
- jmx avoids the cost of a virtual dom. instead, jsx expressions are transformed into update functions that take the real dom
27
- element as argument and sync that element when called.
28
-
29
- since the model is just a pojo and the controller a plane class with methods for the applications operations, the only missing piece is the specific jsx view.
30
- the jmx library therefore provides:
31
- a vite plugin that transforms the js code for jsx fragments a little bit
32
- a real dom update system that has similarities with v-dom libraries, and equals their rather low complexity
33
-
34
- in addition to that library, jmx provides a style guide on how to write js applications (a strict layer pattern), how to debug them and finally a simple router.
1
+ # jmc
2
+
3
+ A minimal JSX/TSX view library that syncs your views directly with the real DOM.
4
+
5
+ - small enough to read in one sitting: the core is a single file of about 200 lines
6
+ - statically typed views with TSX
7
+ - you decide what to update and when: one call, scoped to any element
8
+ - plain objects as model, plain classes as controller, nothing hidden in between
9
+
10
+ ```tsx
11
+ import { patch, updateview } from '@snupo/jmc'
12
+
13
+ const model = { count: 0 }
14
+
15
+ const App = () =>
16
+ <body>
17
+ <button onclick={() => { model.count++; updateview() }}>+1</button>
18
+ <span>{model.count}</span>
19
+ </body>
20
+
21
+ patch(document.body, <App />)
22
+ ```
23
+
24
+ Upgrading from 1.0? See [UPGRADING.md](UPGRADING.md).
25
+
26
+ ## Install
27
+
28
+ ```sh
29
+ npm install @snupo/jmc
30
+ ```
31
+
32
+ Tell TypeScript and your bundler to take JSX from jmc. jmc supports both JSX setups that TypeScript offers.
33
+
34
+ ### Automatic runtime (recommended)
35
+
36
+ The compiler imports what JSX needs by itself, so your `.tsx` files need no JSX import. In `tsconfig.json`:
37
+
38
+ ```jsonc
39
+ {
40
+ "compilerOptions": {
41
+ "jsx": "react-jsx",
42
+ "jsxImportSource": "@snupo/jmc"
43
+ }
44
+ }
45
+ ```
46
+
47
+ Your bundler needs the same. With Vite's oxc transformer:
48
+
49
+ ```ts
50
+ // vite.config.ts
51
+ export default defineConfig({
52
+ oxc: {
53
+ jsx: { runtime: 'automatic', importSource: '@snupo/jmc' },
54
+ },
55
+ })
56
+ ```
57
+
58
+ With esbuild, the options are `jsx: 'automatic'` and `jsxImportSource: '@snupo/jmc'`.
59
+
60
+ ### Classic
61
+
62
+ Every `.tsx` file imports jmc's factory functions `jsx`, and `jsxf` if it uses fragments (`<>…</>`). In `tsconfig.json`:
63
+
64
+ ```jsonc
65
+ {
66
+ "compilerOptions": {
67
+ "jsx": "react",
68
+ "jsxFactory": "jsx",
69
+ "jsxFragmentFactory": "jsxf"
70
+ }
71
+ }
72
+ ```
73
+
74
+ With Vite's oxc transformer:
75
+
76
+ ```ts
77
+ // vite.config.ts
78
+ export default defineConfig({
79
+ oxc: {
80
+ jsx: { runtime: 'classic', pragma: 'jsx', pragmaFrag: 'jsxf' },
81
+ },
82
+ })
83
+ ```
84
+
85
+ With esbuild, the options are `jsxFactory: 'jsx'` and `jsxFragment: 'jsxf'`.
86
+
87
+ Both setups render the same, and the same components work in both.
88
+
89
+ ## The idea
90
+
91
+ An application is split into three parts with clear responsibilities.
92
+
93
+ **Model**: a plain object. No proxies, no observables, no special setters. You change a value by assigning it. The model instance itself stays stable.
94
+
95
+ **Controller**: a plain class whose methods are the application's operations. Only the controller changes the model. Other parts, like the view, treat it as read-only. After an action, the controller updates the parts of the view that the action affected.
96
+
97
+ Deciding which parts to update is a small, explicit step for the programmer. In return, there is no hidden machinery to learn, debug or work around, and no diffing of old and new state.
98
+
99
+ **View**: the DOM, described with statically typed TSX. jmc renders it and keeps it in sync. An update can be as coarse as the whole page or as fine as a single element.
100
+
101
+ ## Rendering and updating
102
+
103
+ `patch(node, h)` renders `h` in place of `node` and returns the rendered element. The usual start is to patch `document.body` with a `<body>` element:
104
+
105
+ ```tsx
106
+ patch(document.body, <App />)
107
+ ```
108
+
109
+ `updateview(...commands)` brings rendered parts of the page up to date. jmc remembers how each element was rendered, so it renders it again with the current model:
110
+
111
+ ```tsx
112
+ updateview() // the whole body
113
+ updateview('#todos') // all elements matching a selector
114
+ updateview(element) // one element
115
+ updateview('#todos', '.badge') // several targets
116
+ ```
117
+
118
+ jmc compares the new render with the existing DOM and changes only what differs. Existing elements are reused, so focus, selection and scroll positions stay intact.
119
+
120
+ Two more kinds of commands change how the targets after them are updated:
121
+
122
+ - **a number** limits the depth. `updateview(1, el)` updates only the props of `el`, not its children. `updateview(0, el)` discards the children of `el` and renders them from scratch.
123
+ - **an object** is passed as update context to all `update` callbacks (see below): `updateview({ resized: true })`.
124
+
125
+ Without a target, `updateview` updates `body`.
126
+
127
+ ### Batching
128
+
129
+ These variants collect updates and run them together:
130
+
131
+ | function | runs the update |
132
+ |---|---|
133
+ | `updateviewmicro(...)` | at the next microtask |
134
+ | `updateviewaf(...)` | at the next animation frame |
135
+ | `updateviewsync(...)` | immediately, together with everything queued |
136
+ | `flush()` | runs everything queued, immediately |
137
+
138
+ An element queued several times is updated once.
139
+
140
+ ## Components
141
+
142
+ ### Function components
143
+
144
+ A function component receives its props and children and returns JSX:
145
+
146
+ ```tsx
147
+ const TodoList = (p: { items: string[] }) =>
148
+ <ul id='todos'>{p.items.map(t => <li>{t}</li>)}</ul>
149
+
150
+ patch(document.body, <body><h1>Todos</h1><TodoList items={model.todos} /></body>)
151
+
152
+ model.todos.push('bread')
153
+ updateview('#todos') // runs TodoList again
154
+ ```
155
+
156
+ When you update the root element of a function component, the function runs again. A component that returns a fragment has no single root element. It is updated through its parent.
157
+
158
+ A component gets its children in `props.children`, as an array:
159
+
160
+ ```tsx
161
+ const Box = (p: { title: string, children?: Children }) =>
162
+ <section title={p.title}>{p.children}</section>
163
+
164
+ <Box title='hello'><b>world</b></Box>
165
+ ```
166
+
167
+ ### Class components
168
+
169
+ A class component keeps state between renders. Its instance is created once and reused as long as the same class is rendered at the same place:
170
+
171
+ ```tsx
172
+ class Counter extends Component<{ start: number }> {
173
+ count = this.props.start
174
+ inc() { this.count++; this.updateview() }
175
+ view(): H { return <button onclick={this.inc}>{this.count}</button> }
176
+ }
177
+
178
+ patch(document.body, <body><Counter start={5} /></body>)
179
+ ```
180
+
181
+ | member | |
182
+ |---|---|
183
+ | `view()` | returns the component's JSX: exactly one root element, or `null` to render nothing |
184
+ | `props` | the current props, updated on every render by the parent |
185
+ | `element` | the rendered root element |
186
+ | `mounted()` | called once, after the first render |
187
+ | `update(uc)` | called before each re-render. Return `true` to skip the re-render, for example after updating the DOM yourself |
188
+ | `updateview()` | updates this component |
189
+ | `ismounted` | `true` once rendered |
190
+
191
+ Methods are bound to the instance, so they can be used directly as event handlers, as `onclick={this.inc}` above shows.
192
+
193
+ A component whose `view()` returns `null` keeps its state and can show itself again later.
194
+
195
+ ## Elements
196
+
197
+ ### Props: attributes and properties
198
+
199
+ jmc sets a prop as a DOM **property** when the value is an object or a function, or when the element has a property of that name, as `value`, `checked` and `onclick` do. Otherwise it sets an **attribute**. Names listed in `jmcconfig.attributes` are always set as attributes (see [Configuration](#configuration)). `style` given as a string is set as an attribute.
200
+
201
+ `null`, `undefined` and `false` remove the attribute. On `aria-*` attributes, `false` is kept as the value `"false"`.
202
+
203
+ A prop whose value is wrapped in `lazy` is evaluated at each render:
204
+
205
+ ```tsx
206
+ <dd class={lazy(() => cc('item', { active: model.active }))} />
207
+ ```
208
+
209
+ ### Children
210
+
211
+ Strings and numbers render as text. `null`, `undefined`, `false` and `true` render nothing, so conditions read naturally:
212
+
213
+ ```tsx
214
+ <div>{model.error && <p class='error'>{model.error}</p>}</div>
215
+ ```
216
+
217
+ A child that renders nothing still keeps its place, as an invisible empty text node. So when `model.error` appears or disappears, the elements after it stay the same elements, with their focus, scroll position and state.
218
+
219
+ Arrays are flattened, so `items.map(…)` works anywhere. jmc matches children by position, so elements inside a list that grows or shrinks can be reused for different items.
220
+
221
+ ### Lifecycle callbacks
222
+
223
+ Elements accept two lifecycle callbacks:
224
+
225
+ ```tsx
226
+ <canvas
227
+ mounted={(n) => draw(n)} // once, after the element is created
228
+ update={(n, uc) => { draw(n, uc); return true }} // before each update. true: skip the default update
229
+ />
230
+ ```
231
+
232
+ ### Islands
233
+
234
+ Some content is managed by other code, such as a map or an editor. Mark its element with `const`: jmc renders the element and its children once, then never touches it again, neither its props nor its children. The library can take over in `mounted`, and the `update` callback passes later model changes on to it:
235
+
236
+ ```tsx
237
+ <div class='map' const
238
+ mounted={(n) => map = new maplibregl.Map({ container: n })}
239
+ update={() => { map.setStyle(model.style) }}
240
+ />
241
+ ```
242
+
243
+ The `const` attribute stays visible in the DOM, which helps to spot islands in the dev tools.
244
+
245
+ jmc also leaves the children of web components (tags containing `-`) to the component itself.
246
+
247
+ ### SVG
248
+
249
+ SVG is a different world from HTML, so entering it is explicit: `<svg>` needs its namespace, and the types require it. Its children inherit the namespace, and the children of `<foreignObject>` are HTML again:
250
+
251
+ ```tsx
252
+ <svg xmlns='http://www.w3.org/2000/svg'><circle r={5} /></svg>
253
+ ```
254
+
255
+ ### Custom elements
256
+
257
+ jmc's element types live on the `jsx` function, not in a global `JSX` namespace. So they never clash with the JSX types of other libraries in the same project. Declare your own tags and their props by extending them:
258
+
259
+ ```ts
260
+ import type { HtmlHTMLAttributes } from '@snupo/jmc'
261
+
262
+ declare module '@snupo/jmc' {
263
+ namespace jsx {
264
+ namespace JSX {
265
+ interface IntrinsicElements {
266
+ 'my-chart': HtmlHTMLAttributes & { data: number[] }
267
+ }
268
+ }
269
+ }
270
+ }
271
+ ```
272
+
273
+ ## Configuration
274
+
275
+ `jmcconfig` holds the settings that adjust jmc:
276
+
277
+ ```ts
278
+ import { jmcconfig } from '@snupo/jmc'
279
+
280
+ jmcconfig.debug = true // mark component roots with comp="Name"
281
+ jmcconfig.attributes.add('list') // always set this prop as an attribute
282
+ ```
283
+
284
+ **`debug`**: every component root shows the component's name, as in `<section comp="Panel">`, so the dev tools reveal which component rendered what. The attribute is only set while `debug` is on. To switch it from the browser console, make the object reachable there with `mount({ jmcconfig })`, then run `jmcconfig.debug = true; updateview()`.
285
+
286
+ **`attributes`**: the prop names that jmc always sets as attributes, even where the element has a property of that name. By default `selected` and `viewBox`.
287
+
288
+ ## Utilities
289
+
290
+ | | |
291
+ |---|---|
292
+ | `cc(...)` | joins class names. Objects contribute their keys with truthy values: `cc('item', { active })` |
293
+ | `<When cond={…}>` | renders its children only if `cond` is true |
294
+ | `lazy(f)` | a prop value that is evaluated at each render |
295
+ | `closestby(node, pred)` | the nearest ancestor (or the node itself) matching `pred` |
296
+ | `focuselement(node)` | focuses the node |
297
+ | `rebind(o)` | binds the prototype methods of `o` to `o` |
298
+ | `mount({ … })` | puts values on `globalThis`, handy for debugging in the console |
299
+ | `loggedmethods(o)` | logs each method call of `o` with its arguments and result |
300
+
301
+ ## License
302
+
303
+ [MIT](LICENSE)
package/src/base.ts CHANGED
@@ -5,28 +5,24 @@ export function rebind<T extends object>(o: T, proto = Object.getPrototypeOf(o))
5
5
  return o
6
6
  }
7
7
 
8
- export function mount(o: Record<string, any>) { Object.assign(globalThis, o) }
9
-
8
+ /** wraps o so that each method call is reported to logger, after the method returned */
10
9
  export const loggedmethodsex = <T extends Record<string, any>>(o: T, logger: (name: string, args: any[], result: any) => void) => new Proxy(o, {
11
10
  get(target, name: string, receiver) {
12
- if (typeof target[name] === "function") {
13
- return function (this: T, ...args: any[]) {
14
-
15
- logger(name, args, undefined)
16
- let r = target[name].apply(this, args)
17
- return r
18
- }
11
+ if (typeof target[name] !== 'function') return Reflect.get(target, name, receiver)
12
+ return function (this: T, ...args: any[]) {
13
+ let result = target[name].apply(this, args)
14
+ logger(name, args, result)
15
+ return result
19
16
  }
20
- return Reflect.get(target, name, receiver)
21
17
  },
22
18
  })
23
19
 
24
- export const loggedmethods = <T extends Record<string, any>>(o: T): T => loggedmethodsex(o, (name, args, result) => console.log("%c" + name, "background:#585059;color:white;padding:2px;font-weight:bold", args))
25
- export const loggedmethodscolored = <T extends Record<string, any>>(bgcolor: string, o: T): T => loggedmethodsex(o, (name, args, result) => console.log("%c" + name, `background:${bgcolor};color:white;padding:2px;font-weight:bold`, args))
20
+ export const loggedmethodscolored = <T extends Record<string, any>>(bgcolor: string, o: T): T => loggedmethodsex(o, (name, args, result) => console.log('%c' + name, `background:${bgcolor};color:white;padding:2px;font-weight:bold`, args, result))
21
+
22
+ export const loggedmethods = <T extends Record<string, any>>(o: T): T => loggedmethodscolored('#585059', o)
26
23
 
27
24
  export function closestby(e: Node | null, pred: (e: Node) => boolean): Node | null { return (e == null || pred(e)) ? e : closestby(e.parentNode, pred) }
28
25
 
29
- // export type Expr<T> = T | (() => T)
30
- // export let evaluate = <T>(expr: Expr<T>): T => (expr instanceof Function ? expr() : expr)
26
+ export function lazy<T>(f: () => T) { (f as any).thunk = 1; return f }
31
27
 
32
- export function lazy<T>(f: () => T) { (f as any).thunk = 1; return f }
28
+ export function mount(o: Record<string, any>) { Object.assign(globalThis, o) }
package/src/events.ts CHANGED
@@ -1,4 +1,4 @@
1
-
1
+ // future work: maybe lifecycle callbacks should occur in a phase 2 after a phase 1 that does all dom updates
2
2
 
3
3
  declare global {
4
4
  interface Element {