Skip to content

rx.ui: compiled component package and JS shell fixes - #8037

Draft
FarhanAliRaza wants to merge 27 commits into
mainfrom
ccr-5792db6b-a8cwgd
Draft

FarhanAliRaza wants to merge 27 commits into
mainfrom
ccr-5792db6b-a8cwgd

Conversation

@FarhanAliRaza

@FarhanAliRaza FarhanAliRaza commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Draft, work in progress. One PR for the whole rx.ui plan for now; it may be split along the step boundaries below later, so each step lands as its own merge commit.

What this is

reflex-components-ui, exposed as rx.ui: a compiled component set. The Reflex compiler emits plain HTML elements with static class names, StyleX compiles the styles in the app's own Vite build into one small stylesheet, and behaviour comes from the browser plus a small set of shared hooks. No component library ships to the browser. Props match today's Radix-backed rx.* and the visual target is pixel parity with Radix Themes, so moving a component is an import change. reflex-components-radix is not touched.

It also carries three fixes to Reflex's JS shell that every existing app gets, independent of the new package.

Steps

Shell (all existing apps):

  • 1. Stop importing whole libraries into the app root
  • 2. Scripts start after first paint on prerendered pages
  • 3. State runtime and toaster ship only when used

Foundation:

  • 4. Plugin.get_vite_plugins() hook in reflex-base
  • 5. Package scaffold, rx.ui namespace, JS tooling in CI
  • 6. UIPlugin: StyleX in the build, rx.ui.box as a plain element
  • 7. Tokens, color scales, themes, rx.ui.theme (StyleX modules landed; Theme, rx.ui.theme, rx.ui.tokens in progress)
  • 8. Style compiler, style tables, typed style
  • 9. Parity harness and behaviour contract (Chromium only so far; a readiness race is being fixed)

Components:

  • 10. Layout and typography (19)
  • 11. Display and actions (12)
  • 12. Form controls (13)
  • 13. Overlays and disclosure (10)
  • 14. App-level: theme panel, color-mode controls (3)

Proof and adoption:

  • 15. Benchmark app and CI budgets
  • 16. Emotion-free pages in reflex-base (in progress)
  • 17. Migration codemod and guide
  • 18. Docs: library pages, styling guide

Needs a maintainer's eye

  • Step 1 flips a default (frontend_lazy_bundled_libraries=True, breaking fragment).
  • Step 2 delays hydration by design. First working click on a throttled connection moves from about 4.1 s to about 4.6 s while paint moves 1.28 s earlier; a click made before hydration is replayed, a pointerdown is not.
  • Step 3 changes the connection-error message of a stateful app that sends no toast from a sonner toast to a plain notice.
  • Step 8: one runtime case is slower than Emotion (1,000 rows all bound to one changing value: 14.7 ms against 12.7 ms).
  • Step 9: Firefox and WebKit have not run yet. The CI job added here is their first run.

Landed so far

1. Dynamic-component libraries load on demand. root.jsx no longer imports whole library namespaces (such as @radix-ui/themes) so that dynamic components can find them. Each registered library gets a small generated module that becomes its own chunk, fetched the first time a dynamic component needs it; libraries the compiler registered are only kept when the app actually renders a dynamic component. Blank app JS, production build, gzip of every client .js: 239.8 kB before, 170.8 kB after. An app with a dynamic Radix component ships 189.0 kB up front plus a 53.9 kB chunk on first use.

Behaviour change, with a breaking fragment in reflex-base: frontend_lazy_bundled_libraries now defaults to True. A custom script that reads a library straight from window.__reflex must first await window.__reflex_load(["<library>"]), or the app sets the flag to False to get the old eager root. Dynamic components and rx.bundle_library need no change. Known gap: a failed chunk fetch surfaces as an unhandled promise rejection, as a failed dynamic import did before.

2. Scripts start after first paint on prerendered pages. A wrapper around react-router's Scripts ($/utils/scripts) drops the module preloads from a prerendered document and replaces the module script with one small inline script that adds them back on the first paint entry, on the first pointer or key input, on a visibility change, or after 1 s, whichever comes first. Dev mode and client-rendered routes are untouched. Lighthouse 12 mobile on the blank app, median of five runs: simulated 90 to 91 / LCP 2.85 s before, 100 / 1.21 s after; with real throttling 88 to 89 / 2.91 to 3.06 s before, 98 / 1.75 s after. CLS stays 0.

Cost, measured as time from navigation to a click taking effect (medians of two 11-run sets): about 116 ms to about 150 ms on a fast connection, about 4.09 s to about 4.6 s on slow 4G with 4x CPU. The last click made before hydration is dispatched again afterwards unless it landed on a link or a form control; only click is replayed. The window load event no longer waits for the app's scripts, so an end-to-end test that types or presses right after navigation can run before hydration. The wrapper reads react-router internals and falls back to react-router's own output if it does not find the module script. A dev checkout with an existing .web needs reflex init after pulling this.

3. State runtime and toaster ship only when used. The socket, session, cookie and storage-sync code moved from utils/state.js to a new utils/socket.js that only a stateful app's context imports, so an app with enable_state=False bundles no Socket.io and no cookie library and opens no websocket. The default toaster is bundled only when a toast is used: a toast call compiled into a page or app wrap, an on_load toast, a state handler, exception handler or app-module helper that refers to rx.toast, or an explicit App(toaster=...). Measured as gzip of every client .js of an rx.el-only app: stateless 158.7 kB to 130.8 kB, stateful with no toast 161.6 kB to 153.9 kB.

Visible change: a stateful app that sends no toast shows connection errors (and any toast the detection missed) through a small plain-DOM notice instead of a sonner toast, with a one-time console hint. A stateless app that calls the toaster from a raw rx.call_script string gets none. utils/state.js keeps its full export list. Open: test_toast.py::test_upload_callbacks failed one case in 2 of 3 full-suite runs in one container and passed alone, on this branch and on main; cause not established.

4. Vite plugin hook. A Reflex plugin overrides Plugin.get_vite_plugins() and returns rx.plugins.VitePluginEntry(call=..., imports=[...]) objects; vite.config.js renders them ahead of reactRouter(), in rxconfig.py plugin order. Shared import statements are written once, and a malformed entry stops the compile with an InvalidVitePluginError naming the plugin. With no entries the generated file is byte-identical to today's (compared across 3072 argument combinations of the template). Documented under "Adding Vite Plugins" in docs/api-reference/plugins.md.

5. Package scaffold. packages/reflex-components-ui is an installable package. rx.ui resolves lazily to it and import reflex does not import it (import time unchanged within noise, against a +5 ms limit). It is an optional extra: without it rx.ui raises `rx.ui` requires the reflex-components-ui package, which is not installed. Install it with `pip install 'reflex[ui]'`. The wheel embeds js/src; in a checkout the JS resolves in place. The JS package has its own lint (no JSX or React components in js/src, no barrel files, StyleX rules), strict type-check, a generator driver with a drift check, and vitest, run by a new ui-js-checks job that is part of unit-tests-gate. Note: the ui extra is unpinned until the package has a first release, so pip install 'reflex[ui]' from PyPI cannot resolve before then.

6. UIPlugin and rx.ui.box. With rx.plugins.UIPlugin() in rxconfig.py, rx.ui.box compiles to a plain <div> whose style is declared in the module that renders it and folded by StyleX to a className string in the app's Vite build. Without the plugin, compile stops with rx.ui components need rx.plugins.UIPlugin() in rxconfig.py plugins. Measured on a box-only app against a blank one: build +0.18 s, cold dev render +0.19 s, CSS +119 B gzipped, no new JS chunk, zero StyleX runtime in the client JS. base.css declares the cascade order once (@layer __reflex_base, theme, base, reflex-ui, components, utilities;): verified with Tailwind v4 that a class_name utility beats a component, a component beats the resets, and unlayered CSS beats both. The shipped Vite wrapper fixes two StyleX plugin defects: the CSS asset rename that breaks react-router build, and a chunk keeping its hashed name while its content changed (covered by a rebuild test).

Limits: Tailwind v3 has no native cascade layers, so its preflight and utilities beat rx.ui styles (only v4 is tested). In dev, a cold first load shows the element unstyled for up to about 150 ms. A component held in state never reaches StyleX: literal styles fall back to an inline style, a conditional or state-bound style there is a compile error. Adds reflex_base.components.dynamic.is_rendering_dynamic_component().

7a. Tokens, color scales and themes as StyleX modules. 81 modules generated from the token CSS of the @radix-ui/themes version Reflex installs (3.3.0, pin asserted), drift-tested: one defineVars module per color scale and token group with Radix's variable names kept literal (--space-4, --blue-9, --accent-9), light-dark() for the two appearances and display-P3 values under @supports, and createTheme classes for each accent, gray, radius, scaling and panel background. A module's CSS is emitted only when something imports it. A sweep in headless Chromium compares every custom property Radix defines with the real stylesheet and Theme component: 10,556 theme combinations x 1,068 properties, in sRGB and display-P3, zero differences (npm run sweep, about four minutes; a 470-theme subset runs in npm test). Two listed exceptions: shadow tokens carry transparent layers so one definition serves both appearances, and four tokens Radix declares as inherit are undefined on both sides. Gzipped CSS: tokens alone 2.0 kB, a whole root theme with one accent and one gray 4.6 kB, about 0.87 kB per extra accent (all 26: 26.4 kB).

Known limit: a nested theme that sets only a gray while inheriting the gray accent keeps the outer gray as its accent, because the cascade cannot see the inherited accent the way React context does.

8. Style compiler and typed styles. reflex_components_ui.style has StyleProps (a TypedDict of 521 CSS properties with their keywords, generated from the pinned StyleX's own types and drift-tested), ComponentStyles for a component's style table (base, variants, compound, parts), and lower / merge / emit. A component's table and the user's style=, CSS keyword arguments and layout props are merged in Python, by property, with the user's value last, and emitted as one declaration per distinct result in the module that renders the element:

const sx_62330ed6a3 = stylex.create({ s: {"padding": "var(--space-3)", "boxShadow": {"default": "var(--shadow-2)", ":hover": "var(--shadow-3)"}, "width": "var(--v0)"} });
const sx_62330ed6a3_c = stylex.props(sx_62330ed6a3.s).className;
jsx("div",{className:sx_62330ed6a3_c, style:({ "--v0": (state.width) ?? "initial" })})

_hover blocks and responsive values become per-property conditions, shorthands expand to longhands, rx.color("ruby", 9) becomes var(--ruby-9) plus an import of its scale module, a state value becomes a CSS variable set inline, and a variant prop bound to state becomes a module-level table of folded class strings the element indexes. No shape leaves a StyleX runtime call, so no page ships the StyleX runtime. In the generated stubs style is typed Sequence[StyleProps] | StyleProps | Var[Mapping[str, Any]] | Breakpoints | None, so style={"paddng": "1em"} is a type error; a misspelled keyword argument is a compile error: rx.ui.card: unknown CSS property "paddng". Did you mean "padding"?. A nested selector is a compile error that says to style the child directly.

Measured: compiling 1,000 rx.ui.box against 1,000 rx.box takes 0.99x for flat styles and about 0.7x for styles with hover, responsive values and shorthands (limit 1.15x); Vite build 0.98x of the equivalent Emotion page (limit +20%), which needed the shipped wrapper to hand StyleX only the declaration lines and cache per file, because React Router transforms a route module seven times per build. Re-rendering 1,000 rows: 10.9 ms against Emotion's 17.3 ms for literal styles, 19.8 against 27.7 ms with each row bound to its own value, and 14.7 against 12.7 ms with all rows bound to one changing value (slower: an inline custom property changes on every row where Emotion swaps one shared class).

Consequences of StyleX silently dropping some shorthands: border* is always split per side, background is split into color and image where it can be and is otherwise a compile error naming the longhands (so background=State.color must become background_color=State.color), and animation is a compile error. A property StyleX's types do not know is rejected; --custom properties pass.

9. Parity harness and behaviour contract. uv run python scripts/ui_parity.py [component] builds one generated app and, per component, renders a declared matrix (variants, sizes, colors, appearance, hover / focus-visible / active, viewport widths) in rx.* and in rx.ui, then compares pixels (a pixelmatch port with anti-aliasing detection), computed styles on 70 properties and the accessibility tree, and writes a browsable report with reference, candidate and diff images per cell. A behaviour contract is declared once and run against both systems: server HTML, hydration with no warnings, JavaScript disabled, plus the component's own steps. tests/units/reflex_components_ui/test_api_parity.py compares props, literal values and event triggers with the Radix counterpart. Intended differences live in parity/allowlist.toml with reasons; an unused entry fails. CI: ui-parity (Chromium, uploads the report, 15 minute budget) and ui-contracts (Chromium, Firefox, WebKit), both in integration-tests-gate.

State: box shows zero differing pixels over 8 cells, and a deliberate 3px padding change fails with the cell, the pixel count and the image paths. Run time scales at about 11 to 16 ms per cell at rest and 0.14 s per interactive cell. Firefox and WebKit have not been run (the development containers cannot download them). rx.ui.box still lacks the 16 global HTML attribute props of rx.box and passes API parity only through an allowlist entry; the first component wave removes it. A readiness race in the runner (it could read a page before hydration committed) is being fixed.

All Submissions:

  • Have you followed the guidelines stated in CONTRIBUTING.md file?
  • Have you checked to ensure there aren't any other open Pull Requests for the desired changed?

Type of change

  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected): the default flip in step 1
  • This change requires a documentation update

New Feature Submission:

  • Does your submission pass the tests? (per step; see "Landed so far")
  • Have you linted your code locally prior to submission?

Changes To Core Features:

  • Have you added an explanation of what your changes do and why you'd like us to include them?
  • Have you written new tests for your core changes, as applicable?
  • Have you successfully ran tests with your changes locally?

https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v

Plugin.get_vite_plugins() returns VitePluginEntry objects, each carrying the
import statements and the expression to place in the plugins array of the
generated vite.config.js, ahead of reactRouter(). Entries keep rxconfig plugin
order then entry order, shared imports render once, and a malformed entry
raises InvalidVitePluginError naming the plugin. With no entries the rendered
file is unchanged.

Claude-Session: https://claude.ai/code/session_014AwvTNGETBu7Fzvwjqecm4
An installable, empty package: `pip install 'reflex[ui]'` adds
reflex-components-ui, which `rx.ui` resolves on first use. reflex does not
depend on it, and without the extra `rx.ui` raises an error that names
the extra.

The package embeds its javascript, js/src, in the wheel, and reads it in
place in a checkout. js/ carries its own tooling: ESLint with the StyleX
rules and rules against components and barrel files in js/src, a type
check from JSDoc, vitest, and a driver that writes generated files and
fails CI when a committed one drifts. Each lint rule has a test that
feeds it a file it must reject.

Claude-Session: https://claude.ai/code/session_014AwvTNjM7Q5Te2EY2FTHrZ
@FarhanAliRaza FarhanAliRaza added documentation Improvements or additions to documentation enhancement Anything you want improved labels Nov 27, 2026 — with ChatGPT Codex Connector
@greptile-apps

greptile-apps Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 3/5 · The PR still needs fixes before merging because state-held boxes can fail to build and grouped state-bound variants can lose valid styles.RetriggerView in GreptileConfidence Score: 3/5

[High impact] The PR changes browser startup and generated frontend output across existing apps, alongside a new optional UI package.

The PR still needs fixes before merging because state-held boxes can fail to build and grouped state-bound variants can lose valid styles.

Findings

  1. P1 State-held boxes fail to build ▶
  2. P1 Grouped variants lose valid styles ▶
  3. P2 Malformed entries lose plugin details ▶
  4. P2 Tests check only fragments ▶
  5. P2 New tests lack required docstrings ▶
  6. P2 Earlier styles override later ones ▶
  7. P2 Inherited styles lose properties ▶
  8. P2 Old background settings remain ▶
  9. P2 Valid styles fail type checks ▶
  10. P2 Borders use the wrong sides ▶
  11. P2 Local font definitions are missing ▶
  12. P2 Closed toasts still block clicks ▶
  13. P2 Invisible stack blocks clicks ▶
  14. P2 Forms can reset twice ▶
  15. P2 Accessibility changes go unchecked ▶
  16. P2 Default layout values disappear ▶
  17. P2 Later styles do not win ▶

Summary

This PR adds the compiled rx.ui package and reduces the JavaScript existing apps load.

  • Dynamic components load their registered libraries only when needed.
  • Prerendered pages start their scripts after the page begins to paint.
  • Apps include backend connection and toast code only when they need it.
  • rx.ui.box builds into HTML with styles folded into the app stylesheet.
  • Radix color scales and themes are available as generated StyleX modules.
  • Reflex plugins can add entries to the app's generated Vite config.

Reviews (11) · Last reviewed commit: "Merge the parity harness readiness fix: ..." · Reviewed by Greptile

Comment on lines +659 to +664
if isinstance(entry.imports, str):
return (
f"has imports={entry.imports!r}, which must be a sequence of import "
"statements, not a single string"
)
for statement in entry.imports:

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.

P2 Malformed entries lose plugin details

_vite_plugin_entry_problem rejects a string for imports but assumes every other value can be looped over. For example, VitePluginEntry(call="a()", imports=None) raises a plain TypeError before _get_vite_plugins can add the plugin name and entry number. This makes a plugin mistake harder to trace.

Check the container before looping and add a test so this case raises the promised InvalidVitePluginError.

root.jsx imported the whole namespace of every library registered for
dynamic components, which kept all of Radix Themes in the chunks every
page loads. frontend_lazy_bundled_libraries now defaults to True, and the
lazy path is fixed so it actually splits:

- Each optional library is loaded through a generated module under
  utils/dynamic_libraries/. Importing the library itself from root.jsx
  made the bundler fold the namespace back into a statically loaded chunk
  whenever a page also imported from it.
- Libraries the compiler registered are only made loadable when a page
  renders a dynamic component (one evaluated by evalReactComponent).
  Libraries the app registered with bundle_library always are.

A production build of the blank template goes from 239.8 kB to 170.8 kB
of gzipped JS.

Claude-Session: https://claude.ai/code/session_014AwvTL12cX7g6Zn6HEiwG1
@codspeed

codspeed Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

1 warning

⚠️ 21 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 146 untouched benchmarks
⏩ 8 skipped benchmarks1


Comparing ccr-5792db6b-a8cwgd (c9dfa02) with main (6f5c39c)

Open in CodSpeed

Footnotes

  1. 8 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

Comment on lines +634 to +637
assert (
' "d3-format": () => import("$/utils/dynamic_libraries/d3_format")'
".then((module) => module.default),"
) in code.splitlines()

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.

P2 Tests check only fragments

These new assertions check whether one loader line appears in the generated file. CLAUDE.md requires tests of generated code to compare the complete output, not fragments. These checks can pass when other loaders are missing or extra imports appear.

Compare the full expected output, as test_compile_app_root_loads_optional_libraries_on_demand already does. Apply this to the other new loader assertions too, including those in test_dynamic_components_codegen.py. This repository requirement must be met before merging.

Context Used: CLAUDE.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment on lines +539 to +540
def test_rewrite_component_import(module: str, is_reflex_package: bool, expected: str):
assert _rewrite_component_import(module, is_reflex_package) == expected

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.

P2 New tests lack required docstrings

This new test starts directly with an assertion, but CLAUDE.md requires Google-style docstrings on all functions, including argument descriptions where needed. Add them here and to the other new tests missing them, including those in test_init.py and test_js_package.py. This repository requirement must be satisfied before merging.

Context Used: CLAUDE.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

A prerendered page is visible without javascript, but react-router's
<Scripts> preloads every route module from the head, where the downloads
compete with the stylesheet the page needs to paint.

The document's Scripts component now renders $/utils/scripts, which wraps
react-router's. On a prerendered page it leaves the module preloads out of
the document and replaces the module script with an inline one that adds
both back on the first paint. A user input, a hidden tab, a browser without
paint timing or a one second timeout start them as well. Dev mode and the
SPA fallback render what react-router renders.

The last click that comes before the page can handle one is dispatched
again after hydration, unless the browser already acted on it.

Claude-Session: https://claude.ai/code/session_014AwvTNacWVsm7SEvVjhfGM
An app without state bundled Socket.io, the cookie library and the code
that connects to the backend, and every app bundled the toaster whether
or not it ever showed a toast.

State runtime. The connection to the backend (socket, session, browser
storage sync, the event loop over the socket) moves out of
utils/state.js into utils/socket.js. Only the compiled context module of
an app with state imports it; it registers itself with utils/state.js
through a registry in the new utils/event_loop.js, which also holds the
event queue the two share. utils/state.js keeps every export it had:
the ones that need the connection delegate to it, and useEventLoop runs
the events the browser handles by itself (scripts, redirects, refs,
storage, downloads) when there is none. _remove_cookie writes the
expired cookie itself, so it needs no cookie library.

Toaster. The app's default toaster is bundled when the app sends a
toast: a toast call compiled into a page or an app wrap carries a
ToasterRequest app wrap in its var data, an on_load toast is read from
the event, and the functions of the state tree are read for references
to rx.toast (by name, through helpers in the app's own modules). A
toaster passed to rx.App is always bundled. Since code that runs on the
backend cannot be ruled out by reading names, an app with state that
gets no toaster gets a plain-DOM stand-in for the toast function
instead, so a toast sent anyway and a connection error still show. The
connection toaster no longer asks for the toaster by itself.

Total gzipped client JS of a production build, rx.el only, no Radix or
Tailwind plugin: 158.7 kB to 130.8 kB without state, 161.6 kB to
153.9 kB with state and no toast.

Claude-Session: https://claude.ai/code/session_014AwvTNmJCFr12bYVhV8efZ
UIPlugin wires StyleX into the app's Vite build: the compiler and its
plugin as development dependencies, the javascript package copied to
.web/reflex-ui, and base.css imported first by the root stylesheet to
declare the cascade layer order.

UIComponent renders a plain element. Its style is emitted as a
stylex.create declaration into whichever module renders the element, and
spread with stylex.props, which StyleX folds to a class name string. A
component held in state falls back to an inline style.

The Vite wrapper fixes the React Router build (the renamed stylesheet),
names the chunk that links the stylesheet after the compiled styles so a
changed style never alters a file under an unchanged name, and loads the
StyleX development module from the client entry.

Claude-Session: https://claude.ai/code/session_014AwvTPBw2eYQiwgtLmDkpC
Recording stopped when the scripts module was imported, which left the time
until hydrateRoot with no one handling a click. The entry points now take
the click over immediately before they hydrate.

Claude-Session: https://claude.ai/code/session_014AwvTNacWVsm7SEvVjhfGM
Comment on lines +143 to +148
if is_rendering_dynamic_component():
return {}
# The plugin installs it as a development dependency.
return {
"@stylexjs/stylex": ImportVar(
tag="*", alias="stylex", is_default=True, install=False

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.

P1 State-held boxes fail to build

For an rx.ui.box in initial state, _compile_initial_state() calls _get_all_imports() before the dynamic-render flag is set. That caches and bundles @stylexjs/stylex. The serializer then reuses those imports even though it renders inline styles.

Without UIPlugin, the frontend therefore gets a generated module importing StyleX, but nothing installs that package because this import has install=False. The build fails on a path meant to work without the plugin. Collect initial-state imports in the dynamic context too, and prevent cached imports from leaking between the two rendering paths.

StyleProps is generated from the type definitions of the pinned StyleX
package, so a type checker catches a misspelt CSS property or keyword.
lower() turns a style into the style object StyleX compiles: conditions per
property, media queries for responsive values, color scales with the module
each needs, and shorthands split into longhands. merge() resolves a
component's style table against the props and the style of one element, by
property with the last one winning, and returns the alternatives of a prop
bound to state without resolving them.

StyleX silently drops the border and background shorthands, so both are
always split, and animation is refused with what to set instead.

Claude-Session: https://claude.ai/code/session_014AwvTMtxnRhQBAehyWjUwF
…erging

Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v

# Conflicts:
#	packages/reflex-components-ui/README.md
#	packages/reflex-components-ui/src/reflex_components_ui/style/__init__.py
Comment on lines +470 to +475
for combo in product(*[domains[member] for member in group]):
change = _difference(
static, merged_with(dict(zip(group, combo, strict=True)))
)
if change:
values[combo] = finish(change, unset=True)

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.

P1 Grouped variants lose valid styles

_merge_dynamic only builds combinations from values explicitly listed in the table. When two state-bound props share a compound style, a valid value of one prop is lost if the other has an unlisted value. For example, a tone="red" variant combined with a loading="true" compound style produces no alternative for tone="red", loading=False. The static style excludes both bound props, so callers cannot recover the red variant. Include a no-match fallback for each grouped prop.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment on lines +685 to +687
_put(out, camel, path, value)
if replaces is not None and not path:
replaced.extend(replaces)

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.

P2 Earlier styles override later ones

A retained shorthand does not remove earlier longhands from the same style. For example, lower("box", {"margin_top": "1em", "margin": "var(--gap)"}) keeps both marginTop and margin. _leaf only records what to remove from a previous layer, and apply_layer adds the current layer’s stale longhand back. StyleX gives the longhand priority, so the later spacing value loses. Remove replaced values from the current layer too.

Comment on lines +503 to +508
parts = (
("Width", "medium" if width is None else width),
("Style", style or "none"),
("Color", color or "currentcolor"),
)
return [(f"{side}{part}", item) for side in sides for part, item in parts]

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.

P2 Inherited styles lose properties

border: inherit becomes width medium, style none, and color inherit, so it removes the visible border instead of inheriting it. background: inherit similarly inherits only the color and resets the image to none. Handle CSS-wide keywords before splitting these shorthands, and apply keywords such as inherit, initial, and unset to every affected longhand.

Comment on lines +533 to +535
if _IMAGE.match(value.strip().lower()):
return [("backgroundColor", "transparent"), ("backgroundImage", value)]
return [("backgroundColor", value), ("backgroundImage", "none")]

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.

P2 Old background settings remain

_background resets only the color and image, but CSS background also resets size, position, repeat, attachment, origin, and clip. For example, merging a base background_size="cover" with a later background="url(new.png)" keeps cover instead of resetting it to auto. Emit the remaining reset values when expanding the shorthand.

Comment on lines +266 to +268
_Value: TypeAlias = (
_T | Sequence[_T] | Breakpoints[Any, Any] | Mapping[str, _T | Mapping[str, _T]]
)

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.

P2 Valid styles fail type checks

The generated _Value type excludes None, although lower supports it to unset a property and skip a responsive breakpoint. Valid inputs such as {"width": None} and {"width": [None, "50%"]} therefore fail when assigned to StyleProps. Include None in the supported value shapes and add these cases to the type-check fixtures.

Comment on lines +165 to +167
"borderBlock": ("borderTop", "borderBottom"),
"borderBlockStart": ("borderTop",),
"borderBlockEnd": ("borderBottom",),

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.

P2 Borders use the wrong sides

borderBlock, borderBlockStart, and borderBlockEnd are expanded to physical top and bottom borders. That changes their meaning when writing_mode is vertical, where the block sides are left and right. Preserve the logical sides by expanding to borderBlockStartWidth, borderBlockStartStyle, and the corresponding logical longhands.

Every custom property Radix Themes defines becomes a StyleX variable with the
same name and value, generated from the token stylesheet of the version the
Radix components install. A color is one light-dark() value with a display-P3
variant, so an appearance is the color-scheme of an element; accent, gray,
radius, scaling and panel are createTheme classes, one module per accent and
per gray so an app carries only what it imports.

A sweep in headless Chromium compares every custom property under these
modules with @radix-ui/themes and its Theme component: part of it in npm test,
the whole product of the theme props in npm run sweep.

Claude-Session: https://claude.ai/code/session_014AwvTMTA184ecs3JHWuggN
…leX modules

Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v

# Conflicts:
#	packages/reflex-components-ui/README.md
#	packages/reflex-components-ui/js/scripts/generate.js
#	tests/units/reflex_components_ui/test_js_package.py
export function parseTokens(css) {
/** @type {Model} */
const model = { tokens: new Map(), themes: {}, element: {} };
postcss.parse(css).walkRules((rule) => {

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.

P2 Local font definitions are missing

parseTokens reads style rules but skips @font-face declarations. The generated font lists still name aliases such as Consolas (Custom), but no shipped stylesheet defines them. On Windows, code styled with --code-font-family therefore skips installed Consolas and falls back to another monospace font. This changes text widths and wrapping compared with Radix. Preserve the local font aliases when generating the theme files.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment on lines +110 to +114
const remove = () => {
clearTimeout(timer);
notices.delete(id);
notice.remove();
};

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.

P2 Closed toasts still block clicks

remove deletes the notice but leaves its fixed stack in document.body. The empty stack still has padding, the highest stacking order, and normal pointer events. After a toast closes—or a connection error clears—this invisible box keeps intercepting clicks in that corner. Remove an empty stack, or disable pointer events on the stack and restore them on notices.

Comment on lines +110 to +114
const remove = () => {
clearTimeout(timer);
notices.delete(id);
notice.remove();
};

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.

P2 Invisible stack blocks clicks

When the last plain notice closes, remove() deletes the notice but leaves its fixed-position stack on the page. The empty stack still has 1rem padding and the highest z-index, so it blocks clicks in that corner after a connection error clears or a toast expires. Remove the stack when it becomes empty, or let clicks pass through the stack while keeping notices clickable.

Comment on lines +69 to +70
const ACTS_WITHOUT_SCRIPTS =
"a[href],area[href],input,select,textarea,label,summary,[contenteditable]";

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.

P2 Forms can reset twice

replayEarlyClick replays clicks on native buttons even when the browser already acted on them. ACTS_WITHOUT_SCRIPTS excludes inputs but not reset or submit buttons. If a user resets a form and starts typing while scripts load, the replay resets the form again when hydration finishes and erases those edits. Exclude buttons with native actions, including clicks on their children, from replay.

One command, scripts/ui_parity.py, checks an rx.ui component against the
Radix component it replaces. A production app generated from the
declarations in packages/reflex-components-ui/parity renders each
component's matrix in both systems; the runner compares pixels (the
pixelmatch method, anti-aliasing ignored), computed styles and the
accessibility tree per cell, and runs each step of a behaviour contract
against both systems in whichever engines are asked for. A matrix says
which dimensions cross and which are swept, the cells at rest of a page
load are read from one screenshot, and hover, focus and active are driven
through the pointer and the keyboard.

Intended differences live in parity/allowlist.toml with a reason, per
component and per engine where needed; an entry nothing matches fails.
tests/units/reflex_components_ui/test_api_parity.py compares props, types
and event triggers with the same file.

The integration workflow gains ui-parity (Chromium, report uploaded, 15
minute budget) and ui-contracts (Chromium, Firefox, WebKit), both behind
the gate. box is the first component: zero differing pixels.

Claude-Session: https://claude.ai/code/session_014AwvTQ75r2sBu4cRnbDwHn
Comment on lines +911 to +915
a11y = None
if cell.state != REST:
images, styles = _drive(
current, cell, states[cell.state], frames, clips
)

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.

P2 Accessibility changes go unchecked

run_matrix reads the accessibility tree only on the first page load and skips it for every interactive cell. A component can show the right pixels but expose the wrong accessible name or expanded state after interaction, and the matrix still passes. Responsive content can also expose a different tree at another screen size.

Read and compare the tree in each tested environment and after entering each interactive state.

Join the lowering and merging of the style package with the emitter into the
style compiler of the rx.ui components.

A component's style table, its layout props and the element's style are
merged once in Python. Each distinct result is declared once per module,
followed by a constant that StyleX folds into its class names, so no shape
needs the StyleX runtime:

- a literal is an atomic class in the constant;
- a value bound to state is `var(--vN)` in the declaration and a custom
  property in the element's inline style;
- a variant prop bound to state gets one style per value, folded into a
  table of class names that the element indexes;
- a whole style from state is the inline style.

UIComponent splits keyword arguments into props, event triggers, attributes,
layout props and CSS properties, raises a StyleError where the component is
created, binds `Part` children to the parts of the table, applies the styles
of the app, and falls back to an inline style in a component held in state.

The stub generator takes a per-class annotation for a prop
(`_pyi_overwrite_types`, `_pyi_imports`), which types `style` of every rx.ui
component as CSS.

The Vite plugin hands StyleX only the statements that declare styles and
compiles a module once per build: React Router transformed a route module
seven times, each a whole pass of Babel.

Claude-Session: https://claude.ai/code/session_014AwvTNpEJAmVnKpLAWUGN1
Comment on lines +206 to +212
self._layout = (
{prop: kwargs.pop(prop) for prop in layout_props if prop in kwargs}
if layout_props
else None
)
super()._post_init(*args, **kwargs)
self._merge_styles()

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.

P2 Default layout values disappear

_layout reads only explicit keyword arguments. A subclass declaring gap: Var[str] = field(default=LiteralVar.create("3")) therefore gets no gap when callers omit it. _exclude_props also keeps the field off the element, so the default never takes effect.

Read layout defaults after initialization, then apply explicit values over them.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment on lines +203 to +205
self._styles: list[Any] = [_combine(written)] if written else []
if inline is not None:
self._styles.append(inline)

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.

P2 Later styles do not win

Whole-style Var values bypass the documented style order:

  • In rx.ui.box(style=State.styles, color="blue"), a color from State.styles still wins. The keyword becomes a class, while the dictionary becomes an inline style.
  • Lists retain only the last whole-style Var, dropping unrelated properties from earlier dictionaries.

Combine these dictionaries in input order and apply later CSS keywords over them.

A fiber key on a frame is set while React still renders the hydration,
before Emotion moves its prerendered style tags and before any effect
runs, so the look runner could measure a style tag as the Radix box and
the contract runner could drive a page whose hooks were not attached.
Every page of the harness app now ends in a marker whose effect flags
the document, both runners wait for the flag, and a frame's element is
its first child that renders.

Claude-Session: https://claude.ai/code/session_014AwvTQ75r2sBu4cRnbDwHn

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation enhancement Anything you want improved

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant