Repository navigation
feat(compiler): sibling-scoped style blocks, $class, and apply (tsrx RFC #1) - #939
Conversation
Implement RFC tsrx-org/RFCs#1 on the Octane compiler with one copy-on-write pre-pass per top-level statement (src/compiler/style-scopes.js): - scopes: component render, nested @{ }, every control-flow branch body (including @else if chains), assigned element/fragment templates; several blocks per scope share the first block's hash and ONE injectStyle call; nested scopes get their own; injections are pushed in lexical pre-order with an order key that sorts among module-level entries on the server - stamping: every host element carries its enclosing scope hashes outer→ inner, then applied theme classes (same-module themes inline as literals so static templates stay hoisted; imports read theme.$class at runtime through the dynamic class path); {style(expr)} resolves to the chain in the pre-pass, so resolveStyleExpr no longer sees style calls - assigned blocks lower anywhere a declaration is legal (component bodies, nested blocks, plain functions, object properties), expose $class, and render in theme or class-map mode from the core analyzer's classification - Float <style href precedence> resources stay outside the model - applyStyleMap/applyCssScoping/componentStyleRoots/annotateRootWithHash/ addHashClassToElement/wrapScopedClassExprs are removed - OCTANE_HYDRATE_SPLIT_STYLE names the style scope, not the component - scripts/sync-style-conformance-fixtures.mjs vendors the tsrx conformance fixtures and parser spec table (pnpm sync:style-fixtures[:check]) Co-Authored-By: Claude Fable 5.1 <[email protected]>
… of vendoring Co-Authored-By: Claude Fable 5.1 <[email protected]>
…e CSS on the server
- inheritOriginLoc no longer descends into StyleSheet subtrees: their
positions are CSS-relative, and stamping module positions onto them
rendered a control-flow scope's CSS as '.hash b {}' on the client
- server: assigned blocks lower to styleMap(hash, css, map, applied), a
proxy that injects the sheet (after the sheets of the themes it applies)
into the active request on property access, and every component touches
the imported themes its scopes apply (touchStyleMap) before its own
injectStyle calls, so a theme from another module reaches the css
collector ahead of the applying scope's rules
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…rules, evals, and scaffold - docs/tsrx-basics.md Styles section; stale single-scope claims fixed in deferred-hydration, ssr, differences-from-react (with the STYLE_* codes), getting-started, css-module-constants, universal-renderer-architecture, product-example-regressions, octane-cleanup-plan - website: new Learn Octane › Styling page (docs-meta, docs, sitemap, llms index, pagination pin), styles mentioned on tsrx-vs-tsx and quick-start, build-tools notes per bundler, llms.txt authoring bullets, regenerated TextMate grammar, scoped-styles playground example - rulesync: tsrx-authoring Styles section, skill enumeration, one-line project pointer within the context budget; MCP skills; CONTRIBUTING and README mentions - evals: scoped-styles coverage axis with tsrx.nested-scope-styles and octane.theme-apply tasks, corpus regenerated (21 tasks) - scaffold: the link styles are an applied theme; harbor PriceBadge dark variant via apply; examples catalog regenerated - tests: conformance runner over @tsrx/core's fixtures (client + server + evaluation) and the parser spec-table fallback replay Co-Authored-By: Claude Fable 5.1 <[email protected]>
…browser coverage
- fixtures: style-scopes, style-theme(+consumer), style-element-rooted,
style-local-assigned, style-order-theme/applier, returned nested scopes
- suites: RFC class table and head order, multi-block/nested/control-flow/
sibling scopes, {style()} chains, $class pins, SSR cascade with in-body
themes, streaming per-hash dedupe and theme waves, Float sibling and
apply-is-not-a-resource, clsx spread + hashes + theme.$class parity,
frozen-AST run over every fixture, per-scope inspect origins, emit audit,
deferred-hydration split message, universal renderer rejection, React-
hosted multi-hash islands, injectStyle DOM order, HMR hazard pin
(it.fails, #938), Playwright cascade (client, SSR+hydrate)
- runtime: the client dedupe matches React's batched data-href by token,
so hydrating a multi-hash island no longer re-injects its sheets
- typetest: theme.$class is string under tsrx-tsc
- docs: server-side lazy theme injection described in tsrx-basics and the
Styling page; Scoped CSS notes in the bundler plugin READMEs
Co-Authored-By: Claude Fable 5.1 <[email protected]>
A minor bump cascades into major bumps for every dependent's peer range; the release plan checker rejects it without a coordinated peer expansion. Co-Authored-By: Claude Fable 5.1 <[email protected]>
# Conflicts: # packages/octane-evals/datasets/train/user-apps-v1/manifest.jsonl
Co-Authored-By: Claude Fable 5.1 <[email protected]>
packages/octane, @octanejs/evals, and website depend on github:tsrx-org/tsrx#feat/scoped-styles-apply&path:packages/tsrx (a git dependency is not allowed as a subdependency, so the spec lives on the direct dependents); overrides pin the branch manifest's workspace/catalog dependencies to the published runtime and the tsrx catalog ranges. Also: the client injectStyle refreshes a sheet it already owns when an HMR re-evaluation arrives with an unchanged hash and changed CSS (#938). Co-Authored-By: Claude Fable 5.1 <[email protected]>
…e hashes The published @tsrx/prettier-plugin cannot parse the fixtures that place a <style> beside a code block's output node until its release ships the new parser; the react-parity audit files hash the lockfile, which the branch dependency changed. Co-Authored-By: Claude Fable 5.1 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
Autofix Details
Bugbot Autofix prepared fixes for both issues found in the latest run.
- ✅ Fixed: Theme touches stolen by nested helpers
- ssrCompileBody now claims _serverThemeTouches before nested helpers compile, so imported theme CSS is injected before the applying scope's injectStyle.
- ✅ Fixed: Spread classes dropped on styled hosts
- addScopeClasses composes the winning spread class with scope hashes instead of appending a later class that replaced props.class.
Or push these changes by commenting:
@cursor push 5fdeeb11f3
Preview (5fdeeb11f3)
diff --git a/packages/octane/scripts/verify-dist.mjs b/packages/octane/scripts/verify-dist.mjs
--- a/packages/octane/scripts/verify-dist.mjs
+++ b/packages/octane/scripts/verify-dist.mjs
@@ -63,6 +63,7 @@
'child',
'childSlot',
'childTextHole',
+ 'classFromSpreads',
'clone',
'cloneElement',
'compilerCacheContext',
@@ -231,6 +232,7 @@
'__useReducerWithGetter',
'__useStateWithGetter',
'addTransitionType',
+ 'classFromSpreads',
'cloneElement',
'createContext',
'createElement',
diff --git a/packages/octane/src/compiler/compile.js b/packages/octane/src/compiler/compile.js
--- a/packages/octane/src/compiler/compile.js
+++ b/packages/octane/src/compiler/compile.js
@@ -10486,6 +10486,13 @@
returnedFragmentTemplate,
returnedFragmentRoot,
) {
+ // Nested helpers (@if/@for/@switch/@try, nested `@{ … }`) compile through
+ // this same function during the emit below. Claim imported-theme touches
+ // for THIS body first so a nested helper cannot drain the slot — the
+ // applying component must inject them before its own injectStyle, or the
+ // theme sheet lands after the local scope and wins at equal specificity.
+ const themeTouches = ctx._serverThemeTouches;
+ ctx._serverThemeTouches = null;
const returnedOutput = node.body?.type === 'JSXCodeBlock' && hasOwnValueReturn(node);
const mapTemps = ctx.currentMapTemps;
@@ -10638,8 +10645,7 @@
ctx._valueDirectiveLowering = prevValueDirectiveLowering;
const body = [];
- body.push(...serverThemeTouchStatements(ctx._serverThemeTouches ?? [], ctx, node));
- ctx._serverThemeTouches = null;
+ body.push(...serverThemeTouchStatements(themeTouches ?? [], ctx, node));
if (cssEntries && cssEntries.length) {
ctx.runtimeNeeded.add('injectStyle');
for (const entry of cssEntries) {
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
@@ -839,9 +839,33 @@
const chain = [...hashes, ...applied];
let newAttrs;
if (index === -1) {
+ // A later explicit class replaces a spread's class (later-writer). When
+ // the host takes its class only from spreads, compose those values with
+ // the chain so `{...props}` keeps `props.class` ahead of the hashes.
+ /** @type {any[]} */
+ const spreadArgs = [];
+ for (const attr of attrs) {
+ if (
+ (attr?.type === 'JSXSpreadAttribute' || attr?.type === 'SpreadAttribute') &&
+ attr.argument
+ ) {
+ spreadArgs.push(attr.argument);
+ }
+ }
+ let sequence = chain;
+ if (spreadArgs.length > 0) {
+ ctx.runtimeNeeded.add('normalizeClass');
+ ctx.runtimeNeeded.add('classFromSpreads');
+ const winning = tools.inheritOriginLoc(
+ b.call('_$classFromSpreads', ...spreadArgs.map((arg) => cloneAstNode(arg))),
+ openingElement,
+ );
+ const base = tools.inheritOriginLoc(b.call('_$normalizeClass', winning), openingElement);
+ sequence = [base, ...chain];
+ }
// A synthesized class attribute maps to the element's opening tag; it is
// marked NOT AUTHORED so inspection does not claim the tag as its origin.
- const value = buildClassValue(chain);
+ const value = buildClassValue(sequence);
newAttrs = [
...attrs,
tools.markSynthesizedAttr(
diff --git a/packages/octane/src/css.ts b/packages/octane/src/css.ts
--- a/packages/octane/src/css.ts
+++ b/packages/octane/src/css.ts
@@ -6,6 +6,27 @@
* clsx-style class composition (strings, numbers, arrays, objects, nesting;
* falsy drops out). Octane's `class`/`className` semantics at every apply site.
*/
+/**
+ * Last own enumerable `class` / `className` among JSX spread sources, matching
+ * the later-writer rule used by setSpread / ssrAttrs. Returns `undefined` when
+ * no source enumerates either key.
+ */
+export function classFromSpreads(...sources: unknown[]): unknown {
+ let found = false;
+ let value: unknown;
+ for (let i = 0; i < sources.length; i++) {
+ const source = sources[i];
+ if (source == null || (typeof source !== 'object' && typeof source !== 'function')) continue;
+ for (const key of Object.keys(Object(source))) {
+ if (key === 'class' || key === 'className') {
+ found = true;
+ value = (source as Record<string, unknown>)[key];
+ }
+ }
+ }
+ return found ? value : undefined;
+}
+
export function normalizeClass(value: unknown): string {
if (typeof value === 'string') return value;
if (typeof value !== 'object') {
diff --git a/packages/octane/src/index.ts b/packages/octane/src/index.ts
--- a/packages/octane/src/index.ts
+++ b/packages/octane/src/index.ts
@@ -170,6 +170,7 @@
setAriaAttribute,
setClassName,
setClassAttr,
+ classFromSpreads,
normalizeClass,
setStyle,
setStyleProperty,
diff --git a/packages/octane/src/runtime.server.ts b/packages/octane/src/runtime.server.ts
--- a/packages/octane/src/runtime.server.ts
+++ b/packages/octane/src/runtime.server.ts
@@ -87,8 +87,14 @@
// Shared client/SSR CSS helpers (single source in css.ts so class strings and
// hyphenated style keys stay byte-equal across the two runtimes).
-import { devWarnStyleCoercion, devWarnStyleProperty, normalizeClass, styleName } from './css.js';
import {
+ classFromSpreads,
+ devWarnStyleCoercion,
+ devWarnStyleProperty,
+ normalizeClass,
+ styleName,
+} from './css.js';
+import {
invalidHtmlNestingWithAncestor,
invalidHtmlNestingWithParent,
invalidHtmlTextNesting,
@@ -114,7 +120,7 @@
type NativeSeedReads,
type NativeSignalManifest,
} from './signals/native-read-seeds.js';
-export { EXTERNAL_HYDRATION_PROMISE, HYDRATION_RANGE_BOUNDARY, normalizeClass };
+export { EXTERNAL_HYDRATION_PROMISE, HYDRATION_RANGE_BOUNDARY, classFromSpreads, normalizeClass };
export { validateNativeReadWitness };
export type { NativeSignalManifest };
diff --git a/packages/octane/src/runtime.ts b/packages/octane/src/runtime.ts
--- a/packages/octane/src/runtime.ts
+++ b/packages/octane/src/runtime.ts
@@ -15279,8 +15279,14 @@
// clsx-style `class`/`className` composition — shared with the SSR serializer
// via css.ts so client and server compose byte-equal class strings (hydration
// parity). Re-exported here because it is part of the semi-public surface.
-import { devWarnStyleCoercion, devWarnStyleProperty, normalizeClass, styleName } from './css.js';
-export { normalizeClass };
+import {
+ classFromSpreads,
+ devWarnStyleCoercion,
+ devWarnStyleProperty,
+ normalizeClass,
+ styleName,
+} from './css.js';
+export { classFromSpreads, normalizeClass };
export function setClassName(el: Element, value: unknown): void {
// clsx-compose first so arrays / objects become a class string (and the hydration
diff --git a/packages/octane/src/server/index.ts b/packages/octane/src/server/index.ts
--- a/packages/octane/src/server/index.ts
+++ b/packages/octane/src/server/index.ts
@@ -134,6 +134,7 @@
ssrChild,
ssrChildText,
ssrAttr,
+ classFromSpreads,
normalizeClass,
ssrStyle,
ssrClass,
diff --git a/packages/octane/tests/_fixtures/style-scopes.tsrx b/packages/octane/tests/_fixtures/style-scopes.tsrx
--- a/packages/octane/tests/_fixtures/style-scopes.tsrx
+++ b/packages/octane/tests/_fixtures/style-scopes.tsrx
@@ -242,6 +242,34 @@
</section>
}
+// A host that takes its class only from a spread must still keep that class
+// ahead of the scope hashes (later-writer must not let a synthesized class
+// replace `props.class`).
+export function SpreadScoped(props: { attrs: Record<string, unknown> }) @{
+ <>
+ <style>
+ .host {
+ padding: 1px;
+ }
+ </style>
+ <div id="ss-host" {...props.attrs}>{'spread'}</div>
+ </>
+}
+
+export function SpreadScopedMany(props: {
+ first: Record<string, unknown>;
+ second: Record<string, unknown>;
+}) @{
+ <>
+ <style>
+ .many {
+ padding: 2px;
+ }
+ </style>
+ <div id="ssm-host" {...props.first} {...props.second}>{'many'}</div>
+ </>
+}
+
export function StreamedScopes(props: { a: Promise<string>; b: Promise<string> }) @{
<div id="streamed-scopes" class="shell">
<style>
diff --git a/packages/octane/tests/clsx-class.test.ts b/packages/octane/tests/clsx-class.test.ts
--- a/packages/octane/tests/clsx-class.test.ts
+++ b/packages/octane/tests/clsx-class.test.ts
@@ -5,7 +5,7 @@
import { mount } from './_helpers';
import { loadCompiledFixtureSource, loadServerFixture } from './_server-fixture';
import { compile } from 'octane/compiler';
-import { hydrateRoot, flushSync, normalizeClass } from '../src/index.js';
+import { hydrateRoot, flushSync, classFromSpreads, normalizeClass } from '../src/index.js';
import { theme } from './_fixtures/style-theme.tsrx';
import { SpreadApplied } from './_fixtures/style-theme-consumer.tsrx';
import {
@@ -64,6 +64,22 @@
});
});
+describe('classFromSpreads — later-writer among spread sources', () => {
+ it('returns undefined when no source enumerates class or className', () => {
+ expect(classFromSpreads(null, { id: 'x' })).toBeUndefined();
+ });
+
+ it('takes the last enumerated class or className', () => {
+ expect(classFromSpreads({ class: 'a' })).toBe('a');
+ expect(classFromSpreads({ className: 'b' })).toBe('b');
+ expect(classFromSpreads({ class: 'a' }, { className: ['last', { on: true }] })).toEqual([
+ 'last',
+ { on: true },
+ ]);
+ expect(classFromSpreads({ class: 'a', className: 'b' })).toBe('b');
+ });
+});
+
describe('clsx class composition — client mount', () => {
it('array class — falsy entries drop out', () => {
const on = mount(ArrayClass, { on: true });
diff --git a/packages/octane/tests/ssr.test.ts b/packages/octane/tests/ssr.test.ts
--- a/packages/octane/tests/ssr.test.ts
+++ b/packages/octane/tests/ssr.test.ts
@@ -3,6 +3,7 @@
import { join } from 'node:path';
import { compile } from 'octane/compiler';
import * as RT from 'octane/server';
+import { loadCompiledFixtureSource } from './_server-fixture.js';
import {
createElement as createClientElement,
flushSync,
@@ -197,6 +198,73 @@
// A map lookup is a dynamic class: normalized first, then the chain.
expect(html).toContain(`class="${mapHash} note ${scopeHash} ${themeHash}"`);
});
+
+ it('injects an imported theme before the applying scope when a nested helper compiles first', () => {
+ const themeModule = loadCompiledFixtureSource(
+ `export const theme = <style>div { color: rgb(255, 0, 0); }</style>;`,
+ {
+ id: '/packages/octane/tests/_fixtures/theme-nested-helper-theme.tsrx',
+ mode: 'server',
+ compileOptions: { hmr: false, dev: false },
+ },
+ );
+ const applier = loadCompiledFixtureSource(
+ `import { theme } from './theme.tsrx';
+ export function Card(props) @{
+ <>
+ <style apply={theme}>div { color: rgb(0, 0, 255); }</style>
+ @if (props.show) {
+ <div class="card">{'card'}</div>
+ }
+ </>
+ }`,
+ {
+ id: '/packages/octane/tests/_fixtures/theme-nested-helper-applier.tsrx',
+ mode: 'server',
+ compileOptions: { hmr: false, dev: false },
+ runtimeModules: { './theme.tsrx': themeModule },
+ },
+ );
+ const themeHash = themeModule.theme.$class as string;
+ expect(themeHash).toMatch(/^tsrx-/);
+
+ const hidden = RT.renderToString(applier.Card, { show: false });
+ expect(hidden.css).toContain(`data-octane="${themeHash}"`);
+ const hiddenScope = hidden.css.match(/div\.(tsrx-[0-9a-f]+) \{ color: rgb\(0, 0, 255\)/)?.[1];
+ expect(hiddenScope).toBeTruthy();
+ expect(hidden.css.indexOf(`data-octane="${themeHash}"`)).toBeLessThan(
+ hidden.css.indexOf(`data-octane="${hiddenScope}"`),
+ );
+
+ const shown = RT.renderToString(applier.Card, { show: true });
+ const scopeHash = shown.html
+ .match(/class="card ([^"]+)"/)![1]
+ .split(' ')
+ .find((cls) => cls !== themeHash)!;
+ expect(shown.html).toContain(`class="card ${scopeHash} ${themeHash}"`);
+ expect(shown.css.indexOf(`data-octane="${themeHash}"`)).toBeLessThan(
+ shown.css.indexOf(`data-octane="${scopeHash}"`),
+ );
+ });
+
+ it('keeps a spread-supplied class on a styled host ahead of the scope hash', () => {
+ const mod = evalServer(
+ `
+ export function Host(props) @{
+ <>
+ <style>.host { padding: 1px; }</style>
+ <div id="h" {...props.attrs}>{'x'}</div>
+ </>
+ }
+ `,
+ 'spread-scoped-host.tsrx',
+ );
+ const { html } = RT.renderToString(mod.Host, {
+ attrs: { class: 'from-spread', 'data-x': '1' },
+ });
+ expect(html).toMatch(/class="from-spread tsrx-[0-9a-f]+"/);
+ expect(html).toContain('data-x="1"');
+ });
});
describe.each([
diff --git a/packages/octane/tests/style.test.ts b/packages/octane/tests/style.test.ts
--- a/packages/octane/tests/style.test.ts
+++ b/packages/octane/tests/style.test.ts
@@ -34,6 +34,8 @@
StyleCallChain,
ControlFlow,
SiblingScopes,
+ SpreadScoped,
+ SpreadScopedMany,
} from './_fixtures/style-scopes.tsrx';
import { base, theme } from './_fixtures/style-theme.tsrx';
import { Panel } from './_fixtures/style-theme-consumer.tsrx';
@@ -1210,6 +1212,35 @@
r.unmount();
});
+ it('composes a spread-only class ahead of the scope hash', () => {
+ const r = mount(SpreadScoped, { attrs: { class: 'from-spread', 'data-x': '1' } });
+ const host = r.find('#ss-host');
+ const [hash] = hashesOf(host);
+ expect(hash).toMatch(/^tsrx-/);
+ expect(host.className).toBe(`from-spread ${hash}`);
+ expect(host.getAttribute('data-x')).toBe('1');
+ r.update(SpreadScoped, { attrs: { className: ['next', { on: true }], 'data-x': '2' } });
+ expect(host.className).toBe(`next on ${hash}`);
+ expect(host.getAttribute('data-x')).toBe('2');
+ r.update(SpreadScoped, { attrs: { 'data-x': '3' } });
+ expect(host.className.trim()).toBe(hash);
+ expect(host.getAttribute('data-x')).toBe('3');
+ r.unmount();
+ });
+
+ it('keeps the last spread class and appends the scope hash', () => {
+ const r = mount(SpreadScopedMany, {
+ first: { class: 'first', 'data-a': '1' },
+ second: { className: ['second', { on: true }], 'data-b': '2' },
+ });
+ const host = r.find('#ssm-host');
+ const [hash] = hashesOf(host);
+ expect(host.className).toBe(`second on ${hash}`);
+ expect(host.getAttribute('data-a')).toBe('1');
+ expect(host.getAttribute('data-b')).toBe('2');
+ r.unmount();
+ });
+
it('a nested @{} is its own scope: A reaches into B, B never reaches A', () => {
const r = mount(NestedBlocks);
const outer = r.find('#nb-outer');You can send follow-ups to the cloud agent here.
…body The touches were handed to the shared body emitter through a context slot that the first nested branch helper drained; they are now a parameter that only the component body passes (nested helpers pass none), with a test pinning the placement ahead of the component's own injectStyle calls. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
… test The non-frozen install that introduced the branch dependency also swapped the happy-dom peer suffix of five vitest snapshots, which changed which vitest instance packages/pdf resolved and broke its typecheck (TS2769); those hunks are reverted. The conformance runner asserts the documented compiled-output-only reason instead of skipping (test-marker policy). Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
The pack validator and the Lynx consumer generators write their own pnpm-workspace.yaml; while octane depends on @tsrx/core from a git branch they now emit blockExoticSubdeps: false (pnpm 11 blocks a git dependency below a packed package by default) plus the branch-manifest pins read from the root workspace, so the block disappears with that override at release. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
…lease That directory is type-checked through the published @tsrx/react and its released @tsrx/core, which has no $class yet; the compiled-output checks in the conformance and style-map suites cover $class on the Octane side. Co-Authored-By: Claude Fable 5.1 <[email protected]>
Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
Vercel previews for
|
Document `class={theme.$class}` (and passing it to a child through a prop)
as the selective counterpart of `apply` in tsrx-basics, the Styling page,
llms.txt, and the tsrx-authoring rule; extend the playground's scoped-styles
example with an `accent` theme, a Footnote child, and an untouched sibling;
add a client/server test suite for the pattern. Lockfile moves to the tsrx
branch commit that classifies a block whose $class is read as a theme
(and ships the class-opt-in conformance fixture), with the parity and
corpus hashes regenerated.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
Autofix Details
Bugbot Autofix prepared a fix for 1 of the 2 issues found in the latest run.
- ✅ Fixed: style() rewritten outside class position
- The style-scope walk now rewrites style() only inside class/className attributes, and the emit-time fallback no longer expands leftover helper calls such as style={style(props)}.
Or push these changes by commenting:
@cursor push b3c377fd95
Preview (b3c377fd95)
diff --git a/packages/octane/src/compiler/compile.js b/packages/octane/src/compiler/compile.js
--- a/packages/octane/src/compiler/compile.js
+++ b/packages/octane/src/compiler/compile.js
@@ -6732,7 +6732,8 @@
// Recognise `{style (expr)}` — TSRX parses it as a plain
// `CallExpression(style, [expr])` (the dedicated `Style` intrinsic node is
-// gone); resolveStyleExpr rewrites it into a scoped class-string expression.
+// gone). The style-scope pre-pass rewrites this only in class / className
+// position; leftover `style(...)` calls are helpers.
function isStyleCall(node) {
return (
node &&
@@ -6744,26 +6745,11 @@
);
}
-// Resolve a `{style (expr)}` CallExpression (see isStyleCall) into a plain
-// expression that yields a class string, with the component's scoped css hash
-// prepended (so `{style ('row')}` in a component with hash "tsrx-abc" produces
-// "tsrx-abc row"). Literal values inline; dynamic values become a runtime
-// string concat. Components without a <style> block (no hash) — and any other
-// expression shape — pass through untouched.
-function resolveStyleExpr(node, cssHash) {
- if (!node) return node;
- if (!isStyleCall(node) || !cssHash) return node;
- const inner = node.arguments[0];
- if (inner.type === 'Literal' && typeof inner.value === 'string') {
- const combined = inner.value ? `${cssHash} ${inner.value}` : cssHash;
- // The resolved class string maps to the authored `{style (…)}` call.
- return b.literal(combined, JSON.stringify(combined), node);
- }
- // Dynamic: emit `(<hash> + ' ' + (expr))` so absent/null produces "<hash> ".
- return inheritOriginLoc(
- b.binary('+', b.literal(cssHash + ' ', JSON.stringify(cssHash + ' ')), inner),
- node,
- );
+// Class-position `{style(expr)}` is already resolved by the style-scope
+// pre-pass. Leftover `style(...)` calls are helpers (e.g. `style={style(props)}`),
+// so the emitters must not expand them.
+function resolveStyleExpr(node, _cssHash) {
+ return node;
}
/**
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
@@ -51,8 +51,10 @@
* what the class map exposes. The classification comes from the core
* analyzer (`metadata.styleKind`, `metadata.styleApplies`), which runs on
* the parser AST before it is adopted, so this pass reads it read-only.
- * - `{style(expr)}` calls resolve to the scope chain plus the value, so the
- * emitters no longer need a `cssHash` to expand them.
+ * - `{style(expr)}` calls in `class` / `className` position resolve to the
+ * scope chain plus the value, so the emitters no longer need a `cssHash`
+ * to expand them. A `style(...)` call anywhere else — a local helper, or
+ * `style={style(props)}` — is left alone.
* - Float style resources (`<style href precedence>`) stay in the tree.
*
* The parser AST may be frozen (see `adoptParserAst`): nodes are never
@@ -99,6 +101,7 @@
* staticClasses: Map<any, string | null>,
* appliedParts: Map<any, Array<string | any>>,
* runtimeApplied: any[],
+ * inClassPosition: boolean,
* }} PassState
*/
@@ -133,6 +136,7 @@
staticClasses: new Map(),
appliedParts: new Map(),
runtimeApplied: [],
+ inClassPosition: false,
};
const node = walk(root, state, 'statement');
return { node, cssHash: state.firstHash, runtimeApplied: state.runtimeApplied };
@@ -263,8 +267,20 @@
return rewriteChildren(node, (child) => walk(child, state, 'expression'));
case 'ExpressionStatement':
return rewriteChildren(node, (child) => walk(child, state, 'statement'));
+ case 'JSXAttribute': {
+ const name = node.name?.type === 'JSXIdentifier' ? node.name.name : '';
+ const previous = state.inClassPosition;
+ state.inClassPosition = name === 'class' || name === 'className';
+ try {
+ return rewriteChildren(node, (child) => walk(child, state, 'expression'));
+ } finally {
+ state.inClassPosition = previous;
+ }
+ }
case 'CallExpression':
- if (state.tools.isStyleCall(node)) return resolveStyleCall(node, state);
+ if (state.inClassPosition && state.tools.isStyleCall(node)) {
+ return resolveStyleCall(node, state);
+ }
break;
default:
if (isDirective(node)) return processDirective(node, state);
diff --git a/packages/octane/tests/compiler/compiler-ast-emit-audit.test.ts b/packages/octane/tests/compiler/compiler-ast-emit-audit.test.ts
--- a/packages/octane/tests/compiler/compiler-ast-emit-audit.test.ts
+++ b/packages/octane/tests/compiler/compiler-ast-emit-audit.test.ts
@@ -191,15 +191,15 @@
});
});
-// RFC tsrx-org/RFCs#1: `{style(expr)}` is resolved by the scope pre-pass
-// (style-scopes.js) into the scope chain plus the value. By the time the
-// emitters run — and compile.js's `resolveStyleExpr` fallback with them — no
-// `style(...)` call is left on the AST, so the output never carries one.
+// RFC tsrx-org/RFCs#1: `{style(expr)}` in class position is resolved by the
+// scope pre-pass (style-scopes.js) into the scope chain plus the value. By
+// the time the emitters run — and compile.js's `resolveStyleExpr` fallback
+// with them — no class-position `style(...)` call is left on the AST.
describe('scoped style pre-pass', () => {
const SOURCE = `export function App(props) @{
<>
<style>.x { color: red; }</style>
- <p class={style('x')}>{style('x y')}</p>
+ <p class={style('x')}>{'x'}</p>
<i class={style(props.cls)}>{'i'}</i>
</>
}`;
@@ -208,15 +208,39 @@
['client', {}],
['client prod', { hmr: false as const }],
['server', { mode: 'server' as const }],
- ])('resolves every {style(...)} call before the emitters run — %s', (_label, options) => {
- const { code } = compile(SOURCE, 'style-call.tsrx', options);
- expect(code).not.toMatch(/\bstyle\(/);
- const hash = code.match(/injectStyle\("(tsrx-[0-9a-f]+)"/)![1];
- // Static values fold to a literal that opens with the scope chain…
- expect(code).toContain(`${hash} x`);
- expect(code).toContain(`${hash} x y`);
- // …and a dynamic value concatenates after the chain at runtime.
- expect(code).toContain(`"${hash} " + props.cls`);
+ ])(
+ 'resolves every class-position {style(...)} call before the emitters run — %s',
+ (_label, options) => {
+ const { code } = compile(SOURCE, 'style-call.tsrx', options);
+ expect(code).not.toMatch(/\bstyle\(/);
+ const hash = code.match(/injectStyle\("(tsrx-[0-9a-f]+)"/)![1];
+ // Static values fold to a literal that opens with the scope chain…
+ expect(code).toContain(`${hash} x`);
+ // …and a dynamic value concatenates after the chain at runtime.
+ expect(code).toContain(`"${hash} " + props.cls`);
+ },
+ );
+
+ it.each([
+ ['client', {}],
+ ['client prod', { hmr: false as const }],
+ ['server', { mode: 'server' as const }],
+ ])('leaves a style() helper on the style prop alone — %s', (_label, options) => {
+ const { code } = compile(
+ `function style(props) {
+ return { color: props.color };
+}
+export function App(props) @{
+ <>
+ <style>.box { padding: 2px; }</style>
+ <div class="box" style={style(props)}>{'x'}</div>
+ </>
+}`,
+ 'style-prop-helper.tsrx',
+ options,
+ );
+ expect(code).toMatch(/\bstyle\(props\)/);
+ expect(code).not.toMatch(/"[^"]*tsrx-[0-9a-f]+[^"]*"\s*\+\s*props/);
});
it('keeps the emitter fallback out of the shipped path (no cssHash-driven rewrite)', () => {
diff --git a/packages/octane/tests/style-list-scopes.test.ts b/packages/octane/tests/style-list-scopes.test.ts
--- a/packages/octane/tests/style-list-scopes.test.ts
+++ b/packages/octane/tests/style-list-scopes.test.ts
@@ -215,6 +215,44 @@
}
});
+ it('keeps selectors that a dynamic-tag sibling can match', () => {
+ const source = `
+export function Host(props: { tag: string }) @{
+ <>
+ <style>div { color: rgb(1, 2, 3); }</style>
+ <{props.tag} id="dyn" />
+ </>
+}
+`;
+ for (const mode of ['client', 'server'] as const) {
+ const { code } = compile(source, 'dynamic-tag-prune.tsrx', { ...COMPILE_OPTIONS, mode });
+ const sheets = injections(code);
+ expect(sheets).toHaveLength(1);
+ expect(sheets[0].css).toContain(`div.${sheets[0].hash}`);
+ expect(sheets[0].css).not.toContain('(unused)');
+ }
+
+ const { code } = compile(source, 'dynamic-tag-prune.tsrx', {
+ ...COMPILE_OPTIONS,
+ mode: 'client',
+ });
+ const [sheet] = injections(code);
+ const client = loadCompiledFixtureSource(source, {
+ id: 'dynamic-tag-prune.tsrx',
+ mode: 'client',
+ compileOptions: COMPILE_OPTIONS,
+ });
+ const r = mount(client.Host, { tag: 'div' });
+ try {
+ const el = r.find('#dyn') as HTMLElement;
+ expect(el.tagName).toBe('DIV');
+ expect(hashesOf(el)).toEqual([sheet.hash]);
+ expect(getComputedStyle(el).color).toBe('rgb(1, 2, 3)');
+ } finally {
+ r.unmount();
+ }
+ });
+
it('apply on a standalone block reaches the same elements as its CSS', () => {
const source = `
const theme = <style>div { color: red; }</style>;
diff --git a/packages/octane/tests/style.test.ts b/packages/octane/tests/style.test.ts
--- a/packages/octane/tests/style.test.ts
+++ b/packages/octane/tests/style.test.ts
@@ -1252,6 +1252,30 @@
r.unmount();
});
+ it('a style() helper used as the style prop keeps the object, not a class string', () => {
+ const source = `
+function style(props: { color: string }) {
+ return { color: props.color };
+}
+export function Styled(props: { color: string }) @{
+ <>
+ <style>.box { padding: 2px; }</style>
+ <div id="styled-helper" class="box" style={style(props)}>{'x'}</div>
+ </>
+}
+`;
+ const client = loadCompiledFixtureSource(source, {
+ id: 'style-prop-helper.tsrx',
+ mode: 'client',
+ compileOptions: { hmr: false, dev: false },
+ });
+ const r = mount(client.Styled, { color: 'rgb(9, 8, 7)' });
+ const el = r.find('#styled-helper') as HTMLElement;
+ expect(el.style.color).toBe('rgb(9, 8, 7)');
+ expect(el.className).toMatch(/^box tsrx-[0-9a-f]+$/);
+ r.unmount();
+ });
+
it('every directive branch is a scope whose CSS ships even while inactive', () => {
const r = mount(ControlFlow, { ready: false, maybe: false, items: [], kind: 2 });
const [R] = hashesOf(r.find('#cf-root'));You can send follow-ups to the cloud agent here.
Bugbot on #939: the style-scope pre-pass rewrote every one-argument call to an identifier named `style` it walked — a local `const s = style(props)` became `const s = props`, an imported helper in `style={style(props)}` was rewritten too. Before the pre-pass the emitters expanded `style(expr)` only as the expression of a JSX attribute value or of a template expression child, so that is the rule now: an attribute value (the `style` attribute excepted — its value is CSS, never a class list, so the old rewrite there was a quirk and is retired) or a template child hole, directly or nested in the array/conditional/logical/template expressions of that container. Every other `style(...)` — a statement, a declaration initializer, a call argument, a callback body — is a user call and prints as authored. The attribute walk now runs before the stamp so nested calls resolve first, and a resolved value is marked so the stamp does not append the chain again; the emitters' `resolveStyleExpr` fallback is a pass-through. Also pins that a rule matched only by a dynamic-tag sibling stays in the sheet on both emitters (a `<{expr}>` can match any selector). Co-Authored-By: Claude Fable 5.1 <[email protected]>
The scroller sweep waited two animation frames per step, which a slow runner can outpace, so a keyword's lines were sometimes never in the DOM when read ("@empty not found" on the production run). Each step now waits until a line is painted inside the visible range, uses half-height steps, and the final read retries until the target line appears.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
This comment has been minimized.
This comment has been minimized.
…tsrx 393d1754 The $class opt-in example declared a .local rule the article never used; the article now carries local alongside the passed theme class, and the opt-in test expects it on client and server. The lockfile moves to the tsrx commit whose class-opt-in conformance fixture has the same shape, with parity hashes and the evals corpus regenerated. Co-Authored-By: Claude Fable 5.1 <[email protected]>
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]>
tsrx-org/tsrx#68 shipped the sibling-scoped style blocks, `$class`, and `apply` this branch was consuming from the `feat/scoped-styles-apply` git branch, so: - `packages/octane`, `@octanejs/evals`, and `website` depend on `@tsrx/core` through `catalog:default` again; - the catalog moves every `@tsrx/*` entry to that release (core 0.1.66, prettier/typescript plugins 0.3.132, react 0.2.66, solid 0.1.66, vite plugins 0.0.99/0.0.96) and `minimumReleaseAgeExclude` follows; - the INTERIM override block that made the branch manifest installable is deleted, and the pack validator, its canary tests, and the Lynx consumer generators drop the `blockExoticSubdeps` shim (back to main's versions); - `pnpm sync` regenerates the lockfile-hashed parity audits and the evals manifest. Co-Authored-By: Claude Fable 5.1 <[email protected]>
* fix(octane): allow complete style scopes inside Hydrate splits Lift OCTANE_HYDRATE_SPLIT_STYLE when a lexical style scope sits entirely inside the extracted child (plan S8.5). Keep the error when the scope has blocks or stamped hosts on both sides of the boundary. Co-authored-by: Jon Wheeler <[email protected]> * fix(octane): keep hydrate extraction from writing frozen style nodes Extraction now reaches complete in-boundary style scopes. Skip frozen parser/StyleSheet nodes when stamping generated origins, and assert the split child's sheet after the child hydrates. Co-authored-by: Jon Wheeler <[email protected]> * fix(octane): count namespaced hosts in hydrate style-scope straddle check JSXNamespacedName hosts are stamped by the style-scope pass. Treat them as stampable so a parent-list scoped style with only namespaced hosts inside a split Hydrate is rejected as OCTANE_HYDRATE_SPLIT_STYLE. Co-authored-by: Jon Wheeler <[email protected]> --------- Co-authored-by: Cursor Agent <[email protected]> Co-authored-by: Jon Wheeler <[email protected]>
Migrate the Core APIs live examples off a class-map plus :global descendants
onto sibling scopes, control-flow scopes, and <style apply={theme} />. Move
PortalEventDemo toast rules into ToastBody. Document the class-map pruning
trap and the apply path for shared chrome.
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Jon Wheeler <[email protected]>
Brings in #968 (server, SSR, and adapter defects); no conflicts. Co-Authored-By: Claude Fable 5.1 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Bugbot Autofix prepared a fix for the issue found in the latest run.
- ✅ Fixed: Nested style() stamps hashes twice
- addScopeClasses now skips a second hash/theme stamp when a nested class expression always includes a resolved style(), so forms like class={[style('row'), extra]} no longer duplicate the chain.
Or push these changes by commenting:
@cursor push c0a0297ee5
Preview (c0a0297ee5)
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
@@ -990,8 +990,13 @@
} else {
const expression = value.type === 'JSXExpressionContainer' ? value.expression : value;
let base;
- if (tools.isStyleCall(expression) || expression.metadata?.tsrx_style_resolved === true) {
- // `class={style(expr)}` already resolves to the chain plus the value.
+ if (
+ tools.isStyleCall(expression) ||
+ expression.metadata?.tsrx_style_resolved === true ||
+ alwaysCarriesResolvedStyle(expression)
+ ) {
+ // `class={style(expr)}` — and nested forms that always include one —
+ // already resolve to the chain plus the value.
return element;
}
if (expression.type === 'Literal' && typeof expression.value === 'string') {
@@ -1075,3 +1080,39 @@
node.metadata = { ...(node.metadata ?? {}), tsrx_style_resolved: true };
return node;
}
+
+/**
+ * True when every evaluation of this class-string expression already includes
+ * a resolved `style(expr)` (the chain is present, so the host stamp must not
+ * append it again). An array or template that contains one such part always
+ * does; a conditional or logical only does when every branch does.
+ *
+ * @param {any} node
+ * @returns {boolean}
+ */
+function alwaysCarriesResolvedStyle(node) {
+ if (node === null || typeof node !== 'object' || typeof node.type !== 'string') return false;
+ if (node.metadata?.tsrx_style_resolved === true) return true;
+ switch (node.type) {
+ case 'ArrayExpression':
+ return node.elements.some(
+ (element) => element?.type !== 'SpreadElement' && alwaysCarriesResolvedStyle(element),
+ );
+ case 'ConditionalExpression':
+ return (
+ alwaysCarriesResolvedStyle(node.consequent) && alwaysCarriesResolvedStyle(node.alternate)
+ );
+ case 'LogicalExpression':
+ return alwaysCarriesResolvedStyle(node.left) && alwaysCarriesResolvedStyle(node.right);
+ case 'TemplateLiteral':
+ return node.expressions.some(alwaysCarriesResolvedStyle);
+ case 'ParenthesizedExpression':
+ case 'TSAsExpression':
+ case 'TSSatisfiesExpression':
+ case 'TSNonNullExpression':
+ case 'TSTypeAssertion':
+ return alwaysCarriesResolvedStyle(node.expression);
+ default:
+ return false;
+ }
+}
diff --git a/packages/octane/tests/_fixtures/style-scopes.tsrx b/packages/octane/tests/_fixtures/style-scopes.tsrx
--- a/packages/octane/tests/_fixtures/style-scopes.tsrx
+++ b/packages/octane/tests/_fixtures/style-scopes.tsrx
@@ -73,6 +73,7 @@
</style>
<p id="sc-static" class={style('sc-row')}>{'static'}</p>
<p id="sc-dynamic" class={style(props.cls)}>{'dynamic'}</p>
+ <p id="sc-nested" class={[style('sc-row'), props.cls]}>{'nested'}</p>
</>
}</div>
</>
diff --git a/packages/octane/tests/compiler/style-call-positions.test.ts b/packages/octane/tests/compiler/style-call-positions.test.ts
--- a/packages/octane/tests/compiler/style-call-positions.test.ts
+++ b/packages/octane/tests/compiler/style-call-positions.test.ts
@@ -104,6 +104,10 @@
expect(code).not.toMatch(/\bstyle\(/);
expect(code).toMatch(new RegExp(`["']${hash} a["']`));
expect(code).toMatch(new RegExp(`props\\.cond && ["']${hash} b["']`));
+ // Nested `style()` already carries the chain; the host stamp must not
+ // wrap the array in normalizeClass and append the hash again.
+ expect(code).not.toContain('_$normalizeClass');
+ expect(code).not.toMatch(new RegExp(`\\} ${hash}`));
});
it.each(MODES)(
diff --git a/packages/octane/tests/style.test.ts b/packages/octane/tests/style.test.ts
--- a/packages/octane/tests/style.test.ts
+++ b/packages/octane/tests/style.test.ts
@@ -1257,6 +1257,22 @@
r.unmount();
});
+ it('nested style() in an array class does not stamp the chain twice', () => {
+ const r = mount(StyleCallChain, { cls: 'sc-cell' });
+ const host = r.find('#sc-host');
+ const stat = r.find('#sc-static');
+ const nested = r.find('#sc-nested');
+ const [A] = hashesOf(host);
+ const B = hashesOf(stat)[1];
+ // `class={style('sc-row')}` and `class={[style('sc-row'), extra]}` share
+ // one chain; the extra token is appended, the hashes are not.
+ expect(stat.className).toBe(`${A} ${B} sc-row`);
+ expect(nested.className).toBe(`${A} ${B} sc-row sc-cell`);
+ expect(hashesOf(nested)).toEqual([A, B]);
+ expect(getComputedStyle(nested).color).toBe('rgb(4, 5, 6)');
+ r.unmount();
+ });
+
it('every directive branch is a scope whose CSS ships even while inactive', () => {
const r = mount(ControlFlow, { ready: false, maybe: false, items: [], kind: 2 });
const [R] = hashesOf(r.find('#cf-root'));You can send follow-ups to the cloud agent here.
Reviewed by Cursor Bugbot for commit 10018e4. Configure here.
…ss value A `style(expr)` nested in an array, conditional, logical, or template class value resolved to the chain plus its value, and the element's stamp then appended the chain again (Bugbot on #939). Inside the class of an element the chain is stamped on, a call that is only part of the value now yields its value alone and the stamp adds the chain once to the composed value, so the chain is present whichever branch runs and never twice. A whole-value `class={style(expr)}` keeps its chain-first form, now also through parenthesized and TS wrapper expressions. Co-Authored-By: Claude Fable 5.1 <[email protected]>
The released plugin drops the stray `;` after `@try` blocks in three fixtures, and #958's styling table is realigned. Co-Authored-By: Claude Fable 5.1 <[email protected]>


Implements RFC tsrx-org/RFCs#1 — sibling-scoped
<style>blocks,$class, andapply— on the Octane compiler and runtime, on top of the@tsrx/corechanges in tsrx-org/tsrx (branchfeat/scoped-styles-apply).Compiler
src/compiler/style-scopes.js: one copy-on-write pre-pass per top-level statement (frozen-AST safe). Scopes were originally statement lists; since amendment A1 below a scope is the children list of one element or fragment (a sibling scope). Several blocks per scope share the first block's hash and ONEinjectStylecall; nested scopes get their own; injections are pushed in lexical pre-order with an order key that sorts among module-level entries on the server.theme.$classat runtime through the dynamic class path.{style(expr)}resolves to the chain in the pre-pass.$class, and render in theme or class-map mode from the core analyzer's classification. Float<style href precedence>resources stay outside the model.applyStyleMap,applyCssScoping,componentStyleRoots,annotateRootWithHash,addHashClassToElement,wrapScopedClassExprs.inheritOriginLocno longer descends intoStyleSheetsubtrees (their positions are CSS-relative).Server and runtime
styleMap(hash, css, map, applied)(octane/server), a proxy that injects the sheet — after the sheets of the themes it applies — into the active request on property access; applying components emittouchStyleMap(theme)before their owninjectStylecalls, so a theme from another module precedes the scope that applies it.injectStyle: refreshes a sheet whose id is unchanged but whose CSS differs (HMR of a later block in a multi-block scope, injectStyle drops a re-injection with an unchanged hash but changed CSS (HMR hazard) #938) and token-matches React's batcheddata-hrefso hydrating a multi-hash island does not re-inject.OCTANE_HYDRATE_SPLIT_STYLEnames the style scope, not the component.Docs, rules, evals, scaffold
docs/tsrx-basics.mdStyles section and stale-claim fixes across docs; newLearn Octane › Stylingwebsite page (including opting single elements in withclass={theme.$class}and passing it to a child through a prop), llms bullets, per-bundler notes, playgroundScoped styles & themes (multi-file)example with anaccenttheme, aFootnotechild, and an untouched sibling, regenerated TextMate grammar; rulesynctsrx-authoringStyles section and skill enumeration (context budget kept); MCP skills; evalsscoped-stylescoverage axis (21 tasks); scaffold templates apply a link theme; harborPriceBadgedark variant; bundler plugin README notes.Tests
Conformance runner over
@tsrx/core/test-harness/scoped-styles-fixtures(15 fixtures × client/server, evaluated, pruning asserted), parser spec-table fallback replay (16 forms fall back, 4 native-shape divergences pinned for the oxc-tsrx port), new fixtures and suites (RFC class table and head order, control-flow parity,$classpins,$classopt-in suite (element opt-in, prop pass-through, untouched sibling, imported theme; client mount and SSR), SSR cascades with in-body themes, streaming per-hash dedupe and theme waves, Float sibling, clsx spread + hashes +theme.$class, frozen-AST run, per-scope inspect origins, emit audit, React-hosted multi-hash islands,injectStyleDOM order, universal renderer rejection), Playwright cascade test (client and SSR+hydration), tsrx-tsc typetest fortheme.$class.Local gates:
rules:check,context:budget:check,error-codes:check,scaffold:manifest:check,examples:catalog:check,cli:data:check,changeset:check,virtual-tsx:check,tsrx-decls:check,lynx:demo:check.Amendment A1 (2026-09-03, agreed with a second maintainer; RFC body amended; core side in tsrx-org/tsrx#53 at c05ca370)
style-scopes.jsnow opens a scope per children list (collectOwnBlocksreads direct children only; statement-list scope machinery removed) and prunes each standalone block against the list's other children like core does, so the conformance runner asserts pruning too.<style>beside the output node of a@{}or control-flow body is the multiple-outputs parser error again (D3 reverted in core); a lone<style>output reportstsrx-style-standalone-needs-fragment. Every fixture, doc, playground example, scaffold template, evals task, and 41 website.tsrxfiles moved to the fragment form. The interim.prettierignoreentries are gone: the fragment forms parse with the published plugin.<style>is TSRX template syntax. A standalone block with a CSS body outside a@{}/control-flow body (plainreturn <section><style>…, module-level assigned template) istsrx-style-standalone-outside-templatefrom the core analyzer, surfaced throughanalyzeTsrx.<style>{expr}</style>is an ordinary element on both emitters (never stamped, noinjectStyle). The native oxc-tsrx facade rejects that shape with a bareErrorfrom its CSS reader, soparser.node.jsretries through the JavaScript parser when the source carries a<style …>{child. The fallback replay now pins 10 forms as JS-parser fallbacks (6 multiple-outputs recoveries, 4 expression-child styles) and one native-shape divergence for Track oxc port of the scoped <style> parser changes tsrx-org/tsrx#46 (cssomitted on self-closed<style />).styleMaplists every block itsapplynames — same-module blocks as well as imported reads — as injection dependencies, so touching an exported theme injects its whole apply chain first (applied before applier, once each); body-less bundles lower to astyleMapwith no sheet that only forwards the touch.tests/ssr-theme-chain.test.tspins base → theme → applier order, the body-less export, and a diamond.@{ <>…</> }is transparent grouping for the value classifier, as it already is for children normalization, so a plain function returning a styled fragment keeps the staticFragmentelement the signals tests inspect.tests/style-list-scopes.test.ts(Status class table A/B/C/D client+server, per-list hash sharing, nested fragments,applyreach) andtests/compiler/style-standalone-placement.test.ts(Rule B error forms, containers, editor collect mode; Rule C pass-through).Merged main (2026-09-05)
Main's #957, #960, and #961 landed on the statement-scoped machinery this PR replaces; the merge keeps the sibling-scope pre-pass and resolves each against it:
fix: refresh injectStyle sheets when HMR keeps the hash #957
injectStyleHMR refresh — already here (injectStyle drops a re-injection with an unchanged hash but changed CSS (HMR hazard) #938); the branch'sdata-href~=token match for React-batched multi-hash islands is kept, and main'sdocument-less test case is adopted.fix: merge styled host scope class with a spread class #961 spread
class+ scope hash — main's synthesized-class merge flag (isSynthesizedClassAttr,ssrDirectSource/setHostPropSources/ssrAttrs4th cell,mergeClass) applies unchanged to the attributes the pre-pass stamps; main's fixtures already use the fragment form and pass on this model.fix: write style-block class maps to ref targets #960
<style ref>class maps — deliberately not carried over.refon a block stays unsupported in Octane (the attribute is ignored, as before fix: write style-block class maps to ref targets #960) pending its removal from TSRX; the fixture, tests, and changeset from fix: write style-block class maps to ref targets #960 are dropped and the immutability fixture no longer uses it. Compiler silently drops <style ref={…}> (class-map ref supported by the tsrx JSX targets) #940 therefore stays a non-goal here.Bugbot on the merged head: a
style(expr)that is only part of a stamped element's class value (array, conditional, logical, template) now yields its value alone and the stamp adds the chain once, so a composed class never carries a hash twice; a whole-valueclass={style(expr)}keeps its chain-first form, also through wrappers (589da18).Validation (current head)
pnpm installagainst the released packages; lockfile has no git-hosted entries.pnpm sync(parity audit hashes, evals manifest, rules, context budget).pnpm format:files:check,pnpm typecheck:files,pnpm changeset:checkon the changed files.node --test scripts/package-pack-canaries.test.mjs.octane, plus the style/conformance/SSR/hydration suites after merging refactor(website): dogfood sibling-scoped styles in CoreApiDemo #958, fix(octane): allow complete style scopes inside Hydrate splits #959, fix: address high-priority server, SSR, and adapter defects #968 and the Bugbot fix (see PR checks for the full matrix).pnpm format:check(the released prettier plugin reformats three.tsrxfixtures).Provenance
agent-authored)Follow-ups
#935 (relax
OCTANE_HYDRATE_SPLIT_STYLE), #936 (dogfood CoreApiDemo), tsrx-org/tsrx#46 (oxc-tsrx port).🤖 Generated with Claude Code
Note
Medium Risk
Touches compiler emission, SSR CSS collection, and hydration class/hash matching across client and server; breadth is mitigated by conformance fixtures and extensive tests described in the PR.
Overview
Adds sibling-scoped
<style>blocks to.tsrxper RFC #1: a block styles its siblings and descendants in the same children list (fragment siblings when you need to style a host element), with nested scopes, shared hashes per list,const theme = <style>…</style>class maps ($class), and<style apply={theme} />composition. The Octane compiler gains astyle-scopes.jspre-pass (replacing the old per-component scoping helpers), client/server emitinjectStyle/styleMapwith theme-chain ordering, and{style(expr)}resolves the scope chain in class positions.Amendment A1 tightens placement (fragment-wrap for lone blocks, diagnostics for CSS outside template bodies, plain TSX
<style>{css}</style>passthrough with JS-parser fallback). Hydrate split children may include a scope when the whole lexical scope stays inside the boundary. Docs, authoring rules/skills, scaffoldlinkTheme, HarborPriceBadge, eval corpus (scoped-styles), and changesets document the model;refon scoped<style>from merged main is not carried forward.Reviewed by Cursor Bugbot for commit 81e1015. Bugbot is set up for automated code reviews on this repo. Configure here.