Repository navigation
fix: write style-block class maps to ref targets - #960
Merged
Merged
Conversation
Honor ref on scoped <style> blocks by emitting the prepared class map through assignment, callback, and current/value refs instead of silently dropping the attribute when the block is stripped. Closes #940. Co-authored-by: Jon Wheeler <[email protected]>
Keep assignment lowering for `ref={classes as T}` so a typed binding still
receives the class map instead of taking the dynamic path and staying unset.
Co-authored-by: Jon Wheeler <[email protected]>
jonkwheeler
marked this pull request as ready for review
September 4, 2026 19:14
Graft a cloned class-map write before every owned return so if/else and
braceless arms, plus early returns in @{ } scopes, receive the map
instead of leaving let classes unset.
Co-authored-by: Jon Wheeler <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Autofix Details
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: Shared-scope const collisions at returns
- graftReturnsInList now wraps each return in a block so cloned const __styleMap bindings no longer collide in unbraced switch cases or @{ } statement lists.
Or push these changes by commenting:
@cursor push 81ae2bef0c
Preview (81ae2bef0c)
diff --git a/packages/octane/src/compiler/style-scopes.js b/packages/octane/src/compiler/style-scopes.js
--- a/packages/octane/src/compiler/style-scopes.js
+++ b/packages/octane/src/compiler/style-scopes.js
@@ -228,8 +228,9 @@
/**
* Insert a cloned setup copy immediately before every owned `return`
* (if/else/switch/try/loops). Nested function bodies are left alone — those
- * are compiled as their own components. Braceless `return` arms become a
- * block so the write and the return stay a single consequent.
+ * are compiled as their own components. Each return is wrapped in a block so
+ * the cloned `const` bindings stay in their own lexical scope — switch cases
+ * and statement lists share the enclosing scope, so sibling `const`s collide.
*
* @param {any} stmt
* @param {any[]} statements
@@ -326,15 +327,7 @@
const next = [];
let foundReturn = false;
for (let i = 0; i < list.length; i++) {
- const stmt = list[i];
- if (stmt && stmt.type === 'ReturnStatement') {
- const cloned = cloneSetupStatements(statements);
- for (let j = 0; j < cloned.length; j++) next.push(cloned[j]);
- next.push(stmt);
- foundReturn = true;
- continue;
- }
- const grafted = graftReturnsInStatement(stmt, statements);
+ const grafted = graftReturnsInStatement(list[i], statements);
next.push(grafted.node);
if (grafted.foundReturn) foundReturn = true;
}
diff --git a/packages/octane/tests/_fixtures/style-ref.tsrx b/packages/octane/tests/_fixtures/style-ref.tsrx
--- a/packages/octane/tests/_fixtures/style-ref.tsrx
+++ b/packages/octane/tests/_fixtures/style-ref.tsrx
@@ -167,3 +167,55 @@
</style>
</>
}
+
+export function SwitchReturnStyleRef(props: { kind: 'alt' | 'main' }) {
+ let classes: StyleClassMap | undefined;
+ switch (props.kind) {
+ case 'alt':
+ return <>
+ <div id="switch-alt" class="card">
+ {classes && classes.card ? classes.card as string : 'missing'}
+ </div>
+ <style ref={classes as never}>
+ .card {
+ color: rgb(71, 72, 73);
+ }
+ </style>
+ </>;
+ default:
+ return <>
+ <div id="switch-main" class="card">
+ {classes && classes.card ? classes.card as string : 'missing'}
+ </div>
+ <style ref={classes as never}>
+ .card {
+ color: rgb(71, 72, 73);
+ }
+ </style>
+ </>;
+ }
+}
+
+export function SwitchScopeStyleRef(props: { kind: 'alt' | 'main' | 'fallback' }) @{
+ let classes: StyleClassMap | undefined;
+ switch (props.kind) {
+ case 'alt':
+ return <div id="switch-scope-alt" class="card">
+ {classes && classes.card ? classes.card as string : 'missing'}
+ </div>;
+ case 'main':
+ return <div id="switch-scope-main" class="card">
+ {classes && classes.card ? classes.card as string : 'missing'}
+ </div>;
+ }
+ <>
+ <div id="switch-scope-fallback" class="card">
+ {classes && classes.card ? classes.card as string : 'missing'}
+ </div>
+ <style ref={classes as never}>
+ .card {
+ color: rgb(81, 82, 83);
+ }
+ </style>
+ </>
+}
diff --git a/packages/octane/tests/style-ref.test.ts b/packages/octane/tests/style-ref.test.ts
--- a/packages/octane/tests/style-ref.test.ts
+++ b/packages/octane/tests/style-ref.test.ts
@@ -11,6 +11,8 @@
IdentifierCallbackStyleRef,
NestedReturnStyleRef,
ReturnedStyleRef,
+ SwitchReturnStyleRef,
+ SwitchScopeStyleRef,
ValueStyleRef,
} from './_fixtures/style-ref.tsrx';
@@ -126,6 +128,33 @@
main.unmount();
});
+ it('assigns the class map before unbraced switch returns', function () {
+ const alt = mount(SwitchReturnStyleRef as any, { kind: 'alt' });
+ expectClassMap(alt.find('#switch-alt') as HTMLElement, 'rgb(71, 72, 73)');
+ alt.unmount();
+ const main = mount(SwitchReturnStyleRef as any, { kind: 'main' });
+ expectClassMap(main.find('#switch-main') as HTMLElement, 'rgb(71, 72, 73)');
+ main.unmount();
+ });
+
+ it('assigns the class map before switch returns in a statement-list scope', function () {
+ const alt = mount(SwitchScopeStyleRef as any, { kind: 'alt' });
+ const early = alt.find('#switch-scope-alt') as HTMLElement;
+ const text = early.textContent || '';
+ expect(text).not.toBe('missing');
+ expect(text).toMatch(/tsrx-[a-z0-9]+ card/i);
+ expect(early.classList.contains('card')).toBe(true);
+ alt.unmount();
+ const main = mount(SwitchScopeStyleRef as any, { kind: 'main' });
+ expect((main.find('#switch-scope-main') as HTMLElement).textContent).toMatch(
+ /tsrx-[a-z0-9]+ card/i,
+ );
+ main.unmount();
+ const fallback = mount(SwitchScopeStyleRef as any, { kind: 'fallback' });
+ expectClassMap(fallback.find('#switch-scope-fallback') as HTMLElement, 'rgb(81, 82, 83)');
+ fallback.unmount();
+ });
+
it('assigns the class map during SSR of a nested if/else return', function () {
const alt = ServerRT.renderToString(server.NestedReturnStyleRef, { alt: true });
expect(alt.html).toContain('id="nested-alt"');You can send follow-ups to the cloud agent here.
Functions whose only JSX exits sit inside if/else were compiled as generic values, so scoped style never ran. Walk owned nested returns when classifying, and write each identifier style-ref once. Co-authored-by: Jon Wheeler <[email protected]>
Wrap each grafted class-map write (and the @{ } fall-through append)
in its own block so const __styleMap is not redeclared across unbraced
switch cases or a return plus fall-through in the same list.
Co-authored-by: Jon Wheeler <[email protected]>
Use a single style block and an any-typed ref so tsrx-tsc does not treat the class-map write as never across unbraced switch cases. Co-authored-by: Jon Wheeler <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
There are 2 total unresolved issues (including 1 from previous review).
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: Block wrap hides return-JSX lowering
- List-position returns now keep their ReturnStatement so compileReturnJsxFunction and ssrCompileBody can still extract them; blocks wrap only unbraced arms, switch cases, and @{ } fall-through.
Or push these changes by commenting:
@cursor push 2b93a587c4
Preview (2b93a587c4)
diff --git a/packages/octane/src/compiler/style-scopes.js b/packages/octane/src/compiler/style-scopes.js
--- a/packages/octane/src/compiler/style-scopes.js
+++ b/packages/octane/src/compiler/style-scopes.js
@@ -226,9 +226,11 @@
}
/**
- * Each graft owns a block so `const __styleMap` is not redeclared in a
- * shared scope (unbraced `switch` cases, or a `@{ }` return plus the
- * fall-through append).
+ * Wrap setup in a block so `const __styleMap` is block-scoped. Needed when
+ * the graft is a single statement (unbraced if/for/while) or shares a scope
+ * with another copy (unbraced `switch` cases, `@{ }` fall-through append).
+ * List-position function-body returns stay unwrapped so later return-JSX
+ * lowering still sees them.
*
* @param {any[]} statements
* @param {any[]} [extra]
@@ -245,8 +247,8 @@
/**
* Insert a cloned setup copy immediately before every owned `return`
* (if/else/switch/try/loops). Nested function bodies are left alone — those
- * are compiled as their own components. Each write is a block so the
- * `const __styleMap` binding stays local to that site.
+ * are compiled as their own components. Braceless `return` arms become a
+ * block so the write and the return stay a single consequent.
*
* @param {any} stmt
* @param {any[]} statements
@@ -289,7 +291,9 @@
const switchCase = authored[i];
const grafted = graftReturnsInList(switchCase.consequent || [], statements);
if (grafted.foundReturn) foundReturn = true;
- cases.push(grafted.foundReturn ? { ...switchCase, consequent: grafted.list } : switchCase);
+ cases.push(
+ grafted.foundReturn ? { ...switchCase, consequent: [b.block(grafted.list)] } : switchCase,
+ );
}
return {
node: foundReturn ? { ...stmt, cases } : stmt,
@@ -335,6 +339,10 @@
}
/**
+ * Insert a cloned setup copy immediately before every list-position
+ * `return`, leaving the `ReturnStatement` in place so
+ * `compileReturnJsxFunction` and `ssrCompileBody` still see it.
+ *
* @param {any[]} list
* @param {any[]} statements
* @returns {{ list: any[], foundReturn: boolean }}
@@ -345,7 +353,9 @@
for (let i = 0; i < list.length; i++) {
const stmt = list[i];
if (stmt && stmt.type === 'ReturnStatement') {
- next.push(wrapSetupBlock(statements, [stmt]));
+ const cloned = cloneSetupStatements(statements);
+ for (let j = 0; j < cloned.length; j++) next.push(cloned[j]);
+ next.push(stmt);
foundReturn = true;
continue;
}
diff --git a/packages/octane/tests/_fixtures/style-ref.tsrx b/packages/octane/tests/_fixtures/style-ref.tsrx
--- a/packages/octane/tests/_fixtures/style-ref.tsrx
+++ b/packages/octane/tests/_fixtures/style-ref.tsrx
@@ -98,6 +98,18 @@
</>;
}
+export function ReturnedHostStyleRef() {
+ let classes: StyleClassMap | undefined;
+ return <div id="returned-host" class="card">
+ {classes && classes.card ? classes.card as string : 'missing'}
+ <style ref={classes as never}>
+ .card {
+ color: rgb(91, 92, 93);
+ }
+ </style>
+ </div>;
+}
+
export function NestedReturnStyleRef(props: { alt: boolean }) {
let classes: StyleClassMap | undefined;
if (props.alt) {
diff --git a/packages/octane/tests/style-ref.test.ts b/packages/octane/tests/style-ref.test.ts
--- a/packages/octane/tests/style-ref.test.ts
+++ b/packages/octane/tests/style-ref.test.ts
@@ -1,4 +1,6 @@
+import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
+import { compile } from 'octane/compiler';
import * as ServerRT from 'octane/server';
import { mount } from './_helpers';
import { loadServerFixture } from './_server-fixture';
@@ -10,6 +12,7 @@
EarlyReturnScopeStyleRef,
IdentifierCallbackStyleRef,
NestedReturnStyleRef,
+ ReturnedHostStyleRef,
ReturnedStyleRef,
SwitchReturnStyleRef,
SwitchScopeStyleRef,
@@ -95,6 +98,31 @@
expect(css).toMatch(/\.card\.tsrx-[a-z0-9]+/i);
});
+ it('assigns the class map in a returned host element', function () {
+ const r = mount(ReturnedHostStyleRef as any);
+ expectClassMap(r.find('#returned-host') as HTMLElement, 'rgb(91, 92, 93)');
+ r.unmount();
+ });
+
+ it('assigns the class map during SSR of a returned host element', function () {
+ const { html, css } = ServerRT.renderToString(server.ReturnedHostStyleRef);
+ expect(html).toContain('id="returned-host"');
+ expect(html).not.toContain('missing');
+ expect(html).toMatch(/tsrx-[a-z0-9]+ card/i);
+ expect(css).toMatch(/\.card\.tsrx-[a-z0-9]+/i);
+ });
+
+ it('compiles a returned host with a style ref as a static fragment', function () {
+ const source = readFileSync(FIXTURE, 'utf8');
+ const client = compile(source, FIXTURE, { hmr: false, dev: false });
+ const server = compile(source, FIXTURE, { mode: 'server', hmr: false, dev: false });
+ // lowerReturnJsx / ssrCompileBody only see top-level ReturnStatements.
+ // Wrapping that return in a block deopts to value lowering, so the host
+ // never becomes a compiled template string (printed with escaped quotes).
+ expect(client.code).toMatch(/<div id=\\?"returned-host\\?"/);
+ expect(server.code).toMatch(/<div id=\\?"returned-host\\?"/);
+ });
+
it('assigns the class map before nested if/else returns', function () {
const alt = mount(NestedReturnStyleRef as any, { alt: true });
expectClassMap(alt.find('#nested-alt') as HTMLElement, 'rgb(41, 42, 43)');You can send follow-ups to the cloud agent here.
Reviewed by Cursor Bugbot for commit 7ca982f. Configure here.
Leave each ReturnStatement as a sibling of the scoped class-map block so compileReturnJsxFunction and SSR still see a top-level return. The const stays inside the block to avoid switch collisions. Co-authored-by: Jon Wheeler <[email protected]>
Sibling const __styleMap in shared switch scope is a SyntaxError. Compile the fixture and Function-parse SwitchReturnStyleRef so that regression fails by name without importing the broken module. Co-authored-by: Jon Wheeler <[email protected]>
leonidaz
added a commit
that referenced
this pull request
Sep 5, 2026
Resolve against main's #957, #960, and #961, which landed on the statement-scoped style machinery this branch replaces: - runtime.ts: keep the branch's `injectStyle` (main's in-place refresh is already here; the React Float match stays a `data-href` token match for batched multi-hash islands). - style-hmr-reinject.test.ts: take main's superset (adds the document-less case). - compile.js / style-scopes.js: keep the sibling-scope pre-pass; drop main's `componentStyleRoots`/`annotateRootWithHash`/`applyCssScoping` and the `applyStyleRefs` import. Main's synthesized-class merge flag (#961) applies unchanged to the pre-pass's stamped attributes. - `<style ref>` (#960) is not carried over: the attribute stays unsupported in Octane pending its removal from TSRX, so its fixture, tests, and changeset are dropped and the immutability fixture no longer uses it. Co-Authored-By: Claude Fable 5.1 <[email protected]>
1 task done
14 of 21 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


Summary
Closes #940 by implementing
<style ref={x}>instead of reporting it as unsupported.@tsrx/coreJSX targets already hand a scoped<style>block's class-map object ({ card: "tsrx-… card", … }) toref={x}throughcreateStyleRefSetupStatements. Octane's analyzer acceptedrefon the block, then the scope pass stripped the element and never wrote the target —let classesstayedundefinedwith no diagnostic.This lands the class-map write in
packages/octane/src/compiler/style-scopes.js, whichapplyCssScopingcalls after the sheets and hash are already built. Statement-list@{ … }scopes append the setup after authored declarations (avoids TDZ onlet classes) and also write before earlyreturns in that setup list. Returned templates insert a cloned copy before every ownedreturn, including nestedif/else/switcharms — not only the first top-level one. Each write (and the@{ }fall-through append) is its own block soconst __styleMapis not redeclared across unbracedswitchcases or a return plus fall-through in the same list. Thereturnstays a sibling of that block socompileReturnJsxFunctionand SSR still see a top-levelReturnStatement. Identifier refs cover assignment, callback, andcurrent/valueobjects; other shapes reusecreateStyleRefSetupStatements. Type assertions around the ref expression (ref={classes as T}) unwrap so assignment still hits the binding.Functions whose only JSX exits sit inside
if/elsewere previously compiled as generic values, so scoped<style>never ran.isReturnJsxFunctionnow walks owned nested returns so those functions take the return-JSX path (hash stamp,injectStyle, and the class-map write).Not mixed with #941 spread-class work.
Why
Silent drop of a public
@tsrx/coreattribute is a compiler defect. The class map is already available at the scope pass, so emitting the write is cheaper and more useful than a diagnostic-only deferral. Grafting only the first top-levelreturnreintroduced the same silent drop on nestedif/elsepaths. A function that only returns JSX fromif/elsearms also never entered the return-JSX compile path, so scoping itself was skipped.Changes
style-scopes.jsbuilds the class map from prepared sheets (createStyleClassMap/createStyleClassMapFromStylesheet) and grafts a cloned setup copy before every ownedreturn.@{ }fall-through append) wraps only the class-map write in a block; thereturnstays a sibling so return-JSX / SSR lowering still see it.isReturnJsxFunctiontreats owned nested JSX returns as return-JSX functions soapplyCssScopingruns for if/else-only exits.ref={classes}.current,value, returned-template, nested if/else, braceless if-return, unbraced switch,@{ }early-return, and switch-plus-fall-through forms on client and SSR.SwitchReturnStyleRef: siblingconst __styleMapin a shared switch scope is aSyntaxError;new Functionfails without the block wrap.ref={classes}so the new path stays copy-on-write.Validation
pnpm format:files:checkon the changed compiler/test/changeset files (not repo-widepnpm format:check)pnpm typecheck:fileson the changed paths (not repo-widepnpm typecheck)pnpm test(full suite not run locally)7d79847c1:packages/octane/tests/style-ref.test.ts(octane + octane-prod, 30/30), including unbraced switch,@{ }switch-plus-fall-through, and a compile-shape check thatReturnedStyleRefstill has a top-levelreturnafter the class-map blockdb8a7ab2a:style-ref-compile.test.ts+style-ref.test.ts(octane + octane-prod, 32/32). Without the block wrap the compile-parse test fails withSyntaxError: Identifier '__styleMap$10' has already been declared.Risk / follow-ups
ref={x}uses a hybrid of the core helper's assignment and dynamic paths solet x,function x, and{ current }/{ value }objects all work. Nested@{ }scopes that declare their ownletfor a parent-collected style block are not separately grafted.<style>ref (HTMLStyleElement). Scoped blocks never become that host; the fixture asserts the class-map target. WideningStyleHTMLAttributes.refis a follow-up.style-scopes.json feat(compiler): sibling-scoped style blocks, $class, and apply (tsrx RFC #1) #939 will need to keep this write when that branch lands; this PR only targetsmain's component-scoped model.isReturnJsxFunctionsends if/else-only JSX functions throughcompileReturnJsxFunction(hooks slotted, styles scoped). That matches a top-levelreturn <jsx>.Provenance
agent-authored)Need help on this PR? Tag
@codesmith-botwith what you need. Autofix is disabled.