Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add package @preact/signals-react-transform #375

Merged
merged 44 commits into from
Aug 2, 2023
Merged
Show file tree
Hide file tree
Changes from 33 commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
cb1b618
Add hello world babel plugin
andrewiggins May 22, 2023
476b216
Fix browser tests to only run browser and shared test files
andrewiggins Jun 9, 2023
b0d846f
Lazily add import statement and add hook to template
andrewiggins Jun 9, 2023
76014fa
Detect value member expressions and only transform functions with may…
andrewiggins Jun 20, 2023
e8c583d
Use replaceWith to change function body
andrewiggins Jun 20, 2023
594593a
Improve types and clean up comments
andrewiggins Jun 12, 2023
528f190
Add manual mode support using `@trackSignals` comment
andrewiggins Jun 12, 2023
f7863bc
Add support for function expressions
andrewiggins Jun 12, 2023
df40e32
Add notes for future work
andrewiggins Jun 15, 2023
4ad28ab
Add ability to opt-out of transform using comment
andrewiggins Jun 20, 2023
c46c7cd
Fix: Add missing exports declaration for runtime package
andrewiggins Jun 21, 2023
eb838c4
Have useSignals clear the current updater after a microtick
andrewiggins Jun 21, 2023
15e83de
Add tests for calling useSignals directly
andrewiggins Jun 22, 2023
73fb6f4
Move try/finally wrapping logic into a function
andrewiggins Jun 22, 2023
c705084
Add option to not use try/finally to wrap stop tracking signals
andrewiggins Jun 22, 2023
b2f8b9d
Update comments
andrewiggins Jun 22, 2023
73da9dc
Use regex to match opt-in/opt-out comments
andrewiggins Jun 22, 2023
be03ccf
Update component detection logic to include JSX and top-level functio…
andrewiggins Jun 22, 2023
ff17284
Share implementation of function-like visitors
andrewiggins Jun 22, 2023
e4a8ce8
Initial write of react-transform readme
andrewiggins Jun 23, 2023
b0bcd75
Merge branch 'main' into react-babel-plugin
andrewiggins Jun 26, 2023
74696f3
Add missing build scripts to package.json
andrewiggins Jun 28, 2023
6802bfc
Add support for transforming custom hooks
andrewiggins Jul 5, 2023
372671a
Setup react-transform E2E test infra
andrewiggins Jul 6, 2023
58b3a25
Update E2E test infra
andrewiggins Jul 6, 2023
2e6e4ae
Use testRequire for jsx in tests
andrewiggins Jul 7, 2023
959a83f
WIP: Add test for multi-hooks in component
andrewiggins Jul 10, 2023
67d6099
Align babel versions to fix tsc errors
andrewiggins Jul 11, 2023
d5527a6
Manually track if the babel transform is used to end signal tracking …
andrewiggins Jul 12, 2023
fe7f7f2
Simplify render tracking by never stopping signal tracking in a custo…
andrewiggins Jul 12, 2023
a76706b
Re-organize transform file a bit
andrewiggins Jul 12, 2023
ed01656
Fix test:prod tests
andrewiggins Jul 12, 2023
a122e59
Merge branch 'main' into react-babel-plugin
andrewiggins Jul 12, 2023
50bc4ee
Reorganize tests
andrewiggins Jul 13, 2023
1ace900
Add importSource plugin option
andrewiggins Jul 13, 2023
dd070c9
Add support for using `using`
andrewiggins Jul 14, 2023
1bab05b
Add note about higher order components
andrewiggins Jul 14, 2023
59115d9
Add changesets
andrewiggins Jul 14, 2023
cd3a22d
Cleanup effect store reference after using it
andrewiggins Jul 14, 2023
b90a938
Add test for not transforming hook callbacks
andrewiggins Jul 14, 2023
f01b413
Add support for trackSignals comments on object properties that are f…
andrewiggins Jul 18, 2023
033224a
Add support for trackSignals comments on object property assignment
andrewiggins Jul 18, 2023
1099b7b
Merge branch 'main' into react-babel-plugin
andrewiggins Aug 2, 2023
255208a
Final PR tweaks
andrewiggins Aug 2, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"react-dom": "^18.2.0"
},
"devDependencies": {
"@babel/core": "^7.18.10",
"@babel/core": "^7.22.8",
"@preact/preset-vite": "^2.3.0",
"@types/react": "^18.0.18",
"@types/react-dom": "^18.0.6",
Expand Down
1 change: 1 addition & 0 deletions global.d.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
declare const expect: Chai.ExpectStatic;
declare const sinon: import("sinon").SinonStatic;
declare const transformSignalCode: (code: string, options?: import("@preact/signals-react-transform").PluginOptions) => string;
31 changes: 27 additions & 4 deletions karma.conf.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const subPkgPath = pkgName => {
// Resolve from package.exports field
const pkgJson = path.join(__dirname, pkgName, "package.json");
const pkgExports = require(pkgJson).exports;
const file = pkgExports["."].browser;
const file = pkgExports["."].browser ?? pkgExports["."].import;
return path.join(__dirname, pkgName, file);
};

Expand All @@ -62,6 +62,7 @@ function createEsbuildPlugin() {
"@preact/signals-core": subPkgPath("./packages/core"),
"@preact/signals": subPkgPath("./packages/preact"),
"@preact/signals-react": subPkgPath("./packages/react"),
"@preact/signals-react-transform": subPkgPath("./packages/react-transform"),
};

return {
Expand Down Expand Up @@ -90,6 +91,11 @@ function createEsbuildPlugin() {
};
});

// Mock fs module to run babel in a browser environment
build.onResolve({ filter: /^fs$/ }, () => {
return { path: path.join(__dirname, "test/browser/mockFs.js") };
});

// Apply babel pass whenever we load a .js file
build.onLoad({ filter: /\.[mc]?[jt]sx?$/ }, async args => {
const contents = await fs.readFile(args.path, "utf-8");
Expand Down Expand Up @@ -190,6 +196,8 @@ function createEsbuildPlugin() {
};
}

const pkgList = ["core", "preact", "react", "react/runtime", "react-transform"];

module.exports = function (config) {
config.set({
browsers: Object.keys(localLaunchers),
Expand Down Expand Up @@ -254,7 +262,20 @@ module.exports = function (config) {

files: [
{
pattern: process.env.TESTS || "packages/*/test/**/*.test.tsx",
// Provide some NodeJS globals to run babel in a browser environment
pattern: "test/browser/nodeGlobals.js",
watched: false,
type: "js",
},
{
pattern: "test/browser/babel.js",
watched: false,
type: "js",
},
{
pattern:
process.env.TESTS ||
`packages/{${pkgList.join(",")}}/test/{,browser,shared}/*.test.tsx`,
watched: false,
type: "js",
},
Expand All @@ -265,7 +286,9 @@ module.exports = function (config) {
},

preprocessors: {
"packages/*/test/**/*": ["esbuild"],
[`packages/{${pkgList.join(",")}}/test/**/*`]: ["esbuild"],
[`test/browser/babel.js`]: ["esbuild"],
[`test/browser/nodeGlobals.js`]: ["esbuild"],
},

plugins: [
Expand All @@ -283,7 +306,7 @@ module.exports = function (config) {
jsx: "preserve",

// esbuild options
target: downlevel ? "es5" : "es2015",
target: downlevel ? "es5" : "es2019",
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Whoops - will undo this. Did this to not downlevel async/await while debugging tests

define: {
COVERAGE: coverage,
"process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV || ""),
Expand Down
14 changes: 10 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
"private": true,
"scripts": {
"prebuild": "rimraf packages/core/dist/ packages/preact/dist",
"build": "pnpm build:core && pnpm build:preact && pnpm build:react-runtime && pnpm build:react",
"build": "pnpm build:core && pnpm build:preact && pnpm build:react-runtime && pnpm build:react && pnpm build:react-transform",
"build:core": "microbundle --raw --cwd packages/core && pnpm postbuild:core",
"build:preact": "microbundle --raw --cwd packages/preact && pnpm postbuild:preact",
"build:react": "microbundle --raw --cwd packages/react && pnpm postbuild:react",
"build:react-runtime": "microbundle --raw --cwd packages/react/runtime && pnpm postbuild:react-runtime",
"build:react-transform": "microbundle --no-compress --raw --cwd packages/react-transform",
"postbuild:core": "cd packages/core/dist && mv -f index.d.ts signals-core.d.ts",
"postbuild:preact": "cd packages/preact/dist && mv -f preact/src/index.d.ts signals.d.ts && rm -dr preact",
"postbuild:react": "cd packages/react/dist && mv -f react/src/index.d.ts signals.d.ts && rm -dr react",
Expand All @@ -24,8 +25,8 @@
"test:karma:watch": "karma start karma.conf.js --no-single-run",
"test:karma:prod": "cross-env MINIFY=true NODE_ENV=production karma start karma.conf.js --single-run",
"test:karma:prod:watch": "cross-env NODE_ENV=production karma start karma.conf.js --no-single-run",
"test:mocha": "cross-env COVERAGE=true mocha --require test/node/setup.js --recursive packages/react/test/node/**.test.tsx",
"test:mocha:prod": "cross-env COVERAGE=true NODE_ENV=production mocha --require test/node/setup.js --recursive packages/react/test/node/**.test.tsx",
"test:mocha": "cross-env COVERAGE=true mocha --require test/node/setup.js --recursive packages/*/test/node/**.test.tsx",
"test:mocha:prod": "cross-env COVERAGE=true NODE_ENV=production mocha --require test/node/setup.js --recursive packages/*/test/node/**.test.tsx",
"docs:start": "cd docs && pnpm start",
"docs:build": "cd docs && pnpm build",
"docs:preview": "cd docs && pnpm preview",
Expand All @@ -39,12 +40,16 @@
],
"license": "MIT",
"devDependencies": {
"@babel/core": "^7.19.1",
"@babel/core": "^7.22.8",
"@babel/plugin-syntax-jsx": "^7.21.4",
"@babel/plugin-transform-modules-commonjs": "^7.22.5",
"@babel/plugin-transform-react-jsx": "^7.21.4",
"@babel/plugin-transform-typescript": "^7.19.1",
"@babel/preset-env": "^7.19.1",
"@babel/preset-react": "^7.18.6",
"@babel/preset-typescript": "^7.18.6",
"@babel/register": "^7.21.0",
"@babel/standalone": "^7.22.6",
"@changesets/changelog-github": "^0.4.6",
"@changesets/cli": "^2.24.2",
"@types/chai": "^4.3.3",
Expand All @@ -56,6 +61,7 @@
"@typescript-eslint/parser": "^5.33.0",
"babel-plugin-istanbul": "^6.1.1",
"babel-plugin-transform-rename-properties": "^0.1.0",
"buffer": "^6.0.3",
"chai": "^4.3.6",
"cross-env": "^7.0.3",
"errorstacks": "^2.4.0",
Expand Down
119 changes: 119 additions & 0 deletions packages/react-transform/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# Signals React Transform
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unsure what's the right level of detail here. Would love other's thoughts.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's perfectly fine. We could theoretically shorten the intro paragraph about what signals are by just pointing to the blog post. But then again that I think leaving as is, is fine too.


> A Babel plugin to transform React components to automatically subscribe to Preact Signals.

Signals is a performant state management library with two primary goals:

1. Make it as easy as possible to write business logic for small up to complex apps. No matter how complex your logic is, your app updates should stay fast without you needing to think about it. Signals automatically optimize state updates behind the scenes to trigger the fewest updates necessary. They are lazy by default and automatically skip signals that no one listens to.
2. Integrate into frameworks as if they were native built-in primitives. You don't need any selectors, wrapper functions, or anything else. Signals can be accessed directly and your component will automatically re-render when the signal's value changes.

Read the [announcement post](https://preactjs.com/blog/introducing-signals/) to learn more about which problems signals solves and how it came to be.

## Installation:

```sh
npm install @preact/signals-react-transform
```

## Usage

This package works with the `@preact/signals-react` package to integrate signals into React. You use the `@preact/signals-react` package to setup and access signals inside your components and this package is one way to automatically subscribe your components to rerender when the signals you use change.

To understand how to use signals in your components, check out the [Signals React documentation](../react/README.md). This babel transform is one of a couple different ways to use signals in React. To see other ways, including integrations that don't require a build step, see the [Signals React documentation](../react/README.md).

Then, setup the transform plugin in your Babel config:

```js
// babel.config.js
module.exports = {
plugins: [["@preact/signals-react-transform"]],
};
```

Here is an example of a component using signals:

```js
import { signal } from "@preact/signals-react";

const count = signal(0);

function CounterValue() {
// Whenever the `count` signal is updated, we'll
// re-render this component automatically for you
return <p>Value: {count.value}</p>;
}
```

After the babel transform runs, it'll look something like:

```js
import { signal, useSignals } from "@preact/signals-react";

const count = signal(0);

function CounterValue() {
const endTracking = useSignals();
try {
// Whenever the `count` signal is updated, we'll
// re-render this component automatically for you
return <p>Value: {count.value}</p>;
} finally {
endTracking();
}
}
```

The `useSignals` hook setups the machinery to observe what signals are used inside the component and then automatically re-render the component when those signals change. The `endTracking` function notifies the tracking mechanism that this component has finished rendering. When your component unmounts, it also unsubscribes from all signals it was using.

Fundamentally, this Babel transform needs to answer two questions in order to know whether to transform a function:

1. Is a function a component?
2. If so, does this component use signals?

Currently we use the following heuristics to answer these questions:

1. A function is a component if it has a capitalized name (e.g. `function MyComponent() {}`) and contains JSX.
2. If a function's body includes a member expression referencing `.value` (i.e. `something.value`), we assume it's a signal.

If your function/component meets these criteria, this plugin will transform it. If not, it will be left alone. If you have a function that uses signals but does not meet these criteria (e.g. a function that manually calls `createElement` instead of using JSX), you can add a comment with the string `@trackSignals` to instruct this plugin to transform this function. You can also manually opt-out of transforming a function by adding a comment with the string `@noTrackSignals`.

```js
// This function will be transformed
/** @trackSignals */
function MyComponent() {
return createElement("h1", null, signal.value);
}

// This function will not be transformed
/** @noTrackSignals */
function MyComponent() {
return <p>{signal.value}</p>;
}
```

## Plugin Options

### `mode`

The `mode` option enables you to control how the plugin transforms your code. There are two modes:

- `mode: "auto"` (default): This mode will automatically transform any function that meets the criteria described above. This is the easiest way to get started with signals.
- `mode: "manual"`: This mode will only transform functions that have a comment with the string `@trackSignals`. This is useful if you want to manually control which functions are transformed.

```js
// babel.config.js
module.exports = {
plugins: [
[
"@preact/signals-react-transform",
{
mode: "manual",
},
],
],
};
```

## License

`MIT`, see the [LICENSE](../../LICENSE) file.
61 changes: 61 additions & 0 deletions packages/react-transform/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
{
"name": "@preact/signals-react-transform",
"version": "0.0.1-alpha.0",
"license": "MIT",
"description": "Manage state with style in React",
"keywords": [],
"authors": [
"The Preact Authors (https://github.com/preactjs/signals/contributors)"
],
"repository": {
"type": "git",
"url": "https://github.com/preactjs/signals",
"directory": "packages/react"
},
"bugs": "https://github.com/preactjs/signals/issues",
"homepage": "https://preactjs.com",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/preact"
},
"main": "dist/signals-transform.js",
"module": "dist/signals-transform.module.js",
"types": "dist/signals-transform.d.ts",
"source": "src/index.ts",
"exports": {
".": {
"types": "./dist/signals-transform.d.ts",
"import": "./dist/signals-transform.mjs",
"require": "./dist/signals-transform.js"
}
},
"mangle": "../../mangle.json",
"scripts": {
"prepublishOnly": "cd ../.. && pnpm build:react-transform"
},
"dependencies": {
"@babel/helper-module-imports": "^7.22.5",
"@babel/helper-plugin-utils": "^7.22.5",
"@preact/signals-react": "workspace:^1.3.2",
"use-sync-external-store": "^1.2.0"
},
"peerDependencies": {
"@babel/core": "^7.22.8",
"react": "^16.14.0 || 17.x || 18.x"
},
"devDependencies": {
"@babel/core": "^7.22.8",
"@types/babel__core": "^7.20.1",
"@types/babel__helper-module-imports": "^7.18.0",
"@types/babel__helper-plugin-utils": "^7.10.0",
"@types/react": "^18.0.18",
"@types/react-dom": "^18.0.6",
"@types/use-sync-external-store": "^0.0.3",
"assert": "^2.0.0",
"buffer": "^6.0.3",
"path": "^0.12.7",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.9.0"
}
}
Loading
Loading