Repository navigation
rx.ui: compiled component package and JS shell fixes - #8037
FarhanAliRaza wants to merge 27 commits into
Conversation
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
[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
SummaryThis PR adds the compiled
Reviews (11) · Last reviewed commit: "Merge the parity harness readiness fix: ..." · Reviewed by Greptile |
| 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: |
There was a problem hiding this comment.
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
Merging this PR will not alter performance1 warning
Comparing Footnotes
|
| assert ( | ||
| ' "d3-format": () => import("$/utils/dynamic_libraries/d3_format")' | ||
| ".then((module) => module.default)," | ||
| ) in code.splitlines() |
There was a problem hiding this comment.
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!
| def test_rewrite_component_import(module: str, is_reflex_package: bool, expected: str): | ||
| assert _rewrite_component_import(module, is_reflex_package) == expected |
There was a problem hiding this comment.
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
| 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 |
There was a problem hiding this comment.
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
| 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) |
There was a problem hiding this comment.
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!
| _put(out, camel, path, value) | ||
| if replaces is not None and not path: | ||
| replaced.extend(replaces) |
There was a problem hiding this comment.
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.
| 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] |
There was a problem hiding this comment.
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.
| if _IMAGE.match(value.strip().lower()): | ||
| return [("backgroundColor", "transparent"), ("backgroundImage", value)] | ||
| return [("backgroundColor", value), ("backgroundImage", "none")] |
There was a problem hiding this comment.
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.
| _Value: TypeAlias = ( | ||
| _T | Sequence[_T] | Breakpoints[Any, Any] | Mapping[str, _T | Mapping[str, _T]] | ||
| ) |
There was a problem hiding this comment.
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.
| "borderBlock": ("borderTop", "borderBottom"), | ||
| "borderBlockStart": ("borderTop",), | ||
| "borderBlockEnd": ("borderBottom",), |
There was a problem hiding this comment.
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
…n used Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v # Conflicts: # pyi_hashes.json
…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) => { |
There was a problem hiding this comment.
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!
| const remove = () => { | ||
| clearTimeout(timer); | ||
| notices.delete(id); | ||
| notice.remove(); | ||
| }; |
There was a problem hiding this comment.
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.
| const remove = () => { | ||
| clearTimeout(timer); | ||
| notices.delete(id); | ||
| notice.remove(); | ||
| }; |
There was a problem hiding this comment.
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.
…endered pages Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v
| const ACTS_WITHOUT_SCRIPTS = | ||
| "a[href],area[href],input,select,textarea,label,summary,[contenteditable]"; |
There was a problem hiding this comment.
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
Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v # Conflicts: # packages/reflex-components-ui/README.md
| a11y = None | ||
| if cell.state != REST: | ||
| images, styles = _drive( | ||
| current, cell, states[cell.state], frames, clips | ||
| ) |
There was a problem hiding this comment.
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
| 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() |
There was a problem hiding this comment.
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!
| self._styles: list[Any] = [_combine(written)] if written else [] | ||
| if inline is not None: | ||
| self._styles.append(inline) |
There was a problem hiding this comment.
Whole-style Var values bypass the documented style order:
- In
rx.ui.box(style=State.styles, color="blue"), acolorfromState.stylesstill 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
Draft, work in progress. One PR for the whole
rx.uiplan 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 asrx.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-backedrx.*and the visual target is pixel parity with Radix Themes, so moving a component is an import change.reflex-components-radixis 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):
Foundation:
Plugin.get_vite_plugins()hook inreflex-baserx.uinamespace, JS tooling in CIUIPlugin: StyleX in the build,rx.ui.boxas a plain elementrx.ui.theme(StyleX modules landed;Theme,rx.ui.theme,rx.ui.tokensin progress)styleComponents:
Proof and adoption:
reflex-base(in progress)Needs a maintainer's eye
frontend_lazy_bundled_libraries=True,breakingfragment).pointerdownis not.Landed so far
1. Dynamic-component libraries load on demand.
root.jsxno 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
breakingfragment inreflex-base:frontend_lazy_bundled_librariesnow defaults toTrue. A custom script that reads a library straight fromwindow.__reflexmust firstawait window.__reflex_load(["<library>"]), or the app sets the flag toFalseto get the old eager root. Dynamic components andrx.bundle_libraryneed 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
clickis replayed. The windowloadevent 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.webneedsreflex initafter pulling this.3. State runtime and toaster ship only when used. The socket, session, cookie and storage-sync code moved from
utils/state.jsto a newutils/socket.jsthat only a stateful app's context imports, so an app withenable_state=Falsebundles 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, anon_loadtoast, a state handler, exception handler or app-module helper that refers torx.toast, or an explicitApp(toaster=...). Measured as gzip of every client.jsof anrx.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_scriptstring gets none.utils/state.jskeeps its full export list. Open:test_toast.py::test_upload_callbacksfailed one case in 2 of 3 full-suite runs in one container and passed alone, on this branch and onmain; cause not established.4. Vite plugin hook. A Reflex plugin overrides
Plugin.get_vite_plugins()and returnsrx.plugins.VitePluginEntry(call=..., imports=[...])objects;vite.config.jsrenders them ahead ofreactRouter(), inrxconfig.pyplugin order. Shared import statements are written once, and a malformed entry stops the compile with anInvalidVitePluginErrornaming 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" indocs/api-reference/plugins.md.5. Package scaffold.
packages/reflex-components-uiis an installable package.rx.uiresolves lazily to it andimport reflexdoes not import it (import time unchanged within noise, against a +5 ms limit). It is an optional extra: without itrx.uiraises`rx.ui` requires the reflex-components-ui package, which is not installed. Install it with `pip install 'reflex[ui]'`.The wheel embedsjs/src; in a checkout the JS resolves in place. The JS package has its own lint (no JSX or React components injs/src, no barrel files, StyleX rules), strict type-check, a generator driver with a drift check, and vitest, run by a newui-js-checksjob that is part ofunit-tests-gate. Note: theuiextra is unpinned until the package has a first release, sopip install 'reflex[ui]'from PyPI cannot resolve before then.6.
UIPluginandrx.ui.box. Withrx.plugins.UIPlugin()inrxconfig.py,rx.ui.boxcompiles to a plain<div>whose style is declared in the module that renders it and folded by StyleX to aclassNamestring in the app's Vite build. Without the plugin, compile stops withrx.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.cssdeclares the cascade order once (@layer __reflex_base, theme, base, reflex-ui, components, utilities;): verified with Tailwind v4 that aclass_nameutility 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 breaksreact-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.uistyles (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 inlinestyle, a conditional or state-bound style there is a compile error. Addsreflex_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/themesversion Reflex installs (3.3.0, pin asserted), drift-tested: onedefineVarsmodule 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, andcreateThemeclasses 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 andThemecomponent: 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 innpm test). Two listed exceptions: shadow tokens carry transparent layers so one definition serves both appearances, and four tokens Radix declares asinheritare 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.stylehasStyleProps(a TypedDict of 521 CSS properties with their keywords, generated from the pinned StyleX's own types and drift-tested),ComponentStylesfor a component's style table (base, variants, compound, parts), andlower/merge/emit. A component's table and the user'sstyle=, 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:_hoverblocks and responsive values become per-property conditions, shorthands expand to longhands,rx.color("ruby", 9)becomesvar(--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 stubsstyleis typedSequence[StyleProps] | StyleProps | Var[Mapping[str, Any]] | Breakpoints | None, sostyle={"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.boxagainst 1,000rx.boxtakes 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,backgroundis split into color and image where it can be and is otherwise a compile error naming the longhands (sobackground=State.colormust becomebackground_color=State.color), andanimationis a compile error. A property StyleX's types do not know is rejected;--customproperties 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) inrx.*and inrx.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.pycompares props, literal values and event triggers with the Radix counterpart. Intended differences live inparity/allowlist.tomlwith reasons; an unused entry fails. CI:ui-parity(Chromium, uploads the report, 15 minute budget) andui-contracts(Chromium, Firefox, WebKit), both inintegration-tests-gate.State:
boxshows 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.boxstill lacks the 16 global HTML attribute props ofrx.boxand 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:
Type of change
New Feature Submission:
Changes To Core Features:
https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v