React support: JSX handlers, four React rules, helpers and a docs section #19
Loading…
Reference in a new issue
No description provided.
Delete branch "react-support"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
React support, with its own docs section, set up the same way as Vue.
What changed
Checker on
.tsx..tsxfiles were already parsed with JSX and most rules ran inside JSX expressions. Event props were the gap. They are now read the way@clickis in a Vue template (analyze.rs,project.rs):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 aPropagateErrorleaving them isuncaught-propagation, and an async one that can reject isfloating-rejection.onClick={save}andonClick={() => save()}dropping aResultaremust-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, sincevoid savewould stop calling it.() => save()gets thevoidfix.no-param-mutationapplies to them because they are a parameter.React rules (
react.rs). These run on.tsx/.jsxfiles and on.tsfiles that importreact:react-async-race: an effect sets state afterawait, in.then, or via.then(setX), and neither returns a cleanup nor uses anAbortController/signal.react-split-state:setLoading(true)beforeawaitandfalseafter it, next to other setters after it. Same logic asvue-split-state.react-uncached-promise:use(fetch(...)),use(new Promise(...)),use(Promise.x(...)),use(p.then(...)), oruse(load(id))whereloadis anasyncfunction, here or imported. The imported case is resolved in the project pass.react-dangerous-html:dangerouslySetInnerHTMLwhose value isn't a constant or a*sanitize*call. Same test asvue-v-html.listener-cleanupnow 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 bylints.rs.lib.rsand in the oxlint plugin and preset (as errors). oxlint runs the plugin on.tsx; I checked this by hand.Decided against:
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 replacesjavascript:URLs inhref/src/actionitself. I checked react-dom 19.3.1'ssanitizeURL. The docs point React 18 users tosafeHref.@evobug/safe-ts-react:useTaskkeeps oneAsyncState, aborts superseded runs, and keepsrun/abortstable 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.runner.tsand 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.tsxholds the compile-time checks.AsyncStateandsafeUrl/safeHrefmoved to std (@evobug/safe-ts-std/async-state,/url), so Vue and React share them.safe-ts-vue/stateand/urlre-export them, so nothing breaks. The checker'sAsyncStatespecial case accepts the new specifiers.examples/react: the Vue example app in React: Vite,safeTs({ check: "error" })beforereact(), StrictMode,useTask+<Match>. It hasdev,buildandtypecheckscripts.Docs
docs/react/: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.rules/has an overview and four rule pages.config.mtsgets the/react/sidebar, React in the Frameworks nav and the guide's Frameworks group, andrulePageforreact-*.```tsxblocks get the Compiled tab astsones do.docs/README.mdFrameworks 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 thelistener-cleanupandno-param-mutationrule pages.```tsx good|badblocks are checked bytests/docs.rsand compiled byscripts/docs-typecheck.mjs(withjsx: react-jsx). React examples can import./api, a tsc-only stub inscripts/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:CallSitenow carries aCalleeand a displayname. A handler passed by name (onClick={onSave}) is built throughcall_targetlike any other call, so a helper declared in the component resolves asCallee::Localafter the walk. That replaces this PR's own check for nested functions returning aResult(local_result_handlers, removed), with the same report. Side effect, which I think is better: a nested handler that propagates (const onReload = () => { reload(); }withonClick={onReload}) is now reported once, atonClick={onReload}, the same as a top-level one, instead of at thereload()inside it. Thereactfixture says so.use(load(id))looks uploadasCallee::Name.floating-rejection, the restuncaught-propagation. A handler passed by name splits the same way, with the React message ("syncis passed toonClickand rejects withOffline: 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 itstrys.unhandled-failurekeeps #11's new throw/reject wording; a handler call gets no fix there either.use(fetch(...)), which has no signal: correct, so the fixture expects it. The docs page'suse(fetch(url))example isn't reported by it (the docs test checks the exact set), and the React example already passes a signal.safeUrl(x)alone is rejected,unwrapOr(safeUrl(x), fallback)andsafeHref(x[, safe fallback])accepted. The rule knows the helpers by name, so imports from@evobug/safe-ts-std/urlalready 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.@evobug/safe-ts-reactgetsrepository,bugs,files,publishConfig, std as a^0.1.0peer (*is refused by the build), and is inCOMPILEDinscripts/build-packages.mjs, after safe-ts-vue. std's newasync-stateandurlmodules are picked up by the build as they are. Building exposed a bug in the script that was there on main but hidden: thepathsmapping 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 onasync-state.ts's extensionless relative imports. The mapping now ends in.d.ts.scripts/verify-packages.mjsinstalls safe-ts-react (withreact,@types/react), runsstd/async-state,std/urland safe-ts-react from node_modules (oneAsyncStateobject 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.examples/react. In the Vite dev server the example gets dev checks (thetoSortedcomparator inApp.tsx,qinusers.ts), and they pass when run.docs.rsanddocs-typecheck.mjskeep main'sno-tscmarker next to the ```tsx fences; std'spackage.jsonkeeps #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.mjsandnode scripts/verify-packages.mjs --no-build: all package checks pass, safe-ts-react included.examples/react:vite build(check: "error"),tsc -p .andsafe-ts check src/main.tsxall clean.npm run bench:check: not run; this PR touches no benches or the transform.Left for later / uncertain
<Profile />) isn't a call the checker follows, so a failure thrown during render isn't traced to an error boundary.react-async-raceonly 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-stateonly seesawait, not.thenchains. It only knowsuseStatesetters, notuseReduceror stores.onClick={store.save}) isn't followed; only plain names are.react-*rules for SSR or hydration (Vue has two), and no rule forReact.lazywithout an error boundary.f().then(cb)as a statement reportsmust-use-resultonf(), because "discarded" is keyed by span start, which the inner call shares with.then(...).match()infers its result asunknownwhen the handlers mix plain arrows with destructuring ones and nothing gives the type. The React async docs annotateconst status: string = match(...)for that reason.🤖 Generated with Claude Code
c96b9cd102to1a3f37d32d1a3f37d32d76d3a68d47