Skip to content

Commit 38bc438

Browse files
committed
fix(core): capture spread children before later statements
A JSX spread child counted as render output, so a following statement made the body interleaved, but the spread itself was left to evaluate inside the returned fragment. Snapshot its expression at the source position and spread the captured value, matching an expression child.
1 parent 26d8a36 commit 38bc438

5 files changed

Lines changed: 106 additions & 15 deletions

File tree

‎.changeset/jsx-spread-children.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@ JSX spread children (`<div>{...children}</div>`) now parse, in templates and in
99
plain TSX, instead of failing with `Unexpected token`:
1010

1111
- React, Preact, and Hono compile them unchanged, and the JSX compiler spreads
12-
the array into the element's children.
12+
the array into the element's children. A spread that appears before a later
13+
statement is evaluated at that point in the source, same as `{children}`, so
14+
a following assignment does not change what it renders.
1315
- Solid compiles `{...children}` to `{children}`, which Solid's JSX compiler
1416
renders the same way. Solid's JSX compiler would otherwise render a spread
1517
child after the static siblings that follow it.

‎packages/tsrx/src/transform/jsx-interleave.js‎

Lines changed: 39 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ export function is_interleaved_body(body_nodes, is_jsx_child) {
4343
* `const`. Static text children (`JSXText`) and comment-only containers
4444
* (`{/* … *\/}`) are inert and don't need capturing — their position relative
4545
* to mutations doesn't change output, and neither has an expression to bind.
46+
* A spread child (`{...items}`) is not inert: it reads its expression when the
47+
* returned fragment is built, so it is snapshotted the same way as `{items}`.
4648
*
4749
* @param {AST.Node | null | undefined} jsx
4850
* @returns {jsx is ESTreeJSX.JSXCapturableChild}
@@ -55,34 +57,59 @@ export function is_capturable_jsx_child(jsx) {
5557
if (jsx.metadata?.tsrx_reactive_block === true) return false;
5658
const t = jsx.type;
5759
if (t === 'JSXExpressionContainer') return jsx.expression.type !== 'JSXEmptyExpression';
58-
return t === 'JSXElement' || t === 'JSXFragment';
60+
return t === 'JSXElement' || t === 'JSXFragment' || t === 'JSXSpreadChild';
5961
}
6062

6163
/**
6264
* Build a `VariableDeclaration` that captures a JSX child into a const at
63-
* its source position, along with a JSXExpressionContainer referencing the
64-
* capture. The caller inserts the declaration into the enclosing block's
65-
* statements in source order and uses the reference in place of the JSX
66-
* child inside the returned fragment.
65+
* its source position, along with a reference used in its place inside the
66+
* returned fragment. An element, fragment, or expression child is referenced
67+
* as `{_tsrx_child_N}`; a spread child is referenced as `{..._tsrx_child_N}`.
68+
* The caller inserts the declaration into the enclosing block's statements in
69+
* source order.
6770
*
6871
* @param {ESTreeJSX.JSXCapturableChild} jsx
6972
* @param {number} capture_index
7073
* @param {(id: AST.Identifier, init: AST.Expression) => AST.Identifier} [anchor_id] gives the
7174
* capture's NAME an authored origin — the only anchorable token when the captured
7275
* expression itself starts with punctuation
73-
* @returns {{ declaration: AST.VariableDeclaration, reference: ESTreeJSX.JSXExpressionContainer }}
76+
* @returns {{
77+
* declaration: AST.VariableDeclaration,
78+
* reference: ESTreeJSX.JSXExpressionContainer | ESTreeJSX.JSXSpreadChild
79+
* }}
7480
*/
7581
export function capture_jsx_child(jsx, capture_index, anchor_id) {
7682
const name = `_tsrx_child_${capture_index}`;
77-
const init = jsx.type === 'JSXExpressionContainer' ? jsx.expression : jsx;
83+
const init =
84+
jsx.type === 'JSXExpressionContainer' || jsx.type === 'JSXSpreadChild' ? jsx.expression : jsx;
7885

7986
const declaration = b.const(anchor_id ? anchor_id(b.id(name), init) : b.id(name), init);
8087

81-
// NOTE: JSXExpressionContainer nodes are intentionally created without
82-
// loc — they're synthetic wrappers whose source positions don't
83-
// correspond to source-map entries and adding loc causes Volar mapping
84-
// failures.
85-
const reference = b.jsx_expression_container(b.id(name));
88+
// NOTE: JSXExpressionContainer and JSXSpreadChild nodes are intentionally
89+
// created without loc — they're synthetic wrappers whose source positions
90+
// don't correspond to source-map entries and adding loc causes Volar
91+
// mapping failures. A spread keeps a pointer at the authored node so a
92+
// target that rejects spread children can still report that source range.
93+
const reference =
94+
jsx.type === 'JSXSpreadChild'
95+
? spread_child_reference(b.id(name), jsx)
96+
: b.jsx_expression_container(b.id(name));
8697

8798
return { declaration, reference };
8899
}
100+
101+
/**
102+
* `{..._tsrx_child_N}` standing in for an authored spread. No location of its
103+
* own — see {@link capture_jsx_child}.
104+
*
105+
* @param {AST.Expression} expression
106+
* @param {ESTreeJSX.JSXSpreadChild} authored
107+
* @returns {ESTreeJSX.JSXSpreadChild}
108+
*/
109+
function spread_child_reference(expression, authored) {
110+
return {
111+
type: 'JSXSpreadChild',
112+
expression,
113+
metadata: { path: [], tsrx_spread_diagnostic: authored },
114+
};
115+
}

‎packages/tsrx/src/transform/jsx/index.js‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -754,7 +754,10 @@ export function createJsxTransform(platform) {
754754
const spread = /** @type {ESTreeJSX.JSXSpreadChild} */ (next() ?? node);
755755
const unsupported = state.platform.validation.unsupportedSpreadChildMessage;
756756
if (unsupported) {
757-
error(unsupported, state.filename, node, state.errors, state.comments);
757+
// A captured spread is a synthetic `{..._tsrx_child_N}` with no
758+
// location. Report against the authored spread it replaced.
759+
const diagnostic = node.metadata?.tsrx_spread_diagnostic ?? node;
760+
error(unsupported, state.filename, diagnostic, state.errors, state.comments);
758761
return spread;
759762
}
760763
// Type-only output keeps the spread, so TypeScript still checks that

‎packages/tsrx/tests/shared/compile.js‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2185,6 +2185,58 @@ export function App() @{
21852185
},
21862186
];
21872187

2188+
it('evaluates a spread child at its source position when a statement follows it', () => {
2189+
const sources = [
2190+
`export function App() @{
2191+
let items = [<b>a</b>]
2192+
<div>
2193+
{...items}
2194+
@{ items = [] }
2195+
<span />
2196+
</div>
2197+
}`,
2198+
`export function App() @{
2199+
let items = [<b>a</b>]
2200+
<>
2201+
{...items}
2202+
@{ items = [] }
2203+
<span />
2204+
</>
2205+
}`,
2206+
];
2207+
2208+
for (const source of sources) {
2209+
const start = source.indexOf('{...items}');
2210+
if (name === 'vue') {
2211+
expect(() => compile(source, 'App.tsrx')).toThrow(
2212+
expect.objectContaining({
2213+
message:
2214+
'Vue TSRX does not support JSX spread children (`{...children}`). Render the array as an expression child instead: `{children}`.',
2215+
pos: start,
2216+
end: start + '{...items}'.length,
2217+
}),
2218+
);
2219+
const { errors } = compile(source, 'App.tsrx', { collect: true });
2220+
expect(errors.map((error) => [error.pos, error.end])).toEqual([
2221+
[start, start + '{...items}'.length],
2222+
]);
2223+
continue;
2224+
}
2225+
2226+
const { code } = compile(source, 'App.tsrx');
2227+
const captured = code.indexOf('const _tsrx_child_0 = items');
2228+
const mutated = code.indexOf('items = []');
2229+
// Solid's host compiler mis-orders a spread child, so the snapshot
2230+
// is rendered as an expression child. Other targets keep the spread.
2231+
const child = name === 'solid' ? '{_tsrx_child_0}' : '{..._tsrx_child_0}';
2232+
expect(captured, code).toBeGreaterThan(-1);
2233+
expect(mutated, code).toBeGreaterThan(captured);
2234+
expect(code.indexOf(child), code).toBeGreaterThan(mutated);
2235+
expect(code, code).not.toContain('{...items}');
2236+
expect(virtual_parse_diagnostics(code), code).toEqual([]);
2237+
}
2238+
});
2239+
21882240
for (const { label, source, output } of cases) {
21892241
if (name === 'vue') {
21902242
it(`reports ${label} at its location`, () => {

‎packages/tsrx/types/index.d.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,12 @@ export interface BaseNodeMetaData {
228228
has_unmappable_value?: boolean;
229229
synthetic_ref?: boolean;
230230
tsrx_reactive_block?: boolean;
231+
/**
232+
* Authored `{...expr}` that a capture stand-in replaced. The stand-in has
233+
* no location (a located wrapper breaks Volar); a target that rejects
234+
* spread children reports against this node instead.
235+
*/
236+
tsrx_spread_diagnostic?: ESTreeJSX.JSXSpreadChild;
231237
/** Generated dynamic-tag render-block closure, not a user component boundary. */
232238
tsrx_dynamic_wrapper?: boolean;
233239
/** Scoped-class definition sites, for editor definitions/hover on `style.x`. */
@@ -1004,7 +1010,8 @@ declare module 'estree-jsx' {
10041010
type JSXCapturableChild =
10051011
| AST.TSRXJSXElement
10061012
| AST.TSRXJSXFragment
1007-
| (JSXExpressionContainer & { expression: AST.Expression });
1013+
| (JSXExpressionContainer & { expression: AST.Expression })
1014+
| JSXSpreadChild;
10081015

10091016
/** An attribute accepted by and emitted from the shared JSX transformer. */
10101017
type JSXAttributeNode = JSXAttribute | JSXSpreadAttribute;

0 commit comments

Comments
 (0)