Skip to content

feat: sibling-scoped style blocks, $class, and apply (RFC #1) - #53

Merged
leonidaz merged 30 commits into
mainfrom
feat/scoped-styles-apply
Sep 5, 2026
Merged

leonidaz merged 30 commits into
mainfrom
feat/scoped-styles-apply

Conversation

@leonidaz

@leonidaz leonidaz commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Implements RFC tsrx-org/RFCs#1 — sibling-scoped <style> blocks, $class, and apply — in @tsrx/core, the shared editor tooling, grammars, and docs. Octane's compiler side is octanejs/octane#939, which consumes @tsrx/core from this branch as a git dependency (github:tsrx-org/tsrx#feat/scoped-styles-apply&path:packages/tsrx) until the release ships. Two small changes here exist for that consumer: packages/tsrx/LICENSE (bundlers look for a notice inside the package) and the inlined is_reference helper (the analyzer now bundles scope.js, and is-reference ships no license file).

Language and compiler (@tsrx/core)

  • Parser: self-closing <style … /> (no body, no scope hash); <style> blocks may sit before or after the single output node in @{ … } bodies and @if/@for/@switch/@try bodies. The parser spec table packages/tsrx/tests/utils/fixtures/style-syntax.js (23 cases) is the porting spec for oxc-tsrx (Track oxc port of the scoped <style> parser changes #46).
  • Analyzer (analyze/style-analyze.js, run by analyzeTsrx together with createScopes): classifies assigned blocks as theme (exported, applied, or whose $class is read — the selective opt-in class={theme.$class} on an element or passed to a child through a prop) or class-map, resolves apply targets through real bindings with declared-before-use, and reports STYLE_APPLY_VALUE, STYLE_APPLY_TARGET, STYLE_APPLY_BEFORE_DECLARATION, STYLE_APPLY_DUPLICATE, STYLE_APPLY_UNSUPPORTED_HOST, STYLE_RESERVED_CLASS_KEY, STYLE_STANDALONE_AT_MODULE_SCOPE, STYLE_UNKNOWN_ATTRIBUTE, and CSS_GLOBAL_PLACEMENT (replacing raw throws).
  • Transform (transform/jsx/style-scopes.js pre-pass): scope discovery (originally per statement list; since amendment A1 below a scope is the children list of one element or fragment, a sibling scope), lexical CSS emission order (outer before inner, applied before applier, source order within a scope), and class stamping (authored hashes… applied…). Several blocks per scope share one hash; element-rooted assigned templates keep their CSS (RFC problem 4); every assigned block exposes $class; same-module themes inline as literals, imports read theme.$class at runtime; prepareStylesheetForRender(sheet, 'scope' | 'class-map' | 'theme') with a boolean shim; cssHash deduped per scope.
  • Editor output: scoped blocks stay as void <style> stand-ins; apply becomes data-tsrx-apply={theme.$class} mapped for verification only, so TypeScript checks the target and errors land on the authored identifier.

Tooling and grammars

typescript-plugin fallback CSS extraction, language server (snippets, coded diagnostics, tag matching, auto-close), prettier, eslint parser/plugin, MCP review tool, TextMate and tree-sitter grammars (corpus green), vscode/zed/nvim/intellij/sublime outputs. pnpm sync-zed-grammar-rev runs after the grammar commit lands on main.

Docs

Normative spec sections (grammar, scope model, static constraints, $class opt-in), features page (theme opt-in subsection), llms.txt, README wording ("sibling-scoped"), rulesync rules, MCP docs index, packages/tsrx/README.md API notes.

Tests

Parser spec table, analyzer placement × apply-site matrix (81 tests), shared scope/theme/diagnostic cases on React/Preact/Solid/Vue, a seeded ordering property test, type-level $class tests, $class opt-in cases (shared runner, analyzer, class-opt-in conformance fixture), 14 conformance fixtures under packages/tsrx/tests/fixtures/scoped-styles/ (exposed as @tsrx/core/test-harness/scoped-styles-fixtures for consumer compilers), tooling suites. Full suite, typecheck, format, and changeset checks are green.

Deviations from the RFC text

Declared-before-use is stricter than JS TDZ (same-module CSS emits in lexical order); apply members resolve only when rooted at an import or a module-local object literal holding a block; same-module $class inlines as a literal; static diamonds are deduped, no runtime dedupe.

Amendment A1 (2026-09-03, agreed with a second maintainer; RFC body amended)

  • A standalone block is a child of an element or fragment and styles its siblings. The scope of a standalone <style> is the children list it sits in; it styles the other children of that list and their descendants, never the element that contains it nor any ancestor. To style an element, make the block and the element siblings in a fragment. Blocks in one children list share a hash; nested lists with blocks are nested scopes; elements carry every enclosing list's hash outer first. Pruning runs per list, so a selector that only matches the container is pruned.
  • The single-output rule stands (D3 reverted). A <style> beside the output node of a @{} or control-flow body is the ordinary multiple-outputs parser error again; a lone <style> as the output reports tsrx-style-standalone-needs-fragment.
  • Raw CSS in <style> is TSRX template syntax. A standalone block with a CSS body is only allowed lexically inside a @{} body or a control-flow body; a plain-TSX return <section><style>…</style>…</section>, or a module-level / plain-function assigned template holding one, reports tsrx-style-standalone-outside-template instead of emitting (React/Preact/Solid/Vue used to emit and stamp there) or dropping CSS. <head> styles, href resources, and assigned blocks are unaffected.
  • <style>{expr}</style> is an ordinary element. The parser now produces a plain JSXElement for a <style> whose content starts with an expression container, and every target and the type-only output pass it through untouched (it used to fail with "Expected identifier").
  • Tests: new sibling-scope fixture pinning the Status class table, Rule B/needs-fragment placement matrices, spec-table cases flipped (beside-output forms are error cases with pinned recovery; <style>{css}</style> added), property generator models children-list scopes. Track oxc port of the scoped <style> parser changes #46 has a comment with the parser-facing facts.

Follow-ups

#44 (@try has no @finally), #45 (CSS diagnostics lack positions), #46 (oxc-tsrx port), #47/#48 (loose-mode recovery), #49–#51 (other targets, Ripple, opt-in control-flow rule).

🤖 Generated with Claude Code


Note

High Risk
This changes the language’s CSS scoping model, parser AST, analyzer, and emit path across @tsrx/core and all style-aware tooling—behavioral breaks for existing component-scoped styles are likely without migration.

Overview
Replaces component-scoped <style> with sibling-scoped styling (RFC #1 / amendment A1): a standalone block lives in an element or fragment’s children list and affects siblings and descendants below it, not its parent; multiple blocks in one list share one hash. Assigned blocks become themes with $class and per-class keys; <style apply={theme} /> stamps a scope, with analyzer/transform support and structured STYLE_* / CSS_GLOBAL_PLACEMENT diagnostics (including standalone placement rules and plain <style>{css}</style> as a normal JSX element).

Grammars and editor tooling now recognize bodied and self-closing <style> (including apply={…} with >), with <style> parsed as setup/trailing statements in @{…} and control-flow bodies rather than as the sole output node. Docs and agent rules describe the new model; loose-mode Volar mappings for recovered unclosed tags are fixed so closing names align with the opening tag.

Reviewed by Cursor Bugbot for commit a5cabbd. Bugbot is set up for automated code reviews on this repo. Configure here.

leonidaz and others added 12 commits September 2, 2026 18:23
Implement RFC tsrx-org/RFCs#1 in @tsrx/core:

- parser: self-closing <style … /> (no body, no scope hash) and <style>
  siblings around the single output node in @{ } and directive bodies;
  raw-text elements restore the tokenizer context before reading the token
  after their closing tag, so a <style> in a @case body no longer breaks
  the following } or @case
- analyzer: style-analyze pass (run with createScopes inside analyzeTsrx)
  classifies assigned blocks as theme or class-map, resolves apply targets
  through real bindings with declared-before-use, and reports the new
  STYLE_* and CSS_GLOBAL_PLACEMENT diagnostic codes
- transform: a style-scopes pre-pass owns scope discovery, lexical CSS
  emission order, and class stamping (hashes outer→inner, then applied
  themes); replaces the per-fragment collection and the 'one style tag'
  error; element-rooted assigned templates keep their CSS; assigned blocks
  expose $class; prepareStylesheetForRender gains scope/class-map/theme
  modes; cssHash is deduped per scope
- tests: parser spec table (oxc-tsrx porting spec), analyzer matrix,
  shared scope/theme/diagnostic cases for every JSX target, an ordering
  property test, and type-level $class tests

Co-Authored-By: Claude Fable 5.1 <[email protected]>
- the style pre-pass and analyzer treat the plain IfStatement alternates
  of an @if directive (@else if chains) as branch scopes
- statically resolvable hashes appear once in $class and in stamped
  classes when a theme is applied directly and through another theme (D12)
- conformance fixtures under tests/fixtures/scoped-styles with a
  fixture-driven describe for every JSX target (Octane vendors them)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
- typescript-plugin: attribute-aware <style> fallback regex (self-closing,
  '>' inside apply={…}), real cssMappings in workspace fixtures
- language tooling tests for prettier (idempotent formatting of every
  new form), eslint rules (style siblings are not output nodes), eslint
  parser scope references through apply={…}
- tsrx-mcp review_tsrx_styles recognizes self-closed blocks and themes
- TextMate and tree-sitter grammars: self-closing <style … />, style
  siblings in code-block and directive bodies; regenerated bundle, queries
  copied to zed/nvim; vscode grammar scope tests
- changesets for the vscode and zed extensions

Co-Authored-By: Claude Fable 5.1 <[email protected]>
- completion snippets for <style> and <style apply={…} />
- style diagnostics keep their core codes (tsrx-style-apply-target, …)
- auto-insert matches opening tags with a brace/quote-aware scanner, so
  '>' inside apply={…} and self-closed <style … /> behave, and closes an
  unclosed <style> even while the file only has fallback mappings
- tests: embedded CSS codes per block, snippets, auto-insert, diagnostics
  on the apply target, hover/definition on $class through TypeScript

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The synthesized `theme.$class` read in editor output borrows the target's
span so type errors land on the authored identifier, but it no longer
serves hover or navigation there, and the renamed data-tsrx-apply
attribute is unmapped.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
- specification.tsrx: grammar (self-closing <style>, apply targets, style
  siblings in code-block and directive bodies), scope model, $class and
  theme vs class-map, apply resolution and declared-before-use, normative
  emission order, and one static-constraint entry per STYLE_* code
- features.tsrx, llms.txt, demo snippets: lexical scopes, precedence,
  themes and apply; the playground shows Octane's injected CSS
- README and bundler READMEs say lexically scoped; rulesync rules gain the
  scope/theme authoring assumptions (generated files regenerated)
- tsrx-mcp docs index regenerated with the new spec sections
- core exports buildStyleClassMap for consumer compilers

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…pec table

Consumer compilers run them from @tsrx/core/test-harness/scoped-styles-fixtures
and @tsrx/core/test-harness/style-syntax instead of vendoring copies; the
fixture files ship in the package.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Consecutive <style> siblings in a code-block or directive body printed as
adjacent JSX expression statements in editor output, which TypeScript
rejects (TS2657); each stand-in is now its own void expression.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@vercel

vercel Bot commented Sep 3, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
tsrx-website Ready Ready Preview Sep 5, 2026 5:46pm UTC
tsrx-website-mcp Ready Ready Preview Sep 5, 2026 5:46pm UTC

Request Review

Consumers that bundle the package (Octane's Volar compiler bundle) look for
a license notice inside the package directory, which a git checkout lacked.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…n extra notice

analyzeTsrx now runs createScopes, which pulls scope.js into consumer
bundles (Octane's Volar compiler bundle); [email protected] ships no
license file, so the 40-line helper is inlined with attribution.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Reading `theme.$class` opts one element (or a child component's element,
through a prop) into the block's whole stylesheet, so such a block keeps
every selector like an exported or applied one instead of pruning its
element selectors as a class map.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

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.

Fix All in Cursor

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: Object theme $class reads ignored
    • is_class_read now resolves one-level object members the same way apply does, so themes.dark.$class opts that block in as a theme.

Create PR

Or push these changes by commenting:

@cursor push 47d633d170
Preview (47d633d170)
diff --git a/packages/tsrx/src/analyze/style-analyze.js b/packages/tsrx/src/analyze/style-analyze.js
--- a/packages/tsrx/src/analyze/style-analyze.js
+++ b/packages/tsrx/src/analyze/style-analyze.js
@@ -209,20 +209,41 @@
 }
 
 /**
- * Whether any reference to the binding reads its `$class` property.
+ * Whether `member` is a `$class` property access (`x.$class` or `x['$class']`).
  *
+ * @param {AST.MemberExpression} member
+ * @returns {boolean}
+ */
+function is_class_member(member) {
+	if (member.computed) {
+		return member.property.type === 'Literal' && member.property.value === '$class';
+	}
+	return member.property.type === 'Identifier' && member.property.name === '$class';
+}
+
+/**
+ * Whether any reference to the binding reads `$class` of this style block.
+ * Direct assignment: `theme.$class`. Object member: `themes.dark.$class`.
+ *
  * @param {Binding | null} binding
+ * @param {AST.JSXStyleElement} style
  * @returns {boolean}
  */
-function is_class_read(binding) {
+function is_class_read(binding, style) {
 	if (!binding) return false;
 	return binding.references.some(({ node, path }) => {
 		const parent = path.at(-1);
 		if (parent?.type !== 'MemberExpression' || parent.object !== node) return false;
-		if (parent.computed) {
-			return parent.property.type === 'Literal' && parent.property.value === '$class';
+		if (is_class_member(parent)) {
+			return binding.initial === style;
 		}
-		return parent.property.type === 'Identifier' && parent.property.name === '$class';
+		const grandparent = path.at(-2);
+		return (
+			grandparent?.type === 'MemberExpression' &&
+			grandparent.object === parent &&
+			is_class_member(grandparent) &&
+			resolve_local_member(binding, parent) === style
+		);
 	});
 }
 
@@ -420,12 +441,13 @@
 						parent?.type === 'ExportDefaultDeclaration' ||
 						export_parent?.type === 'ExportNamedDeclaration' ||
 						(declared_name !== null && exported_names.has(declared_name));
-					// Reading `theme.$class` opts an element (or a child component's
-					// element, through a prop) into the block's whole stylesheet, so
-					// such a block is a theme: every selector stays, like `apply`.
+					// Reading `theme.$class` or `themes.dark.$class` opts an element
+					// (or a child component's element, through a prop) into the
+					// block's whole stylesheet, so such a block is a theme: every
+					// selector stays, like `apply`.
 					node.metadata.styleClassRead =
 						declared_name !== null &&
-						is_class_read(nearest_scope(path, scopes)?.get(declared_name) ?? null);
+						is_class_read(nearest_scope(path, scopes)?.get(declared_name) ?? null, node);
 
 					const stylesheet = get_style_element_stylesheet(node);
 					if (stylesheet && get_style_class_map_names(stylesheet).includes('$class')) {

diff --git a/packages/tsrx/tests/analyze/styles.test.js b/packages/tsrx/tests/analyze/styles.test.js
--- a/packages/tsrx/tests/analyze/styles.test.js
+++ b/packages/tsrx/tests/analyze/styles.test.js
@@ -1116,6 +1116,40 @@
 			expect(styles.metadata.styleClassRead).toBe(false);
 			expect(styles.metadata.styleKind).toBe('class-map');
 		});
+
+		it('classifies an object-property block whose $class is read as a theme', () => {
+			for (const source of [
+				`function App() @{
+					const themes = { dark: <style>div {} .card {}</style> };
+					<><div class={themes.dark.$class} /><Child cls={themes.dark['$class']} /></>
+				}`,
+				`function App() @{
+					const themes = { 'dark': <style>div {} .card {}</style> };
+					<div class={themes.dark.$class} />
+				}`,
+			]) {
+				const result = analyze(source);
+				const [dark] = result.styles.assigned;
+
+				expect(dark.metadata.styleClassRead, source).toBe(true);
+				expect(dark.metadata.styleKind, source).toBe('theme');
+			}
+		});
+
+		it('classifies object-property $class reads individually', () => {
+			const result = analyze(
+				`function App() @{
+					const themes = { dark: <style>div {}</style>, light: <style>div {}</style> };
+					<div class={themes.dark.$class} />
+				}`,
+			);
+			const [dark, light] = result.styles.assigned;
+
+			expect(dark.metadata.styleClassRead).toBe(true);
+			expect(dark.metadata.styleKind).toBe('theme');
+			expect(light.metadata.styleClassRead).toBe(false);
+			expect(light.metadata.styleKind).toBe('class-map');
+		});
 	});
 
 	describe('assigned @{} blocks', () => {

diff --git a/packages/tsrx/tests/shared/scoped-styles.js b/packages/tsrx/tests/shared/scoped-styles.js
--- a/packages/tsrx/tests/shared/scoped-styles.js
+++ b/packages/tsrx/tests/shared/scoped-styles.js
@@ -803,6 +803,28 @@
 			expect(code).toContain(`<h2 ${classAttrName}={\`\${parentClass} ${local}\`}>`);
 		});
 
+		it('rfc1-class-opt-in: reading themes.dark.$class keeps every selector', () => {
+			const { code, css, cssHash } = compile(
+				`export function App() @{
+					const themes = { dark: <style>
+						div { color: blue; }
+						.card { color: red; }
+					</style> };
+					<>
+						<div ${classAttrName}={themes.dark.$class}>{'opted in'}</div>
+						<div ${classAttrName}={themes.dark.card}>{'card'}</div>
+					</>
+				}`,
+				'App.tsrx',
+			);
+
+			const theme = hashes_of(cssHash)[0];
+			expect(css).not.toContain('(unused)');
+			expect(css).toContain(`div.${theme} { color: blue; }`);
+			expect(code).toContain(`${classAttrName}={themes.dark.$class}`);
+			expect(code).toContain(`${classAttrName}={themes.dark.card}`);
+		});
+
 		it('keeps class-map pruning when only class entries of a local block are read', () => {
 			const { css } = compile(
 				`export function App() @{

You can send follow-ups to the cloud agent here.

Want reviews to match your repository better? Bugbot Learning can learn team-specific rules from PR activity. A team admin can enable Learning in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit c9ef3d8. Configure here.

leonidaz and others added 4 commits September 2, 2026 23:05
Spec 4.6.3 (theme = exported, applied, or `$class` read; `styleClassRead`
metadata), a features-page subsection with a Card/App example, llms.txt
bullets and a cheat-sheet row, a demo snippet, the rulesync clause, and
the regenerated MCP docs index.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
Each style section now makes one point, its title states that point,
and it opens with the rule, then an example, then what to do. "Hash
class" is defined once up front on every surface (the class the compiler
adds to an element so the block's selectors match only there) and used
afterwards. Jargon is replaced with plain words: branch for arm, "adds
the hash class" for stamp, "the block that applies it" for applier, "a
block with CSS in it" for bodied, and "output", "removed as unused",
"moved to the top of the module", and "source order, outer first" for
emit, prune, hoist, and pre-order.

Covers features.tsrx (new subsections and a before/after fragment
example), llms.txt, README.md, packages/tsrx/README.md, specification
4.6 prose and the 5.1 closing paragraph, and the MCP docs index with its
test. No fact, example output, code, grammar, or diagnostic changes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Expand the features page's ":global()" section into a full treatment: the
four forms with their compiled output, the specificity rule (hash on the
first compound only, :where on the rest), and a decision table for choosing
between :global and passing theme.$class to a child. Add a compact version
with the same table to llms.txt and the MCP docs index, one rule line to the
agent rules, and one normative sentence to specification 4.6.

Pin the :global output shapes for every target in the shared scoped-styles
tests.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Add the block form, :global { ... }, beside the selector form in the
features page, llms.txt, the MCP docs index, the agent rules, and the one
normative sentence in specification 4.6. Show a :global block nested under
a scoped selector as the way to style several classes of a child you cannot
change, and contrast it with plain nesting, which scopes both parts.

Pin the block, nested, and plain-nesting output shapes for every target in
the shared global-forms test.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The $class opt-in example declared a .local rule the article never used. The article now carries local alongside the passed theme class, written as a template literal because array class values are a target-specific feature; the shared test, the class-opt-in conformance fixture, and the generated MCP docs index follow.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Loose-mode recovery synthesized a closing element with the whole
element's location, so the generated </span> name mapped to <spa and
the opening < lost its mapping. Leave the synthesized close unlocated
and clone the name from the opening tag token.

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Jon Wheeler <[email protected]>
@cursor

cursor Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

This PR is too large for Bugbot to review. It changes 97,100 lines and 4,060,175 characters. Split the change into smaller pull requests to get a review.

This branch was successfully deployed

2 active deployments
Preview – tsrx-website — c6fd2934 Deployed Sep 5, 2026 by vercel[bot]
Preview – tsrx-website-mcp — c6fd2934 Deployed Sep 5, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants