Repository navigation
rx.ui: compiled component package and JS shell fixes - #8037
FarhanAliRaza wants to merge 296 commits into
Conversation
[High impact] The PR changes startup behavior for existing Reflex apps and adds a large optional component set. Fix the radio item name scope before merging; repeated groups with item lifecycle handlers can fail to render. Findings
SummaryAdds the compiled
Reviews (53) · Last reviewed commit: "Name the radio buttons of each rendered ..." · Reviewed by Greptile |
Merging this PR will not alter performance1 warning
Comparing Footnotes
|
A component asks for Emotion's jsx through its imports when its rendered tag has a css prop; every generated module otherwise imports React's createElement as jsx. A css key anywhere in a module's code asks for Emotion too, for code that reaches it without imports. Dynamic components load Emotion on demand. The connection indicator, the badge and the error boundary fallback are styled by class names and a hoisted stylesheet. Claude-Session: https://claude.ai/code/session_014AwvTP2WjJKEVdjMR1jQ6p
…_ and as_child; add text.kbd Claude-Session: https://claude.ai/code/session_014AwvTLCq1szzUoBK5m7hvB
Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v # Conflicts: # tests/units/reflex_components_ui/conftest.py # tests/units/reflex_components_ui/test_base.py
…, and settle the types of the style tables Claude-Session: https://claude.ai/code/session_014AwvTLCq1szzUoBK5m7hvB
…dy the wave after review Claude-Session: https://claude.ai/code/session_014AwvTLCq1szzUoBK5m7hvB
Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v # Conflicts: # tests/units/reflex_components_ui/test_base.py
The click recorded before hydration was dispatched from the mount effect of Scripts, a leaf: providers above it had not run their own effects yet, and the updates of those that had were not applied. It is now dispatched from the effect of a transition started on mount, which React renders only after every update of a higher priority. A click between hydrateRoot and that point had the same problem without any replay: React hydrates synchronously and runs the handler before the mount effects, so the theme provider restored the stored color mode over the one the click had just set. Such a click is now held back from React at the window and dispatched with the recorded one. Clicks in a form or on a control the browser acts on are left alone, and a ten second limit lets clicks through again if hydration never completes. Claude-Session: https://claude.ai/code/session_014AwvTNacWVsm7SEvVjhfGM
…d keep the imports of a component held in state apart from a page's Claude-Session: https://claude.ai/code/session_014AwvTPiaWA4G3wD7R3s5zR
…the page has settled Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v
Props a compound style combines are looked up together, and only the values the table lists were in that lookup. A value of one prop the table does not list, such as high_contrast=False where only "true" has a style, missed the lookup and dropped what the other props picked too: a bound badge variant lost its look while high_contrast was off. A group of several props now holds every combination with each prop's default, and the page falls back to the default of each prop on its own. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v
StyleX gives px to a number of any property outside its unitless list, and columns is not on it, so columns=2 compiled to columns:2px. A literal number of columns, and the few other properties that take a plain number, now goes to StyleX as text, and a state-bound one gets no px. The migrate command no longer reports columns="2" as a length without a unit. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v
Emits a variant of kind and a compound style of kind with size, both bound to state, and compares the whole source. Before 9074763 the table listed red only under size "2", so kind="red" with any other size fell back to the base color. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v
write_text turns their LF into CRLF on Windows, which the codemod keeps, so the comparison with LF expectations failed there. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v
The bindings that hide rx were collected from nested functions too, so a helper assigning its own rx stopped the migration of the function around it. Only the function's own scope counts now. A function that reads a name it binds over the reflex module or an import keeps RadixThemesPlugin, since what it reaches through it may be a Radix component. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v
A state may describe the page once it is entered; a failing cell reports what it says of each system. The states of dropdown_menu report the scroll and size of the window, the boxes of the trigger and of the menu, its side and alignment, the inline styles that place it and its wrapper, and the overflow, padding and style of the root and the body. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v
…ion may still read A from-import of reflex inside a function counted as a binding that hides the name, so a component it imported and built in a state skipped the state check, while the import was moved to reflex_components_ui anyway. An import of reflex now binds no name of its own. An import a function may still read under a name it binds itself stays on reflex, and is reported. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v
Since each rx.ui theme panel names its radio groups apart (e5210d6), an option is in data-rx-theme-option. The shared app's theme panel test, and a contract step of the parity harness, found no radio button by name; the matrix's readiness and its swatch and card parts matched nothing in rx.ui, so it compared less than it said. They now find an option by its name in Radix and by the attribute in rx.ui. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v
A local binding counted as the file's binding of reflex by the kind of statement, so from reflex import el as rx passed as the reflex module and rx.button under it became rx.ui.button. Each binding a scope makes now resolves to its target: the reflex module, a name imported from reflex, or something unknown. It is the file's binding only when the target is the same; anything else hides the name, keeps an import the scope reads on reflex, and keeps RadixThemesPlugin. Scopes follow Python: comprehensions are scopes of their own, decorators, defaults, annotations and the first iterable of a comprehension run in the enclosing scope, and global or nonlocal binds nothing in the scope. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v
Whether the plugin stays was read off the scope tracking, so a read it missed, such as rx.text in a comprehension, generator or lambda under a function that binds rx itself, let the command replace RadixThemesPlugin while the Radix component stayed. A pass over the whole file after the rewrite, blind to scopes, now keeps the plugin for every reference that may still reach a Radix component: the reflex module read whole, a covered component or radix reached through it that was not rewritten, and a component imported from reflex whose import stays. The report names each. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v
Radix and UI SDK give the focus back to the trigger once a menu has closed, which can be a task after the menu is gone: in 11 of 104 closes locally the trigger took the focus 1 to 4ms after close_menu blurred it. Under load it can come during the next cell, after its trigger has the focus or the menu has opened. close_menu now waits, at most a second, until the focus is back on the trigger before blurring it. A state that fails to be entered now names the component, the cell and the system, the error, and what the state says of the page; the menu's description says what has the focus and whether the trigger is open. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v
…he focus back Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v
state.js conflicted where main added dataUrlToBlob beside the localStorage helpers this branch moved to socket.js; the helpers stay in socket.js. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v
main's #7853 adds dataUrlToBlob to state.js, which every stateful app ships: el_stateful js_gzip is 155,207 B against a 155,000 B limit that had 12 B of headroom. The limit becomes the measured value plus 5 %, like the other size budgets. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v
An rx.ui radio group or radio cards given no name took one while compiling, so every group a list rendered shared it: a choice in one row cleared the choice in another. A group given no name now names its radio buttons from React's useId, the same on the server and in the browser, in a hook it adds; it is memoized whole, so each rendered group, each row of an rx.foreach included, runs it in a component of its own. A given name is used as it is, and checkbox groups keep their names. Claude-Session: https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v
| # Its items render in that component, where the name is defined. | ||
| group._memoization_mode = dataclasses.replace( | ||
| group._memoization_mode, recursive=False | ||
| ) | ||
| return Var(_js_expr=ident, _var_type=str) |
There was a problem hiding this comment.
Repeated radio items can crash
An unnamed radio group inside rx.foreach fails to render when an item has on_mount, on_unmount, or its own added hook. _scope_instance_hooks() wraps those items before wrapping the group, despite recursive=False.
The item's separate function still reads rx_radio_name_N, but that variable exists only inside the group's function and is not passed as a prop. This causes a ReferenceError. Keep these items inside the group's function, or pass the generated name into their wrappers.
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 interactive behaviour comes from UI SDK (@ui-sdk/core+@ui-sdk/react, pinned at 0.1.0-beta.17), loaded per component only by pages that render it. rx.ui carries no re-implementation of primitives; the only script of its own left is the theme panel's. 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.themestyleComponents (57 of 57):
Proof and adoption:
UI SDK
The first version of the components drove their behaviour with hand-written scripts (native popover,
<dialog>, roving focus, listbox, menus, sliders...). To avoid maintaining a second implementation of primitives, every interactive component now renders UI SDK's parts with rx.ui's StyleX classes: tabs, dropdown and context menus, dialog, alert dialog, drawer, popover, select, hover card, tooltip, accordion, slider, segmented control, avatar, form fields and messages, text field slots. Native checkbox, switch, radio group and radio cards stay native (no script).Cost: the kitchen sink ships 269.2 kB gzipped JS with rx.ui against 240.7 kB with rx (171.3 kB before UI SDK); a page without interactive parts is unchanged. On the docs site's home page (a content page with no interactive rx.ui parts), Lighthouse mobile goes from 95 to 99 and LCP from 2.34 s to 1.89 s, almost all from 72 % less render-blocking CSS.
Behaviour differences from Radix that users will notice, all in the allowlist with reasons: dialogs, menus, popovers, selects, accordions and segmented controls need hydration (as Radix); disabled tabs, menu items and accordion headers take focus (ARIA patterns); Tab closes an open menu or select; tabs without a value select the first tab; Enter does not choose a segmented-control item and Home/End do nothing there; form messages follow typing after a failed submit; tooltips close when a press ends; drawers fade under reduced motion.
CI state
On a2de2ff every gate passes: unit tests on all OS and Python legs, integration tests (app harness on memory and redis, the shared rx.ui app in dev and prod),
ui-parity(three shards),ui-contractsin Chromium, Firefox and WebKit, docs tests, size budgets, package builds, min-deps, CodSpeed and the performance tests. Every Greptile review thread is answered and resolved (latest confidence score 5/5).reflex/app.py:859-860(the one-timelogger.warningof_SocketOriginCheck._warn, which logs the rejected websocket origin and the request's Host / X-Forwarded-* headers). That code is unchanged by this PR: it is onmainas is (reflex/app.py:870), and CodeQL notes it may report alerts not introduced by a PR when the diff is this large. It needs a maintainer's call on main: dismiss it if those values are not considered sensitive, or fix it there in its own PR.Needs a maintainer's eye
frontend_lazy_bundled_libraries=True,breakingfragment).pointerdown, key presses and typed input are not."blue", not Radix's indigo. Since step 14, theappearanceof theUIPlugintheme sets the app's default color mode.Varalways wins over a later keyword argument (inline style against a class).rxpixel for pixel. The Radix margin and padding shorthands (m,px, ...) and lengths without a unit (gap="2") are refused with the spelling that works, becauserxsilently drops them. Text given torx.ui.switch(...)is refused with the label to wrap it in, becauserx.switchdrops it.parity/allowlist.toml) holds 159 entries, each with its reason: UI SDK behaviour (above), steps the Radix reference itself fails in one engine, and the differences below. The harness waits for 500 ms without DOM mutations before reading a page (a time constant).rx.ui.form(UI SDK has no API for it).rx.ui.container(stack_children_full_width=True)raises and says how to get the same result.scroll_areascrolls natively (no drawn scrollbars;typeandscroll_hide_delayhave no effect) and is a tab stop, which Radix's is not;progressis adivwith progressbar ARIA.rx(or an imported component name) to anything other than what the file imports is left as written;RadixThemesPluginis removed only when a final pass over the result finds no reference that could still reach a Radix component. It does not catch Tailwind classes that resolve to Radix colour scales (rx.ui only declares the scales its components use).rx.uicomponents with conditional styles (buttons, 12 of the 13 form controls) raise aStyleErrorwhen stored in state as a component.BackendDisabledoverlay (default on Reflex Cloud), the connection banner and the connection modal still usecssprops, and anrx.iconon a page brings Emotion'sjsx, so such pages still ship Emotion.Landed so far
1. Dynamic-component libraries load on demand. Blank app JS (gzip of every client
.js): 239.8 kB to 170.8 kB.frontend_lazy_bundled_librariesnow defaults toTrue: a custom script that reads a library fromwindow.__reflexmust firstawait window.__reflex_load([...]), or the app sets the flag toFalse.2. Scripts start after first paint on prerendered pages. Lighthouse mobile on the blank app: simulated 90 / LCP 2.85 s to 100 / 1.21 s; throttled 88 / 2.99 s to 98 / 1.75 s; CLS 0. Dev mode and client-rendered routes are untouched. A dev checkout with an existing
.webneedsreflex initafter pulling this.3. State runtime and toaster ship only when used.
rx.el-only app: stateless 158.7 kB to 130.8 kB, stateful with no toast 161.6 kB to 153.9 kB. A stateless app keeps the event runtime off pages without handlers.refsimported from$/utils/state(as published packages do) is redirected to$/utils/refs, so it loads no state runtime.4. Vite plugin hook.
Plugin.get_vite_plugins()returnsrx.plugins.VitePluginEntry(call=..., imports=[...]); with no entriesvite.config.jsis byte-identical to before.5. Package scaffold.
packages/reflex-components-ui, the optional extrareflex[ui], lazyrx.ui(no cost atimport reflex), a JS package with lint, strict type-check, a generator drift check and vitest in a gated CI job. The extra is unpinned until the package has a first release.6.
UIPlugin. StyleX runs in the app's Vite build through a shipped wrapper.base.cssdeclares the cascade once: resets, then UI SDK, thenreflex-ui, then Tailwind's components and utilities, with unlayered CSS on top; verified with Tailwind v4 (v3 has no native layers and wins overrx.ui).7. Tokens and themes. 81 StyleX modules generated from the installed
@radix-ui/themestoken CSS, drift-tested. A Chromium sweep against the real stylesheet: 10,556 theme combinations x 1,068 custom properties, sRGB and display-P3, zero differences.UIPlugin(theme=rx.ui.Theme(...)),rx.ui.theme(...), typedrx.ui.tokens,color_schemeandradiuson components. Root theme: 4.6 kB gzipped CSS, 0.6 kB gzipped JS.8. Style compiler and typed styles. Tables and user styles are merged in Python, user last, and emitted as literal StyleX declarations that fold to class strings; state values become inline CSS variables, state-bound variants become tables of class strings; no page ships the StyleX runtime.
styleis typed from a generatedStyleProps(521 properties); misuse is a compile error naming the component as the app writes it (rx.ui.callout.root).keyframes({...})animates. Compile time 0.7x to 0.99x of the Emotion path.9. Parity harness.
uv run python scripts/ui_parity.py [component] [--fonts TEXT CODE] [--shard i/n]compares pixels, computed styles (including elements inside a cell where the trees correspond, and named parts down to pseudo-elements) and the accessibility tree against the Radix-backed component, runs a behaviour contract against both systems, and writes a browsable report. CI:ui-parity(Chromium, three shards balanced by recorded timings) andui-contracts(Chromium, Firefox, WebKit), all gated. A Playwright check loads every page of the shared test app in dev and prod and fails on any console warning or error. A cell that cannot be driven names its system and says where the page's focus and menus are.10 to 14. Components. All 57: layout and typography (19), display and actions (12), form controls (13), overlays and disclosure (10: tabs, accordion, dialog, alert dialog, drawer, popover, tooltip, hover card, dropdown menu, context menu), and app-level (theme panel, color-mode button and switch). Each has its namespaces and parts and is based on the same HTML element classes as the Radix wrappers, so props match (API parity test). Every non-allowlisted parity cell is within its matrix's tolerance, most at exactly zero. Native checkbox, switch and radio controls work with JavaScript disabled. Interactive components run on UI SDK (see above).
15. Benchmarks and budgets.
examples/pages/holds blank,rx.elstateless and stateful, onerx.uibutton, and the same kitchen sink inrxand inrx.ui.uv run reflex-bench run --suite pagesmeasures them, andpackages/reflex-bench/budgets.jsonfails CI on overshoot. Gzipped JS: kitchen sink 240.7 kB withrx, 269.2 kB withrx.uion UI SDK (CSS 82.4 kB to 22.6 kB, zero Emotion files); onerx.uibutton 146.8 kB;rx.elstateless first page 124.5 kB.16. Emotion-free pages. A generated module imports React's
createElementunless its code has acssprop, decided once per module from its code. Anrx.ui-only app: 157.7 kB to 149.6 kB gzipped JS, with a permanent test that no script contains Emotion. Compile benchmarks are level withmain.17. Migration codemod and guide.
python -m reflex_components_ui.migrate <paths> [--check] [--diff] [--fix-spacing]rewritesrx.*Radix components torx.ui, moves the theme torx.plugins.UIPlugininrxconfig.py, and reports with file, line and column every style or prop it cannot carry over. It keeps each file's line endings. The migration guide's table of API differences is generated from the allowlist.18. Docs.
rx.uidemos on 51 library pages, beside theirrxcounterparts, plus an overview and styling and theming guides (what the style compiler accepts and refuses, tokens, themes, color mode).All Submissions:
Type of change
New Feature Submission:
Changes To Core Features:
https://claude.ai/code/session_014AwvTPMyGMj9KHaq66r64v
Generated by Claude Code