@rrjs/babel-plugin 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,89 @@
1
+ # babel-plugin-reactive-react
2
+
3
+ Babel plugin that compiles JSX to `h()` calls compatible with `@rrjs/renderer`. Dynamic expressions inside JSX are wrapped in thunks so the renderer can establish reactive bindings.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install -D babel-plugin-reactive-react @babel/core
9
+ ```
10
+
11
+ ## Setup
12
+
13
+ ### Vite
14
+
15
+ ```js
16
+ // vite.config.ts
17
+ import { defineConfig } from 'vite'
18
+ import babel from '@babel/core'
19
+ import reactiveReact from 'babel-plugin-reactive-react'
20
+
21
+ export default defineConfig({
22
+ esbuild: { jsx: 'preserve' },
23
+ plugins: [
24
+ {
25
+ name: 'reactive-react-jsx',
26
+ enforce: 'pre',
27
+ async transform(code, id) {
28
+ if (!id.endsWith('.tsx') && !id.endsWith('.jsx')) return null
29
+ const result = await babel.transformAsync(code, {
30
+ filename: id,
31
+ plugins: [reactiveReact],
32
+ presets: ['@babel/preset-typescript'],
33
+ parserOpts: { plugins: ['jsx', 'typescript'] },
34
+ })
35
+ return { code: result?.code ?? code, map: result?.map }
36
+ },
37
+ },
38
+ ],
39
+ })
40
+ ```
41
+
42
+ In your entry file:
43
+
44
+ ```js
45
+ import { h } from '@rrjs/renderer'
46
+ ;(globalThis as any).h = h
47
+ ```
48
+
49
+ The plugin assumes `h` is in scope where JSX is used.
50
+
51
+ ## What it transforms
52
+
53
+ | Input | Output |
54
+ |---|---|
55
+ | `<div>hello</div>` | `h('div', null, 'hello')` |
56
+ | `<div>{count}</div>` | `h('div', null, () => count)` |
57
+ | `<div className={cls}>` | `h('div', { className: () => cls })` |
58
+ | `<button onClick={fn}>` | `h('button', { onClick: fn })` |
59
+ | `<input disabled={true}>` | `h('input', { disabled: true })` |
60
+ | `<Counter />` | `h(Counter, null)` |
61
+
62
+ Static literals are not wrapped. Event handlers (anything matching `on[A-Z]`) are passed through directly.
63
+
64
+ ## Why thunks
65
+
66
+ Inside the renderer, thunks run inside an `effect`. That effect subscribes to any signals read by the thunk. When those signals change, the thunk re-runs and the bound DOM node updates — without re-running the component function. This is what makes the "component runs once" property possible.
67
+
68
+ ## License
69
+ MIT License
70
+
71
+ Copyright (c) 2026 Saman Abaasi
72
+
73
+ Permission is hereby granted, free of charge, to any person obtaining a copy
74
+ of this software and associated documentation files (the "Software"), to deal
75
+ in the Software without restriction, including without limitation the rights
76
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
77
+ copies of the Software, and to permit persons to whom the Software is
78
+ furnished to do so, subject to the following conditions:
79
+
80
+ The above copyright notice and this permission notice shall be included in all
81
+ copies or substantial portions of the Software.
82
+
83
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
84
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
85
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
86
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
87
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
88
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
89
+ SOFTWARE.
@@ -0,0 +1,2 @@
1
+ import type { PluginObj, PluginPass } from '@babel/core';
2
+ export default function reactiveReactPlugin(): PluginObj<PluginPass>;
package/dist/index.js ADDED
@@ -0,0 +1,254 @@
1
+ import * as t from '@babel/types';
2
+ import jsxSyntaxPlugin from '@babel/plugin-syntax-jsx';
3
+ // ─── The Plugin ──────────────────────────────────────────────────────────────
4
+ // Transforms JSX into h() calls.
5
+ // Dynamic expressions (signals, computeds, variables that may change)
6
+ // are wrapped in thunks so the renderer can subscribe them to signal changes.
7
+ export default function reactiveReactPlugin() {
8
+ return {
9
+ name: 'babel-plugin-reactive-react',
10
+ inherits: jsxSyntaxPlugin.default ?? jsxSyntaxPlugin,
11
+ visitor: {
12
+ JSXElement(path) {
13
+ const replacement = transformElement(path.node);
14
+ path.replaceWith(replacement);
15
+ },
16
+ JSXFragment(path) {
17
+ // Fragments: <>...</> → [child, child, ...]
18
+ // We use an array because there's no h() call for fragments yet
19
+ const children = filterChildren(path.node.children).map(transformChild);
20
+ path.replaceWith(t.arrayExpression(children));
21
+ },
22
+ },
23
+ };
24
+ }
25
+ // ─── Transform a JSX element into an h() call ────────────────────────────────
26
+ // ─── Transform the tag name ──────────────────────────────────────────────────
27
+ // <div> → 'div' (string — lowercase, native HTML element)
28
+ // <App> → App (identifier — a component function)
29
+ function transformTag(name) {
30
+ if (t.isJSXIdentifier(name)) {
31
+ // Lowercase = native element, uppercase = component
32
+ if (/^[a-z]/.test(name.name)) {
33
+ return t.stringLiteral(name.name);
34
+ }
35
+ return t.identifier(name.name);
36
+ }
37
+ // <Module.Component> → Module.Component
38
+ if (t.isJSXMemberExpression(name)) {
39
+ return convertMemberExpression(name);
40
+ }
41
+ // <namespace:tag> — not supported
42
+ throw new Error('JSXNamespacedName is not supported');
43
+ }
44
+ function convertMemberExpression(node) {
45
+ const object = t.isJSXMemberExpression(node.object)
46
+ ? convertMemberExpression(node.object)
47
+ : t.identifier(node.object.name);
48
+ return t.memberExpression(object, t.identifier(node.property.name));
49
+ }
50
+ // ─── Transform props/attributes ──────────────────────────────────────────────
51
+ function getAttributeName(name) {
52
+ if (t.isJSXIdentifier(name))
53
+ return name.name;
54
+ throw new Error('Namespaced JSX attributes not supported');
55
+ }
56
+ function transformElement(element) {
57
+ const openingElement = element.openingElement;
58
+ const tag = transformTag(openingElement.name);
59
+ const isNativeElement = t.isStringLiteral(tag);
60
+ const props = transformProps(openingElement.attributes, isNativeElement);
61
+ const children = filterChildren(element.children).map(transformChild);
62
+ return t.callExpression(t.identifier('h'), [
63
+ tag,
64
+ props,
65
+ ...children,
66
+ ]);
67
+ }
68
+ function transformProps(attrs, isNativeElement) {
69
+ if (attrs.length === 0)
70
+ return t.nullLiteral();
71
+ const properties = [];
72
+ for (const attr of attrs) {
73
+ if (t.isJSXSpreadAttribute(attr)) {
74
+ properties.push(t.spreadElement(attr.argument));
75
+ continue;
76
+ }
77
+ const name = getAttributeName(attr.name);
78
+ const value = transformAttributeValue(name, attr.value, isNativeElement);
79
+ properties.push(t.objectProperty(t.stringLiteral(name), value));
80
+ }
81
+ return t.objectExpression(properties);
82
+ }
83
+ function transformAttributeValue(name, value, isNativeElement) {
84
+ if (value === null || value === undefined) {
85
+ return t.booleanLiteral(true);
86
+ }
87
+ if (t.isStringLiteral(value)) {
88
+ return value;
89
+ }
90
+ if (t.isJSXExpressionContainer(value)) {
91
+ const expr = value.expression;
92
+ if (t.isJSXEmptyExpression(expr)) {
93
+ return t.nullLiteral();
94
+ }
95
+ // ref is special: never wrap.
96
+ if (name === 'ref') {
97
+ return expr;
98
+ }
99
+ // Event handlers: never wrap.
100
+ if (isEventHandler(name)) {
101
+ return expr;
102
+ }
103
+ // Static literals: pass through.
104
+ if (isStaticExpression(expr)) {
105
+ return expr;
106
+ }
107
+ // The critical distinction:
108
+ // - On native HTML elements, dynamic prop values become reactive bindings.
109
+ // The renderer wraps them in an effect to keep the DOM attribute in sync.
110
+ // So we wrap them in thunks here.
111
+ // - On user-defined components (uppercase tag), props are passed through.
112
+ // The component receives the plain value and uses it directly.
113
+ // Wrapping in a thunk would corrupt the prop type.
114
+ if (!isNativeElement) {
115
+ return expr;
116
+ }
117
+ return wrapInThunk(expr);
118
+ }
119
+ if (t.isJSXElement(value) || t.isJSXFragment(value)) {
120
+ return isNativeElement ? wrapInThunk(value) : value;
121
+ }
122
+ return t.nullLiteral();
123
+ }
124
+ // ─── Transform a child of a JSX element ──────────────────────────────────────
125
+ function transformChild(child) {
126
+ if (t.isJSXText(child)) {
127
+ return t.stringLiteral(child.value);
128
+ }
129
+ if (t.isJSXExpressionContainer(child)) {
130
+ const expr = child.expression;
131
+ if (t.isJSXEmptyExpression(expr)) {
132
+ return t.nullLiteral();
133
+ }
134
+ if (isStaticExpression(expr)) {
135
+ return expr;
136
+ }
137
+ // Try the list-as-JSX transform first.
138
+ // If the expression matches items.map((item) => <X key={...} />),
139
+ // rewrite it to a list() call for keyed reconciliation.
140
+ const listCall = tryTransformMapToList(expr);
141
+ if (listCall)
142
+ return listCall;
143
+ // Call expressions (like h(...) or list(...)) return Nodes directly
144
+ // and must NOT be wrapped in a thunk.
145
+ if (t.isCallExpression(expr)) {
146
+ return expr;
147
+ }
148
+ return wrapInThunk(expr);
149
+ }
150
+ if (t.isJSXElement(child) || t.isJSXFragment(child)) {
151
+ return t.isJSXElement(child)
152
+ ? transformElement(child)
153
+ : t.arrayExpression(filterChildren(child.children).map(transformChild));
154
+ }
155
+ if (t.isJSXSpreadChild(child)) {
156
+ return child.expression;
157
+ }
158
+ return t.nullLiteral();
159
+ }
160
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
161
+ function wrapInThunk(expr) {
162
+ // expr → () => expr
163
+ return t.arrowFunctionExpression([], expr);
164
+ }
165
+ // ─── List-as-JSX transform ──────────────────────────────────────────────────
166
+ // Detects {items.map((item) => <Foo key={item.id} ... />)} and rewrites it
167
+ // to list(() => items, (item) => item.id, (item) => h(Foo, ...)).
168
+ // This wires standard JSX iteration into the keyed list reconciler
169
+ // without requiring developers to call list() directly.
170
+ function tryTransformMapToList(expr) {
171
+ // Must be a method call to .map
172
+ if (!t.isCallExpression(expr))
173
+ return null;
174
+ if (!t.isMemberExpression(expr.callee))
175
+ return null;
176
+ if (!t.isIdentifier(expr.callee.property, { name: 'map' }))
177
+ return null;
178
+ // Must have a single callback argument
179
+ if (expr.arguments.length !== 1)
180
+ return null;
181
+ const callback = expr.arguments[0];
182
+ if (!t.isArrowFunctionExpression(callback) && !t.isFunctionExpression(callback))
183
+ return null;
184
+ // Callback should have at least one parameter (the item)
185
+ if (callback.params.length === 0)
186
+ return null;
187
+ const itemParam = callback.params[0];
188
+ if (!t.isIdentifier(itemParam))
189
+ return null; // skip destructured params for safety
190
+ // Callback body must return a JSX element with a `key` prop.
191
+ // Support both expression-bodied and block-bodied arrows.
192
+ let returnedJsx = null;
193
+ if (t.isJSXElement(callback.body)) {
194
+ returnedJsx = callback.body;
195
+ }
196
+ else if (t.isBlockStatement(callback.body)) {
197
+ // Find a top-level return statement
198
+ for (const stmt of callback.body.body) {
199
+ if (t.isReturnStatement(stmt) && t.isJSXElement(stmt.argument)) {
200
+ returnedJsx = stmt.argument;
201
+ break;
202
+ }
203
+ }
204
+ }
205
+ if (!returnedJsx)
206
+ return null;
207
+ // Find the key attribute
208
+ const keyAttr = returnedJsx.openingElement.attributes.find((a) => t.isJSXAttribute(a) && t.isJSXIdentifier(a.name, { name: 'key' }));
209
+ if (!keyAttr)
210
+ return null;
211
+ if (!keyAttr.value || !t.isJSXExpressionContainer(keyAttr.value))
212
+ return null;
213
+ const keyExpr = keyAttr.value.expression;
214
+ if (t.isJSXEmptyExpression(keyExpr))
215
+ return null;
216
+ // We have all the pieces. Build:
217
+ // list(
218
+ // () => <source>,
219
+ // (item) => <keyExpr>,
220
+ // (item) => <transformed JSX>
221
+ // )
222
+ const sourceExpression = expr.callee.object;
223
+ const transformedRenderJsx = transformElement(returnedJsx);
224
+ return t.callExpression(t.identifier('list'), [
225
+ // getItems: () => items
226
+ t.arrowFunctionExpression([], sourceExpression),
227
+ // getKey: (item) => item.id
228
+ t.arrowFunctionExpression([t.identifier(itemParam.name)], keyExpr),
229
+ // render: (item) => h(...)
230
+ t.arrowFunctionExpression([t.identifier(itemParam.name)], transformedRenderJsx),
231
+ ]);
232
+ }
233
+ function isEventHandler(name) {
234
+ // onClick, onInput, onMouseDown, etc.
235
+ return /^on[A-Z]/.test(name);
236
+ }
237
+ function isStaticExpression(expr) {
238
+ // These can never change between renders, so no thunk needed
239
+ return (t.isStringLiteral(expr) ||
240
+ t.isNumericLiteral(expr) ||
241
+ t.isBooleanLiteral(expr) ||
242
+ t.isNullLiteral(expr) ||
243
+ t.isBigIntLiteral(expr));
244
+ }
245
+ function filterChildren(children) {
246
+ // Strip whitespace-only JSXText nodes (caused by JSX formatting)
247
+ return children.filter(child => {
248
+ if (t.isJSXText(child)) {
249
+ // Trim and check if anything remains
250
+ return child.value.trim().length > 0;
251
+ }
252
+ return true;
253
+ });
254
+ }
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@rrjs/babel-plugin",
3
+ "version": "0.1.1",
4
+ "description": "Babel plugin that compiles JSX to h() calls with reactive bindings for Reactive React",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "files": [
9
+ "dist",
10
+ "README.md",
11
+ "LICENSE"
12
+ ],
13
+ "scripts": {
14
+ "build": "tsc",
15
+ "test": "vitest run",
16
+ "test:watch": "vitest",
17
+ "prepublishOnly": "npm run build && npm test"
18
+ },
19
+ "dependencies": {
20
+ "@babel/core": "^7.24.0",
21
+ "@babel/plugin-syntax-jsx": "^7.24.0",
22
+ "@babel/types": "^7.24.0"
23
+ },
24
+ "devDependencies": {
25
+ "@babel/preset-typescript": "^7.24.0",
26
+ "@types/babel__core": "^7.20.5",
27
+ "vitest": "^1.0.0",
28
+ "typescript": "^5.0.0"
29
+ },
30
+ "license": "MIT",
31
+ "author": "Saman Abaasi <samabaasii@gmail.com>",
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "https://github.com/SamAbaasi/reactive-react.git",
35
+ "directory": "packages/babel-plugin"
36
+ },
37
+ "keywords": ["babel", "babel-plugin", "jsx", "reactive-react", "signals"]
38
+ }