Skip to content

Commit b3c377f

Browse files
committed
fix: rewrite style() only in class position
The style-scope walk treated every one-argument style(...) call as the class-string intrinsic, so style={style(props)} became a hash concat. Resolve the intrinsic only on class/className values and leave leftover style(...) calls for helpers.
1 parent 825926f commit b3c377f

5 files changed

Lines changed: 126 additions & 38 deletions

File tree

‎packages/octane/src/compiler/compile.js‎

Lines changed: 7 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -6732,7 +6732,8 @@ const { applyStyleScopes } = createStyleScopePass({
67326732

67336733
// Recognise `{style (expr)}` — TSRX parses it as a plain
67346734
// `CallExpression(style, [expr])` (the dedicated `Style` intrinsic node is
6735-
// gone); resolveStyleExpr rewrites it into a scoped class-string expression.
6735+
// gone). The style-scope pre-pass rewrites this only in class / className
6736+
// position; leftover `style(...)` calls are helpers.
67366737
function isStyleCall(node) {
67376738
return (
67386739
node &&
@@ -6744,26 +6745,11 @@ function isStyleCall(node) {
67446745
);
67456746
}
67466747

6747-
// Resolve a `{style (expr)}` CallExpression (see isStyleCall) into a plain
6748-
// expression that yields a class string, with the component's scoped css hash
6749-
// prepended (so `{style ('row')}` in a component with hash "tsrx-abc" produces
6750-
// "tsrx-abc row"). Literal values inline; dynamic values become a runtime
6751-
// string concat. Components without a <style> block (no hash) — and any other
6752-
// expression shape — pass through untouched.
6753-
function resolveStyleExpr(node, cssHash) {
6754-
if (!node) return node;
6755-
if (!isStyleCall(node) || !cssHash) return node;
6756-
const inner = node.arguments[0];
6757-
if (inner.type === 'Literal' && typeof inner.value === 'string') {
6758-
const combined = inner.value ? `${cssHash} ${inner.value}` : cssHash;
6759-
// The resolved class string maps to the authored `{style (…)}` call.
6760-
return b.literal(combined, JSON.stringify(combined), node);
6761-
}
6762-
// Dynamic: emit `(<hash> + ' ' + (expr))` so absent/null produces "<hash> ".
6763-
return inheritOriginLoc(
6764-
b.binary('+', b.literal(cssHash + ' ', JSON.stringify(cssHash + ' ')), inner),
6765-
node,
6766-
);
6748+
// Class-position `{style(expr)}` is already resolved by the style-scope
6749+
// pre-pass. Leftover `style(...)` calls are helpers (e.g. `style={style(props)}`),
6750+
// so the emitters must not expand them.
6751+
function resolveStyleExpr(node, _cssHash) {
6752+
return node;
67676753
}
67686754

67696755
/**

‎packages/octane/src/compiler/style-scopes.js‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,10 @@
5151
* what the class map exposes. The classification comes from the core
5252
* analyzer (`metadata.styleKind`, `metadata.styleApplies`), which runs on
5353
* the parser AST before it is adopted, so this pass reads it read-only.
54-
* - `{style(expr)}` calls resolve to the scope chain plus the value, so the
55-
* emitters no longer need a `cssHash` to expand them.
54+
* - `{style(expr)}` calls in `class` / `className` position resolve to the
55+
* scope chain plus the value, so the emitters no longer need a `cssHash`
56+
* to expand them. A `style(...)` call anywhere else — a local helper, or
57+
* `style={style(props)}` — is left alone.
5658
* - Float style resources (`<style href precedence>`) stay in the tree.
5759
*
5860
* The parser AST may be frozen (see `adoptParserAst`): nodes are never
@@ -99,6 +101,7 @@ const DIRECTIVE_TYPES = new Set([
99101
* staticClasses: Map<any, string | null>,
100102
* appliedParts: Map<any, Array<string | any>>,
101103
* runtimeApplied: any[],
104+
* inClassPosition: boolean,
102105
* }} PassState
103106
*/
104107

@@ -133,6 +136,7 @@ export function createStyleScopePass(tools) {
133136
staticClasses: new Map(),
134137
appliedParts: new Map(),
135138
runtimeApplied: [],
139+
inClassPosition: false,
136140
};
137141
const node = walk(root, state, 'statement');
138142
return { node, cssHash: state.firstHash, runtimeApplied: state.runtimeApplied };
@@ -263,8 +267,20 @@ function walk(node, state, mode) {
263267
return rewriteChildren(node, (child) => walk(child, state, 'expression'));
264268
case 'ExpressionStatement':
265269
return rewriteChildren(node, (child) => walk(child, state, 'statement'));
270+
case 'JSXAttribute': {
271+
const name = node.name?.type === 'JSXIdentifier' ? node.name.name : '';
272+
const previous = state.inClassPosition;
273+
state.inClassPosition = name === 'class' || name === 'className';
274+
try {
275+
return rewriteChildren(node, (child) => walk(child, state, 'expression'));
276+
} finally {
277+
state.inClassPosition = previous;
278+
}
279+
}
266280
case 'CallExpression':
267-
if (state.tools.isStyleCall(node)) return resolveStyleCall(node, state);
281+
if (state.inClassPosition && state.tools.isStyleCall(node)) {
282+
return resolveStyleCall(node, state);
283+
}
268284
break;
269285
default:
270286
if (isDirective(node)) return processDirective(node, state);

‎packages/octane/tests/compiler/compiler-ast-emit-audit.test.ts‎

Lines changed: 38 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -191,15 +191,15 @@ describe('compiler AST emit architecture', () => {
191191
});
192192
});
193193

194-
// RFC tsrx-org/RFCs#1: `{style(expr)}` is resolved by the scope pre-pass
195-
// (style-scopes.js) into the scope chain plus the value. By the time the
196-
// emitters run — and compile.js's `resolveStyleExpr` fallback with them — no
197-
// `style(...)` call is left on the AST, so the output never carries one.
194+
// RFC tsrx-org/RFCs#1: `{style(expr)}` in class position is resolved by the
195+
// scope pre-pass (style-scopes.js) into the scope chain plus the value. By
196+
// the time the emitters run — and compile.js's `resolveStyleExpr` fallback
197+
// with them — no class-position `style(...)` call is left on the AST.
198198
describe('scoped style pre-pass', () => {
199199
const SOURCE = `export function App(props) @{
200200
<>
201201
<style>.x { color: red; }</style>
202-
<p class={style('x')}>{style('x y')}</p>
202+
<p class={style('x')}>{'x'}</p>
203203
<i class={style(props.cls)}>{'i'}</i>
204204
</>
205205
}`;
@@ -208,15 +208,39 @@ describe('scoped style pre-pass', () => {
208208
['client', {}],
209209
['client prod', { hmr: false as const }],
210210
['server', { mode: 'server' as const }],
211-
])('resolves every {style(...)} call before the emitters run — %s', (_label, options) => {
212-
const { code } = compile(SOURCE, 'style-call.tsrx', options);
213-
expect(code).not.toMatch(/\bstyle\(/);
214-
const hash = code.match(/injectStyle\("(tsrx-[0-9a-f]+)"/)![1];
215-
// Static values fold to a literal that opens with the scope chain…
216-
expect(code).toContain(`${hash} x`);
217-
expect(code).toContain(`${hash} x y`);
218-
// …and a dynamic value concatenates after the chain at runtime.
219-
expect(code).toContain(`"${hash} " + props.cls`);
211+
])(
212+
'resolves every class-position {style(...)} call before the emitters run — %s',
213+
(_label, options) => {
214+
const { code } = compile(SOURCE, 'style-call.tsrx', options);
215+
expect(code).not.toMatch(/\bstyle\(/);
216+
const hash = code.match(/injectStyle\("(tsrx-[0-9a-f]+)"/)![1];
217+
// Static values fold to a literal that opens with the scope chain…
218+
expect(code).toContain(`${hash} x`);
219+
// …and a dynamic value concatenates after the chain at runtime.
220+
expect(code).toContain(`"${hash} " + props.cls`);
221+
},
222+
);
223+
224+
it.each([
225+
['client', {}],
226+
['client prod', { hmr: false as const }],
227+
['server', { mode: 'server' as const }],
228+
])('leaves a style() helper on the style prop alone — %s', (_label, options) => {
229+
const { code } = compile(
230+
`function style(props) {
231+
return { color: props.color };
232+
}
233+
export function App(props) @{
234+
<>
235+
<style>.box { padding: 2px; }</style>
236+
<div class="box" style={style(props)}>{'x'}</div>
237+
</>
238+
}`,
239+
'style-prop-helper.tsrx',
240+
options,
241+
);
242+
expect(code).toMatch(/\bstyle\(props\)/);
243+
expect(code).not.toMatch(/"[^"]*tsrx-[0-9a-f]+[^"]*"\s*\+\s*props/);
220244
});
221245

222246
it('keeps the emitter fallback out of the shipped path (no cssHash-driven rewrite)', () => {

‎packages/octane/tests/style-list-scopes.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,44 @@ export function Twice() @{
215215
}
216216
});
217217

218+
it('keeps selectors that a dynamic-tag sibling can match', () => {
219+
const source = `
220+
export function Host(props: { tag: string }) @{
221+
<>
222+
<style>div { color: rgb(1, 2, 3); }</style>
223+
<{props.tag} id="dyn" />
224+
</>
225+
}
226+
`;
227+
for (const mode of ['client', 'server'] as const) {
228+
const { code } = compile(source, 'dynamic-tag-prune.tsrx', { ...COMPILE_OPTIONS, mode });
229+
const sheets = injections(code);
230+
expect(sheets).toHaveLength(1);
231+
expect(sheets[0].css).toContain(`div.${sheets[0].hash}`);
232+
expect(sheets[0].css).not.toContain('(unused)');
233+
}
234+
235+
const { code } = compile(source, 'dynamic-tag-prune.tsrx', {
236+
...COMPILE_OPTIONS,
237+
mode: 'client',
238+
});
239+
const [sheet] = injections(code);
240+
const client = loadCompiledFixtureSource(source, {
241+
id: 'dynamic-tag-prune.tsrx',
242+
mode: 'client',
243+
compileOptions: COMPILE_OPTIONS,
244+
});
245+
const r = mount(client.Host, { tag: 'div' });
246+
try {
247+
const el = r.find('#dyn') as HTMLElement;
248+
expect(el.tagName).toBe('DIV');
249+
expect(hashesOf(el)).toEqual([sheet.hash]);
250+
expect(getComputedStyle(el).color).toBe('rgb(1, 2, 3)');
251+
} finally {
252+
r.unmount();
253+
}
254+
});
255+
218256
it('apply on a standalone block reaches the same elements as its CSS', () => {
219257
const source = `
220258
const theme = <style>div { color: red; }</style>;

‎packages/octane/tests/style.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1252,6 +1252,30 @@ describe('scoped <style> blocks', () => {
12521252
r.unmount();
12531253
});
12541254

1255+
it('a style() helper used as the style prop keeps the object, not a class string', () => {
1256+
const source = `
1257+
function style(props: { color: string }) {
1258+
return { color: props.color };
1259+
}
1260+
export function Styled(props: { color: string }) @{
1261+
<>
1262+
<style>.box { padding: 2px; }</style>
1263+
<div id="styled-helper" class="box" style={style(props)}>{'x'}</div>
1264+
</>
1265+
}
1266+
`;
1267+
const client = loadCompiledFixtureSource(source, {
1268+
id: 'style-prop-helper.tsrx',
1269+
mode: 'client',
1270+
compileOptions: { hmr: false, dev: false },
1271+
});
1272+
const r = mount(client.Styled, { color: 'rgb(9, 8, 7)' });
1273+
const el = r.find('#styled-helper') as HTMLElement;
1274+
expect(el.style.color).toBe('rgb(9, 8, 7)');
1275+
expect(el.className).toMatch(/^box tsrx-[0-9a-f]+$/);
1276+
r.unmount();
1277+
});
1278+
12551279
it('every directive branch is a scope whose CSS ships even while inactive', () => {
12561280
const r = mount(ControlFlow, { ready: false, maybe: false, items: [], kind: 2 });
12571281
const [R] = hashesOf(r.find('#cf-root'));

0 commit comments

Comments
 (0)