Skip to content

fix: write style-block class maps to ref targets - #960

Merged
trueadm merged 8 commits into
mainfrom
cursor/style-ref-940-7409
Sep 5, 2026
Merged

trueadm merged 8 commits into
mainfrom
cursor/style-ref-940-7409

Conversation

@jonkwheeler

@jonkwheeler jonkwheeler commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #940 by implementing <style ref={x}> instead of reporting it as unsupported.

@tsrx/core JSX targets already hand a scoped <style> block's class-map object ({ card: "tsrx-… card", … }) to ref={x} through createStyleRefSetupStatements. Octane's analyzer accepted ref on the block, then the scope pass stripped the element and never wrote the target — let classes stayed undefined with no diagnostic.

This lands the class-map write in packages/octane/src/compiler/style-scopes.js, which applyCssScoping calls after the sheets and hash are already built. Statement-list @{ … } scopes append the setup after authored declarations (avoids TDZ on let classes) and also write before early returns in that setup list. Returned templates insert a cloned copy before every owned return, including nested if/else/switch arms — not only the first top-level one. Each write (and the @{ } fall-through append) is its own block so const __styleMap is not redeclared across unbraced switch cases or a return plus fall-through in the same list. The return stays a sibling of that block so compileReturnJsxFunction and SSR still see a top-level ReturnStatement. Identifier refs cover assignment, callback, and current/value objects; other shapes reuse createStyleRefSetupStatements. 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/else were previously compiled as generic values, so scoped <style> never ran. isReturnJsxFunction now 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/core attribute 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-level return reintroduced the same silent drop on nested if/else paths. A function that only returns JSX from if/else arms also never entered the return-JSX compile path, so scoping itself was skipped.

Changes

  • New style-scopes.js builds the class map from prepared sheets (createStyleClassMap / createStyleClassMapFromStylesheet) and grafts a cloned setup copy before every owned return.
  • Each graft (and the @{ } fall-through append) wraps only the class-map write in a block; the return stays a sibling so return-JSX / SSR lowering still see it.
  • isReturnJsxFunction treats owned nested JSX returns as return-JSX functions so applyCssScoping runs for if/else-only exits.
  • Identifier style-refs are written once per binding when several blocks share ref={classes}.
  • Fixture + tests for assignment, function-expression callback, identifier callback, current, value, returned-template, nested if/else, braceless if-return, unbraced switch, @{ } early-return, and switch-plus-fall-through forms on client and SSR.
  • Compile-parse test for SwitchReturnStyleRef: sibling const __styleMap in a shared switch scope is a SyntaxError; new Function fails without the block wrap.
  • Frozen-AST fixture now includes ref={classes} so the new path stays copy-on-write.

Validation

  • pnpm format:files:check on the changed compiler/test/changeset files (not repo-wide pnpm format:check)
  • pnpm typecheck:files on the changed paths (not repo-wide pnpm typecheck)
  • pnpm test (full suite not run locally)
  • targeted tests on 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 that ReturnedStyleRef still has a top-level return after the class-map block
  • targeted tests on db8a7ab2a: style-ref-compile.test.ts + style-ref.test.ts (octane + octane-prod, 32/32). Without the block wrap the compile-parse test fails with SyntaxError: Identifier '__styleMap$10' has already been declared.

Risk / follow-ups

  • Identifier ref={x} uses a hybrid of the core helper's assignment and dynamic paths so let x, function x, and { current } / { value } objects all work. Nested @{ } scopes that declare their own let for a parent-collected style block are not separately grafted.
  • JSX types still describe a host <style> ref (HTMLStyleElement). Scoped blocks never become that host; the fixture asserts the class-map target. Widening StyleHTMLAttributes.ref is a follow-up.
  • Sibling-scope style-scopes.js on 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 targets main's component-scoped model.
  • Widening isReturnJsxFunction sends if/else-only JSX functions through compileReturnJsxFunction (hooks slotted, styles scoped). That matches a top-level return <jsx>.
  • No Styled host without an authored class loses the class from a spread #941 spread-class changes.

Provenance

  • An agent produced this diff (agent-authored)
Open in Web Open in Cursor 

View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

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]>
@github-actions github-actions Bot added agent-authored Diff or issue body substantially produced by an AI agent fix PR: bug fix labels Sep 4, 2026
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
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]>

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Create PR

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]>
cursoragent and others added 2 commits September 4, 2026 19:39
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]>

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Fix All in Cursor

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.

Create PR

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.

cursoragent and others added 2 commits September 4, 2026 19:51
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]>
@trueadm
trueadm merged commit e841a49 into main Sep 5, 2026
31 checks passed
@trueadm
trueadm deleted the cursor/style-ref-940-7409 branch September 5, 2026 17:30
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agent-authored Diff or issue body substantially produced by an AI agent fix PR: bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Compiler silently drops <style ref={…}> (class-map ref supported by the tsrx JSX targets)

3 participants