@snupo/jmc 1.0.62 → 1.2.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 (61) hide show
  1. package/LICENSE +21 -0
  2. package/design-guide.md +193 -0
  3. package/dist/base.d.ts +3 -2
  4. package/dist/base.d.ts.map +1 -1
  5. package/dist/base.js +11 -13
  6. package/dist/base.js.map +1 -1
  7. package/dist/events.js +1 -0
  8. package/dist/events.js.map +1 -1
  9. package/dist/h.d.ts +14 -7
  10. package/dist/h.d.ts.map +1 -1
  11. package/dist/h.js +7 -4
  12. package/dist/h.js.map +1 -1
  13. package/dist/index.d.ts +2 -1
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +2 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist/jmc.d.ts +1 -12
  18. package/dist/jmc.d.ts.map +1 -1
  19. package/dist/jmc.js +80 -119
  20. package/dist/jmc.js.map +1 -1
  21. package/dist/jsx-dev-runtime.d.ts +5 -0
  22. package/dist/jsx-dev-runtime.d.ts.map +1 -0
  23. package/dist/jsx-dev-runtime.js +6 -0
  24. package/dist/jsx-dev-runtime.js.map +1 -0
  25. package/dist/jsx-runtime.d.ts +14 -0
  26. package/dist/jsx-runtime.d.ts.map +1 -0
  27. package/dist/jsx-runtime.js +10 -0
  28. package/dist/jsx-runtime.js.map +1 -0
  29. package/dist/jsx.d.ts +39 -46
  30. package/dist/jsx.d.ts.map +1 -1
  31. package/dist/jsx.js.map +1 -1
  32. package/dist/lib.d.ts +5 -3
  33. package/dist/lib.d.ts.map +1 -1
  34. package/dist/lib.js +4 -5
  35. package/dist/lib.js.map +1 -1
  36. package/dist/props.d.ts +11 -0
  37. package/dist/props.d.ts.map +1 -0
  38. package/dist/props.js +43 -0
  39. package/dist/props.js.map +1 -0
  40. package/dist/update.d.ts +10 -0
  41. package/dist/update.d.ts.map +1 -0
  42. package/dist/update.js +48 -0
  43. package/dist/update.js.map +1 -0
  44. package/package.json +31 -4
  45. package/readme.md +313 -34
  46. package/src/base.ts +11 -15
  47. package/src/events.ts +1 -1
  48. package/src/h.ts +29 -18
  49. package/src/index.ts +2 -1
  50. package/src/jmc.ts +90 -138
  51. package/src/jsx-dev-runtime.ts +8 -0
  52. package/src/jsx-runtime.ts +17 -0
  53. package/src/jsx.ts +18 -30
  54. package/src/lib.ts +10 -8
  55. package/src/props.ts +43 -0
  56. package/src/update.ts +54 -0
  57. package/dist/updateview.d.ts +0 -17
  58. package/dist/updateview.d.ts.map +0 -1
  59. package/dist/updateview.js +0 -43
  60. package/dist/updateview.js.map +0 -1
  61. package/src/updateview.ts +0 -48
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,MAAM,EAAE,GAAG,QAAQ,CAAA;IACnB,QAAQ,GAAG,EAAE,CAAA;IACb,MAAM,IAAI,GAAc,EAAE,CAAA;IAC1B,KAAK,MAAM,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,EAAE;QAChC,KAAK,MAAM,CAAC,IAAI,OAAO,MAAM,IAAI,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;YACpF,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;gBAC7D,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,CAAA;gBACzB,UAAU,CAAC,KAAK,EAAE,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC,CAAA;YAClC,CAAC;AACb,CAAC,CAAA;AAED,mGAAmG;AACnG,IAAI,KAAK,GAAG,CAAC,QAAiC,EAAE,EAAE,CAAC,CAAC,GAAG,IAAe,EAAQ,EAAE;IAC5E,OAAO,CAAC,IAAI,CAAC,CAAA;IACb,IAAI,CAAC,WAAW,EAAE,CAAC;QACf,WAAW,GAAG,IAAI,CAAA;QAClB,QAAQ,CAAC,KAAK,CAAC,CAAA;IACnB,CAAC;AACL,CAAC,CAAA;AAED,+CAA+C;AAC/C,MAAM,CAAC,MAAM,eAAe,GAAG,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,CAAA;AAE5D,qDAAqD;AACrD,MAAM,CAAC,MAAM,YAAY,GAAG,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC,CAAA,CAAC,sDAAsD;AAEvH,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.2.0",
5
21
  "publishConfig": {
6
22
  "access": "public"
7
23
  },
@@ -12,19 +28,30 @@
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
- "src"
44
+ "src",
45
+ "design-guide.md"
20
46
  ],
21
47
  "scripts": {
22
48
  "prebuild": "rimraf dist",
23
49
  "build": "tsc -p tsconfig.json",
50
+ "test": "vitest run",
24
51
  "release": "release-it patch"
25
52
  },
26
53
  "devDependencies": {
27
- "@vitest/coverage-v8": "^4.1.10",
54
+ "@vitest/coverage-v8": "4.1.10",
28
55
  "happy-dom": "^16.8.1",
29
56
  "release-it": "^21.0.2",
30
57
  "rimraf": "^6.1.3",
@@ -34,7 +61,7 @@
34
61
  "release-it": {
35
62
  "hooks": {
36
63
  "before:init": [
37
- "pnpm vitest"
64
+ "pnpm vitest run"
38
65
  ],
39
66
  "after:bump": "pnpm build"
40
67
  },
package/readme.md CHANGED
@@ -1,34 +1,313 @@
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
+ ## Working with Claude and other coding agents
27
+
28
+ jmc ships a [design guide](design-guide.md) that explains to coding agents how a jmc app is structured: model, view and controller, and the rules between them. To have Claude follow it in your app, reference it from your project's `CLAUDE.md`:
29
+
30
+ ```md
31
+ This app uses jmc. Follow @node_modules/@snupo/jmc/design-guide.md
32
+ ```
33
+
34
+ The `@` import loads the guide into every session, and it stays current when you update jmc.
35
+
36
+ ## Install
37
+
38
+ ```sh
39
+ npm install @snupo/jmc
40
+ ```
41
+
42
+ Tell TypeScript and your bundler to take JSX from jmc. jmc supports both JSX setups that TypeScript offers.
43
+
44
+ ### Automatic runtime (recommended)
45
+
46
+ The compiler imports what JSX needs by itself, so your `.tsx` files need no JSX import. In `tsconfig.json`:
47
+
48
+ ```jsonc
49
+ {
50
+ "compilerOptions": {
51
+ "jsx": "react-jsx",
52
+ "jsxImportSource": "@snupo/jmc"
53
+ }
54
+ }
55
+ ```
56
+
57
+ Your bundler needs the same. With Vite's oxc transformer:
58
+
59
+ ```ts
60
+ // vite.config.ts
61
+ export default defineConfig({
62
+ oxc: {
63
+ jsx: { runtime: 'automatic', importSource: '@snupo/jmc' },
64
+ },
65
+ })
66
+ ```
67
+
68
+ With esbuild, the options are `jsx: 'automatic'` and `jsxImportSource: '@snupo/jmc'`.
69
+
70
+ ### Classic
71
+
72
+ Every `.tsx` file imports jmc's factory functions `jsx`, and `jsxf` if it uses fragments (`<>…</>`). In `tsconfig.json`:
73
+
74
+ ```jsonc
75
+ {
76
+ "compilerOptions": {
77
+ "jsx": "react",
78
+ "jsxFactory": "jsx",
79
+ "jsxFragmentFactory": "jsxf"
80
+ }
81
+ }
82
+ ```
83
+
84
+ With Vite's oxc transformer:
85
+
86
+ ```ts
87
+ // vite.config.ts
88
+ export default defineConfig({
89
+ oxc: {
90
+ jsx: { runtime: 'classic', pragma: 'jsx', pragmaFrag: 'jsxf' },
91
+ },
92
+ })
93
+ ```
94
+
95
+ With esbuild, the options are `jsxFactory: 'jsx'` and `jsxFragment: 'jsxf'`.
96
+
97
+ Both setups render the same, and the same components work in both.
98
+
99
+ ## The idea
100
+
101
+ An application is split into three parts with clear responsibilities.
102
+
103
+ **Model**: a plain object. No proxies, no observables, no special setters. You change a value by assigning it. The model instance itself stays stable.
104
+
105
+ **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.
106
+
107
+ 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.
108
+
109
+ **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.
110
+
111
+ ## Rendering and updating
112
+
113
+ `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:
114
+
115
+ ```tsx
116
+ patch(document.body, <App />)
117
+ ```
118
+
119
+ `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:
120
+
121
+ ```tsx
122
+ updateview() // the whole body
123
+ updateview('#todos') // all elements matching a selector
124
+ updateview(element) // one element
125
+ updateview('#todos', '.badge') // several targets
126
+ ```
127
+
128
+ 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.
129
+
130
+ Two more kinds of commands change how the targets after them are updated:
131
+
132
+ - **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.
133
+ - **an object** is passed as update context to all `update` callbacks (see below): `updateview({ resized: true })`.
134
+
135
+ Without a target, `updateview` updates `body`.
136
+
137
+ ### Batching
138
+
139
+ These variants collect updates and run them together:
140
+
141
+ | function | runs the update |
142
+ |---|---|
143
+ | `updateviewmicro(...)` | at the next microtask |
144
+ | `updateviewaf(...)` | at the next animation frame |
145
+ | `updateviewsync(...)` | immediately, together with everything queued |
146
+ | `flush()` | runs everything queued, immediately |
147
+
148
+ An element queued several times is updated once.
149
+
150
+ ## Components
151
+
152
+ ### Function components
153
+
154
+ A function component receives its props and children and returns JSX:
155
+
156
+ ```tsx
157
+ const TodoList = (p: { items: string[] }) =>
158
+ <ul id='todos'>{p.items.map(t => <li>{t}</li>)}</ul>
159
+
160
+ patch(document.body, <body><h1>Todos</h1><TodoList items={model.todos} /></body>)
161
+
162
+ model.todos.push('bread')
163
+ updateview('#todos') // runs TodoList again
164
+ ```
165
+
166
+ 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.
167
+
168
+ A component gets its children in `props.children`, as an array:
169
+
170
+ ```tsx
171
+ const Box = (p: { title: string, children?: Children }) =>
172
+ <section title={p.title}>{p.children}</section>
173
+
174
+ <Box title='hello'><b>world</b></Box>
175
+ ```
176
+
177
+ ### Class components
178
+
179
+ 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:
180
+
181
+ ```tsx
182
+ class Counter extends Component<{ start: number }> {
183
+ count = this.props.start
184
+ inc() { this.count++; this.updateview() }
185
+ view(): H { return <button onclick={this.inc}>{this.count}</button> }
186
+ }
187
+
188
+ patch(document.body, <body><Counter start={5} /></body>)
189
+ ```
190
+
191
+ | member | |
192
+ |---|---|
193
+ | `view()` | returns the component's JSX: exactly one root element, or `null` to render nothing |
194
+ | `props` | the current props, updated on every render by the parent |
195
+ | `element` | the rendered root element |
196
+ | `mounted()` | called once, after the first render |
197
+ | `update(uc)` | called before each re-render. Return `true` to skip the re-render, for example after updating the DOM yourself |
198
+ | `updateview()` | updates this component |
199
+ | `ismounted` | `true` once rendered |
200
+
201
+ Methods are bound to the instance, so they can be used directly as event handlers, as `onclick={this.inc}` above shows.
202
+
203
+ A component whose `view()` returns `null` keeps its state and can show itself again later.
204
+
205
+ ## Elements
206
+
207
+ ### Props: attributes and properties
208
+
209
+ 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.
210
+
211
+ `null`, `undefined` and `false` remove the attribute. On `aria-*` attributes, `false` is kept as the value `"false"`.
212
+
213
+ A prop whose value is wrapped in `lazy` is evaluated at each render:
214
+
215
+ ```tsx
216
+ <dd class={lazy(() => cc('item', { active: model.active }))} />
217
+ ```
218
+
219
+ ### Children
220
+
221
+ Strings and numbers render as text. `null`, `undefined`, `false` and `true` render nothing, so conditions read naturally:
222
+
223
+ ```tsx
224
+ <div>{model.error && <p class='error'>{model.error}</p>}</div>
225
+ ```
226
+
227
+ 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.
228
+
229
+ 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.
230
+
231
+ ### Lifecycle callbacks
232
+
233
+ Elements accept two lifecycle callbacks:
234
+
235
+ ```tsx
236
+ <canvas
237
+ mounted={(n) => draw(n)} // once, after the element is created
238
+ update={(n, uc) => { draw(n, uc); return true }} // before each update. true: skip the default update
239
+ />
240
+ ```
241
+
242
+ ### Islands
243
+
244
+ 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:
245
+
246
+ ```tsx
247
+ <div class='map' const
248
+ mounted={(n) => map = new maplibregl.Map({ container: n })}
249
+ update={() => { map.setStyle(model.style) }}
250
+ />
251
+ ```
252
+
253
+ The `const` attribute stays visible in the DOM, which helps to spot islands in the dev tools.
254
+
255
+ jmc also leaves the children of web components (tags containing `-`) to the component itself.
256
+
257
+ ### SVG
258
+
259
+ 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:
260
+
261
+ ```tsx
262
+ <svg xmlns='http://www.w3.org/2000/svg'><circle r={5} /></svg>
263
+ ```
264
+
265
+ ### Custom elements
266
+
267
+ 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:
268
+
269
+ ```ts
270
+ import type { HtmlHTMLAttributes } from '@snupo/jmc'
271
+
272
+ declare module '@snupo/jmc' {
273
+ namespace jsx {
274
+ namespace JSX {
275
+ interface IntrinsicElements {
276
+ 'my-chart': HtmlHTMLAttributes & { data: number[] }
277
+ }
278
+ }
279
+ }
280
+ }
281
+ ```
282
+
283
+ ## Configuration
284
+
285
+ `jmcconfig` holds the settings that adjust jmc:
286
+
287
+ ```ts
288
+ import { jmcconfig } from '@snupo/jmc'
289
+
290
+ jmcconfig.debug = true // mark component roots with comp="Name"
291
+ jmcconfig.attributes.add('list') // always set this prop as an attribute
292
+ ```
293
+
294
+ **`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()`.
295
+
296
+ **`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`.
297
+
298
+ ## Utilities
299
+
300
+ | | |
301
+ |---|---|
302
+ | `cc(...)` | joins class names. Objects contribute their keys with truthy values: `cc('item', { active })` |
303
+ | `<When cond={…}>` | renders its children only if `cond` is true |
304
+ | `lazy(f)` | a prop value that is evaluated at each render |
305
+ | `closestby(node, pred)` | the nearest ancestor (or the node itself) matching `pred` |
306
+ | `focuselement(node)` | focuses the node |
307
+ | `rebind(o)` | binds the prototype methods of `o` to `o` |
308
+ | `mount({ … })` | puts values on `globalThis`, handy for debugging in the console |
309
+ | `loggedmethods(o)` | logs each method call of `o` with its arguments and result |
310
+
311
+ ## License
312
+
313
+ [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 {
package/src/h.ts CHANGED
@@ -1,22 +1,21 @@
1
+ import type { JmcIntrinsicElements } from './jsx.js'
2
+
1
3
  export type J = Record<string, any> // a json record
2
- export type UC = J // update context
3
4
 
4
- // Overload signatures
5
5
  export type Selector = string | Node
6
6
 
7
- export type FComponent = (props: J | undefined, children?: Children) => HU
8
- export type FComponentT<P> = (pcn: P, cn?: Children) => HU
7
+ /** an updateview command: a target (selector or node), a depth (number) or an update context (object) */
8
+ export type Command = Selector | J | number
9
+
10
+ // TBD REMOVE the children parameter once we know it is unused: components get their children in props.children.
11
+ // the second parameter remains for function components written before props.children existed
12
+ export type FComponent = (props: J, children?: Children) => HU
9
13
 
10
14
  type HKindElement = 1
11
15
  type HKindFunctionComponent = 2
12
16
  type HKindClassComponent = 3
13
17
  type HKindFragment = 4
14
18
 
15
- // export const kindelement : HKindElement = 1
16
- // export const kindfc : HKindFunctionComponent = 2
17
- // export const kindcc : HKindClassComponent = 3
18
- // export const kindfragment : HKindFragment = 4
19
-
20
19
  export type HKind = HKindElement | HKindFunctionComponent | HKindClassComponent | HKindFragment
21
20
 
22
21
  export interface IClassComponent {
@@ -36,7 +35,7 @@ export type Children = HU[]
36
35
  export type HText =
37
36
  | string // text node
38
37
  | number // text node
39
- | boolean // do not allow boolean, that
38
+ | boolean // renders nothing, like null and undefined
40
39
 
41
40
  export type HFragment = {
42
41
  kind: HKindFragment
@@ -46,21 +45,21 @@ export type HFragment = {
46
45
  export type HElement = {
47
46
  kind: HKindElement
48
47
  tag: string
49
- p?: J
48
+ p: J
50
49
  cn?: Children
51
50
  }
52
51
 
53
52
  export type HFunctionComponent = {
54
53
  kind: HKindFunctionComponent
55
54
  tag: FComponent
56
- p?: J
55
+ p: J
57
56
  cn?: Children
58
57
  }
59
58
 
60
59
  export type HClassComponent = {
61
60
  kind: HKindClassComponent
62
61
  tag: CComponent
63
- p?: J
62
+ p: J
64
63
  cn?: Children
65
64
  i?: IClassComponent
66
65
  }
@@ -72,23 +71,35 @@ export type H =
72
71
  | HElement
73
72
  | HFunctionComponent
74
73
  | HClassComponent
75
- | HFragment
74
+ | HFragment
76
75
 
77
76
  export type HU = H | undefined | null
78
77
 
79
78
  let isclass = (f: Function) => /^class\s|^class\{/.test(f.toString())
80
79
 
81
- export function jsx(tag: any, p: any, ...cn: any[]): HElement | HFunctionComponent | HClassComponent | HFragment {
80
+ export function jsx(tag: any, p: any, ...cn: any[]): HElement | HComp | HFragment {
82
81
  if (tag?.kind) return tag // already an H node, flatten tree
83
82
 
84
83
  let kind: HKind = tag == jsxf ? 4 : tag instanceof Function ? (isclass(tag) ? 3 : 2) : 1
85
84
 
86
- let h: any = { kind }
85
+ let h: any = { kind, p: p ?? {} }
87
86
  if (kind != 4) h.tag = tag
88
- if (p) h.p = p
89
- if (cn?.length) h.cn = cn
87
+ if (cn?.length) {
88
+ h.cn = cn
89
+ // components get their children in props.children, as with the automatic runtime (jsx-runtime.ts).
90
+ // elements do not: setprops would write them to the element's read-only children property
91
+ if (kind == 2 || kind == 3) h.p = { ...h.p, children: cn }
92
+ }
90
93
  return h
91
94
  }
92
95
 
96
+ // typescript looks up the JSX types on the factory function first: jsx.JSX instead of a global JSX namespace.
97
+ // so jmc's element types cannot clash with other libraries. add your own elements by augmenting jsx.JSX.IntrinsicElements
98
+ export namespace jsx {
99
+ export namespace JSX {
100
+ export interface IntrinsicElements extends JmcIntrinsicElements { }
101
+ }
102
+ }
103
+
93
104
  // fragment is only used above as a sentinel
94
105
  export let jsxf = Symbol()
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export * from './jmc.js'
2
+ export { jmcconfig } from './props.js'
2
3
  export * from './lib.js'
3
4
  export * from './base.js'
4
5
  export * from './jsx.js'
5
6
  export * from './h.js'
6
- export * from './updateview.js'
7
+ export * from './update.js'