React support: JSX handlers, four React rules, helpers and a docs section #19

Merged
sionzee merged 3 commits from react-support into main 2026-11-04 21:29:29 +01:00
Owner

React support, with its own docs section, set up the same way as Vue.

What changed

Checker on .tsx. .tsx files were already parsed with JSX and most rules ran inside JSX expressions. Event props were the gap. They are now read the way @click is in a Vue template (analyze.rs, project.rs):

  • Any on + capital-letter prop counts as a handler that React calls later. Arrows and functions written in the prop, and functions declared in the component and passed by name (const open = () => ...; onClick={open}), run detached. So a PropagateError leaving them is uncaught-propagation, and an async one that can reject is floating-rejection.
  • onClick={save} and onClick={() => save()} dropping a Result are must-use-result. This applies on DOM elements only, because a component may use what its prop returns. A function passed by name gets no quick fix, since void save would stop calling it. () => save() gets the void fix.
  • Props were already covered: no-param-mutation applies to them because they are a parameter.

React rules (react.rs). These run on .tsx/.jsx files and on .ts files that import react:

  • react-async-race: an effect sets state after await, in .then, or via .then(setX), and neither returns a cleanup nor uses an AbortController/signal.
  • react-split-state: setLoading(true) before await and false after it, next to other setters after it. Same logic as vue-split-state.
  • react-uncached-promise: use(fetch(...)), use(new Promise(...)), use(Promise.x(...)), use(p.then(...)), or use(load(id)) where load is an async function, here or imported. The imported case is resolved in the project pass.
  • react-dangerous-html: dangerouslySetInnerHTML whose value isn't a constant or a *sanitize* call. Same test as vue-v-html.
  • listener-cleanup now also covers an effect that adds a named listener, keeps an interval or creates an observer, and returns no cleanup. Inline listeners and thrown-away interval ids were already reported by lints.rs.
  • The four rules are registered in lib.rs and in the oxlint plugin and preset (as errors). oxlint runs the plugin on .tsx; I checked this by hand.

Decided against:

  • Props or state mutation and setState during render: eslint-plugin-react-hooks (immutability, set-state-in-render) and JSX keys already cover these. The docs name them as complements.
  • react-maybe-undefined: unlike a Vue template, JSX is type-checked by tsc.
  • react-unsafe-url: React 19 replaces javascript: URLs in href/src/action itself. I checked react-dom 19.3.1's sanitizeURL. The docs point React 18 users to safeHref.

@evobug/safe-ts-react:

  • useTask keeps one AsyncState, aborts superseded runs, and keeps run/abort stable so they can go in effect dependencies. It aborts on unmount and survives StrictMode's second mount.
  • <Match on={state} Ready={...} _={...} /> is checked by TypeScript through overloads: a missing variant without _ is a type error.
  • The run logic lives in runner.ts and is tested without React. The hook is tested with react-test-renderer (deprecated, but it still renders hooks without a DOM; its one warning is filtered). match.check.tsx holds the compile-time checks.
  • AsyncState and safeUrl/safeHref moved to std (@evobug/safe-ts-std/async-state, /url), so Vue and React share them. safe-ts-vue/state and /url re-export them, so nothing breaks. The checker's AsyncState special case accepts the new specifiers.

examples/react: the Vue example app in React: Vite, safeTs({ check: "error" }) before react(), StrictMode, useTask + <Match>. It has dev, build and typecheck scripts.

Docs docs/react/:

  • A hero index.md (layout: home, landing classes, a Tour with five before/after pairs). There's no live demo: embedding React in the VitePress site wasn't cheap, so I left it out.
  • Guide pages: setup, state, errors, async, cleanup, security. rules/ has an overview and four rule pages.
  • config.mts gets the /react/ sidebar, React in the Frameworks nav and the guide's Frameworks group, and rulePage for react-*. ```tsx blocks get the Compiled tab as ts ones do.
  • Also updated: the docs/README.md Frameworks table, docs/index.md (hero link and "Where it runs"), README (layout, rule table, a React section, a helpers table, std modules), std-helpers.md, and React sections on the listener-cleanup and no-param-mutation rule pages.
  • ```tsx good|bad blocks are checked by tests/docs.rs and compiled by scripts/docs-typecheck.mjs (with jsx: react-jsx). React examples can import ./api, a tsc-only stub in scripts/docs-api.ts.

Rebased onto main

Rebased onto main at 1fe2d1d (after #2, #3, #4, #5, #6, #8, #9, #10, #11, #12, #13, #16, #23). What had to change, in a second commit on top:

  • #5 (call-following). CallSite now carries a Callee and a display name. A handler passed by name (onClick={onSave}) is built through call_target like any other call, so a helper declared in the component resolves as Callee::Local after the walk. That replaces this PR's own check for nested functions returning a Result (local_result_handlers, removed), with the same report. Side effect, which I think is better: a nested handler that propagates (const onReload = () => { reload(); } with onClick={onReload}) is now reported once, at onClick={onReload}, the same as a top-level one, instead of at the reload() inside it. The react fixture says so. use(load(id)) looks up load as Callee::Name.
  • #11 (rejections vs throws). Propagation is now reported per kind: a kind that rejects and isn't awaited is floating-rejection, the rest uncaught-propagation. A handler passed by name splits the same way, with the React message ("sync is passed to onClick and rejects with Offline: React calls it with nothing around it to catch that") and no fixes. React makes that call, so the call site neither rejects for the enclosing function nor sits in its trys. unhandled-failure keeps #11's new throw/reject wording; a handler call gets no fix there either.
  • #6 (fetch-signal). It reports the fixture's use(fetch(...)), which has no signal: correct, so the fixture expects it. The docs page's use(fetch(url)) example isn't reported by it (the docs test checks the exact set), and the React example already passes a signal.
  • #9 (Vue URL rules). Kept as is: safeUrl(x) alone is rejected, unwrapOr(safeUrl(x), fallback) and safeHref(x[, safe fallback]) accepted. The rule knows the helpers by name, so imports from @evobug/safe-ts-std/url already pass. A new fixture (vue_sfc/Links.vue) shows it; the rule page and the diagnostic's help now name both paths, and the page's "can't see" note says the helpers are known by name, so a function of your own with one of those names is trusted too.
  • #12 (npm packages). @evobug/safe-ts-react gets repository, bugs, files, publishConfig, std as a ^0.1.0 peer (* is refused by the build), and is in COMPILED in scripts/build-packages.mjs, after safe-ts-vue. std's new async-state and url modules are picked up by the build as they are. Building exposed a bug in the script that was there on main but hidden: the paths mapping to other packages' built declarations (dist/*) doesn't resolve under NodeNext (no extension is added to a mapped path), so tsc fell back to the workspace link, i.e. std's sources, and failed on async-state.ts's extensionless relative imports. The mapping now ends in .d.ts. scripts/verify-packages.mjs installs safe-ts-react (with react, @types/react), runs std/async-state, std/url and safe-ts-react from node_modules (one AsyncState object across std, vue and react), and type-checks them. The release workflow needed no change: it publishes every .release/*/ directory, std first. Nothing was published.
  • #10 (dev checks) and #3/#8 (rules). Nothing fires on the React docs, fixtures or examples/react. In the Vite dev server the example gets dev checks (the toSorted comparator in App.tsx, q in users.ts), and they pass when run.
  • Conflicts: docs.rs and docs-typecheck.mjs keep main's no-tsc marker next to the ```tsx fences; std's package.json keeps #12's publishing fields plus the two new exports.

Testing (on the rebased branch, 76d3a68)

  • cargo nextest run --workspace: 104/104 pass.
  • npm run test:std: 144/144 pass (with the 14 safe-ts-react tests).
  • npm run test:vite: passes.
  • npm run test:docs: passes (270 examples compile, docs examples behave as documented, VitePress builds with main's config, no dead links; the React hero, guide and rule pages are in the output).
  • npm run typecheck: passes.
  • node scripts/build-packages.mjs and node scripts/verify-packages.mjs --no-build: all package checks pass, safe-ts-react included.
  • examples/react: vite build (check: "error"), tsc -p . and safe-ts check src/main.tsx all clean.
  • npm run bench:check: not run; this PR touches no benches or the transform.

Left for later / uncertain

  • Rendering (<Profile />) isn't a call the checker follows, so a failure thrown during render isn't traced to an error boundary.
  • react-async-race only looks at effects. A race started from an event handler (search-as-you-type) isn't reported. Any returned cleanup counts, whether or not it stops this request.
  • react-split-state only sees await, not .then chains. It only knows useState setters, not useReducer or stores.
  • A handler passed by member (onClick={store.save}) isn't followed; only plain names are.
  • No react-* rules for SSR or hydration (Vue has two), and no rule for React.lazy without an error boundary.
  • A live React demo on the docs home page.
  • I noticed, but didn't change, two existing issues:
    • f().then(cb) as a statement reports must-use-result on f(), because "discarded" is keyed by span start, which the inner call shares with .then(...).
    • std's match() infers its result as unknown when the handlers mix plain arrows with destructuring ones and nothing gives the type. The React async docs annotate const status: string = match(...) for that reason.

🤖 Generated with Claude Code

React support, with its own docs section, set up the same way as Vue. ## What changed **Checker on `.tsx`.** `.tsx` files were already parsed with JSX and most rules ran inside JSX expressions. Event props were the gap. They are now read the way `@click` is in a Vue template (`analyze.rs`, `project.rs`): - Any `on` + capital-letter prop counts as a handler that React calls later. Arrows and functions written in the prop, and functions declared in the component and passed by name (`const open = () => ...; onClick={open}`), run detached. So a `PropagateError` leaving them is `uncaught-propagation`, and an async one that can reject is `floating-rejection`. - `onClick={save}` and `onClick={() => save()}` dropping a `Result` are `must-use-result`. This applies on DOM elements only, because a component may use what its prop returns. A function passed by name gets no quick fix, since `void save` would stop calling it. `() => save()` gets the `void` fix. - Props were already covered: `no-param-mutation` applies to them because they are a parameter. **React rules (`react.rs`).** These run on `.tsx`/`.jsx` files and on `.ts` files that import `react`: - `react-async-race`: an effect sets state after `await`, in `.then`, or via `.then(setX)`, and neither returns a cleanup nor uses an `AbortController`/`signal`. - `react-split-state`: `setLoading(true)` before `await` and `false` after it, next to other setters after it. Same logic as `vue-split-state`. - `react-uncached-promise`: `use(fetch(...))`, `use(new Promise(...))`, `use(Promise.x(...))`, `use(p.then(...))`, or `use(load(id))` where `load` is an `async` function, here or imported. The imported case is resolved in the project pass. - `react-dangerous-html`: `dangerouslySetInnerHTML` whose value isn't a constant or a `*sanitize*` call. Same test as `vue-v-html`. - `listener-cleanup` now also covers an effect that adds a named listener, keeps an interval or creates an observer, and returns no cleanup. Inline listeners and thrown-away interval ids were already reported by `lints.rs`. - The four rules are registered in `lib.rs` and in the oxlint plugin and preset (as errors). oxlint runs the plugin on `.tsx`; I checked this by hand. **Decided against:** - Props or state mutation and setState during render: eslint-plugin-react-hooks (`immutability`, `set-state-in-render`) and JSX keys already cover these. The docs name them as complements. - `react-maybe-undefined`: unlike a Vue template, JSX is type-checked by tsc. - `react-unsafe-url`: React 19 replaces `javascript:` URLs in `href`/`src`/`action` itself. I checked react-dom 19.3.1's `sanitizeURL`. The docs point React 18 users to `safeHref`. **`@evobug/safe-ts-react`:** - `useTask` keeps one `AsyncState`, aborts superseded runs, and keeps `run`/`abort` stable so they can go in effect dependencies. It aborts on unmount and survives StrictMode's second mount. - `<Match on={state} Ready={...} _={...} />` is checked by TypeScript through overloads: a missing variant without `_` is a type error. - The run logic lives in `runner.ts` and is tested without React. The hook is tested with react-test-renderer (deprecated, but it still renders hooks without a DOM; its one warning is filtered). `match.check.tsx` holds the compile-time checks. - `AsyncState` and `safeUrl`/`safeHref` moved to std (`@evobug/safe-ts-std/async-state`, `/url`), so Vue and React share them. `safe-ts-vue/state` and `/url` re-export them, so nothing breaks. The checker's `AsyncState` special case accepts the new specifiers. **`examples/react`:** the Vue example app in React: Vite, `safeTs({ check: "error" })` before `react()`, StrictMode, `useTask` + `<Match>`. It has `dev`, `build` and `typecheck` scripts. **Docs `docs/react/`:** - A hero `index.md` (layout: home, landing classes, a Tour with five before/after pairs). There's no live demo: embedding React in the VitePress site wasn't cheap, so I left it out. - Guide pages: setup, state, errors, async, cleanup, security. `rules/` has an overview and four rule pages. - `config.mts` gets the `/react/` sidebar, React in the Frameworks nav and the guide's Frameworks group, and `rulePage` for `react-*`. ` ```tsx ` blocks get the Compiled tab as `ts` ones do. - Also updated: the `docs/README.md` Frameworks table, `docs/index.md` (hero link and "Where it runs"), README (layout, rule table, a React section, a helpers table, std modules), `std-helpers.md`, and React sections on the `listener-cleanup` and `no-param-mutation` rule pages. - ` ```tsx good|bad ` blocks are checked by `tests/docs.rs` and compiled by `scripts/docs-typecheck.mjs` (with `jsx: react-jsx`). React examples can import `./api`, a tsc-only stub in `scripts/docs-api.ts`. ## Rebased onto main Rebased onto main at 1fe2d1d (after #2, #3, #4, #5, #6, #8, #9, #10, #11, #12, #13, #16, #23). What had to change, in a second commit on top: - **#5 (call-following).** `CallSite` now carries a `Callee` and a display `name`. A handler passed by name (`onClick={onSave}`) is built through `call_target` like any other call, so a helper declared in the component resolves as `Callee::Local` after the walk. That replaces this PR's own check for nested functions returning a `Result` (`local_result_handlers`, removed), with the same report. Side effect, which I think is better: a nested handler that propagates (`const onReload = () => { reload(); }` with `onClick={onReload}`) is now reported once, at `onClick={onReload}`, the same as a top-level one, instead of at the `reload()` inside it. The `react` fixture says so. `use(load(id))` looks up `load` as `Callee::Name`. - **#11 (rejections vs throws).** Propagation is now reported per kind: a kind that rejects and isn't awaited is `floating-rejection`, the rest `uncaught-propagation`. A handler passed by name splits the same way, with the React message ("`sync` is passed to `onClick` and rejects with `Offline`: React calls it with nothing around it to catch that") and no fixes. React makes that call, so the call site neither rejects for the enclosing function nor sits in its `try`s. `unhandled-failure` keeps #11's new throw/reject wording; a handler call gets no fix there either. - **#6 (fetch-signal).** It reports the fixture's `use(fetch(...))`, which has no signal: correct, so the fixture expects it. The docs page's `use(fetch(url))` example isn't reported by it (the docs test checks the exact set), and the React example already passes a signal. - **#9 (Vue URL rules).** Kept as is: `safeUrl(x)` alone is rejected, `unwrapOr(safeUrl(x), fallback)` and `safeHref(x[, safe fallback])` accepted. The rule knows the helpers by name, so imports from `@evobug/safe-ts-std/url` already pass. A new fixture (`vue_sfc/Links.vue`) shows it; the rule page and the diagnostic's help now name both paths, and the page's "can't see" note says the helpers are known by name, so a function of your own with one of those names is trusted too. - **#12 (npm packages).** `@evobug/safe-ts-react` gets `repository`, `bugs`, `files`, `publishConfig`, std as a `^0.1.0` peer (`*` is refused by the build), and is in `COMPILED` in `scripts/build-packages.mjs`, after safe-ts-vue. std's new `async-state` and `url` modules are picked up by the build as they are. Building exposed a bug in the script that was there on main but hidden: the `paths` mapping to other packages' built declarations (`dist/*`) doesn't resolve under NodeNext (no extension is added to a mapped path), so tsc fell back to the workspace link, i.e. std's *sources*, and failed on `async-state.ts`'s extensionless relative imports. The mapping now ends in `.d.ts`. `scripts/verify-packages.mjs` installs safe-ts-react (with `react`, `@types/react`), runs `std/async-state`, `std/url` and safe-ts-react from node_modules (one `AsyncState` object across std, vue and react), and type-checks them. The release workflow needed no change: it publishes every `.release/*/` directory, std first. Nothing was published. - **#10 (dev checks) and #3/#8 (rules).** Nothing fires on the React docs, fixtures or `examples/react`. In the Vite dev server the example gets dev checks (the `toSorted` comparator in `App.tsx`, `q` in `users.ts`), and they pass when run. - Conflicts: `docs.rs` and `docs-typecheck.mjs` keep main's `no-tsc` marker next to the ```tsx fences; std's `package.json` keeps #12's publishing fields plus the two new exports. ## Testing (on the rebased branch, 76d3a68) - `cargo nextest run --workspace`: 104/104 pass. - `npm run test:std`: 144/144 pass (with the 14 safe-ts-react tests). - `npm run test:vite`: passes. - `npm run test:docs`: passes (270 examples compile, docs examples behave as documented, VitePress builds with main's config, no dead links; the React hero, guide and rule pages are in the output). - `npm run typecheck`: passes. - `node scripts/build-packages.mjs` and `node scripts/verify-packages.mjs --no-build`: all package checks pass, safe-ts-react included. - `examples/react`: `vite build` (`check: "error"`), `tsc -p .` and `safe-ts check src/main.tsx` all clean. - `npm run bench:check`: not run; this PR touches no benches or the transform. ## Left for later / uncertain - Rendering (`<Profile />`) isn't a call the checker follows, so a failure thrown during render isn't traced to an error boundary. - `react-async-race` only looks at effects. A race started from an event handler (search-as-you-type) isn't reported. Any returned cleanup counts, whether or not it stops this request. - `react-split-state` only sees `await`, not `.then` chains. It only knows `useState` setters, not `useReducer` or stores. - A handler passed by member (`onClick={store.save}`) isn't followed; only plain names are. - No `react-*` rules for SSR or hydration (Vue has two), and no rule for `React.lazy` without an error boundary. - A live React demo on the docs home page. - I noticed, but didn't change, two existing issues: - `f().then(cb)` as a statement reports `must-use-result` on `f()`, because "discarded" is keyed by span start, which the inner call shares with `.then(...)`. - std's `match()` infers its result as `unknown` when the handlers mix plain arrows with destructuring ones and nothing gives the type. The React async docs annotate `const status: string = match(...)` for that reason. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
sionzee force-pushed react-support from c96b9cd102 to 1a3f37d32d
Some checks failed
Benchmarks / bench (pull_request) Failing after 4s
2026-11-03 22:04:00 +01:00
Compare
sionzee force-pushed react-support from 1a3f37d32d
Some checks failed
Benchmarks / bench (pull_request) Failing after 4s
to 76d3a68d47
All checks were successful
Benchmarks / bench (pull_request) Successful in 2m35s
2026-11-03 23:25:07 +01:00
Compare
Merge main into react-support
Some checks failed
Benchmarks / bench (pull_request) Failing after 3m2s
994b87720b
Resolve conflicts with the PRs merged before this one: both sides kept
(rule lists, std exports, package checks, CLI usage, README).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sionzee deleted branch react-support 2026-11-04 21:29:30 +01:00
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
Evobug/Safe-Ts!19
No description provided.