fix(react): JSX at module scope, in a top-level const or in a test callback renders from where its calls are attributed (#2611)

JSX outside every function now renders from what a plain call there is
attributed to: a top-level value, or the file. Ownership is by line,
so no tag counts twice. Merged with main's destructuring rules (PRs
2676 and 2677): an owning parent takes a name as its local by its own
lines or by the file's top-level destructuring, and function parents
keep main's scope rules. The viewer's shared-chrome count no longer
counts a file as a render parent.

A/B: excalidraw +132 and bulletproof-react +38 render sites (tests to
the components they render, entries to their root apps, stories to
their components), none removed.

Fixes issue 2587.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Eric Minish
2026-10-20 17:08:28 +00:00
committed by GitHub
co-authored by Claude Opus 5.5
parent b95b316860
commit 63476df6a6
4 changed files with 340 additions and 29 deletions
+98 -28
View File
@@ -1917,6 +1917,16 @@ function writtenBare(src: string, name: string): boolean {
return false;
}
/**
* Whether the lines a file or top-level value owns (#2587) declare `name`
* (`const Card = vi.fn()` in a test callback). Only those lines are read, so
* a parameter or local of a function elsewhere in the file binds nothing here.
*/
function ownLinesBind(name: string, src: string): boolean {
const n = name.replace(/\$/g, '\\$');
return new RegExp(`\\b(?:const|let|var)\\s+${n}\\b(?!\\s*[,\\]}])`).test(src);
}
/**
* What a tag renders when its parent binds the name itself: a component the
* parent declares in its own lines (`const Row = ({ row }) => <tr />` in a
@@ -2190,7 +2200,10 @@ function skipSpace(code: string, at: number, step: 1 | -1): number {
* Phase 5: React JSX child rendering. A component that returns `<Child .../>`
* mounts Child — React calls it — but JSX instantiation isn't a static call edge,
* so a render tree (App.render → StaticCanvas → renderStaticScene) breaks at the
* JSX hop. Link parent → each capitalized JSX child it renders. File-oriented
* JSX hop. Link parent → each capitalized JSX child it renders. A parent is a
* method, function or component — or, for a tag outside all of those, the
* top-level value or the file that holds it (#2587), as for a plain call
* there. File-oriented
* (read each JSX file once). Precision gates: the parent must write the name as
* a tag in its code, not in a comment, a string or a template (react-router's
* "You cannot render a <Router> inside another <Router>"; `jsxCode`), and
@@ -2217,6 +2230,7 @@ async function reactJsxChildEdges(ctx: ResolutionContext, onYield: MaybeYield):
const edges: Edge[] = [];
const seen = new Set<string>();
const PARENT_KINDS = new Set(['method', 'function', 'component']);
const VALUE_PARENT_KINDS = new Set(['constant', 'variable']);
// Once per module and export for the whole pass: what a tag imported from
// the project renders. The lookup reads and comment-strips the module.
const exports = new Map<string, Node | null>();
@@ -2240,9 +2254,55 @@ async function reactJsxChildEdges(ctx: ResolutionContext, onYield: MaybeYield):
// monorepos must not interpret `"<Foo/>"` inside C as JSX (#1560). A
// TypeScript `.ts` file holds no JSX either: a `<Name>` there is a type
// assertion or text, like outline's OpenSearch XML template.
const parents = ctx.getNodesInFile(file).filter(
(n) => PARENT_KINDS.has(n.kind) && JSX_FAMILY.includes(n.language)
);
const inFile = ctx.getNodesInFile(file);
const fns = inFile.filter((n) => PARENT_KINDS.has(n.kind) && JSX_FAMILY.includes(n.language));
// JSX outside every function renders from where a plain call there is
// attributed (#2587): a top-level `const ICONS = { a: <Icon /> }` from the
// const, `createRoot(el).render(<App />)` or a test's
// `it('…', () => render(<Card />))` from the file. Ownership is by line:
// a value owns the lines of its span no function or class holds and no
// other value shares; the file, the lines no node but itself, an import,
// an export or a framework's route holds. So no tag counts twice.
// The file's lines read as code, split once: a tag in a comment or a
// string is text (`jsxCode`).
let code: string | null | undefined;
const codeOf = () => (code === undefined ? (code = jsxCode(content)) : code);
let lines: string[] | null = null;
const holds = (n: Node) => PARENT_KINDS.has(n.kind) || n.kind === 'class';
let fileNode = inFile.find((n) => n.kind === 'file' && JSX_FAMILY.includes(n.language));
const owns = new Map<string, (line: number) => boolean>();
let values: Node[] = [];
if (fileNode) {
// Per line: 1 when a function or class holds it, 2 when any other node does.
const held = new Uint8Array((fileNode.endLine || 0) + 2);
const valuesOn = new Uint8Array(held.length);
for (const n of inFile) {
if (n.kind === 'file' || n.kind === 'import' || n.kind === 'export' || n.kind === 'route' ||
!n.startLine || !n.endLine) continue;
const mark = holds(n) ? 1 : 2;
for (let l = n.startLine; l <= n.endLine && l < held.length; l++) if (held[l] !== 1) held[l] = mark;
}
// A top-level value: its first line is in no function or class.
values = inFile.filter((n) => VALUE_PARENT_KINDS.has(n.kind) && JSX_FAMILY.includes(n.language) &&
held[n.startLine] !== 1);
// A line a value shares with another statement (`const root =
// createRoot(el); root.render(<App />)`) is no one's — not the value's,
// and not the file's, which owns only lines no node holds: ownership is
// by line, so its tags get no edge rather than a wrong one. Read as
// code, so a comment there is no statement.
const raw = (lines ??= (codeOf() ?? content).split('\n'));
for (const v of values) {
for (let l = v.startLine; l <= v.endLine && l < valuesOn.length; l++) if (valuesOn[l]! < 2) valuesOn[l]!++;
const before = (raw[v.startLine - 1] ?? '').slice(0, v.startColumn ?? 0);
const after = (raw[v.endLine - 1] ?? '').slice(v.endColumn ?? Infinity);
if (!/^\s*(?:(?:export|declare|default|const|let|var)\s+)*$/.test(before)) valuesOn[v.startLine] = 2;
if (!/^[\s;]*$/.test(after)) valuesOn[v.endLine] = 2;
}
for (const v of values) owns.set(v.id, (line) => held[line] !== 1 && valuesOn[line] === 1);
if (held.subarray(1, fileNode.endLine + 1).includes(0)) owns.set(fileNode.id, (line) => !held[line]);
else fileNode = undefined;
}
const parents = [...fns, ...values, ...(fileNode ? [fileNode] : [])];
if (parents.length === 0) continue;
// Read once per file, and only when a name actually turns out ambiguous.
let imports: Map<string, string> | null = null;
@@ -2260,18 +2320,18 @@ async function reactJsxChildEdges(ctx: ResolutionContext, onYield: MaybeYield):
// over go-ethereum's graphiql.min.js (2,234 functions on 980 KB). The
// file is split once, not once per function, and read as code once: a
// tag in a comment or a string is text (`jsxCode`).
let code: string | null | undefined;
const codeOf = () => (code === undefined ? (code = jsxCode(content)) : code);
let lines: string[] | null = null;
// Each name a span holds (`spanTags`), read when a function among the
// parents is, or a function around one.
// parents is, or a function around one. A parent that owns its lines
// (#2587) reads only those, the rest left blank, under its own key.
const tagsBySpan = new Map<string, SpanTags>();
const spanOf = (fn: Node): SpanTags => {
const span = `${fn.startLine}:${fn.endLine}`;
const own = owns.get(fn.id);
const span = own ? fn.id : `${fn.startLine}:${fn.endLine}`;
let names = tagsBySpan.get(span);
if (!names) {
lines ??= (codeOf() ?? content).split('\n');
names = spanTags(lines.slice(fn.startLine - 1, fn.endLine).join('\n'), fn.startLine);
const spanLines = lines.slice(fn.startLine - 1, fn.endLine);
names = spanTags((own ? spanLines.map((text, i) => (own(fn.startLine + i) ? text : '')) : spanLines).join('\n'), fn.startLine);
tagsBySpan.set(span, names);
}
return names;
@@ -2302,27 +2362,37 @@ async function reactJsxChildEdges(ctx: ResolutionContext, onYield: MaybeYield):
if (!line) continue;
let child = jsxChild(ctx, name, file, importsOf, ownValueOf, exportOf);
if (child) {
// A name the parent, or a function around it, binds by the parent's
// first tag is that local: excalidraw's example app destructures
// `Sidebar` and `Footer` once and renders them in nested `render…`
// functions too. It renders a component that function declares, if
// any (`declaredInside`).
let binder = scopeBinds(names, parent, name, line, file, ctx) ? parent : undefined;
if (!binder) {
around ??= functionsAround(parents, parent);
for (const fn of around) {
if (scopeBinds(spanOf(fn), fn, name, line, file, ctx)) {
binder = fn;
break;
const own = owns.get(parent.id);
if (own) {
// A tag the file or a top-level value holds (#2587): a name its own
// lines declare (`const Card = vi.fn()` in a test's callback), or one
// the file destructures at its top, is that local.
if ((names.bare.has(name) && ownLinesBind(name, names.src)) || destructuredAtTop(name)) {
child = declaredInside(ctx, name, parent, child);
}
} else {
// A name the parent, or a function around it, binds by the parent's
// first tag is that local: excalidraw's example app destructures
// `Sidebar` and `Footer` once and renders them in nested `render…`
// functions too. It renders a component that function declares, if
// any (`declaredInside`).
let binder = scopeBinds(names, parent, name, line, file, ctx) ? parent : undefined;
if (!binder) {
around ??= functionsAround(fns, parent);
for (const fn of around) {
if (scopeBinds(spanOf(fn), fn, name, line, file, ctx)) {
binder = fn;
break;
}
}
}
if (binder) child = declaredInside(ctx, name, binder, child);
// A name the file destructures at its top is every function's local:
// refine's pages take `const { Title, Text } = Typography` from antd
// and rendered two other examples' `Title` and `Text`. A function
// that declares the name inside itself still renders its own.
else if (destructuredAtTop(name)) child = declaredInside(ctx, name, around?.[around.length - 1] ?? parent, child);
}
if (binder) child = declaredInside(ctx, name, binder, child);
// A name the file destructures at its top is every function's local:
// refine's pages take `const { Title, Text } = Typography` from antd
// and rendered two other examples' `Title` and `Text`. A function
// that declares the name inside itself still renders its own.
else if (destructuredAtTop(name)) child = declaredInside(ctx, name, around?.[around.length - 1] ?? parent, child);
}
if (!child || child.id === parent.id || crossesCodeBoundary(parent.language, child.language)) continue;
const key = `${parent.id}>${child.id}`;
+4 -1
View File
@@ -1621,7 +1621,10 @@ function renderParents(cg: CodeGraph, node: Node, memo: Map<string, number>): nu
const incoming = cg.getIncomingEdgesTo([node.id], ['calls']);
const sources = new Set<string>();
for (const e of incoming) {
if ((e.metadata as Record<string, unknown> | undefined)?.synthesizedBy === 'jsx-render') sources.add(e.source);
// A file renders at module scope — an entry's root, a test's subject
// (#2587) — and is no parent a screen shares chrome with.
if ((e.metadata as Record<string, unknown> | undefined)?.synthesizedBy === 'jsx-render' &&
cg.getNode(e.source)?.kind !== 'file') sources.add(e.source);
}
parents = sources.size;
memo.set(node.id, parents);